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/AutomatedTesting/AssetProcessorGamePlatformConfig.setreg b/AutomatedTesting/AssetProcessorGamePlatformConfig.setreg deleted file mode 100644 index c9876cb1f9..0000000000 --- a/AutomatedTesting/AssetProcessorGamePlatformConfig.setreg +++ /dev/null @@ -1,14 +0,0 @@ -{ - "Amazon": { - "AssetProcessor": { - "Settings": { - "RC cgf": { - "ignore": true - }, - "RC fbx": { - "ignore": true - } - } - } - } -} 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 2e9d450ab8..ffcaf7293a 100644 --- a/AutomatedTesting/Gem/Code/Platform/Mac/tool_dependencies.cmake +++ b/AutomatedTesting/Gem/Code/Platform/Mac/tool_dependencies.cmake @@ -10,10 +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 - Gem::Atom_RHI_Vulkan.Builders - Gem::Atom_RHI_DX12.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 62a6ed7f8c..280c25bcf7 100644 --- a/AutomatedTesting/Gem/Code/runtime_dependencies.cmake +++ b/AutomatedTesting/Gem/Code/runtime_dependencies.cmake @@ -42,17 +42,7 @@ 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::NvCloth Gem::Blast ) diff --git a/AutomatedTesting/Gem/Code/tool_dependencies.cmake b/AutomatedTesting/Gem/Code/tool_dependencies.cmake index a6bbeee350..fc50707c12 100644 --- a/AutomatedTesting/Gem/Code/tool_dependencies.cmake +++ b/AutomatedTesting/Gem/Code/tool_dependencies.cmake @@ -50,24 +50,9 @@ 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::NvCloth.Editor Gem::Blast.Editor ) diff --git a/AutomatedTesting/Gem/PythonTests/NvCloth/C18977329_NvCloth_AddClothSimulationToMesh.py b/AutomatedTesting/Gem/PythonTests/NvCloth/C18977329_NvCloth_AddClothSimulationToMesh.py index 625c9772bd..5cfc57fd5f 100755 --- a/AutomatedTesting/Gem/PythonTests/NvCloth/C18977329_NvCloth_AddClothSimulationToMesh.py +++ b/AutomatedTesting/Gem/PythonTests/NvCloth/C18977329_NvCloth_AddClothSimulationToMesh.py @@ -11,7 +11,6 @@ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # Test case ID : C18977329 # Test Case Title : Add cloth simulation to a Mesh -# URL of the test case : https://testrail.agscollab.com/index.php?/cases/view/18977329 # fmt: off class Tests: diff --git a/AutomatedTesting/Gem/PythonTests/NvCloth/C18977330_NvCloth_AddClothSimulationToActor.py b/AutomatedTesting/Gem/PythonTests/NvCloth/C18977330_NvCloth_AddClothSimulationToActor.py index 9b3135cd2b..c21df8ea4c 100755 --- a/AutomatedTesting/Gem/PythonTests/NvCloth/C18977330_NvCloth_AddClothSimulationToActor.py +++ b/AutomatedTesting/Gem/PythonTests/NvCloth/C18977330_NvCloth_AddClothSimulationToActor.py @@ -11,7 +11,6 @@ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # Test case ID : C18977330 # Test Case Title : Add cloth simulation to an Actor -# URL of the test case : https://testrail.agscollab.com/index.php?/cases/view/18977330 # fmt: off class Tests: diff --git a/AutomatedTesting/Gem/PythonTests/WhiteBox/C28798177_WhiteBox_AddComponentToEntity.py b/AutomatedTesting/Gem/PythonTests/WhiteBox/C28798177_WhiteBox_AddComponentToEntity.py index dabc04575f..86a27e588e 100755 --- a/AutomatedTesting/Gem/PythonTests/WhiteBox/C28798177_WhiteBox_AddComponentToEntity.py +++ b/AutomatedTesting/Gem/PythonTests/WhiteBox/C28798177_WhiteBox_AddComponentToEntity.py @@ -12,7 +12,6 @@ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # Test case ID : C28798177 # Test Case Title : White Box Tool Component can be added to an Entity -# URL of the test case : https://testrail.agscollab.com/index.php?/cases/view/28798177 # fmt:off diff --git a/AutomatedTesting/Gem/PythonTests/WhiteBox/C28798205_WhiteBox_SetInvisible.py b/AutomatedTesting/Gem/PythonTests/WhiteBox/C28798205_WhiteBox_SetInvisible.py index 18a5c3164e..7a2a08a8ce 100755 --- a/AutomatedTesting/Gem/PythonTests/WhiteBox/C28798205_WhiteBox_SetInvisible.py +++ b/AutomatedTesting/Gem/PythonTests/WhiteBox/C28798205_WhiteBox_SetInvisible.py @@ -12,7 +12,6 @@ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # Test case ID : C28798205 # Test Case Title : From the White Box Component Card the White Box Mesh can be set to be invisible in Game View -# URL of the test case : https://testrail.agscollab.com/index.php?/cases/view/28798205 # fmt:off diff --git a/AutomatedTesting/Gem/PythonTests/WhiteBox/C29279329_WhiteBox_SetDefaultShape.py b/AutomatedTesting/Gem/PythonTests/WhiteBox/C29279329_WhiteBox_SetDefaultShape.py index e892285dde..635c804914 100755 --- a/AutomatedTesting/Gem/PythonTests/WhiteBox/C29279329_WhiteBox_SetDefaultShape.py +++ b/AutomatedTesting/Gem/PythonTests/WhiteBox/C29279329_WhiteBox_SetDefaultShape.py @@ -12,7 +12,6 @@ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # Test case ID : C29279329 # Test Case Title : White Box mesh shape can be changed with the Default Shape dropdown on the Component -# URL of the test case : https://testrail.agscollab.com/index.php?/cases/view/29279329 # fmt:off diff --git a/AutomatedTesting/Gem/PythonTests/atom_renderer/test_Atom_MainSuite.py b/AutomatedTesting/Gem/PythonTests/atom_renderer/test_Atom_MainSuite.py index f84e367d1d..0b75760e05 100644 --- a/AutomatedTesting/Gem/PythonTests/atom_renderer/test_Atom_MainSuite.py +++ b/AutomatedTesting/Gem/PythonTests/atom_renderer/test_Atom_MainSuite.py @@ -18,7 +18,7 @@ import pytest import editor_python_test_tools.hydra_test_utils as hydra logger = logging.getLogger(__name__) -EDITOR_TIMEOUT = 120 +EDITOR_TIMEOUT = 300 TEST_DIRECTORY = os.path.join(os.path.dirname(__file__), "atom_hydra_scripts") 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..d0c6fc3c5a 100755 --- a/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/DistanceBetweenFilterOverrides_InstancesPlantAtSpecifiedRadius.py +++ b/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/DistanceBetweenFilterOverrides_InstancesPlantAtSpecifiedRadius.py @@ -82,42 +82,34 @@ 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 \ - 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) - 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 \ - 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) - 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 \ - 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) - 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 + 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 09c5fd63cf..d342afd7ca 100755 --- a/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/DistanceBetweenFilter_InstancesPlantAtSpecifiedRadius.py +++ b/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/DistanceBetweenFilter_InstancesPlantAtSpecifiedRadius.py @@ -80,35 +80,29 @@ 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 \ - 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) - 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 \ - 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) - 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 \ - 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) - 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/physics/C14976308_ScriptCanvas_SetKinematicTargetTransform.py b/AutomatedTesting/Gem/PythonTests/physics/C14976308_ScriptCanvas_SetKinematicTargetTransform.py index c76c5cab80..8400364626 100755 --- a/AutomatedTesting/Gem/PythonTests/physics/C14976308_ScriptCanvas_SetKinematicTargetTransform.py +++ b/AutomatedTesting/Gem/PythonTests/physics/C14976308_ScriptCanvas_SetKinematicTargetTransform.py @@ -68,7 +68,7 @@ def C14976308_ScriptCanvas_SetKinematicTargetTransform(): the script deactivates Signal, Sphere's transform will update to that of Transform_Target. NOTE: There is a known bug (LY-107723) which causes the rotation to update to a value that is not sufficiently close to the expected result when using Set Kinematic Target which will cause the test to fail: - https://jira.agscollab.com/browse/LY-107723 + LY-107723 Test Steps: 1) Open level and enter game mode diff --git a/AutomatedTesting/Gem/PythonTests/physics/C3510644_Collider_CollisionGroups.py b/AutomatedTesting/Gem/PythonTests/physics/C3510644_Collider_CollisionGroups.py index 4ae10288bd..e714da9de7 100755 --- a/AutomatedTesting/Gem/PythonTests/physics/C3510644_Collider_CollisionGroups.py +++ b/AutomatedTesting/Gem/PythonTests/physics/C3510644_Collider_CollisionGroups.py @@ -13,7 +13,6 @@ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # Test case ID : C3510644 # Test Case Title : Check that the collision layer and collision group of the terrain can be changed # and the collision behavior of the terrain changes accordingly -# URL of the test case : https://testrail.agscollab.com/index.php?/cases/view/3510644 # fmt: off diff --git a/AutomatedTesting/Gem/PythonTests/physics/C6321601_Force_HighValuesDirectionAxes.py b/AutomatedTesting/Gem/PythonTests/physics/C6321601_Force_HighValuesDirectionAxes.py index 4b0b036970..08083a7868 100755 --- a/AutomatedTesting/Gem/PythonTests/physics/C6321601_Force_HighValuesDirectionAxes.py +++ b/AutomatedTesting/Gem/PythonTests/physics/C6321601_Force_HighValuesDirectionAxes.py @@ -239,7 +239,7 @@ def C6321601_Force_HighValuesDirectionAxes(): force_notification_handler.add_callback("OnCalculateNetForce", on_calc_net_force) # Wait for 3 secs, because there is a known bug identified and filed in - # JIRA https://jira.agscollab.com/browse/LY-107677 + # JIRA LY-107677 # The error "[Error] Huge object being added to a COctreeNode, name: 'MeshComponentRenderNode', objBox:" # will show (if occured) in about 3 sec into the game mode. helper.wait_for_condition(has_physx_error, 3.0) diff --git a/AutomatedTesting/Gem/PythonTests/physics/TestSuite_InDevelopment.py b/AutomatedTesting/Gem/PythonTests/physics/TestSuite_InDevelopment.py index 8f098941ea..8986c1024a 100755 --- a/AutomatedTesting/Gem/PythonTests/physics/TestSuite_InDevelopment.py +++ b/AutomatedTesting/Gem/PythonTests/physics/TestSuite_InDevelopment.py @@ -50,7 +50,7 @@ class TestAutomation(TestAutomationBase): unexpected_lines = ["Assert"] self._run_test(request, workspace, editor, test_module, expected_lines, unexpected_lines) - # BUG: https://jira.agscollab.com/browse/LY-107723") + # BUG: LY-107723") def test_C14976308_ScriptCanvas_SetKinematicTargetTransform(self, request, workspace, editor): from . import C14976308_ScriptCanvas_SetKinematicTargetTransform as test_module diff --git a/AutomatedTesting/Gem/PythonTests/physics/UtilTest_Physmaterial_Editor.py b/AutomatedTesting/Gem/PythonTests/physics/UtilTest_Physmaterial_Editor.py index 5f24f41083..b6d7c610e3 100755 --- a/AutomatedTesting/Gem/PythonTests/physics/UtilTest_Physmaterial_Editor.py +++ b/AutomatedTesting/Gem/PythonTests/physics/UtilTest_Physmaterial_Editor.py @@ -12,7 +12,7 @@ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ''' This unittest might have to be refactored once changes to Physmaterial_Editor.py are made. These changes will occur after the but, reverence below is resloved. -Bug: https://jira.agscollab.com/browse/LY-107392 +Bug: LY-107392 ''' class Tests: opening_bad_file = ("Bad file could not be opened", "Bad file was opened") diff --git a/AutomatedTesting/Gem/PythonTests/scripting/AssetEditor_CreateScriptEventFile.py b/AutomatedTesting/Gem/PythonTests/scripting/AssetEditor_CreateScriptEventFile.py index dcbbf47f0c..b844f9e4af 100644 --- a/AutomatedTesting/Gem/PythonTests/scripting/AssetEditor_CreateScriptEventFile.py +++ b/AutomatedTesting/Gem/PythonTests/scripting/AssetEditor_CreateScriptEventFile.py @@ -10,7 +10,6 @@ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. Test case ID: T92569013 Test Case Title: Script Event file can be created -URL of the test case: https://testrail.agscollab.com/index.php?/tests/view/92569013 """ diff --git a/AutomatedTesting/Gem/PythonTests/scripting/AssetEditor_NewScriptEvent.py b/AutomatedTesting/Gem/PythonTests/scripting/AssetEditor_NewScriptEvent.py index 1f801d4eeb..e4fec76fe2 100644 --- a/AutomatedTesting/Gem/PythonTests/scripting/AssetEditor_NewScriptEvent.py +++ b/AutomatedTesting/Gem/PythonTests/scripting/AssetEditor_NewScriptEvent.py @@ -12,7 +12,6 @@ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. Test case ID: T92568942 Test Case Title: Clicking the "+" button and selecting "New Script Event" opens the Asset Editor with a new Script Event asset -URL of the test case: https://testrail.agscollab.com/index.php?/tests/view/92568942 """ from PySide2 import QtWidgets diff --git a/AutomatedTesting/Gem/PythonTests/scripting/Debugging_TargetMultipleEntities.py b/AutomatedTesting/Gem/PythonTests/scripting/Debugging_TargetMultipleEntities.py index a26cb4f923..0947b0bb51 100644 --- a/AutomatedTesting/Gem/PythonTests/scripting/Debugging_TargetMultipleEntities.py +++ b/AutomatedTesting/Gem/PythonTests/scripting/Debugging_TargetMultipleEntities.py @@ -11,7 +11,6 @@ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. Test case ID: T92568856 Test Case Title: Multiple Entities can be targeted in the Debugger tool -URLs of the test case: https://testrail.agscollab.com/index.php?/tests/view/92568856 """ diff --git a/AutomatedTesting/Gem/PythonTests/scripting/Debugging_TargetMultipleGraphs.py b/AutomatedTesting/Gem/PythonTests/scripting/Debugging_TargetMultipleGraphs.py index 4aa5c822a7..8d2c39f288 100644 --- a/AutomatedTesting/Gem/PythonTests/scripting/Debugging_TargetMultipleGraphs.py +++ b/AutomatedTesting/Gem/PythonTests/scripting/Debugging_TargetMultipleGraphs.py @@ -11,7 +11,6 @@ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. Test case ID: T92569137 Test Case Title: Multiple Graphs can be targeted in the Debugger tool -URLs of the test case: https://testrail.agscollab.com/index.php?/tests/view/92569137 """ diff --git a/AutomatedTesting/Gem/PythonTests/scripting/Docking_Pane.py b/AutomatedTesting/Gem/PythonTests/scripting/Docking_Pane.py index 4fa1e1257f..537b4d817a 100755 --- a/AutomatedTesting/Gem/PythonTests/scripting/Docking_Pane.py +++ b/AutomatedTesting/Gem/PythonTests/scripting/Docking_Pane.py @@ -10,7 +10,6 @@ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. Test case ID: C1702824 Test Case Title: Docking -URLs of the test case: https://testrail.agscollab.com/index.php?/cases/view/1702824 """ diff --git a/AutomatedTesting/Gem/PythonTests/scripting/EditMenu_UndoRedo.py b/AutomatedTesting/Gem/PythonTests/scripting/EditMenu_UndoRedo.py index a87d9e9be9..38ceb8335b 100644 --- a/AutomatedTesting/Gem/PythonTests/scripting/EditMenu_UndoRedo.py +++ b/AutomatedTesting/Gem/PythonTests/scripting/EditMenu_UndoRedo.py @@ -11,10 +11,8 @@ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. Test case ID: T92569049 Test Case Title: Edit > Undo undoes the last action -URL of the test case: https://testrail.agscollab.com/index.php?/tests/view/92569049 Test case ID: T92569051 Test Case Title: Edit > Redo redoes the last undone action -URL of the test case: https://testrail.agscollab.com/index.php?/tests/view/92569051 """ diff --git a/AutomatedTesting/Gem/PythonTests/scripting/Entity_AddScriptCanvasComponent.py b/AutomatedTesting/Gem/PythonTests/scripting/Entity_AddScriptCanvasComponent.py index fd8e9b1173..47bbb955ec 100644 --- a/AutomatedTesting/Gem/PythonTests/scripting/Entity_AddScriptCanvasComponent.py +++ b/AutomatedTesting/Gem/PythonTests/scripting/Entity_AddScriptCanvasComponent.py @@ -10,7 +10,6 @@ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. Test case ID: T92562978 Test Case Title: Script Canvas Component can be added to an entity -URL of the test case: https://testrail.agscollab.com/index.php?/tests/view/92562978 """ diff --git a/AutomatedTesting/Gem/PythonTests/scripting/FileMenu_New_Open.py b/AutomatedTesting/Gem/PythonTests/scripting/FileMenu_New_Open.py index f72ac8ea01..3206590a8d 100644 --- a/AutomatedTesting/Gem/PythonTests/scripting/FileMenu_New_Open.py +++ b/AutomatedTesting/Gem/PythonTests/scripting/FileMenu_New_Open.py @@ -11,10 +11,8 @@ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. Test case ID: T92569037 Test Case Title: File > New Script creates a new script -URL of the test case: https://testrail.agscollab.com/index.php?/tests/view/92569037 Test case ID: T92569039 Test Case Title: File > Open opens the Open... dialog -URL of the test case: https://testrail.agscollab.com/index.php?/tests/view/92569039 """ import os diff --git a/AutomatedTesting/Gem/PythonTests/scripting/GraphClose_SavePrompt.py b/AutomatedTesting/Gem/PythonTests/scripting/GraphClose_SavePrompt.py index ce610b159b..ec8f0c8fb6 100644 --- a/AutomatedTesting/Gem/PythonTests/scripting/GraphClose_SavePrompt.py +++ b/AutomatedTesting/Gem/PythonTests/scripting/GraphClose_SavePrompt.py @@ -11,11 +11,9 @@ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. Test case ID: T92563070 Test Case Title: Graphs can be closed by clicking X on the Graph name tab -URL of the test case: https://testrail.agscollab.com/index.php?/tests/view/92563070 Test case ID: T92563068 Test Case Title: Save Prompt: User is prompted to save a graph on close after creating a new graph -URL of the test case: https://testrail.agscollab.com/index.php?/tests/view/92563068 """ import os diff --git a/AutomatedTesting/Gem/PythonTests/scripting/Graph_ZoomInZoomOut.py b/AutomatedTesting/Gem/PythonTests/scripting/Graph_ZoomInZoomOut.py index a93b6e61d1..d2765bfdf7 100644 --- a/AutomatedTesting/Gem/PythonTests/scripting/Graph_ZoomInZoomOut.py +++ b/AutomatedTesting/Gem/PythonTests/scripting/Graph_ZoomInZoomOut.py @@ -11,10 +11,8 @@ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. Test case ID: T92569079 Test Case Title: View > Zoom In zooms the graph in -URL of the test case: https://testrail.agscollab.com/index.php?/tests/view/92569079 Test case ID: T92569081 Test Case Title: View > Zoom In zooms the graph out -URL of the test case: https://testrail.agscollab.com/index.php?/tests/view/92569081 """ diff --git a/AutomatedTesting/Gem/PythonTests/scripting/ImportPathHelper.py b/AutomatedTesting/Gem/PythonTests/scripting/ImportPathHelper.py index a45024cebf..23e5f87030 100755 --- a/AutomatedTesting/Gem/PythonTests/scripting/ImportPathHelper.py +++ b/AutomatedTesting/Gem/PythonTests/scripting/ImportPathHelper.py @@ -9,9 +9,9 @@ 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. """ + def init(): import os import sys sys.path.append(os.path.dirname(os.path.abspath(__file__)) + '/../automatedtesting_shared') sys.path.append(os.path.dirname(os.path.abspath(__file__)) + '/../EditorPythonTestTools/editor_python_test_tools') - \ No newline at end of file diff --git a/AutomatedTesting/Gem/PythonTests/scripting/NodeCategory_ExpandOnClick.py b/AutomatedTesting/Gem/PythonTests/scripting/NodeCategory_ExpandOnClick.py new file mode 100644 index 0000000000..141cdbea8d --- /dev/null +++ b/AutomatedTesting/Gem/PythonTests/scripting/NodeCategory_ExpandOnClick.py @@ -0,0 +1,128 @@ +""" +All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or +its licensors. + +For complete copyright and license terms please see the LICENSE at the root of this +distribution (the "License"). All use of this software is governed by the License, +or, if provided, by the license below or the license accompanying this file. Do not +remove or modify any license notices. This file is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + +Test case ID: T92562988 +Test Case Title: Left-click/double click expands and collapses node categories +""" + + +# fmt: off +class Tests(): + pane_open = ("Script Canvas pane successfully opened", "Script Canvas pane failed to open") + click_expand = ("Category expanded on left click", "Category failed to expand on left click") + click_collapse = ("Category collapsed on left click", "Category failed to collapse on left click") + dClick_expand = ("Category expanded on double click", "Category failed to expand on double click") + dClick_collapse = ("Category collapsed on double click", "Category failed to collapse on double click") +# fmt: on + + +def NodeCategory_ExpandOnClick(): + """ + Summary: + Verifying the expand/collapse functionality on node categories + + Expected Behavior: + The node category should expand when double clicked or when the drop down indicator is + left-clicked. Once expanded, it should be collapsed via the same actions. + + Test Steps: + 1) Open Script Canvas pane + 2) Get the SC window objects + 3) Ensure all categories are collapsed for a clean state + 4) Left-Click on a node category arrow to expand it + 5) Verify it expanded + 6) Left-Click on a node category arrow to collapse it + 7) Verify it collapsed + 8) Double-Click on a node category to expand it + 9) Verify it expanded + 10) Double-Click on a node category to collapse it + 11) Verify it collapsed + + Note: + - This test file must be called from the Open 3D Engine Editor command terminal + - Any passed and failed tests are written to the Editor.log file. + Parsing the file or running a log_monitor are required to observe the test results. + + :return: None + """ + from utils import Report + from PySide2 import QtCore, QtWidgets, QtTest + from PySide2.QtTest import QTest + import pyside_utils + import azlmbr.legacy.general as general + + def left_click_arrow(item_view, index): + original_state = item_view.isExpanded(index) + rect_center_y = item_view.visualRect(index).center().y() + rect_left_x = item_view.visualRect(index).left() + for i in range(5): # this range can be increased for safe side + QtTest.QTest.mouseClick( + item_view.viewport(), + QtCore.Qt.LeftButton, + QtCore.Qt.NoModifier, + QtCore.QPoint(rect_left_x - i, rect_center_y), + ) + if item_view.isExpanded(index) != original_state: + break + + def double_click(item_view, index): + item_index_center = item_view.visualRect(index).center() + # Left click on the item before trying to double click, will otherwise fail to expand + # as first click would highlight and second click would be a 'single click' + pyside_utils.item_view_index_mouse_click(item_view, index) + QTest.mouseDClick(item_view.viewport(), QtCore.Qt.LeftButton, QtCore.Qt.NoModifier, item_index_center) + + # 1) Open Script Canvas pane + general.open_pane("Script Canvas") + Report.critical_result(Tests.pane_open, general.is_pane_visible("Script Canvas")) + + # 2) Get the SC window objects + editor_window = pyside_utils.get_editor_main_window() + sc = editor_window.findChild(QtWidgets.QDockWidget, "Script Canvas") + if sc.findChild(QtWidgets.QDockWidget, "NodePalette") is None: + action = pyside_utils.find_child_by_pattern(sc, {"text": "Node Palette", "type": QtWidgets.QAction}) + action.trigger() + node_palette = sc.findChild(QtWidgets.QDockWidget, "NodePalette") + nodeTree = node_palette.findChild(QtWidgets.QTreeView, "treeView") + ai_index = pyside_utils.find_child_by_pattern(nodeTree, "AI") + + # 3) Ensure all categories are collapsed for a clean state + nodeTree.collapseAll() + + # 4) Left-Click on a node category arrow to expand it + left_click_arrow(nodeTree, ai_index) + + # 5) Verify it expanded + Report.result(Tests.click_expand, nodeTree.isExpanded(ai_index)) + + # 6) Left-Click on a node category arrow to collapse it + left_click_arrow(nodeTree, ai_index) + + # 7) Verify it collapsed + Report.result(Tests.click_collapse, not nodeTree.isExpanded(ai_index)) + + # 8) Double-Click on a node category to expand it + double_click(nodeTree, ai_index) + + # 9) Verify it expanded + Report.result(Tests.dClick_expand, nodeTree.isExpanded(ai_index)) + + # 10) Double-Click on a node category to collapse it + double_click(nodeTree, ai_index) + + # 11) Verify it collapsed + Report.result(Tests.dClick_collapse, not nodeTree.isExpanded(ai_index)) + + +if __name__ == "__main__": + import ImportPathHelper as imports + imports.init() + from utils import Report + Report.start_test(NodeCategory_ExpandOnClick) diff --git a/AutomatedTesting/Gem/PythonTests/scripting/NodeInspector_RenameVariable.py b/AutomatedTesting/Gem/PythonTests/scripting/NodeInspector_RenameVariable.py index 33d3f4137a..550969e32a 100644 --- a/AutomatedTesting/Gem/PythonTests/scripting/NodeInspector_RenameVariable.py +++ b/AutomatedTesting/Gem/PythonTests/scripting/NodeInspector_RenameVariable.py @@ -10,7 +10,6 @@ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. Test case ID: T92568982 Test Case Title: Renaming variables in the Node Inspector -URL of the test case: https://testrail.agscollab.com/index.php?/tests/view/92568982 """ diff --git a/AutomatedTesting/Gem/PythonTests/scripting/NodePalette_ClearSelection.py b/AutomatedTesting/Gem/PythonTests/scripting/NodePalette_ClearSelection.py index de30e46767..979bcff02e 100644 --- a/AutomatedTesting/Gem/PythonTests/scripting/NodePalette_ClearSelection.py +++ b/AutomatedTesting/Gem/PythonTests/scripting/NodePalette_ClearSelection.py @@ -10,7 +10,6 @@ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. Test case ID: T92562993 Test Case Title: Clicking the X button on the Search Box clears the currently entered string -URL of the test case: https://testrail.agscollab.com/index.php?/tests/view/92562993 """ diff --git a/AutomatedTesting/Gem/PythonTests/scripting/NodePalette_SearchText_Deletion.py b/AutomatedTesting/Gem/PythonTests/scripting/NodePalette_SearchText_Deletion.py new file mode 100644 index 0000000000..0739a8e637 --- /dev/null +++ b/AutomatedTesting/Gem/PythonTests/scripting/NodePalette_SearchText_Deletion.py @@ -0,0 +1,91 @@ +""" +All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or +its licensors. + +For complete copyright and license terms please see the LICENSE at the root of this +distribution (the "License"). All use of this software is governed by the License, +or, if provided, by the license below or the license accompanying this file. Do not +remove or 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(): + set_search_string = ("Search string is set", "Search string is not set") + search_string_deleted = ("Search string deleted as expected", "Search string not deleted") +# fmt: on + + +def NodePalette_SearchText_Deletion(): + """ + Summary: + We enter some string in the Node Palette Search box, select that text and delete it. + + Expected Behavior: + After RightClick->Delete the text in the Searchbox should be deleted. + + Test Steps: + 1) Open Script Canvas window (Tools > Script Canvas) + 2) Get the SC window object + 3) Open Node Manager if not opened already + 4) Set some string in the Search box + 5) Verify if the test string is set + 6) Delete search string using right click and verify if it is cleared + + Note: + - This test file must be called from the Open 3D Engine Editor command terminal + - Any passed and failed tests are written to the Editor.log file. + Parsing the file or running a log_monitor are required to observe the test results. + + :return: None + """ + + from PySide2 import QtWidgets, QtTest, QtCore + + from utils import TestHelper as helper + + import azlmbr.legacy.general as general + + import pyside_utils + + TEST_STRING = "TestString" + + # 1) Open Script Canvas window (Tools > Script Canvas) + general.idle_enable(True) + general.open_pane("Script Canvas") + helper.wait_for_condition(lambda: general.is_pane_visible("Script Canvas"), 3.0) + + # 2) Get the SC window object + editor_window = pyside_utils.get_editor_main_window() + sc = editor_window.findChild(QtWidgets.QDockWidget, "Script Canvas") + + # 3) Open Node Manager if not opened already + if sc.findChild(QtWidgets.QDockWidget, "NodePalette") is None: + action = pyside_utils.find_child_by_pattern(sc, {"text": "Node Palette", "type": QtWidgets.QAction}) + action.trigger() + node_palette = sc.findChild(QtWidgets.QDockWidget, "NodePalette") + search_frame = node_palette.findChild(QtWidgets.QFrame, "searchFrame") + + # 4) Set some string in the Search box + search_box = search_frame.findChild(QtWidgets.QLineEdit, "searchFilter") + search_box.setText(TEST_STRING) + + # 5) Verify if the test string is set + result = helper.wait_for_condition(lambda: search_box.text() == TEST_STRING, 1.0) + Report.result(Tests.set_search_string, result) + + # 6) Delete search string using right click and verify if it is cleared + QtTest.QTest.keyClick(search_box, QtCore.Qt.Key_A, QtCore.Qt.ControlModifier) + pyside_utils.trigger_context_menu_entry(search_box, "Delete") + result = helper.wait_for_condition(lambda: search_box.text() == "", 2.0) + Report.result(Tests.search_string_deleted, result) + + +if __name__ == "__main__": + import ImportPathHelper as imports + + imports.init() + from utils import Report + + Report.start_test(NodePalette_SearchText_Deletion) diff --git a/AutomatedTesting/Gem/PythonTests/scripting/NodePalette_SelectNode.py b/AutomatedTesting/Gem/PythonTests/scripting/NodePalette_SelectNode.py index 2ab76071a6..374dc4e1a0 100644 --- a/AutomatedTesting/Gem/PythonTests/scripting/NodePalette_SelectNode.py +++ b/AutomatedTesting/Gem/PythonTests/scripting/NodePalette_SelectNode.py @@ -11,7 +11,6 @@ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. Test case ID: T92568940 Test Case Title: Categories and Nodes can be selected -URL of the test case: https://testrail.agscollab.com/index.php?/tests/view/92568940 """ diff --git a/AutomatedTesting/Gem/PythonTests/scripting/OnEntityActivatedDeactivated_PrintMessage.py b/AutomatedTesting/Gem/PythonTests/scripting/OnEntityActivatedDeactivated_PrintMessage.py index 51b63c4268..00893d6acb 100644 --- a/AutomatedTesting/Gem/PythonTests/scripting/OnEntityActivatedDeactivated_PrintMessage.py +++ b/AutomatedTesting/Gem/PythonTests/scripting/OnEntityActivatedDeactivated_PrintMessage.py @@ -10,7 +10,6 @@ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. Test case ID: T92569253 // T92569254 Test Case Title: On Entity Activated // On Entity Deactivated -URL of the test case: https://testrail.agscollab.com/index.php?/tests/view/92569253 // https://testrail.agscollab.com/index.php?/tests/view/92569254 """ diff --git a/AutomatedTesting/Gem/PythonTests/scripting/Opening_Closing_Pane.py b/AutomatedTesting/Gem/PythonTests/scripting/Opening_Closing_Pane.py index 666f052240..48c40eb05e 100755 --- a/AutomatedTesting/Gem/PythonTests/scripting/Opening_Closing_Pane.py +++ b/AutomatedTesting/Gem/PythonTests/scripting/Opening_Closing_Pane.py @@ -10,8 +10,6 @@ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. Test case ID: C1702834 // C1702823 Test Case Title: Opening pane // Closing pane -URLs of the test case: https://testrail.agscollab.com/index.php?/cases/view/1702834 and - https://testrail.agscollab.com/index.php?/cases/view/1702823 """ diff --git a/AutomatedTesting/Gem/PythonTests/scripting/Pane_RetainOnSCRestart.py b/AutomatedTesting/Gem/PythonTests/scripting/Pane_RetainOnSCRestart.py index fa5e9e6068..adf9b5f35a 100644 --- a/AutomatedTesting/Gem/PythonTests/scripting/Pane_RetainOnSCRestart.py +++ b/AutomatedTesting/Gem/PythonTests/scripting/Pane_RetainOnSCRestart.py @@ -10,8 +10,6 @@ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. Test case ID: C1702821 // C1702832 Test Case Title: Retain visibility, size and location upon Script Canvas restart -URLs of the test case: https://testrail.agscollab.com/index.php?/cases/view/1702821 and - https://testrail.agscollab.com/index.php?/cases/view/1702832 """ diff --git a/AutomatedTesting/Gem/PythonTests/scripting/Resizing_Pane.py b/AutomatedTesting/Gem/PythonTests/scripting/Resizing_Pane.py index 180f577953..bbae3afefd 100755 --- a/AutomatedTesting/Gem/PythonTests/scripting/Resizing_Pane.py +++ b/AutomatedTesting/Gem/PythonTests/scripting/Resizing_Pane.py @@ -10,7 +10,6 @@ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. Test case ID: C1702829 Test Case Title: Resizing pane -URLs of the test case: https://testrail.agscollab.com/index.php?/cases/view/1702829 """ diff --git a/AutomatedTesting/Gem/PythonTests/scripting/ScriptCanvas_ChangingAssets.py b/AutomatedTesting/Gem/PythonTests/scripting/ScriptCanvas_ChangingAssets.py index 38d60ad871..bb4de4a6c9 100644 --- a/AutomatedTesting/Gem/PythonTests/scripting/ScriptCanvas_ChangingAssets.py +++ b/AutomatedTesting/Gem/PythonTests/scripting/ScriptCanvas_ChangingAssets.py @@ -11,7 +11,6 @@ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. Test case ID: T92562986 Test Case Title: Changing the assigned Script Canvas Asset on an entity properly updates level functionality -URL of the test case: https://testrail.agscollab.com/index.php?/tests/view/92562986 """ diff --git a/AutomatedTesting/Gem/PythonTests/scripting/ScriptCanvas_TwoComponents.py b/AutomatedTesting/Gem/PythonTests/scripting/ScriptCanvas_TwoComponents.py index 896bee96e5..6187ac81ba 100644 --- a/AutomatedTesting/Gem/PythonTests/scripting/ScriptCanvas_TwoComponents.py +++ b/AutomatedTesting/Gem/PythonTests/scripting/ScriptCanvas_TwoComponents.py @@ -10,7 +10,6 @@ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. Test case ID: T92563190 Test Case Title: A single Entity with two Script Canvas components works properly -URL of the test case: https://testrail.agscollab.com/index.php?/tests/view/92563190 """ diff --git a/AutomatedTesting/Gem/PythonTests/scripting/ScriptCanvas_TwoEntities.py b/AutomatedTesting/Gem/PythonTests/scripting/ScriptCanvas_TwoEntities.py index 401e6c0271..9453c31488 100644 --- a/AutomatedTesting/Gem/PythonTests/scripting/ScriptCanvas_TwoEntities.py +++ b/AutomatedTesting/Gem/PythonTests/scripting/ScriptCanvas_TwoEntities.py @@ -10,7 +10,6 @@ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. Test case ID: T92563191 Test Case Title: Two Entities can use the same Graph asset successfully at RunTime -URL of the test case: https://testrail.agscollab.com/index.php?/tests/view/92563191 """ diff --git a/AutomatedTesting/Gem/PythonTests/scripting/ScriptEvents_ReturnSetType_Successfully.py b/AutomatedTesting/Gem/PythonTests/scripting/ScriptEvents_ReturnSetType_Successfully.py new file mode 100644 index 0000000000..aa9abd110b --- /dev/null +++ b/AutomatedTesting/Gem/PythonTests/scripting/ScriptEvents_ReturnSetType_Successfully.py @@ -0,0 +1,112 @@ +""" +All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or +its licensors. + +For complete copyright and license terms please see the LICENSE at the root of this +distribution (the "License"). All use of this software is governed by the License, +or, if provided, by the license below or the license accompanying this file. Do not +remove or modify any license notices. This file is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + +Test Case Title: Event can return a value of set type successfully +""" + + +# fmt: off +class Tests(): + level_created = ("Successfully created temporary level", "Failed to create temporary level") + entity_created = ("Successfully created test entity", "Failed to create test entity") + enter_game_mode = ("Successfully entered game mode", "Failed to enter game mode") + lines_found = ("Successfully found expected message", "Failed to find expected message") + exit_game_mode = ("Successfully exited game mode", "Failed to exit game mode") +# fmt: on + + +def ScriptEvents_ReturnSetType_Successfully(): + """ + Summary: A temporary level is created with an Entity having ScriptCanvas component. + ScriptEvent(T92569006_ScriptEvent.scriptevents) is created with one Method that has a return value. + ScriptCanvas(T92569006_ScriptCanvas.scriptcanvas) is attached to Entity. Graph has Send node that sends the Method + of the ScriptEvent and prints the returned result ( On Entity Activated -> Send node -> Print) and Receive node is + set to return custom value ( Receive node -> Print). + Verify that the entity containing T92569006_ScriptCanvas.scriptcanvas should print the custom value set in both + Send and Receive nodes. + + Expected Behavior: + After entering game mode, the graph on the entity should print an expected message to the console + + Test Steps: + 1) Create test level + 2) Create test entity + 3) Start Tracer + 4) Enter Game Mode + 5) Read for line + 6) Exit Game Mode + + Note: + - This test file must be called from the Open 3D Engine Editor command terminal + - Any passed and failed tests are written to the Editor.log file. + Parsing the file or running a log_monitor are required to observe the test results. + + :return: None + """ + import os + from editor_entity_utils import EditorEntity as Entity + from utils import Report + from utils import TestHelper as helper + from utils import Tracer + + import azlmbr.legacy.general as general + import azlmbr.asset as asset + import azlmbr.math as math + import azlmbr.bus as bus + + LEVEL_NAME = "tmp_level" + WAIT_TIME = 3.0 # SECONDS + EXPECTED_LINES = ["T92569006_ScriptEvent_Sent", "T92569006_ScriptEvent_Received"] + SC_ASSET_PATH = os.path.join("ScriptCanvas", "T92569006_ScriptCanvas.scriptcanvas") + + def create_editor_entity(name, sc_asset): + entity = Entity.create_editor_entity(name) + sc_comp = entity.add_component("Script Canvas") + asset_id = asset.AssetCatalogRequestBus(bus.Broadcast, "GetAssetIdByPath", sc_asset, math.Uuid(), False) + sc_comp.set_component_property_value("Script Canvas Asset|Script Canvas Asset", asset_id) + Report.critical_result(Tests.entity_created, entity.id.isValid()) + + def locate_expected_lines(line_list: list): + found_lines = [printInfo.message.strip() for printInfo in section_tracer.prints] + + return all(line in found_lines for line in line_list) + + # 1) Create temp level + general.idle_enable(True) + result = general.create_level_no_prompt(LEVEL_NAME, 128, 1, 512, True) + Report.critical_result(Tests.level_created, result == 0) + helper.wait_for_condition(lambda: general.get_current_level_name() == LEVEL_NAME, WAIT_TIME) + general.close_pane("Error Report") + + # 2) Create test entity + create_editor_entity("TestEntity", SC_ASSET_PATH) + + # 3) Start Tracer + with Tracer() as section_tracer: + + # 4) Enter Game Mode + helper.enter_game_mode(Tests.enter_game_mode) + + # 5) Read for line + lines_located = helper.wait_for_condition(lambda: locate_expected_lines(EXPECTED_LINES), WAIT_TIME) + Report.result(Tests.lines_found, lines_located) + + # 6) Exit Game Mode + helper.exit_game_mode(Tests.exit_game_mode) + + +if __name__ == "__main__": + import ImportPathHelper as imports + + imports.init() + + from utils import Report + + Report.start_test(ScriptEvents_ReturnSetType_Successfully) diff --git a/AutomatedTesting/Gem/PythonTests/scripting/ScriptEvents_SendReceiveAcrossMultiple.py b/AutomatedTesting/Gem/PythonTests/scripting/ScriptEvents_SendReceiveAcrossMultiple.py index d671229cdf..a2913d3468 100644 --- a/AutomatedTesting/Gem/PythonTests/scripting/ScriptEvents_SendReceiveAcrossMultiple.py +++ b/AutomatedTesting/Gem/PythonTests/scripting/ScriptEvents_SendReceiveAcrossMultiple.py @@ -10,7 +10,6 @@ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. Test case ID: T92567321 Test Case Title: Script Events: Can send and receive a script event across multiple entities successfully -URL of the test case: https://testrail.agscollab.com/index.php?/tests/view/92567321 """ diff --git a/AutomatedTesting/Gem/PythonTests/scripting/ScriptEvents_SendReceiveSuccessfully.py b/AutomatedTesting/Gem/PythonTests/scripting/ScriptEvents_SendReceiveSuccessfully.py index b5e26d14ae..388e2bb7c0 100644 --- a/AutomatedTesting/Gem/PythonTests/scripting/ScriptEvents_SendReceiveSuccessfully.py +++ b/AutomatedTesting/Gem/PythonTests/scripting/ScriptEvents_SendReceiveSuccessfully.py @@ -10,7 +10,6 @@ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. Test case ID: T92567320 Test Case Title: Script Events: Can send and receive a script event successfully -URL of the test case: https://testrail.agscollab.com/index.php?/tests/view/92567320 """ diff --git a/AutomatedTesting/Gem/PythonTests/scripting/TestSuite_Active.py b/AutomatedTesting/Gem/PythonTests/scripting/TestSuite_Active.py index d87f2986bf..dda75f0a0c 100755 --- a/AutomatedTesting/Gem/PythonTests/scripting/TestSuite_Active.py +++ b/AutomatedTesting/Gem/PythonTests/scripting/TestSuite_Active.py @@ -183,6 +183,27 @@ class TestAutomation(TestAutomationBase): from . import ScriptEvents_SendReceiveSuccessfully as test_module self._run_test(request, workspace, editor, test_module) + @pytest.mark.parametrize("level", ["tmp_level"]) + def test_ScriptEvents_ReturnSetType_Successfully(self, request, workspace, editor, launcher_platform, project, level): + def teardown(): + file_system.delete([os.path.join(workspace.paths.project(), "Levels", level)], True, True) + request.addfinalizer(teardown) + file_system.delete([os.path.join(workspace.paths.project(), "Levels", level)], True, True) + from . import ScriptEvents_ReturnSetType_Successfully as test_module + self._run_test(request, workspace, editor, test_module) + + 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) + + def test_VariableManager_UnpinVariableType_Works(self, request, workspace, editor, launcher_platform): + from . import VariableManager_UnpinVariableType_Works 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 @@ -251,4 +272,4 @@ class TestScriptCanvasTests(object): expected_lines, auto_test_mode=False, timeout=60, - ) \ No newline at end of file + ) diff --git a/AutomatedTesting/Gem/PythonTests/scripting/Toggle_ScriptCanvasTools.py b/AutomatedTesting/Gem/PythonTests/scripting/Toggle_ScriptCanvasTools.py index 4024e28277..42cc42de0d 100644 --- a/AutomatedTesting/Gem/PythonTests/scripting/Toggle_ScriptCanvasTools.py +++ b/AutomatedTesting/Gem/PythonTests/scripting/Toggle_ScriptCanvasTools.py @@ -13,11 +13,6 @@ Test Case Title: Tools > Node Palette toggles the Node Palette Tools > Node Inspector toggles the Node Inspector Tools > Bookmarks toggles the Bookmarks Tools > Variable Manager toggles the Variable Manager - -URLs of the test case: https://testrail.agscollab.com/index.php?/cases/view/92569165 - https://testrail.agscollab.com/index.php?/cases/view/92569167 - https://testrail.agscollab.com/index.php?/cases/view/92569168 - https://testrail.agscollab.com/index.php?/cases/view/92569170 """ diff --git a/AutomatedTesting/Gem/PythonTests/scripting/UnDockedPane_CloseSCWindow.py b/AutomatedTesting/Gem/PythonTests/scripting/UnDockedPane_CloseSCWindow.py index 875f28ec95..da33a8ab80 100644 --- a/AutomatedTesting/Gem/PythonTests/scripting/UnDockedPane_CloseSCWindow.py +++ b/AutomatedTesting/Gem/PythonTests/scripting/UnDockedPane_CloseSCWindow.py @@ -10,8 +10,6 @@ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. Test case ID: C1702825 // C1702831 Test Case Title: Undocking // Closing script canvas with the pane floating -URLs of the test case: https://testrail.agscollab.com/index.php?/cases/view/1702825 & - https://testrail.agscollab.com/index.php?/cases/view/1702831 """ diff --git a/AutomatedTesting/Gem/PythonTests/scripting/VariableManager_CreateDeleteVars.py b/AutomatedTesting/Gem/PythonTests/scripting/VariableManager_CreateDeleteVars.py index 6facc324d4..8b5c78fa87 100644 --- a/AutomatedTesting/Gem/PythonTests/scripting/VariableManager_CreateDeleteVars.py +++ b/AutomatedTesting/Gem/PythonTests/scripting/VariableManager_CreateDeleteVars.py @@ -10,10 +10,8 @@ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. Test case ID: T92564789 Test Case Title: Each Variable type can be created -URL of the test case: https://testrail.agscollab.com/index.php?/tests/view/92564789 Test case ID: T92568873 Test Case Title: Each Variable type can be deleted -URL of the test case: https://testrail.agscollab.com/index.php?/tests/view/92568873 """ diff --git a/AutomatedTesting/Gem/PythonTests/scripting/VariableManager_UnpinVariableType_Works.py b/AutomatedTesting/Gem/PythonTests/scripting/VariableManager_UnpinVariableType_Works.py new file mode 100644 index 0000000000..7076f60385 --- /dev/null +++ b/AutomatedTesting/Gem/PythonTests/scripting/VariableManager_UnpinVariableType_Works.py @@ -0,0 +1,121 @@ +""" +All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or +its licensors. +For complete copyright and license terms please see the LICENSE at the root of this +distribution (the "License"). All use of this software is governed by the License, +or, if provided, by the license below or the license accompanying this file. Do not +remove or 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(): + variable_manager_opened = ("VariableManager is opened successfully", "Failed to open VariableManager") + variable_pinned = ("Variable is pinned", "Variable is not pinned, But it should be unpinned") + variable_unpinned = ("Variable is unpinned", "Variable is not unpinned, But it should be pinned") + variable_unpinned_after_reopen = ("Variable is unpinned after reopening create variable menu", "Variable is not unpinned after reopening create variable menu") +# fmt: on + + +def VariableManager_UnpinVariableType_Works(): + """ + Summary: + Unpin variable types in create variable menu. + Expected Behavior: + The variable unpinned in create variable menu remains unpinned after reopening create variable menu. + Test Steps: + 1) Open Script Canvas window (Tools > Script Canvas) + 2) Get the SC window object + 3) Open Variable Manager in Script Canvas window + 4) Create new graph + 5) Click on the Create Variable button in the Variable Manager + 6) Unpin Boolean by clicking the "Pin" icon on its left side + 7) Close and Reopen Create Variable menu and make sure Boolean is unpinned after reopening Create Variable menu + 8) Restore default layout and close SC window + Note: + - This test file must be called from the Open 3D Engine Editor command terminal + - Any passed and failed tests are written to the Editor.log file. + Parsing the file or running a log_monitor are required to observe the test results. + :return: None + """ + + from PySide2 import QtWidgets + import azlmbr.legacy.general as general + + import pyside_utils + from utils import TestHelper as helper + from utils import Report + from PySide2.QtCore import Qt + + GENERAL_WAIT = 1.0 # seconds + + def find_pane(window, pane_name): + return window.findChild(QtWidgets.QDockWidget, pane_name) + + def click_menu_option(window, option_text): + action = pyside_utils.find_child_by_pattern(window, {"text": option_text, "type": QtWidgets.QAction}) + action.trigger() + + # 1) Open Script Canvas window (Tools > Script Canvas) + general.idle_enable(True) + general.open_pane("Script Canvas") + helper.wait_for_condition(lambda: general.is_pane_visible("Script Canvas"), 6.0) + + # 2) Get the SC window object + editor_window = pyside_utils.get_editor_main_window() + sc = editor_window.findChild(QtWidgets.QDockWidget, "Script Canvas") + sc_main = sc.findChild(QtWidgets.QMainWindow) + + # 3) Open Variable Manager in Script Canvas window + pane = find_pane(sc, "VariableManager") + if not pane.isVisible(): + click_menu_option(sc, "Variable Manager") + pane = find_pane(sc, "VariableManager") + Report.result(Tests.variable_manager_opened, pane.isVisible()) + + # 4) Create new graph + create_new_graph = pyside_utils.find_child_by_pattern( + sc_main, {"objectName": "action_New_Script", "type": QtWidgets.QAction} + ) + create_new_graph.trigger() + + # 5) Click on the Create Variable button in the Variable Manager + variable_manager = sc_main.findChild(QtWidgets.QDockWidget, "VariableManager") + button = variable_manager.findChild(QtWidgets.QPushButton, "addButton") + button.click() + + # 6) Unpin Boolean by clicking the "Pin" icon on its left side + table_view = variable_manager.findChild(QtWidgets.QTableView, "variablePalette") + model_index = pyside_utils.find_child_by_pattern(table_view, "Boolean") + # Make sure Boolean is pinned + is_boolean = model_index.siblingAtColumn(0) + result = helper.wait_for_condition(lambda: is_boolean.data(Qt.DecorationRole) is not None, GENERAL_WAIT) + Report.result(Tests.variable_pinned, result) + # Unpin Boolean and make sure Boolean is unpinned. + pyside_utils.item_view_index_mouse_click(table_view, is_boolean) + result = helper.wait_for_condition(lambda: is_boolean.data(Qt.DecorationRole) is None, GENERAL_WAIT) + Report.result(Tests.variable_unpinned, result) + + # 7) Close and Reopen Create Variable menu and make sure Boolean is unpinned after reopening Create Variable menu + button.click() + button.click() + model_index = pyside_utils.find_child_by_pattern(table_view, "Boolean") + result = helper.wait_for_condition( + lambda: model_index.siblingAtColumn(0).data(Qt.DecorationRole) is None, GENERAL_WAIT + ) + Report.result(Tests.variable_unpinned_after_reopen, result) + + # 8) Restore default layout and close SC window + click_menu_option(sc, "Restore Default Layout") + general.close_pane("Script Canvas") + + +if __name__ == "__main__": + import ImportPathHelper as imports + + imports.init() + + from utils import Report + + Report.start_test(VariableManager_UnpinVariableType_Works) diff --git a/AutomatedTesting/ScriptCanvas/T92569006_ScriptCanvas.scriptcanvas b/AutomatedTesting/ScriptCanvas/T92569006_ScriptCanvas.scriptcanvas new file mode 100644 index 0000000000..626ee29d96 --- /dev/null +++ b/AutomatedTesting/ScriptCanvas/T92569006_ScriptCanvas.scriptcanvas @@ -0,0 +1,1952 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 @@ - - - - - - - - - - - - + + + + + + + + + + + + + + + + - - - - - - - - - - - - - - - - - + diff --git a/AutomatedTesting/TestAssets/T92569006.scriptevents b/AutomatedTesting/TestAssets/T92569006.scriptevents new file mode 100644 index 0000000000..518b1b5733 --- /dev/null +++ b/AutomatedTesting/TestAssets/T92569006.scriptevents @@ -0,0 +1,126 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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/CMakeLists.txt b/CMakeLists.txt index ae8a7a05f8..2ee08a8d16 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -25,13 +25,37 @@ include(cmake/LySet.cmake) include(cmake/Version.cmake) include(cmake/OutputDirectory.cmake) +# Set the engine_path and engine_json +set(o3de_engine_path ${CMAKE_CURRENT_LIST_DIR}) +set(o3de_engine_json ${o3de_engine_path}/engine.json) + if(NOT PROJECT_NAME) project(O3DE LANGUAGES C CXX VERSION ${LY_VERSION_STRING} ) + + # o3de manifest + include(cmake/o3de_manifest.cmake) endif() +################################################################################ +# Resolve this engines name and restricted path +################################################################################ +o3de_engine_name(${o3de_engine_json} o3de_engine_name) +o3de_restricted_path(${o3de_engine_json} o3de_engine_restricted_path) +message(STATUS "O3DE Engine Name: ${o3de_engine_name}") +message(STATUS "O3DE Engine Path: ${o3de_engine_path}") +if(o3de_engine_restricted_path) + message(STATUS "O3DE Engine Restricted Path: ${o3de_engine_restricted_path}") +endif() + +# add the engines cmake folder to the CMAKE_MODULE_PATH +list(APPEND CMAKE_MODULE_PATH "${o3de_engine_path}/cmake") + +################################################################################ +# Initialize +################################################################################ include(cmake/GeneralSettings.cmake) include(cmake/FileUtil.cmake) include(cmake/PAL.cmake) @@ -60,20 +84,19 @@ include(cmake/Projects.cmake) if(NOT INSTALLED_ENGINE) # Add the rest of the targets add_subdirectory(Code) - add_subdirectory(Gems) else() ly_find_o3de_packages() endif() +# Add external subdirectories listed in the manifest +list(APPEND LY_EXTERNAL_SUBDIRS ${o3de_engine_external_subdirectories}) + set(enabled_platforms ${PAL_PLATFORM_NAME} ${LY_PAL_TOOLS_ENABLED}) -foreach(restricted_platform ${PAL_RESTRICTED_PLATFORMS}) - if(restricted_platform IN_LIST enabled_platforms) - add_subdirectory(restricted/${restricted_platform}) - endif() -endforeach() +# Add any engine restricted platforms as external subdirs +o3de_add_engine_restricted_platform_external_subdirs() if(NOT INSTALLED_ENGINE) add_subdirectory(scripts) 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/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/CREBaseCloud.h b/Code/CryEngine/CryCommon/CREBaseCloud.h deleted file mode 100644 index b7a95d88d4..0000000000 --- a/Code/CryEngine/CryCommon/CREBaseCloud.h +++ /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. - -#ifndef __CREBASECLOUD_H__ -#define __CREBASECLOUD_H__ - -//================================================================================ - -class SCloudParticle -{ -public: - inline SCloudParticle(); - inline SCloudParticle(const Vec3& vPos, float fRadius, const ColorF& baseColor, float fTransparency = 0); - inline SCloudParticle(const Vec3& vPos, float fRadiusX, float fRadiusY, float fRotMin, float fRotMax, Vec2 vUV[]); - inline ~SCloudParticle(); - - float GetRadiusX() const { return m_fSize[0]; } - float GetRadiusY() const { return m_fSize[1]; } - float GetTransparency() const { return m_fTransparency; } - const Vec3& GetPosition() const { return m_vPosition; } - const ColorF& GetBaseColor() const { return m_vBaseColor; } - uint32 GetNumLitColors() const { return m_vLitColors.size(); } - inline const ColorF GetLitColor(unsigned int index) const; - float GetSquareSortDistance() const { return m_fSquareSortDistance; } - - //! Sets the radius of the particle. - void SetRadiusX(float rad) { m_fSize[0] = rad; } - void SetRadiusY(float rad) { m_fSize[1] = rad; } - void SetTransparency(float trans) { m_fTransparency = trans; } - void SetPosition(const Vec3& pos) { m_vPosition = pos; } - void SetBaseColor(const ColorF& col) { m_vBaseColor = col; } - void AddLitColor(const ColorF& col) { m_vLitColors.push_back(col); } - void ClearLitColors() { m_vLitColors.clear(); } - void SetSquareSortDistance(float fSquareDistance) { m_fSquareSortDistance = fSquareDistance; } - - bool operator<(const SCloudParticle& p) const - { - return (m_fSquareSortDistance < p.m_fSquareSortDistance); - } - - bool operator>(const SCloudParticle& p) const - { - return (m_fSquareSortDistance > p.m_fSquareSortDistance); - } - -protected: - float m_fTransparency; - Vec3 m_vPosition; - float m_fSize[2]; - float m_fRotMin; - float m_fRotMax; - ColorF m_vBaseColor; - TArray m_vLitColors; - Vec3 m_vEye; - - // for sorting particles during shading - float m_fSquareSortDistance; -public: - Vec2 m_vUV[2]; -}; - -inline SCloudParticle::SCloudParticle() -{ - m_fSize[0] = 0; - m_fTransparency = 0; - m_vPosition = Vec3(0, 0, 0); - m_vBaseColor = Col_Black; - m_vEye = Vec3(0, 0, 0); - m_fSquareSortDistance = 0; - - m_vLitColors.clear(); -} - -inline SCloudParticle::SCloudParticle(const Vec3& pos, float fRadius, const ColorF& baseColor, float fTransparency) -{ - m_fSize[0] = fRadius; - m_fSize[1] = fRadius; - m_fTransparency = fTransparency; - m_vPosition = pos; - m_vBaseColor = baseColor; - m_vUV[0] = Vec2(0, 0); - m_vUV[1] = Vec2(1, 1); - - m_fRotMin = 0; - m_fRotMax = 0; - m_vEye = Vec3(0, 0, 0); - m_fSquareSortDistance = 0; - - m_vLitColors.clear(); -} - -inline SCloudParticle::SCloudParticle(const Vec3& vPos, float fRadiusX, float fRadiusY, float fRotMin, float fRotMax, Vec2 vUV[2]) -{ - m_fSize[0] = fRadiusX; - m_fSize[1] = fRadiusY; - m_vPosition = vPos; - m_vBaseColor = Col_White; - m_vUV[0] = vUV[0]; - m_vUV[1] = vUV[1]; - m_fRotMin = fRotMin; - m_fRotMax = fRotMax; - - m_fTransparency = 1.0f; - m_vEye = Vec3(0, 0, 0); - m_fSquareSortDistance = 0; - - m_vLitColors.clear(); -} - -inline SCloudParticle::~SCloudParticle() -{ - m_vLitColors.clear(); -} - -inline const ColorF SCloudParticle::GetLitColor(unsigned int index) const -{ - if (index <= m_vLitColors.size()) - { - return m_vLitColors[index]; - } - else - { - return Col_Black; - } -} - -//=========================================================================== -class CREBaseCloud - : public CRendElementBase -{ - friend class CRECloud; - -public: - CREBaseCloud() - : CRendElementBase() - { - mfSetType(eDATA_Cloud); - mfUpdateFlags(FCEF_TRANSFORM); - } - virtual void SetParticles(SCloudParticle* pParticles, int nNumParticles) = 0; - - virtual void GetMemoryUsage(ICrySizer* pSizer) const - { - pSizer->AddObject(this, sizeof(*this)); - } -}; - -#endif // __CREBASECLOUD_H__ diff --git a/Code/CryEngine/CryCommon/CREFogVolume.h b/Code/CryEngine/CryCommon/CREFogVolume.h deleted file mode 100644 index 83a024d15e..0000000000 --- a/Code/CryEngine/CryCommon/CREFogVolume.h +++ /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. -#ifndef _CREFOGVOLUME_ -#define _CREFOGVOLUME_ - -#pragma once - -#include "VertexFormats.h" - - -struct IFogVolumeRenderNode; - - -class CREFogVolume - : public CRendElementBase -{ -public: - CREFogVolume(); - - virtual ~CREFogVolume(); - virtual void mfPrepare(bool bCheckOverflow); - virtual bool mfDraw(CShader* ef, SShaderPass* sfm); - - virtual void GetMemoryUsage(ICrySizer* pSizer) const - { - pSizer->AddObject(this, sizeof(*this)); - } - - Vec3 m_center; - uint32 m_viewerInsideVolume : 1; - uint32 m_affectsThisAreaOnly : 1; - uint32 m_stencilRef : 8; - uint32 m_volumeType : 1; - uint32 m_reserved : 21; - AABB m_localAABB; - Matrix34 m_matWSInv; - float m_globalDensity; - float m_densityOffset; - float m_nearCutoff; - Vec2 m_softEdgesLerp; - ColorF m_fogColor; // color already combined with fHDRDynamic - Vec3 m_heightFallOffDirScaled; - Vec3 m_heightFallOffBasePoint; - Vec3 m_eyePosInWS; - Vec3 m_eyePosInOS; - Vec3 m_rampParams; - Vec3 m_windOffset; - float m_noiseScale; - Vec3 m_noiseFreq; - float m_noiseOffset; - float m_noiseElapsedTime; - Vec3 m_scale; -}; - - -#endif // #ifndef _CREFOGVOLUME_ diff --git a/Code/CryEngine/CryCommon/CREGameEffect.h b/Code/CryEngine/CryCommon/CREGameEffect.h deleted file mode 100644 index 17e68813ed..0000000000 --- a/Code/CryEngine/CryCommon/CREGameEffect.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 _CREGameEffect_ -#define _CREGameEffect_ - -#pragma once - -//================================================================================================== -// Name: IREGameEffect -// Desc: Interface for game effect render elements, designed to be instantiated in game code, and -// called from the CREGameEffect within the engine. This then allows render elements -// to be created in game code as well as in the engine. -// Author: James Chilvers -//================================================================================================== -struct IREGameEffect -{ - virtual ~IREGameEffect(){} - - virtual void mfPrepare(bool bCheckOverflow) = 0; - virtual bool mfDraw(CShader* ef, SShaderPass* sfm, CRenderObject* renderObj) = 0; -};//------------------------------------------------------------------------------------------------ - -//================================================================================================== -// Name: CREGameEffect -// Desc: Render element that uses the IREGameEffect interface for its functionality -// Author: James Chilvers -//================================================================================================== -class CREGameEffect - : public CRendElementBase -{ -public: - - CREGameEffect(); - ~CREGameEffect(); - - // CRendElementBase interface - void mfPrepare(bool bCheckOverflow); - bool mfDraw(CShader* ef, SShaderPass* sfm); - - // CREGameEffect interface - inline void SetPrivateImplementation(IREGameEffect* pImpl) { m_pImpl = pImpl; } - inline IREGameEffect* GetPrivateImplementation() const { return m_pImpl; } - - virtual void GetMemoryUsage(ICrySizer* pSizer) const - { - pSizer->AddObject(this, sizeof(*this)); - } -private: - - IREGameEffect* m_pImpl; // Implementation of of render element -};//------------------------------------------------------------------------------------------------ - -#endif // #ifndef _CREGameEffect_ diff --git a/Code/CryEngine/CryCommon/CREGeomCache.h b/Code/CryEngine/CryCommon/CREGeomCache.h deleted file mode 100644 index 6911b8486e..0000000000 --- a/Code/CryEngine/CryCommon/CREGeomCache.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. - -// Description : Backend part of geometry cache rendering - -#ifndef CRYINCLUDE_CRYCOMMON_CREGEOMCACHE_H -#define CRYINCLUDE_CRYCOMMON_CREGEOMCACHE_H -#pragma once - -#if defined(USE_GEOM_CACHES) - -#include -#include - -class CREGeomCache - : public CRendElementBase -{ -public: - struct SMeshInstance - { - AABB m_aabb; - Matrix34 m_matrix; - Matrix34 m_prevMatrix; - }; - - struct SMeshRenderData - { - DynArray m_instances; - _smart_ptr m_pRenderMesh; - }; - - struct UpdateList - { - CryCriticalSection m_mutex; - AZStd::vector> m_geoms; - }; - -public: - CREGeomCache(); - ~CREGeomCache(); - - bool Update(const int flags, const bool bTesselation); - static void UpdateModified(); - - // CRendElementBase interface - virtual bool mfUpdate(int Flags, bool bTessellation); - virtual void mfPrepare(bool bCheckOverflow); - virtual bool mfDraw(CShader* ef, SShaderPass* sfm); - - // CREGeomCache interface - virtual void InitializeRenderElement(const uint numMeshes, _smart_ptr* pMeshes, uint16 materialId); - virtual void SetupMotionBlur(CRenderObject* pRenderObject, const SRenderingPassInfo& passInfo); - - virtual volatile int* SetAsyncUpdateState(int& threadId); - virtual DynArray* GetMeshFillDataPtr(); - virtual DynArray* GetRenderDataPtr(); - virtual void DisplayFilledBuffer(const int threadId); - - - AZ::Vertex::Format GetVertexFormat() const override; - bool GetGeometryInfo(SGeometryInfo &streams) override; - -private: - uint16 m_materialId; - volatile bool m_bUpdateFrame[2]; - volatile int m_transformUpdateState[2]; - - // We use a double buffered m_meshFillData array for input from the main thread. When data - // was successfully sent from the main thread it gets copied to m_meshRenderData - // This simplifies the cases where frame data is missing, e.g. meshFillData is not updated for a frame - // Note that meshFillData really needs to be double buffered because the copy occurs in render thread - // so the next main thread could already be touching the data again - // - // Note: m_meshRenderData is directly accessed for ray intersections via GetRenderDataPtr. - // This is safe, because it's only used in editor. - DynArray m_meshFillData[2]; - DynArray m_meshRenderData; - - static StaticInstance sm_updateList[2]; // double buffered update lists - - AZ::Vertex::Format m_geomCacheVertexFormat; -}; - -#endif -#endif // CRYINCLUDE_CRYCOMMON_CREGEOMCACHE_H diff --git a/Code/CryEngine/CryCommon/CREImposter.h b/Code/CryEngine/CryCommon/CREImposter.h deleted file mode 100644 index 1150212b7d..0000000000 --- a/Code/CryEngine/CryCommon/CREImposter.h +++ /dev/null @@ -1,194 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#pragma once - -#include -#include "Cry_Camera.h" - -//================================================================================ - -struct SDynTexture2; -struct SDynTexture; -class IDynTexture; -class CameraViewParameters; - -struct IImposterRenderElement -{ - virtual void GetMemoryUsage(ICrySizer* pSizer) const = 0; - virtual void mfPrepare(bool bCheckOverflow) = 0; - virtual bool mfDraw(CShader* ef, SShaderPass* sl) = 0; - virtual const SMinMaxBox& mfGetWorldSpaceBounds() = 0; - - virtual bool IsSplit() = 0; - virtual bool IsScreenImposter() = 0; - - virtual float GetRadiusX() = 0; - virtual float GetRadiusY() = 0; - virtual Vec3* GetQuadCorners() = 0; - virtual Vec3 GetNearPoint() = 0; - virtual Vec3 GetFarPoint() = 0; - virtual float GetErrorToleranceCosAngle() = 0; - virtual uint32 GetState() = 0; - virtual int GetAlphaRef() = 0; - virtual ColorF GetColorHelper() = 0; - virtual Vec3 GetLastSunDirection() = 0; - virtual uint8 GetLastBestEdge() = 0; - virtual float GetNear() = 0; - virtual float GetFar() = 0; - virtual float GetTransparency() = 0; - virtual Vec3 GetPosition(); - virtual int GetLogResolutionX() = 0; - virtual int GetLogResolutionY() = 0; - virtual CameraViewParameters& GetLastViewParameters() = 0; - virtual IDynTexture* GetTexture() = 0; - virtual IDynTexture* GetScreenTexture() = 0; - virtual IDynTexture* GetFrontTexture() = 0; - virtual IDynTexture* GetDepthTexture() = 0; - virtual const SMinMaxBox& GetWorldSpaceBounds() = 0; - - virtual void SetBBox(const Vec3& min, const Vec3& max) = 0; - virtual void SetScreenImposterState(bool state) = 0; - virtual void SetState(uint32 state) = 0; - virtual void SetAlphaRef(uint32 ref) = 0; - virtual void SetPosition(Vec3 pos) = 0; - virtual void SetFrameResetValue(int frameResetValue) = 0; - virtual void SetTexture(IDynTexture* texture) = 0; - virtual void SetScreenTexture(IDynTexture* texture) = 0; - virtual void SetFrontTexture(IDynTexture* texture) = 0; - virtual void SetDepthTexture(IDynTexture* texture) = 0; -}; - -class CREImposter - : public CRendElementBase -{ - friend class CRECloud; - static IDynTexture* m_pScreenTexture; - - CameraViewParameters m_LastViewParameters; - bool m_bScreenImposter; - bool m_bSplit; - float m_fRadiusX; - float m_fRadiusY; - Vec3 m_vQuadCorners[4]; // in world space, relative to m_vPos, in clockwise order, can be rotated - Vec3 m_vNearPoint; - Vec3 m_vFarPoint; - int m_nLogResolutionX; - int m_nLogResolutionY; - IDynTexture* m_pTexture; - IDynTexture* m_pFrontTexture; - IDynTexture* m_pTextureDepth; - float m_fErrorToleranceCosAngle; // cosine of m_fErrorToleranceAngle used to check if IsImposterValid - SMinMaxBox m_WorldSpaceBV; - uint32 m_State; - int m_AlphaRef; - float m_fCurTransparency; - ColorF m_ColorHelper; - Vec3 m_vPos; - Vec3 m_vLastSunDir; - uint8 m_nLastBestEdge; // 0..11 this edge is favored to not jitter between different edges - float m_fNear; - float m_fFar; - - bool IsImposterValid(const CameraViewParameters& viewParameters, float fRadiusX, float fRadiusY, float fCamRadiusX, float fCamRadiusY, - const int iRequiredLogResX, const int iRequiredLogResY, const uint32 dwBestEdge); - - bool Display(bool bDisplayFrontOfSplit); - -public: - int m_nFrameReset; - int m_FrameUpdate; - float m_fTimeUpdate; - - static int m_MemUpdated; - static int m_MemPostponed; - static int m_PrevMemUpdated; - static int m_PrevMemPostponed; - - CREImposter() - : CRendElementBase() - , m_pTexture(NULL) - , m_pFrontTexture(NULL) - , m_pTextureDepth(NULL) - , m_bSplit(false) - , m_fRadiusX(0) - , m_fRadiusY(0) - , m_fErrorToleranceCosAngle(cos(DEG2RAD(0.25f))) - , m_bScreenImposter(false) - , m_State(GS_DEPTHWRITE) - , m_AlphaRef(-1) - , m_fCurTransparency(1.0f) - , m_FrameUpdate(0) - , m_nFrameReset(0) - , m_fTimeUpdate(0) - , m_vLastSunDir(0, 0, 0) - , m_nLogResolutionX(0) - , m_nLogResolutionY(0) - , m_nLastBestEdge(0) - { - mfSetType(eDATA_Imposter); - mfUpdateFlags(FCEF_TRANSFORM); - m_ColorHelper = Col_White; - } - virtual ~CREImposter() - { - ReleaseResources(); - } - - bool UpdateImposter(); - void ReleaseResources(); - - bool PrepareForUpdate(); - - virtual void GetMemoryUsage(ICrySizer* pSizer) const - { - pSizer->AddObject(this, sizeof(*this)); - } - virtual void mfPrepare(bool bCheckOverflow); - virtual bool mfDraw(CShader* ef, SShaderPass* sl); - const SMinMaxBox& mfGetWorldSpaceBounds() { return m_WorldSpaceBV; } - - virtual bool IsSplit() { return m_bSplit; } - virtual bool IsScreenImposter() { return m_bScreenImposter; } - - virtual float GetRadiusX() { return m_fRadiusX; } - virtual float GetRadiusY() { return m_fRadiusY; } - virtual Vec3* GetQuadCorners() { return &m_vQuadCorners[0]; } - virtual Vec3 GetNearPoint() { return m_vNearPoint; } - virtual Vec3 GetFarPoint() { return m_vFarPoint; } - virtual float GetErrorToleranceCosAngle() { return m_fErrorToleranceCosAngle; } - virtual uint32 GetState() { return m_State; } - virtual int GetAlphaRef() { return m_AlphaRef; } - virtual ColorF GetColorHelper() { return m_ColorHelper; } - virtual Vec3 GetLastSunDirection() { return m_vLastSunDir; } - virtual uint8 GetLastBestEdge() { return m_nLastBestEdge; } - virtual float GetNear() { return m_fNear; } - virtual float GetFar() { return m_fFar; } - virtual float GetTransparency() { return m_fCurTransparency; } - virtual Vec3 GetPosition(); - virtual int GetLogResolutionX() { return m_nLogResolutionX; } - virtual int GetLogResolutionY() { return m_nLogResolutionY; } - virtual CameraViewParameters& GetLastViewParameters() { return m_LastViewParameters; } - virtual IDynTexture** GetTexture() { return &m_pTexture; } - virtual IDynTexture** GetScreenTexture() { return &m_pScreenTexture; } - virtual IDynTexture** GetFrontTexture() { return &m_pFrontTexture; } - virtual IDynTexture** GetDepthTexture() { return &m_pTextureDepth; } - virtual const SMinMaxBox& GetWorldSpaceBounds() { return m_WorldSpaceBV; } - virtual int GetFrameReset() { return m_nFrameReset; } - virtual void SetBBox(const Vec3& min, const Vec3& max) { m_WorldSpaceBV.SetMin(min); m_WorldSpaceBV.SetMax(max); } - virtual void SetScreenImposterState(bool state) { m_bScreenImposter = state; } - virtual void SetState(uint32 state) { m_State = state; } - virtual void SetAlphaRef(uint32 ref) { m_AlphaRef = ref; } - virtual void SetPosition(Vec3 pos) { m_vPos = pos; } - virtual void SetFrameResetValue(int frameResetValue) { m_nFrameReset = frameResetValue; } -}; diff --git a/Code/CryEngine/CryCommon/CREMesh.h b/Code/CryEngine/CryCommon/CREMesh.h deleted file mode 100644 index 40df816808..0000000000 --- a/Code/CryEngine/CryCommon/CREMesh.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 __CREMESH_H__ -#define __CREMESH_H__ - -class CREMesh - : public CRendElementBase -{ -public: - - struct CRenderChunk* m_pChunk; - class CRenderMesh* m_pRenderMesh; - - // Copy of Chunk to avoid indirections - int32 m_nFirstIndexId; - int32 m_nNumIndices; - - uint32 m_nFirstVertId; - uint32 m_nNumVerts; - -protected: - CREMesh() - { - mfSetType(eDATA_Mesh); - mfUpdateFlags(FCEF_TRANSFORM); - - m_pChunk = NULL; - m_pRenderMesh = NULL; - m_nFirstIndexId = -1; - m_nNumIndices = -1; - m_nFirstVertId = 0; - m_nNumVerts = 0; - } - - virtual ~CREMesh() - { - } - - // Ideally should be declared and left unimplemented to prevent slicing at compile time - // but this would prevent auto code gen in renderer later on. - // To track potential slicing, uncomment the following (and their equivalent in CREMeshImpl) - //CREMesh(CREMesh&); - //CREMesh& operator=(CREMesh& rhs); -}; - -#endif // __CREMESH_H__ diff --git a/Code/CryEngine/CryCommon/CREOcclusionQuery.h b/Code/CryEngine/CryCommon/CREOcclusionQuery.h deleted file mode 100644 index 9350a74104..0000000000 --- a/Code/CryEngine/CryCommon/CREOcclusionQuery.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 __CREOCCLUSIONQUERY_H__ -#define __CREOCCLUSIONQUERY_H__ - -#define SUPP_HMAP_OCCL -#define SUPP_HWOBJ_OCCL - -//============================================================= - -class CRenderMesh; - -class CREOcclusionQuery - : public CRendElementBase -{ - friend class CRender3D; - bool m_bSucceeded; -public: - - int m_nVisSamples; - int m_nCheckFrame; - int m_nDrawFrame; - Vec3 m_vBoxMin; - Vec3 m_vBoxMax; - - UINT_PTR m_nOcclusionID; // this will carry a pointer LPDIRECT3DQUERY9, so it needs to be 64-bit on Windows 64 - - CRenderMesh* m_pRMBox; - static uint32 m_nQueriesPerFrameCounter; - static uint32 m_nReadResultNowCounter; - static uint32 m_nReadResultTryCounter; - - CREOcclusionQuery() - { - m_nOcclusionID = 0; - - m_nVisSamples = 800 * 600; - m_nCheckFrame = 0; - m_nDrawFrame = 0; - m_vBoxMin = Vec3(0, 0, 0); - m_vBoxMax = Vec3(0, 0, 0); - m_pRMBox = NULL; - - mfSetType(eDATA_OcclusionQuery); - mfUpdateFlags(FCEF_TRANSFORM); - } - - bool RT_ReadResult_Try(uint32 nDefaultNumSamples); - - ILINE bool HasSucceeded() const { return m_bSucceeded; } - - virtual ~CREOcclusionQuery(); - - virtual void mfPrepare(bool bCheckOverflow); - virtual bool mfDraw(CShader* ef, SShaderPass* sfm); - virtual void mfReset(); - virtual bool mfReadResult_Try(uint32 nDefaultNumSamples = 1); - virtual bool mfReadResult_Now(); - - virtual void GetMemoryUsage(ICrySizer* pSizer) const - { - pSizer->AddObject(this, sizeof(*this)); - } -}; - -struct OcclusionTestClient -{ - OcclusionTestClient() - : nLastOccludedMainFrameID(0) - , nLastVisibleMainFrameID(0) - { -#ifdef SUPP_HMAP_OCCL - vLastVisPoint.Set(0, 0, 0); - nTerrainOccLastFrame = 0; -#endif -#ifdef SUPP_HWOBJ_OCCL - bOccluded = true; - pREOcclusionQuery = 0; -#endif - //nInstantTestRequested=0; - } -#ifdef SUPP_HWOBJ_OCCL - ~OcclusionTestClient() - { - if (pREOcclusionQuery) - { - pREOcclusionQuery->Release(false); - } - } -#endif - uint32 nLastVisibleMainFrameID, nLastOccludedMainFrameID; - uint32 nLastShadowCastMainFrameID, nLastNoShadowCastMainFrameID; -#ifdef SUPP_HMAP_OCCL - Vec3 vLastVisPoint; - int nTerrainOccLastFrame; -#endif -#ifdef SUPP_HWOBJ_OCCL - CREOcclusionQuery* pREOcclusionQuery; - uint8 bOccluded; -#endif - //uint8 nInstantTestRequested; -}; - - -#endif // CRYINCLUDE_CRYCOMMON_CREOCCLUSIONQUERY_H diff --git a/Code/CryEngine/CryCommon/CREPostProcess.h b/Code/CryEngine/CryCommon/CREPostProcess.h deleted file mode 100644 index 4803ae2166..0000000000 --- a/Code/CryEngine/CryCommon/CREPostProcess.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_CRYCOMMON_CREPOSTPROCESS_H -#define CRYINCLUDE_CRYCOMMON_CREPOSTPROCESS_H -#pragma once - - -class CREPostProcess - : public CRendElementBase -{ - friend class CD3D9Renderer; - -public: - - CREPostProcess(); - virtual ~CREPostProcess(); - - virtual void mfPrepare(bool bCheckOverflow); - virtual bool mfDraw(CShader* ef, SShaderPass* sfm); - - // Use for setting numeric values, vec4 (colors, position, vectors, wtv), strings - virtual int mfSetParameter(const char* pszParam, float fValue, bool bForceValue = false) const; - virtual int mfSetParameterVec4(const char* pszParam, const Vec4& pValue, bool bForceValue = false) const; - virtual int mfSetParameterString(const char* pszParam, const char* pszArg) const; - - virtual void mfGetParameter(const char* pszParam, float& fValue) const; - virtual void mfGetParameterVec4(const char* pszParam, Vec4& pValue) const; - virtual void mfGetParameterString(const char* pszParam, const char*& pszArg) const; - - virtual int32 mfGetPostEffectID(const char* pPostEffectName) const; - - // Reset all post processing effects - virtual void Reset(bool bOnSpecChange = false); - virtual void mfReset() - { - Reset(); - } - - virtual void GetMemoryUsage(ICrySizer* pSizer) const - { - pSizer->AddObject(this, sizeof(*this)); - } -}; - -#endif // CRYINCLUDE_CRYCOMMON_CREPOSTPROCESS_H diff --git a/Code/CryEngine/CryCommon/CREPrismObject.h b/Code/CryEngine/CryCommon/CREPrismObject.h deleted file mode 100644 index 4ec290f1b9..0000000000 --- a/Code/CryEngine/CryCommon/CREPrismObject.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 _CREPRISMOBJECT_ -#define _CREPRISMOBJECT_ - -#pragma once - -#if !defined(EXCLUDE_DOCUMENTATION_PURPOSE) - -class CREPrismObject - : public CRendElementBase -{ -public: - CREPrismObject(); - - virtual ~CREPrismObject() {} - virtual void mfPrepare(bool bCheckOverflow); - virtual bool mfDraw(CShader* ef, SShaderPass* sfm); - - virtual void GetMemoryUsage(ICrySizer* pSizer) const - { - pSizer->AddObject(this, sizeof(*this)); - } - - Vec3 m_center; -}; - -#endif // EXCLUDE_DOCUMENTATION_PURPOSE - -#endif // _CREPRISMOBJECT_ diff --git a/Code/CryEngine/CryCommon/CRESky.h b/Code/CryEngine/CryCommon/CRESky.h deleted file mode 100644 index 3dfc7d184f..0000000000 --- a/Code/CryEngine/CryCommon/CRESky.h +++ /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. - -#ifndef __CRESKY_H__ -#define __CRESKY_H__ - -//============================================================= - -#include "VertexFormats.h" -#include - -struct SSkyLightRenderParams; - -class CRESky - : public CRendElementBase -{ - friend class CRender3D; - -public: - - float m_fTerrainWaterLevel; - float m_fSkyBoxStretching; - float m_fAlpha; - int m_nSphereListId; - -public: - CRESky(); - virtual ~CRESky(); - virtual void mfPrepare(bool bCheckOverflow); - virtual bool mfDraw(CShader* ef, SShaderPass* sfm); - - virtual void GetMemoryUsage(ICrySizer* pSizer) const - { - pSizer->AddObject(this, sizeof(*this)); - } - - AZ::Vertex::Format GetVertexFormat() const override; - bool GetGeometryInfo(SGeometryInfo& streams) override; - -private: - AZ::Vertex::Format m_skyVertexFormat; -}; - -class CREHDRSky - : public CRendElementBase -{ -public: - CREHDRSky(); - virtual ~CREHDRSky(); - virtual void mfPrepare(bool bCheckOverflow); - virtual bool mfDraw(CShader* ef, SShaderPass* sfm); - - virtual void GetMemoryUsage(ICrySizer* pSizer) const - { - pSizer->AddObject(this, sizeof(*this)); - } - - void GenerateSkyDomeTextures(int32 width, int32 height); - - virtual AZ::Vertex::Format GetVertexFormat() const override; - virtual bool GetGeometryInfo(SGeometryInfo& streams) override; - -public: - const SSkyLightRenderParams* m_pRenderParams; - int m_moonTexId; - class CTexture* m_pSkyDomeTextureMie; - class CTexture* m_pSkyDomeTextureRayleigh; - - static void SetCommonMoonParams(CShader* ef, bool bUseMoon = false); - -private: - void Init(); - -private: - int m_skyDomeTextureLastTimeStamp; - int m_frameReset; - class CStars* m_pStars; - AZ::Vertex::Format m_hdrSkyVertexFormat; -}; - - -#endif // __CRESKY_H__ diff --git a/Code/CryEngine/CryCommon/CREVolumeObject.h b/Code/CryEngine/CryCommon/CREVolumeObject.h deleted file mode 100644 index 2137053a8e..0000000000 --- a/Code/CryEngine/CryCommon/CREVolumeObject.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 _CREVOLUMEOBJECT_ -#define _CREVOLUMEOBJECT_ - -#pragma once - -#include "VertexFormats.h" - - -struct IVolumeObjectRenderNode; - -struct IVolumeTexture -{ -public: - virtual ~IVolumeTexture() {} - virtual void Release() = 0; - virtual bool Create(unsigned int width, unsigned int height, unsigned int depth, unsigned char* pData) = 0; - virtual bool Update(unsigned int width, unsigned int height, unsigned int depth, const unsigned char* pData) = 0; - virtual int GetTexID() const = 0; - virtual uint32 GetWidth() const = 0; - virtual uint32 GetHeight() const = 0; - virtual uint32 GetDepth() const = 0; - virtual ITexture* GetTexture() const = 0; -}; - -class CREVolumeObject - : public CRendElementBase -{ -public: - CREVolumeObject(); - - virtual ~CREVolumeObject(); - virtual void mfPrepare(bool bCheckOverflow); - virtual bool mfDraw(CShader* ef, SShaderPass* sfm); - - virtual IVolumeTexture* CreateVolumeTexture() const; - - virtual void GetMemoryUsage(ICrySizer* pSizer) const - { - pSizer->AddObject(this, sizeof(*this)); - } - - Vec3 m_center; - Matrix34 m_matInv; - Vec3 m_eyePosInWS; - Vec3 m_eyePosInOS; - Plane_tpl m_volumeTraceStartPlane; - AABB m_renderBoundsOS; - bool m_viewerInsideVolume; - bool m_nearPlaneIntersectsVolume; - float m_alpha; - float m_scale; - - IVolumeTexture* m_pDensVol; - IVolumeTexture* m_pShadVol; - _smart_ptr m_pHullMesh; -}; - -#endif // #ifndef _CREVOLUMEOBJECT_ diff --git a/Code/CryEngine/CryCommon/CREWaterOcean.h b/Code/CryEngine/CryCommon/CREWaterOcean.h deleted file mode 100644 index e8ca310d41..0000000000 --- a/Code/CryEngine/CryCommon/CREWaterOcean.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 _CREWATEROCEAN_ -#define _CREWATEROCEAN_ - -class CWater; - -class CREWaterOcean - : public CRendElementBase -{ -public: - CREWaterOcean(); - virtual ~CREWaterOcean(); - - virtual void mfPrepare(bool bCheckOverflow); - virtual bool mfDraw(CShader* ef, SShaderPass* sfm); - virtual void mfGetPlane(Plane_tpl& pl); - - virtual void Create(uint32 nVerticesCount, SVF_P3F_C4B_T2F* pVertices, uint32 nIndicesCount, const void* pIndices, uint32 nIndexSizeof); - void ReleaseOcean(); - - virtual Vec3 GetPositionAt(float x, float y) const; - virtual Vec4* GetDisplaceGrid() const; - - virtual void GetMemoryUsage(ICrySizer* pSizer) const - { - pSizer->AddObject(this, sizeof(*this)); - } -private: - - uint32 m_nVerticesCount; - uint32 m_nIndicesCount; - uint32 m_nIndexSizeof; - - void* m_pVertDecl; - void* m_pVertices; - void* m_pIndices; - -private: - - void UpdateFFT(); - void FrameUpdate(); -}; - - -#endif diff --git a/Code/CryEngine/CryCommon/CREWaterVolume.h b/Code/CryEngine/CryCommon/CREWaterVolume.h deleted file mode 100644 index 89102e3097..0000000000 --- a/Code/CryEngine/CryCommon/CREWaterVolume.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 _CREWATERVOLUME_ -#define _CREWATERVOLUME_ - -#pragma once - - -#include "VertexFormats.h" - -class CREWaterVolume - : public CRendElementBase -{ -public: - CREWaterVolume(); - - virtual ~CREWaterVolume(); - virtual void mfPrepare(bool bCheckOverflow); - virtual bool mfDraw(CShader* ef, SShaderPass* sfm); - virtual void mfGetPlane(Plane_tpl& pl); - virtual void mfCenter(Vec3& vCenter, CRenderObject* pObj); - - virtual void GetMemoryUsage(ICrySizer* pSizer) const - { - pSizer->AddObject(this, sizeof(*this)); - } - -public: - struct SParams - { - SParams() - : m_pVertices(0) - , m_pIndices(0) - , m_numVertices(0) - , m_numIndices(0) - , m_center(0, 0, 0) - , m_WSBBox(Vec3(-1, -1, -1), Vec3(1, 1, 1)) - , m_fogPlane(Vec3(0, 0, 1), 0) - , m_fogDensity(0.1f) - , m_fogColor(0.2f, 0.5f, 0.7f) - , m_fogColorAffectedBySun(true) - , m_fogShadowing(0.5f) - , m_caustics(true) - , m_causticIntensity(1.0f) - , m_causticTiling(1.0f) - , m_causticHeight(0.9f) - , m_viewerInsideVolume(false) - , m_viewerCloseToWaterPlane(false) - , m_viewerCloseToWaterVolume(false) - { - } - - const SVF_P3F_C4B_T2F* m_pVertices; - const uint16* m_pIndices; - - size_t m_numVertices; - size_t m_numIndices; - - Vec3 m_center; - AABB m_WSBBox; - - Plane_tpl m_fogPlane; - float m_fogDensity; - Vec3 m_fogColor; - bool m_fogColorAffectedBySun; - float m_fogShadowing; - - bool m_caustics; - float m_causticIntensity; - float m_causticTiling; - float m_causticHeight; - - bool m_viewerInsideVolume; - bool m_viewerCloseToWaterPlane; - bool m_viewerCloseToWaterVolume; - }; - - struct SOceanParams - { - SOceanParams() - : m_fogColor(0.2f, 0.5f, 0.7f) - , m_fogColorShallow(0.2f, 0.5f, 0.7f) - , m_fogDensity(0.2f) - { - } - - Vec3 m_fogColor; - Vec3 m_fogColorShallow; - float m_fogDensity; - }; - -public: - const SParams* m_pParams; - const SOceanParams* m_pOceanParams; - bool m_drawWaterSurface; - bool m_drawFastPath; -}; - - -#endif // #ifndef _CREWATERVOLUME_ 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 8cf49e1a5d..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) { @@ -45,43 +45,6 @@ void CryAssertTrace(const char* szFormat, ...) } } } -/* -bool CryAssert(const char* szCondition, const char* szFile,unsigned int line, bool *pIgnore) -{ - if (!gEnv) return false; - - gEnv->pSystem->OnAssert(szCondition, gs_szMessage, szFile, line); - - if (!gEnv->bNoAssertDialog && !gEnv->bIgnoreAllAsserts) - { - EDialogAction action = MacOSXHandleAssert(szCondition, szFile, line, gs_szMessage, gEnv->pRenderer != NULL); - - switch (action) { - case eDAStop: - raise(SIGABRT); - exit(-1); - case eDABreak: - return true; - case eDAIgnoreAll: - gEnv->bIgnoreAllAsserts = true; - break; - case eDAIgnore: - *pIgnore = true; - break; - case eDAReportAsBug: - if ( gEnv && gEnv->pSystem) - { - gEnv->pSystem->ReportBug("Assert: %s - %s", szCondition,gs_szMessage); - } - - case eDAContinue: - default: - break; - } - } - - return false; -}*/ bool CryAssert(const char* szCondition, const char* szFile, unsigned int line, bool* pIgnore) { 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/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/CryMemoryManager.h b/Code/CryEngine/CryCommon/CryMemoryManager.h index 4547ae70bc..b3f8ba7c8e 100644 --- a/Code/CryEngine/CryCommon/CryMemoryManager.h +++ b/Code/CryEngine/CryCommon/CryMemoryManager.h @@ -116,7 +116,6 @@ namespace CryMemory struct ICustomMemoryHeap; class IGeneralMemoryHeap; class IPageMappingHeap; -class IDefragAllocator; class IMemoryAddressRange; // Description: @@ -180,8 +179,6 @@ struct IMemoryManager virtual IMemoryAddressRange* ReserveAddressRange(size_t capacity, const char* sName) = 0; virtual IPageMappingHeap* CreatePageMappingHeap(size_t addressSpace, const char* sName) = 0; - - virtual IDefragAllocator* CreateDefragAllocator() = 0; }; // Global function implemented in CryMemoryManager_impl.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/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/Cry_Camera.h b/Code/CryEngine/CryCommon/Cry_Camera.h index 56a764d897..d0eb318e94 100644 --- a/Code/CryEngine/CryCommon/Cry_Camera.h +++ b/Code/CryEngine/CryCommon/Cry_Camera.h @@ -620,24 +620,24 @@ public: bool IsPointVisible(const Vec3& p) const; //sphere-frustum test - bool IsSphereVisible_F(const Sphere& s) const; - uint8 IsSphereVisible_FH(const Sphere& s) const; //this is going to be the exact version of sphere-culling + bool IsSphereVisible_F(const ::Sphere& s) const; + uint8 IsSphereVisible_FH(const ::Sphere& s) const; //this is going to be the exact version of sphere-culling // AABB-frustum test // Fast - bool IsAABBVisible_F(const AABB& aabb) const; - uint8 IsAABBVisible_FH(const AABB& aabb, bool* pAllInside) const; - uint8 IsAABBVisible_FH(const AABB& aabb) const; + bool IsAABBVisible_F(const ::AABB& aabb) const; + uint8 IsAABBVisible_FH(const ::AABB& aabb, bool* pAllInside) const; + uint8 IsAABBVisible_FH(const ::AABB& aabb) const; // Exact - bool IsAABBVisible_E(const AABB& aabb) const; - uint8 IsAABBVisible_EH(const AABB& aabb, bool* pAllInside) const; - uint8 IsAABBVisible_EH(const AABB& aabb) const; + bool IsAABBVisible_E(const ::AABB& aabb) const; + uint8 IsAABBVisible_EH(const ::AABB& aabb, bool* pAllInside) const; + uint8 IsAABBVisible_EH(const ::AABB& aabb) const; // Multi-camera - bool IsAABBVisible_EHM(const AABB& aabb, bool* pAllInside) const; - bool IsAABBVisible_EM(const AABB& aabb) const; - bool IsAABBVisible_FM(const AABB& aabb) const; + bool IsAABBVisible_EHM(const ::AABB& aabb, bool* pAllInside) const; + bool IsAABBVisible_EM(const ::AABB& aabb) const; + bool IsAABBVisible_FM(const ::AABB& aabb) const; //OBB-frustum test bool IsOBBVisible_F(const Vec3& wpos, const OBB& obb) const; @@ -1386,7 +1386,7 @@ inline bool CCamera::IsPointVisible(const Vec3& p) const // return values // CULL_EXCLUSION = sphere outside of frustum (very fast rejection-test) // CULL_INTERSECT = sphere and frustum intersects or sphere in completely inside frustum -inline bool CCamera::IsSphereVisible_F(const Sphere& s) const +inline bool CCamera::IsSphereVisible_F(const ::Sphere& s) const { if ((m_fp[0] | s.center) > s.radius) { @@ -1427,7 +1427,7 @@ inline bool CCamera::IsSphereVisible_F(const Sphere& s) const // CULL_EXCLUSION = sphere outside of frustum (very fast rejection-test) // CULL_INTERSECT = sphere intersects the borders of the frustum, further checks necessary // CULL_INCLUSION = sphere is complete inside the frustum, no further checks necessary -inline uint8 CCamera::IsSphereVisible_FH(const Sphere& s) const +inline uint8 CCamera::IsSphereVisible_FH(const ::Sphere& s) const { f32 nc, rc, lc, tc, bc, cc; if ((nc = m_fp[0] | s.center) > s.radius) diff --git a/Code/CryEngine/CryCommon/Cry_Geo.h b/Code/CryEngine/CryCommon/Cry_Geo.h index ebe27a469a..359896157c 100644 --- a/Code/CryEngine/CryCommon/Cry_Geo.h +++ b/Code/CryEngine/CryCommon/Cry_Geo.h @@ -794,7 +794,7 @@ struct HWVSphere radius = r; } - ILINE HWVSphere(const Sphere& sp) + ILINE HWVSphere(const ::Sphere& sp) { center = HWVLoadVecUnaligned(&sp.center); radius = SIMDFLoadFloat(sp.radius); diff --git a/Code/CryEngine/CryCommon/Cry_GeoDistance.h b/Code/CryEngine/CryCommon/Cry_GeoDistance.h index 47794c7671..2329038dc4 100644 --- a/Code/CryEngine/CryCommon/Cry_GeoDistance.h +++ b/Code/CryEngine/CryCommon/Cry_GeoDistance.h @@ -1179,7 +1179,7 @@ namespace Distance { // float result = Distance::Point_TriangleSq( pos, triangle ); //---------------------------------------------------------------------------------- template - ILINE F Sphere_TriangleSq(const Sphere& s, const Triangle_tpl& t) + ILINE F Sphere_TriangleSq(const ::Sphere& s, const Triangle_tpl& t) { F sqdistance = Distance::Point_TriangleSq(s.center, t) - (s.radius * s.radius); if (sqdistance < 0) @@ -1190,7 +1190,7 @@ namespace Distance { } template - ILINE F Sphere_TriangleSq(const Sphere& s, const Triangle_tpl& t, Vec3_tpl& output) + ILINE F Sphere_TriangleSq(const ::Sphere& s, const Triangle_tpl& t, Vec3_tpl& output) { F sqdistance = Distance::Point_TriangleSq(s.center, t, output) - (s.radius * s.radius); if (sqdistance < 0) diff --git a/Code/CryEngine/CryCommon/Cry_GeoIntersect.h b/Code/CryEngine/CryCommon/Cry_GeoIntersect.h index 89f6d8ebaf..f0be567ce2 100644 --- a/Code/CryEngine/CryCommon/Cry_GeoIntersect.h +++ b/Code/CryEngine/CryCommon/Cry_GeoIntersect.h @@ -792,7 +792,7 @@ namespace Intersect { //--- 0x03 = two intersection, lineseg has ENTRY and EXIT point -- //---------------------------------------------------------------------------------- - inline unsigned char Line_Sphere(const Line& line, const Sphere& s, Vec3& i0, Vec3& i1) + inline unsigned char Line_Sphere(const Line& line, const ::Sphere& s, Vec3& i0, Vec3& i1) { Vec3 end = line.pointonline + line.direction; @@ -830,7 +830,7 @@ namespace Intersect { //--- 0x03 = two intersection, lineseg has ENTRY and EXIT point -- //---------------------------------------------------------------------------------- - inline unsigned char Ray_Sphere(const Ray& ray, const Sphere& s, Vec3& i0, Vec3& i1) + inline unsigned char Ray_Sphere(const Ray& ray, const ::Sphere& s, Vec3& i0, Vec3& i1) { Vec3 end = ray.origin + ray.direction; float a = ray.direction | ray.direction; @@ -863,7 +863,7 @@ namespace Intersect { return intersection; } - inline bool Ray_SphereFirst(const Ray& ray, const Sphere& s, Vec3& intPoint) + inline bool Ray_SphereFirst(const Ray& ray, const ::Sphere& s, Vec3& intPoint) { Vec3 p2; unsigned char res = Ray_Sphere(ray, s, intPoint, p2); @@ -886,7 +886,7 @@ namespace Intersect { //--- 0x02 = one intersection, lineseg has just an EXIT point but no ENTRY point (ls.start is inside the sphere) -- //--- 0x03 = two intersection, lineseg has ENTRY and EXIT point -- //---------------------------------------------------------------------------------- - inline unsigned char Lineseg_Sphere(const Lineseg& ls, const Sphere& s, Vec3& i0, Vec3& i1) + inline unsigned char Lineseg_Sphere(const Lineseg& ls, const ::Sphere& s, Vec3& i0, Vec3& i1) { Vec3 dir = (ls.end - ls.start); @@ -931,7 +931,7 @@ namespace Intersect { } - inline bool Lineseg_SphereFirst(const Lineseg& lineseg, const Sphere& s, Vec3& intPoint) + inline bool Lineseg_SphereFirst(const Lineseg& lineseg, const ::Sphere& s, Vec3& intPoint) { Vec3 p2; uint8 res = Lineseg_Sphere(lineseg, s, intPoint, p2); diff --git a/Code/CryEngine/CryCommon/Cry_GeoOverlap.h b/Code/CryEngine/CryCommon/Cry_GeoOverlap.h index ab560b7518..14af81258a 100644 --- a/Code/CryEngine/CryCommon/Cry_GeoOverlap.h +++ b/Code/CryEngine/CryCommon/Cry_GeoOverlap.h @@ -103,7 +103,7 @@ namespace Overlap { // Checks if a point is inside a sphere. // Example: // bool result=Overlap::Point_Sphere( point, sphere ); - ILINE bool Point_Sphere(const Vec3& p, const Sphere& s) + ILINE bool Point_Sphere(const Vec3& p, const ::Sphere& s) { Vec3 distc = p - s.center; f32 sqrad = s.radius * s.radius; @@ -407,7 +407,7 @@ namespace Overlap { //! check if a Lineseg and a Sphere overlap - inline bool Lineseg_Sphere(const Lineseg& ls, const Sphere& s) + inline bool Lineseg_Sphere(const Lineseg& ls, const ::Sphere& s) { float radius2 = s.radius * s.radius; @@ -729,7 +729,7 @@ namespace Overlap { * 0 = no overlap * 1 = overlap *----------------------------------------------------------------------------------*/ - ILINE bool Sphere_AABB(const Sphere& s, const AABB& aabb) + ILINE bool Sphere_AABB(const ::Sphere& s, const AABB& aabb) { Vec3 center(s.center); @@ -746,7 +746,7 @@ namespace Overlap { } // As Sphere_AABB but ignores z parts - ILINE bool Sphere_AABB2D(const Sphere& s, const AABB& aabb) + ILINE bool Sphere_AABB2D(const ::Sphere& s, const AABB& aabb) { Vec3 center(s.center); @@ -776,7 +776,7 @@ namespace Overlap { * 0x01 = Sphere and AABB overlap * 0x02 = Sphere in inside AABB */ - ILINE char Sphere_AABB_Inside(const Sphere& s, const AABB& aabb) + ILINE char Sphere_AABB_Inside(const ::Sphere& s, const AABB& aabb) { if (Sphere_AABB(s, aabb)) { @@ -819,7 +819,7 @@ namespace Overlap { //--- 0 = no overlap --------------------------- //--- 1 = overlap ----------------- //---------------------------------------------------------------------------------- - inline bool Sphere_OBB(const Sphere& s, const OBB& obb) + inline bool Sphere_OBB(const ::Sphere& s, const OBB& obb) { //first we transform the sphere-center into the AABB-space of the OBB Vec3 SphereInOBBSpace = s.center * obb.m33; @@ -861,7 +861,7 @@ namespace Overlap { //--- 0 = no overlap --------------------------- //--- 1 = overlap ----------------- //---------------------------------------------------------------------------------- - inline bool Sphere_Sphere(const Sphere& s1, const Sphere& s2) + inline bool Sphere_Sphere(const ::Sphere& s1, const ::Sphere& s2) { Vec3 distc = s1.center - s2.center; f32 sqrad = (s1.radius + s2.radius) * (s1.radius + s2.radius); @@ -884,7 +884,7 @@ namespace Overlap { //--- 1 = overlap ----------------- //---------------------------------------------------------------------------------- template - ILINE bool Sphere_Triangle(const Sphere& s, const Triangle_tpl& t) + ILINE bool Sphere_Triangle(const ::Sphere& s, const Triangle_tpl& t) { //create a "bouding sphere" around triangle for fast rejection test Vec3_tpl middle = (t.v0 + t.v1 + t.v2) * (1 / 3.0f); @@ -899,7 +899,7 @@ namespace Overlap { SqRad0 = (F)fsel(SqRad0 - SqRad2, SqRad0, SqRad2); //first simple rejection-test... - if (Sphere_Sphere(s, Sphere(middle, sqrt_tpl(SqRad0))) == 0) + if (Sphere_Sphere(s, ::Sphere(middle, sqrt_tpl(SqRad0))) == 0) { return 0; //overlap not possible } 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/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/ICryMiniGUI.h b/Code/CryEngine/CryCommon/ICryMiniGUI.h deleted file mode 100644 index 95db2e6518..0000000000 --- a/Code/CryEngine/CryCommon/ICryMiniGUI.h +++ /dev/null @@ -1,286 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -// Description : Interface to the Mini GUI subsystem - - -#ifndef CRYINCLUDE_CRYCOMMON_ICRYMINIGUI_H -#define CRYINCLUDE_CRYCOMMON_ICRYMINIGUI_H -#pragma once - - -#include -#include -#include - -namespace minigui -{ - struct IMiniCtrl; - - // Rectangle class - struct Rect - { - float left; - float top; - float right; - float bottom; - - Rect() - : left(0) - , top(0) - , right(0) - , bottom(0) {} - Rect(float l, float t, float r, float b) - : left(l) - , top(t) - , right(r) - , bottom(b) {} - Rect(const Rect& rc) { left = rc.left; top = rc.top; right = rc.right; bottom = rc.bottom; } - bool IsPointInside(float x, float y) const { return x >= left && x <= right && y >= top && y <= bottom; } - float Width() const { return right - left; } - float Height() const { return bottom - top; } - }; - - typedef void(* ClickCallback)(void* data, bool onOff); - typedef void(* RenderCallback)(float x, float y); - - enum EMiniCtrlStatus - { - eCtrl_Hidden = BIT(0), // Control is hidden. - eCtrl_Highlight = BIT(1), // Control is highlight (probably mouse over). - eCtrl_Focus = BIT(2), // Control have focus (from keyboard). - eCtrl_Checked = BIT(3), // Control have checked mark. - eCtrl_NoBorder = BIT(4), // Control have no border. - eCtrl_CheckButton = BIT(5), // Button control behave as a check button. - eCtrl_TextAlignCentre = BIT(6), // Draw text aligned centre - eCtrl_AutoResize = BIT(7), // Auto resize depending on text length - eCtrl_Moveable = BIT(8), // Dynamically reposition ctrl - eCtrl_CloseButton = BIT(9), // Control has close button - }; - enum EMiniCtrlEvent - { - eCtrlEvent_LButtonDown = BIT(0), - eCtrlEvent_LButtonUp = BIT(1), - eCtrlEvent_LButtonPressed = BIT(2), - eCtrlEvent_MouseOver = BIT(3), - eCtrlEvent_MouseOff = BIT(4), - eCtrlEvent_DPadLeft = BIT(5), - eCtrlEvent_DPadRight = BIT(6), - eCtrlEvent_DPadUp = BIT(7), - eCtrlEvent_DPadDown = BIT(8), - }; - - // Types of the supported controls - enum EMiniCtrlType - { - eCtrlType_Unknown = 0, - eCtrlType_Button, - eCtrlType_Menu, - eCtrlType_InfoBox, - eCtrlType_Table, - }; - - struct SMetrics - { - float fTextSize; - float fTitleSize; - - // Colors. - ColorB clrFrameBorder; - ColorB clrFrameBorderHighlight; - ColorB clrFrameBorderOutOfFocus; - ColorB clrChecked; - ColorB clrBackground; - ColorB clrBackgroundHighlight; - ColorB clrBackgroundSelected; - ColorB clrTitle; - ColorB clrText; - ColorB clrTextSelected; - - uint8 outOfFocusAlpha; - }; - - enum ECommand - { - eCommand_ButtonPress, - eCommand_ButtonChecked, - eCommand_ButtonUnchecked, - }; - // Command sent from the control. - struct SCommand - { - ECommand command; - IMiniCtrl* pCtrl; - int nCtrlID; - }; - - ////////////////////////////////////////////////////////////////////////// - // Event listener interface for the MiniGUI - ////////////////////////////////////////////////////////////////////////// - struct IMiniGUIEventListener - { - // - virtual ~IMiniGUIEventListener(){} - virtual void OnCommand(SCommand& cmd) = 0; - // - }; - - // Interface to the GUI - struct IMiniGUI - : public ICryUnknown - { - public: - CRYINTERFACE_DECLARE(IMiniGUI, 0xea09d34268814f2a, 0xaf1034e04b076011); - - // - virtual void Init() = 0; - virtual void Done() = 0; - virtual void Draw() = 0; - virtual void Reset() = 0; - - virtual void SaveState() = 0; - virtual void RestoreState() = 0; - - virtual void SetEnabled(bool status) = 0; - virtual void SetInFocus(bool status) = 0; - virtual bool InFocus() = 0; - - virtual void SetEventListener(IMiniGUIEventListener* pListener) = 0; - - virtual SMetrics& Metrics() = 0; - - // Makes a new control - virtual IMiniCtrl* CreateCtrl(IMiniCtrl* pParentCtrl, int nCtrlID, EMiniCtrlType type, int nCtrlFlags, const Rect& rc, const char* title) = 0; - - // Remove all controls. - virtual void RemoveAllCtrl() = 0; - - virtual void OnCommand(SCommand& cmd) = 0; - - virtual IMiniCtrl* GetCtrlFromPoint(float x, float y) const = 0; - - virtual void SetMovingCtrl(IMiniCtrl* pCtrl) = 0; - // - }; - - DECLARE_SMART_POINTERS(IMiniGUI); - - struct IMiniCtrl - : public _reference_target_t - { - // - virtual void Reset() = 0; - - virtual void SaveState() = 0; - virtual void RestoreState() = 0; - - // For system call only. - virtual void SetGUI(IMiniGUI* pGUI) = 0; - virtual IMiniGUI* GetGUI() const = 0; - - virtual EMiniCtrlType GetType() const = 0; - - virtual int GetId() const = 0; - virtual void SetId(int id) = 0; - - virtual const char* GetTitle() const = 0; - virtual void SetTitle(const char* title) = 0; - - virtual Rect GetRect() const = 0; - virtual void SetRect(const Rect& rc) = 0; - - virtual void SetFlag(uint32 flag) = 0; - virtual void ClearFlag(uint32 flag) = 0; - virtual bool CheckFlag(uint32 flag) const = 0; - - // Sub Controls handling. - virtual void AddSubCtrl(IMiniCtrl* pCtrl) = 0; - virtual void RemoveSubCtrl(IMiniCtrl* pCtrl) = 0; - virtual void RemoveAllSubCtrl() = 0; - virtual int GetSubCtrlCount() const = 0; - virtual IMiniCtrl* GetSubCtrl(int nIndex) const = 0; - virtual IMiniCtrl* GetParent() const = 0; - - // Check if point is inside any of the sub controls. - virtual IMiniCtrl* GetCtrlFromPoint(float x, float y) = 0; - - virtual void OnPaint(class CDrawContext& dc) = 0; - - virtual void SetVisible(bool state) = 0; - - // Events from GUI - virtual void OnEvent([[maybe_unused]] float x, [[maybe_unused]] float y, EMiniCtrlEvent) {}; - - ////////////////////////////////////////////////////////////////////////// - // When set, this control will be enabling/disabling specified cvar - // when button not checked fOffValue will be set on cvar, when checked fOnValue will be set. - virtual bool SetControlCVar(const char* sCVarName, float fOffValue, float fOnValue) = 0; - - virtual bool SetClickCallback(ClickCallback callback, void* pCallbackData) = 0; - - virtual bool SetRenderCallback(RenderCallback callback) = 0; - - virtual bool SetConnectedCtrl(IMiniCtrl* pConnectedCtrl) = 0; - - //resize text box based what text is present - virtual void AutoResize() = 0; - - //Create close 'X' button for control - virtual void CreateCloseButton() = 0; - - //Move control - virtual void Move(float x, float y) = 0; - // - }; - typedef _smart_ptr IMiniCtrlPtr; - - class IMiniGuiCommon - { - public: - // - virtual ~IMiniGuiCommon(){} - virtual bool IsHidden() = 0; - virtual void Hide(bool stat) = 0; - // - }; - - class IMiniTable - : public IMiniGuiCommon - { - public: - // - virtual int AddColumn(const char* name) = 0; - virtual void RemoveColumns() = 0; - virtual int AddData(int columnIndex, ColorB col, const char* format, ...) = 0; - virtual void ClearTable() = 0; - // - }; - - class IMiniInfoBox - : public IMiniGuiCommon - { - public: - // - virtual void SetTextIndent(float x) = 0; - virtual void SetTextSize(float sz) = 0; - virtual void ClearEntries() = 0; - virtual void AddEntry(const char* str, ColorB col, float textSize) = 0; - // - }; -} - - -#define MINIGUI_BEGIN namespace minigui { -#define MINIGUI_END } - -#endif // CRYINCLUDE_CRYCOMMON_ICRYMINIGUI_H diff --git a/Code/CryEngine/CryCommon/IDeferredCollisionEvent.h b/Code/CryEngine/CryCommon/IDeferredCollisionEvent.h deleted file mode 100644 index 2dee198d0a..0000000000 --- a/Code/CryEngine/CryCommon/IDeferredCollisionEvent.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_IDEFERREDCOLLISIONEVENT_H -#define CRYINCLUDE_CRYCOMMON_IDEFERREDCOLLISIONEVENT_H -#pragma once - - -#include - -struct EventPhys; - -// Base class for all deferred physics events -// Basically this class works like a future, -// Start() start the computation(some in the main thread, major part in a task/job) -// Result() will sync the task operation and return the result -struct IDeferredPhysicsEvent - : public IThreadTask -{ - // enum list of all types of deferred events - enum DeferredEventType - { - PhysCallBack_OnCollision - }; - - IDeferredPhysicsEvent(){} - // - virtual ~IDeferredPhysicsEvent(){} - - // == "future" like interface == // - - // start the execution of the event - virtual void Start() = 0; - - // sync the event and do all necessary post-processing, then return the result - virtual int Result(EventPhys* pOrigEvent = 0) = 0; - - // just wait for the event to finish - virtual void Sync() = 0; - - // check if the async computation part has finished - virtual bool HasFinished() = 0; - - // Get the concrete Type of this deferred event - virtual DeferredEventType GetType() const = 0; - - // returns a ptr to the original physics event - virtual EventPhys* PhysicsEvent() = 0; - // -}; - - -// Manager class for deferred physics events -struct IDeferredPhysicsEventManager -{ - // type of create function used to create needed deferred events in the HandleEvent function - typedef IDeferredPhysicsEvent*(* CreateEventFunc)(const EventPhys* pEvent); - - IDeferredPhysicsEventManager(){} - // - virtual ~IDeferredPhysicsEventManager(){} - - // dispatch an deferred event to the task thread - virtual void DispatchDeferredEvent(IDeferredPhysicsEvent* pEvent) = 0; - - // Encapsulates common logic for deferred events, should be called from the physics callbacks - // handles the cvar management as well as deferred event creating - virtual int HandleEvent(const EventPhys* pEvent, IDeferredPhysicsEventManager::CreateEventFunc, IDeferredPhysicsEvent::DeferredEventType) = 0; - - // Register and Unregister Deferred events in the manager to allow - virtual void RegisterDeferredEvent(IDeferredPhysicsEvent* pDeferredEvent) = 0; - virtual void UnRegisterDeferredEvent(IDeferredPhysicsEvent* pDeferredEvent) = 0; - - // Delete all Deferred Events in flight, use only when also clearing the physics event queue - // or else this call results in dangling points, mostly used for save/load - virtual void ClearDeferredEvents() = 0; - - virtual void Update() = 0; - - virtual IDeferredPhysicsEvent* GetLastCollisionEventForEntity(IPhysicalEntity* pPhysEnt) = 0; - // -}; - - -#endif // CRYINCLUDE_CRYCOMMON_IDEFERREDCOLLISIONEVENT_H diff --git a/Code/CryEngine/CryCommon/IDefragAllocator.h b/Code/CryEngine/CryCommon/IDefragAllocator.h deleted file mode 100644 index a415b3af67..0000000000 --- a/Code/CryEngine/CryCommon/IDefragAllocator.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. - -#ifndef CRYINCLUDE_CRYCOMMON_IDEFRAGALLOCATOR_H -#define CRYINCLUDE_CRYCOMMON_IDEFRAGALLOCATOR_H -#pragma once - - -struct IDefragAllocatorStats -{ - size_t nCapacity; - size_t nInUseSize; - uint32 nInUseBlocks; - uint32 nFreeBlocks; - uint32 nPinnedBlocks; - uint32 nMovingBlocks; - uint32 nLargestFreeBlockSize; - uint32 nSmallestFreeBlockSize; - uint32 nMeanFreeBlockSize; - uint32 nCancelledMoveCount; -}; - -struct IDefragAllocatorCopyNotification -{ - IDefragAllocatorCopyNotification() - : bDstIsValid(false) - , bSrcIsUnneeded(false) - , bCancel(false) - { - } - - bool bDstIsValid; - bool bSrcIsUnneeded; - - // Flag to indicate that the copy can't be initiated after all - currently only cancelling before a relocate - // is begun is supported, and the destination region must be stable - bool bCancel; -}; - -class IDefragAllocatorPolicy -{ -public: - enum - { - InvalidUserMoveId = 0xffffffff - }; - -public: - // - virtual uint32 BeginCopy(void* pContext, UINT_PTR dstOffset, UINT_PTR srcOffset, UINT_PTR size, IDefragAllocatorCopyNotification* pNotification) = 0; - virtual void Relocate(uint32 userMoveId, void* pContext, UINT_PTR newOffset, UINT_PTR oldOffset, UINT_PTR size) = 0; - virtual void CancelCopy(uint32 userMoveId, void* pContext, bool bSync) = 0; - - // Perform the copy and relocate immediately - will only be called when UnAppendSegment is - virtual void SyncCopy(void* pContext, UINT_PTR dstOffset, UINT_PTR srcOffset, UINT_PTR size) = 0; - // - -protected: - virtual ~IDefragAllocatorPolicy() {} -}; - -class IDefragAllocator -{ -public: - typedef uint32 Hdl; - enum - { - InvalidHdl = 0, - }; - - struct AllocatePinnedResult - { - Hdl hdl; - UINT_PTR offs; - UINT_PTR usableSize; - }; - - enum EBlockSearchKind - { - eBSK_BestFit, - eBSK_FirstFit - }; - - struct Policy - { - Policy() - : pDefragPolicy(NULL) - , maxAllocs(0) - , maxSegments(1) - , blockSearchKind(eBSK_BestFit) - { - } - - IDefragAllocatorPolicy* pDefragPolicy; - size_t maxAllocs; - size_t maxSegments; - EBlockSearchKind blockSearchKind; - }; - -public: - // - virtual void Release(bool bDiscard = false) = 0; - - virtual void Init(UINT_PTR capacity, UINT_PTR alignment, const Policy& policy = Policy()) = 0; - - virtual bool AppendSegment(UINT_PTR capacity) = 0; - virtual void UnAppendSegment() = 0; - - virtual Hdl Allocate(size_t sz, const char* source, void* pContext = NULL) = 0; - virtual Hdl AllocateAligned(size_t sz, size_t alignment, const char* source, void* pContext = NULL) = 0; - virtual AllocatePinnedResult AllocatePinned(size_t sz, const char* source, void* pContext = NULL) = 0; - virtual bool Free(Hdl hdl) = 0; - - virtual void ChangeContext(Hdl hdl, void* pNewContext) = 0; - - virtual size_t GetAllocated() const = 0; - virtual IDefragAllocatorStats GetStats() = 0; - - virtual void DisplayMemoryUsage(const char* title, unsigned int allocatorDisplayOffset = 0) = 0; - - virtual size_t DefragmentTick(size_t maxMoves, size_t maxAmount, bool bForce = false) = 0; - - virtual UINT_PTR UsableSize(Hdl hdl) = 0; - - // Pin the chunk until the next defrag tick, when it will be automatically unpinned - virtual UINT_PTR WeakPin(Hdl hdl) = 0; - - // Pin the chunk until Unpin is called - virtual UINT_PTR Pin(Hdl hdl) = 0; - - virtual void Unpin(Hdl hdl) = 0; - - virtual const char* GetSourceOf(Hdl hdl) = 0; - // - -#ifndef _RELEASE - virtual void DumpState(const char* filename) = 0; - virtual void RestoreState(const char* filename) = 0; -#endif - -protected: - virtual ~IDefragAllocator() {} -}; - -#endif // CRYINCLUDE_CRYCOMMON_IDEFRAGALLOCATOR_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/IFileChangeMonitor.h b/Code/CryEngine/CryCommon/IFileChangeMonitor.h deleted file mode 100644 index 4ad46852ed..0000000000 --- a/Code/CryEngine/CryCommon/IFileChangeMonitor.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_CRYCOMMON_IFILECHANGEMONITOR_H -#define CRYINCLUDE_CRYCOMMON_IFILECHANGEMONITOR_H -#pragma once - -struct IFileChangeListener -{ - enum EChangeType - { - //! error or unknown change type - eChangeType_Unknown, - //! the file was created - eChangeType_Created, - //! the file was deleted - eChangeType_Deleted, - //! the file was modified (size changed,write) - eChangeType_Modified, - //! this is the old name of a renamed file - eChangeType_RenamedOldName, - //! this is the new name of a renamed file - eChangeType_RenamedNewName - }; - - virtual ~IFileChangeListener() = default; - - virtual void OnFileChange(const char* sFilename, EChangeType eType) = 0; -}; - -struct IFileChangeMonitor -{ - virtual ~IFileChangeMonitor() = default; - - // - // Register the path of a file or directory to monitor - // Path is relative to game directory, e.g. "Libs/WoundSystem/" or "Libs/WoundSystem/HitLocations.xml" - virtual bool RegisterListener(IFileChangeListener* pListener, const char* sMonitorItem) = 0; - // This function can be used to monitor files of specific type, e.g. - // RegisterListener(pListener, "Animations", "caf") - virtual bool RegisterListener(IFileChangeListener* pListener, const char* sFolder, const char* sExtension) = 0; - virtual bool UnregisterListener(IFileChangeListener* pListener) = 0; - // -}; - -#endif // CRYINCLUDE_CRYCOMMON_IFILECHANGEMONITOR_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/IFont.h b/Code/CryEngine/CryCommon/IFont.h index 7d573308aa..7e2a3480b1 100644 --- a/Code/CryEngine/CryCommon/IFont.h +++ b/Code/CryEngine/CryCommon/IFont.h @@ -33,8 +33,6 @@ struct ICryFont; struct IFFont; struct FontFamily; -struct IRenderer; - struct SVF_P2F_C4B_T2F_F4B; extern "C" @@ -100,9 +98,6 @@ struct ICryFont //! \param glyphSizeY Height (in pixels) of the characters to be rendered at in the font texture. virtual void AddCharsToFontTextures(FontFamilyPtr pFontFamily, const char* pChars, int glyphSizeX = defaultGlyphSizeX, int glyphSizeY = defaultGlyphSizeY) = 0; - // Summary: - // Globally sets common font render properties based on the initialized renderer - virtual void SetRendererProperties(IRenderer* pRenderer) = 0; // Summary: // Puts the objects used in this module into the sizer interface virtual void GetMemoryUsage(ICrySizer* pSizer) const = 0; 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/IMemory.h b/Code/CryEngine/CryCommon/IMemory.h index 4a96bae2c0..a3b1dc1c2c 100644 --- a/Code/CryEngine/CryCommon/IMemory.h +++ b/Code/CryEngine/CryCommon/IMemory.h @@ -16,7 +16,6 @@ #pragma once #include -#include // <> required for Interfuscator #include // <> required for Interfuscator #include 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/IOverloadSceneManager.h b/Code/CryEngine/CryCommon/IOverloadSceneManager.h deleted file mode 100644 index 9d391c5701..0000000000 --- a/Code/CryEngine/CryCommon/IOverloadSceneManager.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. - -// Description : IOverloadSceneManager interface declaration. - - -#ifndef CRYINCLUDE_CRYCOMMON_IOVERLOADSCENEMANAGER_H -#define CRYINCLUDE_CRYCOMMON_IOVERLOADSCENEMANAGER_H -#pragma once - -//================================================================================================== -// Name: COverloadSceneManager -// Desc: Manages overload values (eg CPU,GPU etc) -// 1.0="everything is ok" 0.0="very bad frame rate" -// various systems can use this information and control what is currently in the scene -// Author: James Chilvers -//================================================================================================== -struct IOverloadSceneManager -{ -public: - // - virtual ~IOverloadSceneManager() {} - - virtual void Reset() = 0; - virtual void Update() = 0; - - // Override auto-calculated scale to reach targetfps. - // frameScale is clamped to internal min/max values, - // dt is the length of time in seconds to transition - virtual void OverrideScale(float frameScale, float dt) = 0; - - // Go back to auto-calculated scale from an overridden scale - virtual void ResetScale(float dt) = 0; - // -};//------------------------------------------------------------------------------------------------ - -#endif // CRYINCLUDE_CRYCOMMON_IOVERLOADSCENEMANAGER_H diff --git a/Code/CryEngine/CryCommon/IPathfinder.h b/Code/CryEngine/CryCommon/IPathfinder.h index 3e50bb09cb..97e5f7b4f1 100644 --- a/Code/CryEngine/CryCommon/IPathfinder.h +++ b/Code/CryEngine/CryCommon/IPathfinder.h @@ -109,7 +109,7 @@ struct NavigationBlocker , costMultMod(0) , radialDecay(false) {AZ_Assert(false, "Should never get called"); } - Sphere sphere; + ::Sphere sphere; bool radialDecay; bool directional; diff --git a/Code/CryEngine/CryCommon/IPerfHud.h b/Code/CryEngine/CryCommon/IPerfHud.h deleted file mode 100644 index 33104435dc..0000000000 --- a/Code/CryEngine/CryCommon/IPerfHud.h +++ /dev/null @@ -1,145 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS 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 Performance HUD - - -#ifndef CRYINCLUDE_CRYCOMMON_IPERFHUD_H -#define CRYINCLUDE_CRYCOMMON_IPERFHUD_H -#pragma once - - -#include -#include -#include -#include - -struct ICryPerfHUDWidget - : public _reference_target_t -{ - // - enum EWidgetID - { - eWidget_Warnings = 0, - eWidget_RenderStats, - eWidget_StreamingStats, - eWidget_RenderBatchStats, - eWidget_FpsBuckets, - eWidget_Particles, - eWidget_PakFile, - eWidget_Num, //number of widgets - }; - - ICryPerfHUDWidget(int id = -1) - : m_id(id) - {} - - // - virtual ~ICryPerfHUDWidget() {} - - virtual void Reset() = 0; - virtual void Update() = 0; - virtual bool ShouldUpdate() = 0; - virtual void LoadBudgets(XmlNodeRef perfXML) = 0; - virtual void SaveStats(XmlNodeRef statsXML) = 0; - virtual void Enable(int mode) = 0; - virtual void Disable() = 0; - // - - int m_id; -}; - -// Base Interface for all engine module extensions -struct ICryPerfHUD - : public ICryUnknown -{ - CRYINTERFACE_DECLARE(ICryPerfHUD, 0x268d142e043d464c, 0xa0776580f81b988a); - - struct PerfBucket - { - ILINE PerfBucket(float _target) - { - target = _target; - timeAtTarget = 0.f; - } - - float target; - float timeAtTarget; - }; - - enum EHudState - { - eHudOff = 0, - eHudInFocus, - eHudOutOfFocus, - eHudNumStates, - }; - - // - // Called once to initialize HUD. - virtual void Init() = 0; - virtual void Done() = 0; - virtual void Draw() = 0; - virtual void LoadBudgets() = 0; - virtual void SaveStats(const char* filename = NULL) = 0; - virtual void ResetWidgets() = 0; - virtual void SetState(EHudState state) = 0; - virtual void Reset() = 0; - virtual void Destroy() = 0; - - // Retrieve name of the extension module. - virtual void Show(bool bRestoreState) = 0; - - virtual void AddWidget(ICryPerfHUDWidget* pWidget) = 0; - virtual void RemoveWidget(ICryPerfHUDWidget* pWidget) = 0; - - virtual minigui::IMiniCtrl* CreateMenu(const char* name, minigui::IMiniCtrl* pParent = NULL) = 0; - virtual bool CreateCVarMenuItem(minigui::IMiniCtrl* pMenu, const char* name, const char* controlVar, float controlVarOn, float controlVarOff) = 0; - virtual bool CreateCallbackMenuItem(minigui::IMiniCtrl* pMenu, const char* name, minigui::ClickCallback clickCallback, void* pCallbackData) = 0; - virtual minigui::IMiniInfoBox* CreateInfoMenuItem(minigui::IMiniCtrl* pMenu, const char* name, minigui::RenderCallback renderCallback, const minigui::Rect& rect, bool onAtStart = false) = 0; - virtual minigui::IMiniTable* CreateTableMenuItem(minigui::IMiniCtrl* pMenu, const char* name) = 0; - - virtual minigui::IMiniCtrl* GetMenu(const char* name) = 0; - - virtual void EnableWidget(ICryPerfHUDWidget::EWidgetID id, int mode) = 0; - virtual void DisableWidget(ICryPerfHUDWidget::EWidgetID id) = 0; - - //Warnings - Widget Specific interface - virtual void AddWarning(float duration, const char* fmt, va_list argList) = 0; - virtual bool WarningsWindowEnabled() const = 0; - - //FPS - Widget Specific interface - virtual const std::vector* GetFpsBuckets(float& totalTime) const = 0; - // -}; - -DECLARE_SMART_POINTERS(ICryPerfHUD); - -void CryPerfHUDWarning(float duration, const char*, ...) PRINTF_PARAMS(2, 3); -inline void CryPerfHUDWarning(float duration, const char* format, ...) -{ - if (gEnv && gEnv->pSystem) - { - ICryPerfHUD* pPerfHud = gEnv->pSystem->GetPerfHUD(); - - if (pPerfHud) - { - va_list args; - va_start(args, format); - pPerfHud->AddWarning(duration, format, args); - va_end(args); - } - } -} - -#endif // CRYINCLUDE_CRYCOMMON_IPERFHUD_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/IRenderer.h b/Code/CryEngine/CryCommon/IRenderer.h index 71c2500d80..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, @@ -1472,7 +1452,6 @@ struct IRenderer ///////////////////////////////////////////////////////////////////////////////// // Shaders/Shaders management ///////////////////////////////////////////////////////////////////////////////// - virtual void EF_SetShaderMissCallback(ShaderCacheMissCallback callback) = 0; virtual const char* EF_GetShaderMissLogPath() = 0; ///////////////////////////////////////////////////////////////////////////////// @@ -1533,10 +1512,6 @@ struct IRenderer virtual int EF_LoadLightmap (const char* name) = 0; virtual bool EF_RenderEnvironmentCubeHDR (int size, Vec3& Pos, TArray& vecData) = 0; - // Summary: - // Creates new RE (RenderElement) of type (edt). - virtual IRenderElement* EF_CreateRE (EDataType edt) = 0; - // Summary: // Starts using of the shaders (return first index for allow recursions). virtual void EF_StartEf (const SRenderingPassInfo& passInfo) = 0; @@ -1874,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: @@ -2385,26 +2358,6 @@ private: virtual void EF_QueryImpl(ERenderQueryTypes eQuery, void* pInOut0, uint32 nInOutSize0, void* pInOut1, uint32 nInOutSize1) = 0; }; -// util class to change wireframe mode -class CScopedWireFrameMode -{ -public: - CScopedWireFrameMode(IRenderer* pRenderer, int nMode) - : m_pRenderer(pRenderer) - , m_nMode(nMode) - { - (void) m_nMode; // removes not used warning - pRenderer->PushWireframeMode(nMode); - } - ~CScopedWireFrameMode() - { - m_pRenderer->PopWireframeMode(); - } -private: - IRenderer* m_pRenderer; - int m_nMode; -}; - struct SShaderCacheStatistics { size_t m_nTotalLevelShaderCacheMisses; 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/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/IShader.h b/Code/CryEngine/CryCommon/IShader.h index 7fcbdefebb..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; @@ -3413,6 +3377,6 @@ struct SShaderGraphBlock typedef std::vector FXShaderGraphBlocks; typedef FXShaderGraphBlocks::iterator FXShaderGraphBlocksItor; -#include "RendElement.h" +#include #endif // CRYINCLUDE_CRYCOMMON_ISHADER_H 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 96d9a6ad10..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,34 +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 IFileChangeMonitor; -struct IVisualLog; struct ILocalizationManager; -struct ICryFactoryRegistry; -struct ISoftCodeMgr; struct IZLibCompressor; struct IZLibDecompressor; struct ILZ4Decompressor; class IZStdDecompressor; struct IOutputPrintSink; -struct IOverloadSceneManager; -struct IThreadManager; -struct IServiceNetwork; -struct IRemoteCommandManager; struct IWindowMessageHandler; struct IImageHandler; -class IResourceCompilerHelper; -class ILmbrAWS; namespace AZ { @@ -116,12 +99,6 @@ namespace AZ } } -class IResourceCompilerHelper; - -namespace Serialization { - struct IArchiveHost; -} - typedef void* WIN_HWND; class CCamera; @@ -129,40 +106,13 @@ struct CLoadingTimeProfiler; class ICmdLine; -struct INotificationNetwork; -struct ICryPerfHUD; 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: @@ -195,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, @@ -574,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) @@ -622,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). @@ -639,35 +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 bSkipRenderer; // Don't load Renderer 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 bShaderCacheGen; // When running in shadercache gen mode 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: @@ -676,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; @@ -696,34 +566,13 @@ struct SSystemInitParams bPreview = false; bTestMode = false; bDedicatedServer = false; - bExecuteCommandLine = true; - bExecuteCommandLine = true; - bSkipFont = false; - bSkipRenderer = 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; - bShaderCacheGen = false; bUnattendedMode = false; bSkipMovie = false; - bSkipAnimation = false; bToolMode = false; - bSkipPhysics = false; pSystem = NULL; - memset(pProtectedFunctions, 0, sizeof(pProtectedFunctions)); - pCvarsDefault = NULL; - pSharedEnvironment = nullptr; } }; @@ -792,9 +641,6 @@ struct SSystemGlobalEnvironment { AZ::IO::IArchive* pCryPak; AZ::IO::FileIOBase* pFileIO; - IFileChangeMonitor* pFileChangeMonitor; - IProfileLogSystem* pProfileLogSystem; - IOpticsManager* pOpticsManager; ITimer* pTimer; ICryFont* pCryFont; ::IConsole* pConsole; @@ -802,84 +648,27 @@ struct SSystemGlobalEnvironment ILog* pLog; IMovieSystem* pMovieSystem; INameTable* pNameTable; - IVisualLog* pVisualLog; IRenderer* pRenderer; - IMaterialEffects* pMaterialEffects; - ISoftCodeMgr* pSoftCodeMgr; - IOverloadSceneManager* pOverloadSceneManager; - IServiceNetwork* pServiceNetwork; - IRemoteCommandManager* pRemoteCommandManager; 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) @@ -909,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 @@ -953,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; @@ -983,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) { }; }; @@ -1049,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. @@ -1108,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; @@ -1127,14 +844,6 @@ struct ISystem // Gets number of CPUs virtual int GetLogicalCPUCount() = 0; - // Summary: - // Return the rendering driver name. GL or Metal - virtual const char* GetRenderingDriverName() const = 0; - - // Summary: - // Dumps the memory usage statistics to the logging default MB. (can be KB) - virtual void DumpMemoryUsageStatistics(bool bUseKB = false) = 0; - // Summary: // Quits the application. virtual void Quit() = 0; @@ -1145,9 +854,6 @@ struct ISystem // Returns true if the application is in the shutdown phase. virtual bool IsQuitting() const = 0; // Summary: - // Returns true if the application was initialized to generate the shader cache. - virtual bool IsShaderCacheGenMode() const = 0; - // Summary: // Tells the system in which way we are using the serialization system. virtual void SerializingFile(int mode) = 0; virtual int IsSerializingFile() const = 0; @@ -1195,8 +901,6 @@ struct ISystem virtual IZLibDecompressor* GetIZLibDecompressor() = 0; virtual ILZ4Decompressor* GetLZ4Decompressor() = 0; virtual IZStdDecompressor* GetZStdDecompressor() = 0; - virtual ICryPerfHUD* GetPerfHUD() = 0; - virtual INotificationNetwork* GetINotificationNetwork() = 0; virtual IViewSystem* GetIViewSystem() = 0; virtual ILevelSystem* GetILevelSystem() = 0; virtual INameTable* GetINameTable() = 0; @@ -1213,31 +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 IFileChangeMonitor* GetIFileChangeMonitor() = 0; - virtual WIN_HWND GetHWND() = 0; - - virtual IRenderer* GetIRenderer() = 0; virtual ITimer* GetITimer() = 0; - virtual IThreadManager* GetIThreadManager() = 0; - - //irtual 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 SetIFileChangeMonitor(IFileChangeMonitor* pFileChangeMonitor) = 0; - virtual void SetIVisualLog(IVisualLog* pVisualLog) = 0; - - //virtual const char *GetGamePath()=0; virtual void DebugStats(bool checkpoint, bool leaks) = 0; virtual void DumpWinHeaps() = 0; @@ -1252,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; ////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////// @@ -1272,10 +954,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; @@ -1371,16 +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: - // Creates and returns a usable object implementing ICrySizer interface. - virtual ICrySizer* CreateSizer() = 0; - // Summary: // Query if system is now paused. // Pause flag is set when calling system update with pause mode. @@ -1400,10 +1068,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 @@ -1451,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; @@ -1491,11 +1147,6 @@ struct ISystem // returns zeroes if no updates happened yet virtual void GetUpdateStats(SSystemUpdateStats& stats) = 0; - // Description: - // Useful to investigate memory fragmentation. - // Every time you call this from the console: #System.DumpMemoryCoverage() - // it adds a line to "MemoryCoverage.bmp" (generated the first time, there is a max line count). - virtual void DumpMemoryCoverage() = 0; virtual ESystemGlobalState GetSystemGlobalState(void) = 0; virtual void SetSystemGlobalState(ESystemGlobalState systemGlobalState) = 0; @@ -1508,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 @@ -1528,15 +1168,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: @@ -1572,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 @@ -1653,7 +1279,7 @@ typedef ISystem* (*PFNCREATESYSTEMINTERFACE)(SSystemInitParams& initParams); ////////////////////////////////////////////////////////////////////////// // Global environment variable. ////////////////////////////////////////////////////////////////////////// -extern SC_API SSystemGlobalEnvironment* gEnv; +extern SSystemGlobalEnvironment* gEnv; // Summary: @@ -1672,11 +1298,6 @@ inline ISystem* GetISystem() } return systemInterface; }; - -inline ISystemScheduler* GetISystemScheduler(void) -{ - return gEnv->pSystemScheduler; -}; ////////////////////////////////////////////////////////////////////////// // Description: @@ -1699,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/LoadScreenComponent.cpp b/Code/CryEngine/CryCommon/LoadScreenComponent.cpp deleted file mode 100644 index 3059e8a1fc..0000000000 --- a/Code/CryEngine/CryCommon/LoadScreenComponent.cpp +++ /dev/null @@ -1,373 +0,0 @@ -/* - * All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or - * its licensors. - * - * For complete copyright and license terms please see the LICENSE at the root of this - * distribution (the "License"). All use of this software is governed by the License, - * or, if provided, by the license below or the license accompanying this file. Do not - * remove or 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 "LoadScreenComponent.h" -#include - -#if AZ_LOADSCREENCOMPONENT_ENABLED - -namespace -{ - // Due to issues with DLLs sometimes there can be different values of gEnv in different DLLs. - // So we use this preferred method of getting the global environment - SSystemGlobalEnvironment* GetGlobalEnv() - { - if (!GetISystem()) - { - return nullptr; - } - - return GetISystem()->GetGlobalEnvironment(); - } - - static const char* const s_gameFixedFpsCvarName = "game_load_screen_sequence_fixed_fps"; - static const char* const s_gameMaxFpsCvarName = "game_load_screen_max_fps"; - static const char* const s_gameMinimumLoadTimeCvarName = "game_load_screen_minimum_time"; - - static const char* const s_levelFixedFpsCvarName = "level_load_screen_sequence_fixed_fps"; - static const char* const s_levelMaxFpsCvarName = "level_load_screen_max_fps"; - static const char* const s_levelMinimumLoadTimeCvarName = "level_load_screen_minimum_time"; -} - -void LoadScreenComponent::Reflect(AZ::ReflectContext* context) -{ - AZ::SerializeContext* serializeContext = azrtti_cast(context); - - if (serializeContext) - { - serializeContext->Class() - ->Version(1) - ; - - AZ::EditContext* editContext = serializeContext->GetEditContext(); - if (editContext) - { - editContext->Class( - "Load screen manager", "Allows management of a load screen") - ->ClassElement(AZ::Edit::ClassElements::EditorData, "") - ->Attribute(AZ::Edit::Attributes::Category, "Game") - ->Attribute(AZ::Edit::Attributes::AppearsInAddComponentMenu, AZ_CRC("System", 0xc94d118b)) - ; - } - } -} - -void LoadScreenComponent::GetProvidedServices(AZ::ComponentDescriptor::DependencyArrayType& provided) -{ - provided.push_back(AZ_CRC("LoadScreenService", 0x901b031c)); -} - -void LoadScreenComponent::GetIncompatibleServices(AZ::ComponentDescriptor::DependencyArrayType& incompatible) -{ - incompatible.push_back(AZ_CRC("LoadScreenService", 0x901b031c)); -} - -void LoadScreenComponent::Reset() -{ - m_loadScreenState = LoadScreenState::None; - - m_fixedDeltaTimeInSeconds = -1.0f; - m_maxDeltaTimeInSeconds = -1.0f; - m_previousCallTimeForUpdateAndRender = CTimeValue(); - m_processingLoadScreen.store(false); - - // Reset CVars so they're not carried over to other levels - SSystemGlobalEnvironment* pGEnv = GetGlobalEnv(); - if (pGEnv && pGEnv->pConsole) - { - if (ICVar* var = pGEnv->pConsole->GetCVar(s_levelFixedFpsCvarName)) - { - var->Set(""); - } - if (ICVar* var = pGEnv->pConsole->GetCVar(s_levelMaxFpsCvarName)) - { - var->Set(""); - } - if (ICVar* var = pGEnv->pConsole->GetCVar(s_levelMinimumLoadTimeCvarName)) - { - var->Set(""); - } - } -} - -void LoadScreenComponent::LoadConfigSettings(const char* fixedFpsVarName, const char* maxFpsVarName, const char* minimumLoadTimeVarName) -{ - m_fixedDeltaTimeInSeconds = -1.0f; - m_maxDeltaTimeInSeconds = -1.0f; - m_minimumLoadTimeInSeconds = 0.0f; - - SSystemGlobalEnvironment* pGEnv = GetGlobalEnv(); - if (pGEnv && pGEnv->pConsole) - { - ICVar* fixedFpsVar = pGEnv->pConsole->GetCVar(fixedFpsVarName); - if (fixedFpsVar && fixedFpsVar->GetFVal() > 0.0f) - { - m_fixedDeltaTimeInSeconds = (1.0f / fixedFpsVar->GetFVal()); - } - - ICVar* maxFpsVar = pGEnv->pConsole->GetCVar(maxFpsVarName); - if (maxFpsVar && maxFpsVar->GetFVal() > 0.0f) - { - m_maxDeltaTimeInSeconds = (1.0f / maxFpsVar->GetFVal()); - } - - if (ICVar* minimumLoadTimeVar = pGEnv->pConsole->GetCVar(minimumLoadTimeVarName)) - { - // Never allow values below 0 seconds - m_minimumLoadTimeInSeconds = AZStd::max(minimumLoadTimeVar->GetFVal(), 0.0f); - } - } -} - -void LoadScreenComponent::Init() -{ - Reset(); -} - -void LoadScreenComponent::Activate() -{ - CrySystemEventBus::Handler::BusConnect(); - LoadScreenBus::Handler::BusConnect(GetEntityId()); -} - -void LoadScreenComponent::Deactivate() -{ - CrySystemEventBus::Handler::BusDisconnect(); - LoadScreenBus::Handler::BusDisconnect(GetEntityId()); -} - -void LoadScreenComponent::OnCrySystemInitialized(ISystem& system, const SSystemInitParams&) -{ - SSystemGlobalEnvironment* pGEnv = system.GetGlobalEnvironment(); - - // Can't use macros here because we have to use our pointer. - if (pGEnv && pGEnv->pConsole) - { - pGEnv->pConsole->Register("ly_EnableLoadingThread", &m_loadingThreadEnabled, 0, VF_NULL, - "EXPERIMENTAL. Enable fully threaded loading where the LoadingScreen is drawn on a thread that isn't loading data."); - } - - if (pGEnv && !pGEnv->IsEditor()) - { - // If not running from the editor, then run GameStart - GameStart(); - } -} - -void LoadScreenComponent::OnCrySystemShutdown(ISystem&) -{ -} - -void LoadScreenComponent::UpdateAndRender() -{ - SSystemGlobalEnvironment* pGEnv = GetGlobalEnv(); - - if (m_loadScreenState == LoadScreenState::Showing && pGEnv && pGEnv->pTimer) - { - AZ_Assert(GetCurrentThreadId() == pGEnv->mMainThreadId, "UpdateAndRender should only be called from the main thread"); - - // Throttling. - if (!m_previousCallTimeForUpdateAndRender.GetValue()) - { - // This is the first call to UpdateAndRender(). - m_previousCallTimeForUpdateAndRender = pGEnv->pTimer->GetAsyncTime(); - } - - const CTimeValue callTimeForUpdateAndRender = pGEnv->pTimer->GetAsyncTime(); - const float deltaTimeInSeconds = fabs((callTimeForUpdateAndRender - m_previousCallTimeForUpdateAndRender).GetSeconds()); - - // Early-out: We DON'T need to execute UpdateAndRender() at a higher frequency than 30 FPS. - const bool shouldThrottle = m_maxDeltaTimeInSeconds > 0.0f && deltaTimeInSeconds < m_maxDeltaTimeInSeconds; - - if (!shouldThrottle) - { - bool expectedValue = false; - if (m_processingLoadScreen.compare_exchange_strong(expectedValue, true)) - { - m_previousCallTimeForUpdateAndRender = callTimeForUpdateAndRender; - - const float updateDeltaTime = (m_fixedDeltaTimeInSeconds == -1.0f) ? deltaTimeInSeconds : m_fixedDeltaTimeInSeconds; - - EBUS_EVENT(LoadScreenUpdateNotificationBus, UpdateAndRender, updateDeltaTime); - - // Some platforms (iOS, OSX) require system events to be pumped in order to update the screen - AzFramework::ApplicationRequests::Bus::Broadcast(&AzFramework::ApplicationRequests::PumpSystemEventLoopUntilEmpty); - - m_processingLoadScreen.store(false); - } - } - } -} - -void LoadScreenComponent::GameStart() -{ - if (m_loadScreenState == LoadScreenState::None) - { - LoadConfigSettings(s_gameFixedFpsCvarName, s_gameMaxFpsCvarName, s_gameMinimumLoadTimeCvarName); - - const bool usingLoadingThread = IsLoadingThreadEnabled(); - - AZ::EBusLogicalResult> anyHandled(false); - EBUS_EVENT_RESULT(anyHandled, LoadScreenNotificationBus, NotifyGameLoadStart, usingLoadingThread); - - if (anyHandled.value) - { - if (usingLoadingThread) - { - m_loadScreenState = LoadScreenState::ShowingMultiThreaded; - - GetGlobalEnv()->pRenderer->StartLoadtimePlayback(this); - } - else - { - m_loadScreenState = LoadScreenState::Showing; - - // Kick-start the first frame. - UpdateAndRender(); - } - - if (ITimer* timer = GetGlobalEnv()->pTimer) - { - m_lastStartTime = timer->GetAsyncTime(); - } - } - } -} - -void LoadScreenComponent::LevelStart() -{ - if (m_loadScreenState == LoadScreenState::None) - { - LoadConfigSettings(s_levelFixedFpsCvarName, s_levelMaxFpsCvarName, s_levelMinimumLoadTimeCvarName); - - const bool usingLoadingThread = IsLoadingThreadEnabled(); - - AZ::EBusLogicalResult> anyHandled(false); - EBUS_EVENT_RESULT(anyHandled, LoadScreenNotificationBus, NotifyLevelLoadStart, usingLoadingThread); - - if (anyHandled.value) - { - if (usingLoadingThread) - { - m_loadScreenState = LoadScreenState::ShowingMultiThreaded; - - GetGlobalEnv()->pRenderer->StartLoadtimePlayback(this); - } - else - { - m_loadScreenState = LoadScreenState::Showing; - - // Kick-start the first frame. - UpdateAndRender(); - } - - if (ITimer* timer = GetGlobalEnv()->pTimer) - { - m_lastStartTime = timer->GetAsyncTime(); - } - } - } -} - -void LoadScreenComponent::Pause() -{ - if (m_loadScreenState == LoadScreenState::Showing) - { - m_loadScreenState = LoadScreenState::Paused; - } - else if (m_loadScreenState == LoadScreenState::ShowingMultiThreaded) - { - m_loadScreenState = LoadScreenState::PausedMultithreaded; - } -} - -void LoadScreenComponent::Resume() -{ - if (m_loadScreenState == LoadScreenState::Paused) - { - m_loadScreenState = LoadScreenState::Showing; - } - else if (m_loadScreenState == LoadScreenState::PausedMultithreaded) - { - m_loadScreenState = LoadScreenState::ShowingMultiThreaded; - } -} - -void LoadScreenComponent::Stop() -{ - // If we were actually in a load screen, check if we need to wait longer. - if (m_loadScreenState != LoadScreenState::None && m_minimumLoadTimeInSeconds > 0.0f) - { - if (ITimer* timer = GetGlobalEnv()->pTimer) - { - CTimeValue currentTime = timer->GetAsyncTime(); - float timeSinceStart = currentTime.GetDifferenceInSeconds(m_lastStartTime); - - while (timeSinceStart < m_minimumLoadTimeInSeconds) - { - // Simple loop that makes sure the loading screens update but also doesn't consume the whole core. - - if (m_loadScreenState == LoadScreenState::Showing) - { - EBUS_EVENT(LoadScreenBus, UpdateAndRender); - } - - CrySleep(0); - - currentTime = timer->GetAsyncTime(); - timeSinceStart = currentTime.GetDifferenceInSeconds(m_lastStartTime); - } - } - } - - if (m_loadScreenState == LoadScreenState::ShowingMultiThreaded) - { - // This will block until the other thread completes. - GetGlobalEnv()->pRenderer->StopLoadtimePlayback(); - } - - if (m_loadScreenState != LoadScreenState::None) - { - EBUS_EVENT(LoadScreenNotificationBus, NotifyLoadEnd); - } - - Reset(); - - m_loadScreenState = LoadScreenState::None; -} - -bool LoadScreenComponent::IsPlaying() -{ - return m_loadScreenState != LoadScreenState::None; -} - -void LoadScreenComponent::LoadtimeUpdate(float deltaTime) -{ - if (m_loadScreenState == LoadScreenState::ShowingMultiThreaded) - { - EBUS_EVENT(LoadScreenUpdateNotificationBus, LoadThreadUpdate, deltaTime); - } -} - -void LoadScreenComponent::LoadtimeRender() -{ - if (m_loadScreenState == LoadScreenState::ShowingMultiThreaded) - { - EBUS_EVENT(LoadScreenUpdateNotificationBus, LoadThreadRender); - } -} - -#endif // if AZ_LOADSCREENCOMPONENT_ENABLED diff --git a/Code/CryEngine/CryCommon/LoadScreenComponent.h b/Code/CryEngine/CryCommon/LoadScreenComponent.h deleted file mode 100644 index 71ed6287f1..0000000000 --- a/Code/CryEngine/CryCommon/LoadScreenComponent.h +++ /dev/null @@ -1,106 +0,0 @@ -/* - * All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or - * its licensors. - * - * For complete copyright and license terms please see the LICENSE at the root of this - * distribution (the "License"). All use of this software is governed by the License, - * or, if provided, by the license below or the license accompanying this file. Do not - * remove or 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 - -#if AZ_LOADSCREENCOMPONENT_ENABLED - -/* -* This component is responsible for managing the load screen. -*/ -class LoadScreenComponent - : public AZ::Component - , public CrySystemEventBus::Handler - , public LoadScreenBus::Handler - , public ILoadtimeCallback -{ -public: - AZ_COMPONENT(LoadScreenComponent, "{97CDBD6C-C621-4427-87C8-10E1B8F947FF}"); - - LoadScreenComponent() = default; - ~LoadScreenComponent() = default; - - ////////////////////////////////////////////////////////////////////////// - // AZ::Component interface implementation - void Init() override; - void Activate() override; - void Deactivate() override; - ////////////////////////////////////////////////////////////////////////// - - //////////////////////////////////////////////////////////////////////// - // CrySystemEvents - void OnCrySystemInitialized(ISystem&, const SSystemInitParams& params) override; - void OnCrySystemShutdown(ISystem&) override; - //////////////////////////////////////////////////////////////////////// - - ////////////////////////////////////////////////////////////////////////// - // LoadScreenBus interface implementation - void UpdateAndRender() override; - void GameStart() override; - void LevelStart() override; - void Pause() override; - void Resume() override; - void Stop() override; - bool IsPlaying() override; - ////////////////////////////////////////////////////////////////////////// - - ////////////////////////////////////////////////////////////////////////// - // ILoadtimeCallback interface implementation - void LoadtimeUpdate(float deltaTime) override; - void LoadtimeRender() override; - ////////////////////////////////////////////////////////////////////////// - - inline bool IsLoadingThreadEnabled() const - { - return m_loadingThreadEnabled != 0; - } - -protected: - static void Reflect(AZ::ReflectContext* context); - static void GetProvidedServices(AZ::ComponentDescriptor::DependencyArrayType& provided); - static void GetIncompatibleServices(AZ::ComponentDescriptor::DependencyArrayType& incompatible); - -private: - void Reset(); - void LoadConfigSettings(const char* fixedFpsVarName, const char* maxFpsVarName, const char* minimumLoadTimeVarName); - - ////////////////////////////////////////////////////////////////////////// - enum class LoadScreenState - { - None, - Showing, - ShowingMultiThreaded, - Paused, - PausedMultithreaded, - }; - LoadScreenState m_loadScreenState{ LoadScreenState::None }; - - float m_fixedDeltaTimeInSeconds{ -1.0f }; - float m_maxDeltaTimeInSeconds{ -1.0f }; - float m_minimumLoadTimeInSeconds{ 0.0f }; - - CTimeValue m_lastStartTime; - CTimeValue m_previousCallTimeForUpdateAndRender; - AZStd::atomic_bool m_processingLoadScreen{ false }; - - int32_t m_loadingThreadEnabled{ 0 }; - ////////////////////////////////////////////////////////////////////////// -}; - -#endif // if AZ_LOADSCREENCOMPONENT_ENABLED 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/IMemoryManagerMock.h b/Code/CryEngine/CryCommon/Mocks/IMemoryManagerMock.h index 3f458d7f52..63df006e14 100644 --- a/Code/CryEngine/CryCommon/Mocks/IMemoryManagerMock.h +++ b/Code/CryEngine/CryCommon/Mocks/IMemoryManagerMock.h @@ -40,6 +40,4 @@ public: IMemoryAddressRange* (size_t capacity, const char* sName)); MOCK_METHOD2(CreatePageMappingHeap, IPageMappingHeap* (size_t addressSpace, const char* sName)); - MOCK_METHOD0(CreateDefragAllocator, - IDefragAllocator*()); }; diff --git a/Code/CryEngine/CryCommon/Mocks/IRendererMock.h b/Code/CryEngine/CryCommon/Mocks/IRendererMock.h index 757c586261..74d072c48c 100644 --- a/Code/CryEngine/CryCommon/Mocks/IRendererMock.h +++ b/Code/CryEngine/CryCommon/Mocks/IRendererMock.h @@ -286,8 +286,6 @@ public: CRenderObject * (SShaderItem & si, CRenderObject * obj, const SRenderingPassInfo& passInfo, int numPts, int ninds, SVF_P3F_C4B_T2F * &verts, SPipTangents * &tangs, uint16 * &inds, int nAW, const SRendItemSorter& rendItemSorter)); MOCK_METHOD0(ForceUpdateGlobalShaderParameters, void()); - MOCK_METHOD1(EF_SetShaderMissCallback, - void(ShaderCacheMissCallback callback)); MOCK_METHOD0(EF_GetShaderMissLogPath, const char*()); MOCK_METHOD1(EF_GetShaderNames, @@ -334,8 +332,6 @@ public: int(const char* name)); MOCK_METHOD3(EF_RenderEnvironmentCubeHDR, bool(int size, Vec3 & Pos, TArray&vecData)); - MOCK_METHOD1(EF_CreateRE, - IRenderElement * (EDataType edt)); MOCK_METHOD1(EF_StartEf, void(const SRenderingPassInfo& passInfo)); MOCK_METHOD3(EF_GetObjData, @@ -589,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 4d2e80a2f3..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, @@ -49,18 +45,12 @@ public: int()); MOCK_METHOD0(GetLogicalCPUCount, int()); - MOCK_CONST_METHOD0(GetRenderingDriverName, - const char*()); - MOCK_METHOD1(DumpMemoryUsageStatistics, - void(bool)); MOCK_METHOD0(Quit, void()); MOCK_METHOD1(Relaunch, void(bool bRelaunch)); MOCK_CONST_METHOD0(IsQuitting, bool()); - MOCK_CONST_METHOD0(IsShaderCacheGenMode, - bool()); MOCK_METHOD1(SerializingFile, void(int mode)); MOCK_CONST_METHOD0(IsSerializingFile, @@ -90,10 +80,6 @@ public: ILZ4Decompressor * ()); MOCK_METHOD0(GetZStdDecompressor, IZStdDecompressor * ()); - MOCK_METHOD0(GetPerfHUD, - ICryPerfHUD * ()); - MOCK_METHOD0(GetINotificationNetwork, - INotificationNetwork * ()); MOCK_METHOD0(GetIViewSystem, IViewSystem * ()); MOCK_METHOD0(GetILevelSystem, @@ -124,36 +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(GetIFileChangeMonitor, - IFileChangeMonitor * ()); - MOCK_METHOD0(GetHWND, - WIN_HWND()); - MOCK_METHOD0(GetIRenderer, - IRenderer * ()); 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(SetIFileChangeMonitor, - void(IFileChangeMonitor * pFileChangeMonitor)); - MOCK_METHOD1(SetIVisualLog, - void(IVisualLog * pVisualLog)); MOCK_METHOD2(DebugStats, void(bool checkpoint, bool leaks)); MOCK_METHOD0(DumpWinHeaps, @@ -170,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, @@ -180,8 +140,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, @@ -227,10 +185,6 @@ public: void(ESystemConfigPlatform platform)); MOCK_METHOD1(AutoDetectSpec, void(bool detectResolution)); - MOCK_METHOD2(SetThreadState, - int(ESubsystem subsys, bool bActive)); - MOCK_METHOD0(CreateSizer, - ICrySizer * ()); MOCK_CONST_METHOD0(IsPaused, bool()); MOCK_METHOD0(GetLocalizationManager, @@ -241,8 +195,6 @@ public: CPNoise3 * ()); MOCK_METHOD0(GetUpdateCounter, uint64()); - MOCK_CONST_METHOD0(GetCryFactoryRegistry, - ICryFactoryRegistry * ()); MOCK_METHOD1(RegisterErrorObserver, bool(IErrorObserver * errorObserver)); MOCK_METHOD1(UnregisterErrorObserver, @@ -261,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, @@ -275,8 +223,6 @@ public: void(bool)); MOCK_METHOD1(GetUpdateStats, void(SSystemUpdateStats & stats)); - MOCK_METHOD0(DumpMemoryCoverage, - void()); MOCK_METHOD0(GetSystemGlobalState, ESystemGlobalState(void)); MOCK_METHOD1(SetSystemGlobalState, @@ -284,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()); @@ -307,10 +239,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/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 9308412c15..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) @@ -162,10 +159,6 @@ typedef uint32 vtx_idx; #endif #endif -#if defined(ENABLE_PROFILING_CODE) - #define USE_PERFHUD -#endif - #if defined(ENABLE_PROFILING_CODE) #define ENABLE_ART_RT_TIME_ESTIMATE #endif @@ -185,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 @@ -296,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/RendElement.h b/Code/CryEngine/CryCommon/RendElement.h deleted file mode 100644 index 41bcf2bf67..0000000000 --- a/Code/CryEngine/CryCommon/RendElement.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 CRYINCLUDE_CRYCOMMON_RENDELEMENT_H -#define CRYINCLUDE_CRYCOMMON_RENDELEMENT_H -#pragma once - - -//============================================================= - -#include "VertexFormats.h" - -class CRendElementBase; -struct CRenderChunk; -struct PrimitiveGroup; -class CShader; -struct SShaderTechnique; -class CParserBin; -struct SParserFrame; - -namespace AZ -{ - namespace Vertex - { - class Format; - } -} - -enum EDataType -{ - eDATA_Unknown = 0, - eDATA_Sky, - eDATA_Beam, - eDATA_ClientPoly, - eDATA_Flare, - eDATA_Terrain, - eDATA_SkyZone, - eDATA_Mesh, - eDATA_Imposter, - eDATA_LensOptics, - eDATA_FarTreeSprites_Deprecated, - eDATA_OcclusionQuery, - eDATA_Particle, - eDATA_GPUParticle, - eDATA_PostProcess, - eDATA_HDRProcess, - eDATA_Cloud, - eDATA_HDRSky, - eDATA_FogVolume, - eDATA_WaterVolume, - eDATA_WaterOcean, - eDATA_VolumeObject, - eDATA_PrismObject, // normally this would be #if !defined(EXCLUDE_DOCUMENTATION_PURPOSE) but we keep it to get consistent numbers for serialization - eDATA_DeferredShading, - eDATA_GameEffect, - eDATA_BreakableGlass, - eDATA_GeomCache, - eDATA_Gem, -}; - -#include - -//======================================================= - -#define FCEF_TRANSFORM 1 -#define FCEF_DIRTY 2 -#define FCEF_NODEL 4 -#define FCEF_DELETED 8 - -#define FCEF_MODIF_TC 0x10 -#define FCEF_MODIF_VERT 0x20 -#define FCEF_MODIF_COL 0x40 -#define FCEF_MODIF_MASK 0xf0 - -#define FCEF_UPDATEALWAYS 0x100 -#define FCEF_ALLOC_CUST_FLOAT_DATA 0x200 -#define FCEF_MERGABLE 0x400 - -#define FCEF_SKINNED 0x800 -#define FCEF_PRE_DRAW_DONE 0x1000 - -#define FGP_NOCALC 1 -#define FGP_SRC 2 -#define FGP_REAL 4 -#define FGP_WAIT 8 - -#define FGP_STAGE_SHIFT 0x10 - -#define MAX_CUSTOM_TEX_BINDS_NUM 2 - -struct SGeometryInfo; -class CRendElement; - -struct IRenderElementDelegate -{ - virtual void mfPrepare(bool bCheckOverflow) = 0; - virtual bool mfDraw(CShader* shader, SShaderPass* pass) = 0; - virtual bool mfSetSampler([[maybe_unused]] int customId, [[maybe_unused]] int nTUnit, [[maybe_unused]] int nTState, [[maybe_unused]] int nTexMaterialSlot, [[maybe_unused]] int nSUnit) { return true; }; -}; - -struct IRenderElement -{ - virtual int mfGetMatId() = 0; - virtual uint16 mfGetFlags() = 0; - virtual void mfSetFlags(uint16 fl) = 0; - virtual void mfUpdateFlags(uint16 fl) = 0; - virtual void mfClearFlags(uint16 fl) = 0; - virtual void mfPrepare(bool bCheckOverflow) = 0; - virtual void mfCenter(Vec3& centr, CRenderObject* pObj) = 0; - virtual void mfGetBBox(Vec3& vMins, Vec3& vMaxs) = 0; - virtual void mfReset() = 0; - virtual void mfGetPlane(Plane_tpl& pl) = 0; - virtual void mfExport(struct SShaderSerializeContext& SC) = 0; - virtual void mfImport(struct SShaderSerializeContext& SC, uint32& offset) = 0; - virtual void mfPrecache(const SShaderItem& SH) = 0; - virtual bool mfIsHWSkinned() = 0; - virtual bool mfCheckUpdate(int Flags, uint16 nFrame, bool bTessellation = false) = 0; - virtual bool mfUpdate(int Flags, bool bTessellation = false) = 0; - virtual bool mfCompile(CParserBin& Parser, SParserFrame& Frame) = 0; - virtual bool mfDraw(CShader* ef, SShaderPass* sfm) = 0; - virtual bool mfPreDraw(SShaderPass* sl) = 0; - virtual bool mfSetSampler(int customId, int nTUnit, int nTState, int nTexMaterialSlot, int nSUnit) = 0; - virtual void mfSetDelegate(IRenderElementDelegate* pDelegate) = 0; - virtual IRenderElementDelegate* mfGetDelegate() = 0; - virtual CRenderChunk* mfGetMatInfo() = 0; - virtual TRenderChunkArray* mfGetMatInfoList() = 0; - virtual void* mfGetPointer(ESrcPointer ePT, int* Stride, EParamType Type, ESrcPointer Dst, int Flags) = 0; - virtual AZ::Vertex::Format GetVertexFormat() const = 0; - virtual void* GetCustomData() const = 0; - virtual int GetCustomTexBind(int i) const = 0; - virtual CRendElementBase* mfCopyConstruct() = 0; - virtual EDataType mfGetType() = 0; - virtual int Size() = 0; - virtual void GetMemoryUsage(ICrySizer* pSizer) const = 0; - -}; - -class CRendElement -{ -public: - static CRendElement m_RootGlobal; - static CRendElement m_RootRelease[]; - CRendElement* m_NextGlobal; - CRendElement* m_PrevGlobal; - - EDataType m_Type; - -protected: - virtual void UnlinkGlobal() - { - if (!m_NextGlobal || !m_PrevGlobal) - { - return; - } - m_NextGlobal->m_PrevGlobal = m_PrevGlobal; - m_PrevGlobal->m_NextGlobal = m_NextGlobal; - m_NextGlobal = m_PrevGlobal = NULL; - } - - virtual void LinkGlobal(CRendElement* Before) - { - if (m_NextGlobal || m_PrevGlobal) - { - return; - } - m_NextGlobal = Before->m_NextGlobal; - Before->m_NextGlobal->m_PrevGlobal = this; - Before->m_NextGlobal = this; - m_PrevGlobal = Before; - } - -public: - CRendElement(); - virtual ~CRendElement(); - virtual void Release(bool bForce = false); - virtual const char* mfTypeString(); - virtual void mfSetType(EDataType t) { m_Type = t; } - virtual void GetMemoryUsage([[maybe_unused]] ICrySizer* pSizer) const {} - virtual int Size() { return 0; } - - static void ShutDown(); - static void Tick(); - static void Cleanup(); -}; - -class CRendElementBase - : public CRendElement - , public IRenderElement -{ -public: - uint16 m_Flags; - uint16 m_nFrameUpdated; - -public: - void* m_CustomData; - int m_CustomTexBind[MAX_CUSTOM_TEX_BINDS_NUM]; - - struct SGeometryStreamInfo - { - const void* pStream; - int nOffset; - int nStride; - }; - struct SGeometryInfo - { - uint32 bonesRemapGUID; // Input paremeter to fetch correct skinning stream. - - int primitiveType; //!< \see eRenderPrimitiveType - AZ::Vertex::Format vertexFormat; - uint32 streamMask; - - int32 nFirstIndex; - int32 nNumIndices; - uint32 nFirstVertex; - uint32 nNumVertices; - - uint32 nMaxVertexStreams; - - SGeometryStreamInfo indexStream; - SGeometryStreamInfo vertexStream[VSF_NUM]; - - void* pTessellationAdjacencyBuffer; - void* pSkinningExtraBonesBuffer; - }; - -public: - CRendElementBase(); - virtual ~CRendElementBase(); - - - virtual void mfPrepare(bool bCheckOverflow) override - { - if (m_delegate) - { - m_delegate->mfPrepare(bCheckOverflow); - } - } - bool mfDraw(CShader* ef, SShaderPass* sfm) override { return m_delegate ? m_delegate->mfDraw(ef, sfm) : true; } - bool mfSetSampler(int customId, int nTUnit, int nTState, int nTexMaterialSlot, int nSUnit) override { return m_delegate ? m_delegate->mfSetSampler(customId, nTUnit, nTState, nTexMaterialSlot, nSUnit) : false; } - void mfSetDelegate(IRenderElementDelegate* pDelegate) override { m_delegate = pDelegate; } - IRenderElementDelegate* mfGetDelegate() { return m_delegate; } - - EDataType mfGetType() override { return m_Type; }; - - CRenderChunk* mfGetMatInfo() override { return nullptr; } - TRenderChunkArray* mfGetMatInfoList() override { return nullptr; } - int mfGetMatId() override { return -1; } - void mfReset() override {}; - CRendElementBase* mfCopyConstruct() override; - void mfCenter(Vec3& centr, CRenderObject* pObj) override; - - bool mfCompile([[maybe_unused]] CParserBin& Parser, [[maybe_unused]] SParserFrame& Frame) override { return false; } - bool mfPreDraw([[maybe_unused]] SShaderPass* sl) override { return true; } - bool mfUpdate([[maybe_unused]] int Flags, [[maybe_unused]] bool bTessellation = false) override { return true; } - void mfPrecache([[maybe_unused]] const SShaderItem& SH) override {} - void mfExport([[maybe_unused]] struct SShaderSerializeContext& SC) override { CryFatalError("mfExport has not been implemented for this render element type"); } - void mfImport([[maybe_unused]] struct SShaderSerializeContext& SC, [[maybe_unused]] uint32& offset) override { CryFatalError("mfImport has not been implemented for this render element type"); } - void mfGetPlane(Plane_tpl& pl) override; - void* mfGetPointer([[maybe_unused]] ESrcPointer ePT, [[maybe_unused]] int* Stride, [[maybe_unused]] EParamType Type, [[maybe_unused]] ESrcPointer Dst, [[maybe_unused]] int Flags) override { return nullptr; } - - uint16 mfGetFlags() override { return m_Flags; } - void mfSetFlags(uint16 fl) override { m_Flags = fl; } - void mfUpdateFlags(uint16 fl) override { m_Flags |= fl; } - void mfClearFlags(uint16 fl) override { m_Flags &= ~fl; } - bool mfCheckUpdate(int Flags, uint16 nFrame, bool bTessellation = false) override - { - if (nFrame != m_nFrameUpdated || (m_Flags & (FCEF_DIRTY | FCEF_SKINNED | FCEF_UPDATEALWAYS))) - { - m_nFrameUpdated = nFrame; - return mfUpdate(Flags, bTessellation); - } - return true; - } - void mfGetBBox(Vec3& vMins, Vec3& vMaxs) override - { - vMins.Set(0, 0, 0); - vMaxs.Set(0, 0, 0); - } - bool mfIsHWSkinned() override { return false; } - int Size() override { return 0; } - void GetMemoryUsage([[maybe_unused]] ICrySizer* pSizer) const override {} - AZ::Vertex::Format GetVertexFormat() const override { return AZ::Vertex::Format(eVF_Unknown); }; - virtual bool GetGeometryInfo([[maybe_unused]] SGeometryInfo& streams) { return false; } - void Draw([[maybe_unused]] CRenderObject* pObj, [[maybe_unused]] const struct SGraphicsPiplinePassContext& ctx) {}; - void* GetCustomData() const { return m_CustomData; } - int GetCustomTexBind(int index) const { return m_CustomTexBind[index]; } - -protected: - IRenderElementDelegate * m_delegate = nullptr; -}; - -#include "CREMesh.h" -#include "CRESky.h" -#include "CREOcclusionQuery.h" -#include "CREImposter.h" -#include "CREBaseCloud.h" -#include "CREPostProcess.h" -#include "CREFogVolume.h" -#include "CREWaterVolume.h" -#include "CREWaterOcean.h" -#include "CREVolumeObject.h" -#include "CREGameEffect.h" -#include "CREGeomCache.h" - -#if !defined(EXCLUDE_DOCUMENTATION_PURPOSE) -#include "CREPrismObject.h" -#endif // EXCLUDE_DOCUMENTATION_PURPOSE - -//========================================================== - -#endif // CRYINCLUDE_CRYCOMMON_RENDELEMENT_H 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/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/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/TypeLibrary.h b/Code/CryEngine/CryCommon/TypeLibrary.h deleted file mode 100644 index 03d608a24e..0000000000 --- a/Code/CryEngine/CryCommon/TypeLibrary.h +++ /dev/null @@ -1,512 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS 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_TYPELIBRARY_H -#define CRYINCLUDE_CRYCOMMON_TYPELIBRARY_H -#pragma once - -#include // <> required for Interfuscator - -#include -#include - -#ifdef SOFTCODE_ENABLED - -// Internal: Used by SC types to auto-remove themselves from their TypeRegistrar on destruction. -struct InstanceTracker -{ - InstanceTracker() - : m_pRegistrar() - {} - - ~InstanceTracker() - { - if (m_pRegistrar) - { - m_pRegistrar->RemoveInstance(this); - } - } - - void SetRegistrar(ITypeRegistrar* pRegistrar) - { - m_pRegistrar = pRegistrar; - } - - ITypeRegistrar* m_pRegistrar; // Valid if created by a registrar, otherwise NULL -}; - -#endif - - -#ifdef SOFTCODE_ENABLED - -// Include this for SEH support - #include - -/* - Used to declare the interface as having an associated TypeLibrary. - Usage: - struct IMyInterface - { - DECLARE_TYPELIB(IMyInterface); -*/ - #define DECLARE_TYPELIB(IName) \ - static void VisitMembers(IExchanger & ex) {} \ - typedef CTypeLibrary TLibrary - -/* - Exposes a class to a TypeLibrary for registration. - Usage: - class MyThing : public IThing - { - DECLARE_TYPE(MyThing, IThing); - ... -*/ - #define DECLARE_TYPE(TName, TSuperType) \ -public: \ - void VisitMembers(IExchanger & ex) { TSuperType::VisitMembers(ex); VisitMember<__START_MEMBERS>(ex); } \ -private: \ - friend class TypeRegistrar; \ - static const size_t __START_MEMBERS = __COUNTER__ + 1; \ - template \ - void VisitMember(IExchanger & exchanger) {} \ - InstanceTracker __instanceTracker - - #ifdef SOFTCODE - #define _EXPORT_TYPE_LIB(Interface) \ - extern "C" ITypeLibrary * GetTypeLibrary() { return CTypeLibrary::Instance(); } - #else - #define _EXPORT_TYPE_LIB(Interface) - #endif - -// Internal: Outputs the specialized method template for the member at index - #define _SOFT_MEMBER_VISITOR(member, index) \ - template <> \ - void VisitMember(IExchanger & ex) { ex.Visit(#member, member); VisitMember(ex); } - -/* - Used to expose a class member to SoftCoding (to allow run-time member exchange) - If SoftCode is disabled this does nothing and simple emits the member. - For array types, use SOFT_ARRAY() instead or use AZStd::array which allows assignment. - Usage: std::vector SOFT(m_myStrings); -*/ - #define SOFT(member) \ - member; \ - _SOFT_MEMBER_VISITOR(member, __COUNTER__) - -/* - Used to expose a primitive array type to SoftCoding. - Declare it directly after the member. - NOTE: It's cleaner to convert the member to AZStd::array as - this avoid having to use this special case while preserving semantics. - Usage: - ColorB m_colors[20]; - SOFT_ARRAY(m_colors); -*/ - #define SOFT_ARRAY(arrayMember) _SOFT_MEMBER_VISITOR(arrayMember, __COUNTER__) - -// Internal: Executes given lambda in an SEH try block. -template -void SoftCodeTry(TLambda& lambda) -{ - __try - { - lambda(); - } - __except (EXCEPTION_EXECUTE_HANDLER) - { - } -} - -// Internal: Used by TypeRegistry. Use SOFTCODE_RETRY() for user code. - #define SOFTCODE_TRY(exp) SoftCodeTry([&](){ exp; }) - #define SOFTCODE_TRY_BLOCK SoftCodeTry([&]() { - #define SOFTCODE_TRY_END }); - -/* - Internal: Attempt a given lambda functor. In the even on an exception execution will pause - to allow the user to provide a replacement implementation for the failing instance. - Usage: See SOFTCODE_RETRY & SOFTCODE_RETRY_BLOCK below. -*/ -template -void SoftCodeRetry(TPtr& pointer, TLambda& lambda) -{ - bool complete = false; - while (pointer && !complete) - { - __try - { - lambda(); - complete = true; - } - __except (EXCEPTION_EXECUTE_HANDLER) - { - if (gEnv->pSoftCodeMgr) - { - pointer = reinterpret_cast(gEnv->pSoftCodeMgr->WaitForUpdate(pointer)); - } - } - } - ; -} - -/* - Attempts to call an expression based the given pointer. - If a Structured Exception is raised the thread will wait for a replacement of - the pointer to be provided via the SoftCodeMgr. This will repeat until no exception is raised. - - Usage: SOFTCODE_RETRY(pThing, (pThing->Update(frameTime))); // Same as pThing->Update(frameTime); -*/ - #define SOFTCODE_RETRY(pointer, exp) SoftCodeRetry(pointer, [&](){ exp; }) - -/* - Attempts to call an expression based the given pointer. - If a Structured Exception is raised the thread will wait for a replacement of - the pointer to be provided via the SoftCodeMgr. This will repeat until no exception is raised. - - Usage: - SOFTCODE_RETRY_BLOCK(pThing) - { - pSomething = pThing->GetSomething(); - } - SOFTCODE_RETRY_END -*/ - #define SOFTCODE_RETRY_BLOCK(pointer) SoftCodeRetry(pointer, [&]() { - #define SOFTCODE_RETRY_END }); - -#else // !SOFTCODE_ENABLED ... - -// IMPORTANT: Docs for these macros are found above. - - #define DECLARE_TYPELIB(IName) \ - typedef CTypeLibrary TLibrary - - #define DECLARE_TYPE(TName, TSuperType) \ -private: \ - friend class TypeRegistrar; - - #define _EXPORT_TYPE_LIB(Interface) - - #define SOFT(member) member - #define SOFT_ARRAY(arrayMember) - - #define SOFTCODE_TRY(exp) (exp) - #define SOFTCODE_TRY_BLOCK { - #define SOFTCODE_TRY_END }; - - #define SOFTCODE_RETRY(pointer, exp) (exp) - #define SOFTCODE_RETRY_BLOCK(pointer) { - #define SOFTCODE_RETRY_END }; - -#endif // !SOFTCODE_ENABLED - -/* - Implements registration for a type to a TypeLibrary. - Usage: - // MyThing.cpp - DECLARE_TYPE(MyThing); -*/ -#define IMPLEMENT_TYPE(TName) \ - static TypeRegistrar s_register##TName(#TName) - -/* - Provides the singleton for the TypeLibrary implementation. - Also exports the accessors function for SoftCode builds. - Usage: - // ThingLibrary.cpp - IMPLEMENT_TYPELIB(IThing, "Things") -*/ -#define IMPLEMENT_TYPELIB(Interface, Name) \ - _EXPORT_TYPE_LIB(Interface) \ - template <> \ - CTypeLibrary* CTypeLibrary::Instance() \ - { \ - static CTypeLibrary s_instance(Name); \ - return &s_instance; \ - } - -/* - Internal: Used to register a type with a TypeLibrary. - Also provides instance construction (factory) access. - For SC builds it also provides copying and instance tracking. -*/ -template -class TypeRegistrar - : public ITypeRegistrar -{ -public: - TypeRegistrar(const char* name) - : m_name(name) - { - typedef typename T::TLibrary TLib; - TLib::Instance()->RegisterType(this); - } - - virtual const char* GetName() const { return m_name; } - - virtual void* CreateInstance() - { - T* pInstance = NULL; - - SOFTCODE_TRY_BLOCK - { - pInstance = ConstructInstance(); - } - SOFTCODE_TRY_END - - if (pInstance) - { - RegisterInstance(pInstance); - } - - return pInstance; - } - -#ifdef SOFTCODE_ENABLED - virtual size_t InstanceCount() const - { - return m_instances.size(); - } - - virtual void RemoveInstance(InstanceTracker* pTracker) - { - T* pInstance = GetInstanceFromTracker(pTracker); - TInstanceVec::iterator iter(std::find(m_instances.begin(), m_instances.end(), pInstance)); - std::swap(*iter, m_instances.back()); - m_instances.pop_back(); - } - - virtual bool ExchangeInstances(IExchanger& exchanger) - { - if (exchanger.IsLoading()) - { - const size_t instanceCount = exchanger.InstanceCount(); - - // Ensure we have the correct number of instances - if (m_instances.size() != instanceCount) - { - // TODO: Destroy any existing instances - for (size_t i = 0; i < instanceCount; ++i) - { - if (!CreateInstance()) - { - return false; - } - } - } - } - - bool complete = false; - SOFTCODE_TRY_BLOCK - { - for (std::vector::iterator iter(m_instances.begin()); iter != m_instances.end(); ++iter) - { - T* pInstance = *iter; - if (exchanger.BeginInstance(pInstance)) - { - // Exchanges the members of pInstance as defined in T - // Should also exchange members of parent types - pInstance->VisitMembers(exchanger); - } - } - complete = true; - } - SOFTCODE_TRY_END - - return complete; - } - - virtual bool DestroyInstances() - { - bool complete = false; - SOFTCODE_TRY_BLOCK - { - while (!m_instances.empty()) - { - delete m_instances.back(); - // NOTE: No need to pop_back() as already done by the InstanceTracker via RemoveInstance() - } - complete = true; - } - SOFTCODE_TRY_END - - return complete; - } - - - virtual bool HasInstance(void* pInstance) const - { - return std::find(m_instances.begin(), m_instances.end(), pInstance) != m_instances.end(); - } -#endif - -private: - void RegisterInstance(T* pInstance) - { -#ifdef SOFTCODE_ENABLED - pInstance->__instanceTracker.SetRegistrar(this); - m_instances.push_back(pInstance); -#endif - } - -#ifdef SOFTCODE_ENABLED - // Util: Avoids having to redundantly store the instance address in the tracker - T* GetInstanceFromTracker(InstanceTracker* pTracker) - { - ptrdiff_t trackerOffset = reinterpret_cast(&((static_cast(0))->__instanceTracker)); - return reinterpret_cast(reinterpret_cast(pTracker) - trackerOffset); - } -#endif - - // Needed to avoid C2712 due to lack of stack unwind within SEH try blocks - T* ConstructInstance() - { - return new T(); - } - -private: - const char* m_name; // Name of the type - -#ifdef SOFTCODE_ENABLED - typedef std::vector TInstanceVec; - TInstanceVec m_instances; // Tracks the active instances (SC only) -#endif -}; - -/* - Provides factory creation support for a set of types that - derive from a single interface T. Users need to provide a - specialization of the static CTypeLibrary* Instance() member - in a cpp file to provide the singleton instance. -*/ -template -class CTypeLibrary - #ifdef SOFTCODE_ENABLED - : public ITypeLibrary - #endif -{ -public: - CTypeLibrary(const char* name) - : m_name(name) -#ifdef SOFTCODE_ENABLED - , m_pOverrideLib() - , m_overrideActive() - , m_registered() -#endif - { - } - - // Implemented in the export cpp - static CTypeLibrary* Instance(); - - void RegisterType(ITypeRegistrar* pType) - { - m_typeMap[pType->GetName()] = pType; - } - - // The global identifier for this library module - /*virtual*/ const char* GetName() { return m_name; } - -#ifdef SOFTCODE_ENABLED - virtual void* CreateInstanceVoid(const char* typeName) - { - return CreateInstance(typeName); - } -#endif - - // Generic creation function - T* CreateInstance(const char* typeName) - { -#ifdef SOFTCODE_ENABLED - RegisterWithSoftCode(); - - // If override is enabled, use it - if (m_pOverrideLib) - { - return reinterpret_cast(m_pOverrideLib->CreateInstanceVoid(typeName)); - } -#endif - - TTypeMap::const_iterator typeIter(m_typeMap.find(typeName)); - if (typeIter != m_typeMap.end()) - { - ITypeRegistrar* pRegistrar = typeIter->second; - return reinterpret_cast(pRegistrar->CreateInstance()); - } - - return NULL; - } - -#ifdef SOFTCODE_ENABLED - // Indicates CreateInstance requests should be forwarded to the specified lib - virtual void SetOverride(ITypeLibrary* pOverrideLib) - { - m_pOverrideLib = pOverrideLib; - } - - virtual size_t GetTypes(ITypeRegistrar** ppTypes, size_t& count) const - { - size_t returnedCount = 0; - - if (ppTypes && count >= m_typeMap.size()) - { - for (TTypeMap::const_iterator iter(m_typeMap.begin()); iter != m_typeMap.end(); ++iter) - { - *ppTypes = iter->second; - ++ppTypes; - ++returnedCount; - } - } - - count = m_typeMap.size(); - return returnedCount; - } - - // Inform the Mgr of this Library and allow it to set an override - inline void RegisterWithSoftCode() - { - // Only register built-in types, SC types are handled directly by - // the SoftCodeMgr, so there's no need to auto-register. -#ifndef SOFTCODE - if (!m_registered) - { - if (ISoftCodeMgr* pSoftCodeMgr = gEnv->pSoftCodeMgr) - { - pSoftCodeMgr->RegisterLibrary(this); - } - - m_registered = true; - } -#endif - } -#endif - -private: - typedef AZStd::basic_string, AZ::AZStdAlloc> TypeString; - typedef AZStd::map, AZ::AZStdAlloc> TTypeMap; - TTypeMap m_typeMap; - - // The name for this TypeLibrary used during SC registration - const char* m_name; - -#ifdef SOFTCODE_ENABLED - // Used to patch in a new TypeLib at run-time - ITypeLibrary* m_pOverrideLib; - // True when the owning object system enables the override - bool m_overrideActive; - // True when registration with SoftCodeMgr has been attempted - bool m_registered; -#endif -}; - -#endif // CRYINCLUDE_CRYCOMMON_TYPELIBRARY_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 7d169c2643..77b51825f1 100644 --- a/Code/CryEngine/CryCommon/crycommon_files.cmake +++ b/Code/CryEngine/CryCommon/crycommon_files.cmake @@ -20,14 +20,8 @@ set(FILES ICmdLine.h IColorGradingController.h IConsole.h - ICryMiniGUI.h - IDeferredCollisionEvent.h - IDefragAllocator.h - IEngineModule.h IEntityRenderState.h IEntityRenderState_info.cpp - IFileChangeMonitor.h - IFlares.h IFont.h IFunctorBase.h IFuncVariable.h @@ -45,31 +39,23 @@ set(FILES ILog.h ILZ4Decompressor.h IMaterial.h - IMaterialEffects.h IMemory.h IMeshBaking.h IMiniLog.h IMovieSystem.h - INotificationNetwork.h - IOverloadSceneManager.h - IPerfHud.h IPhysics.h IPhysicsDebugRenderer.h IPostEffectGroup.h IProcess.h IReadWriteXMLSink.h - IRemoteCommand.h IRenderAuxGeom.h IRenderer.h IRenderMesh.h IResourceCollector.h - IResourceCompilerHelper.h IResourceManager.h ISerialize.h - IServiceNetwork.h IShader.h IShader_info.h - ISoftCodeMgr.h ISplines.h IStatObj.h StatObjBus.h @@ -78,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 @@ -109,7 +92,6 @@ set(FILES FunctorBaseMember.h stridedptr.h Options.h - CREGeomCache.h SerializationTypes.h CryEndian.h CryRandomInternal.h @@ -118,7 +100,6 @@ set(FILES MaterialUtils.h MTPseudoRandom.cpp CryTypeInfo.cpp - IResourceCompilerHelper.cpp BaseTypes.h CompileTimeAssert.h CryThreadSafeWorkerContainer.h @@ -127,7 +108,6 @@ set(FILES MemoryAccess.h Algorithm.h AnimKey.h - AnimTime.h BitFiddling.h CGFContent.h CGFContent_info.cpp @@ -162,7 +142,6 @@ set(FILES CryVersion.h CryZlib.h FrameProfiler.h - GeomCacheFileFormat.h HashGrid.h HeapAllocator.h HeapContainer.h @@ -182,7 +161,6 @@ set(FILES PoolAllocator.h primitives.h primitives_info.h - ProfileLog.h ProjectDefines.h Range.h RenderContextConfig.h @@ -205,7 +183,6 @@ set(FILES TimeValue_info.h TypeInfo_decl.h TypeInfo_impl.h - TypeLibrary.h UnalignedBlit.h UnicodeBinding.h UnicodeEncoding.h @@ -215,25 +192,12 @@ set(FILES VectorSet.h VertexFormats.h XMLBinaryHeaders.h - Bezier.h RenderBus.h MainThreadRenderRequestBus.h OceanConstants.h PakLoadDataUtils.cpp PakLoadDataUtils.h TPool.h - CREBaseCloud.h - CREFogVolume.h - CREGameEffect.h - CREImposter.h - CREMesh.h - CREOcclusionQuery.h - CREPostProcess.h - CRESky.h - CREVolumeObject.h - CREWaterOcean.h - CREWaterVolume.h - RendElement.h Cry_Matrix33.h Cry_Matrix34.h Cry_Matrix44.h @@ -280,108 +244,12 @@ set(FILES Linux_Win32Wrapper.h LinuxSpecific.h LoadScreenBus.h - LoadScreenComponent.cpp - LoadScreenComponent.h MacSpecific.h platform.h 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 @@ -478,7 +346,6 @@ set(FILES Terrain/Bus/TerrainRendererBus.h Terrain/Bus/HeightmapDataBus.h Terrain/Bus/TerrainProviderBus.h - CREPrismObject.h StaticInstance.h Pak/CryPakUtils.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 6c261bb1f1..885ea2984d 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 @@ -34,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) @@ -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 } @@ -161,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 dd7739bb79..aa344684e3 100644 --- a/Code/CryEngine/CrySystem/AutoDetectSpec.cpp +++ b/Code/CryEngine/CrySystem/AutoDetectSpec.cpp @@ -711,31 +711,6 @@ static Win32SysInspect::DXFeatureLevel GetFeatureLevel(D3D_FEATURE_LEVEL feature } } - -static int GetDXGIAdapterOverride() -{ -#if defined(WIN32) || defined(WIN64) - ICVar* pCVar = gEnv->pConsole ? gEnv->pConsole->GetCVar("r_overrideDXGIAdapter") : 0; - return pCVar ? pCVar->GetIVal() : -1; -#else - return -1; -#endif -} - - -static void LogDeviceInfo(unsigned int adapterIdx, const DXGI_ADAPTER_DESC1& ad, Win32SysInspect::DXFeatureLevel fl, bool displaysConnected) -{ - const bool suitableDevice = fl >= Win32SysInspect::DXFL_11_0 && displaysConnected; - - CryLogAlways("- %s (vendor = 0x%.4x, device = 0x%.4x)", CryStringUtils::WStrToUTF8(ad.Description).c_str(), ad.VendorId, ad.DeviceId); - CryLogAlways(" - Adapter index: %d", adapterIdx); - CryLogAlways(" - Dedicated video memory: %d MB", ad.DedicatedVideoMemory >> 20); - CryLogAlways(" - Feature level: %s", GetFeatureLevelAsString(fl)); - CryLogAlways(" - Displays connected: %s", displaysConnected ? "yes" : "no"); - CryLogAlways(" - Suitable rendering device: %s", suitableDevice ? "yes" : "no"); -} - - static bool FindGPU(DXGI_ADAPTER_DESC1& adapterDesc, Win32SysInspect::DXFeatureLevel& featureLevel) { memset(&adapterDesc, 0, sizeof(adapterDesc)); @@ -757,15 +732,7 @@ static bool FindGPU(DXGI_ADAPTER_DESC1& adapterDesc, Win32SysInspect::DXFeatureL if (pD3D11CD) { - const int r_overrideDXGIAdapter = GetDXGIAdapterOverride(); - const bool logDeviceInfo = !gEnv->pRenderer && r_overrideDXGIAdapter < 0; - - if (logDeviceInfo) - { - CryLogAlways("Logging video adapters:"); - } - - unsigned int nAdapter = r_overrideDXGIAdapter >= 0 ? r_overrideDXGIAdapter : 0; + unsigned int nAdapter = 0; IDXGIAdapter1* pAdapter = 0; while (pFactory->EnumAdapters1(nAdapter, &pAdapter) != DXGI_ERROR_NOT_FOUND) { @@ -786,29 +753,16 @@ static bool FindGPU(DXGI_ADAPTER_DESC1& adapterDesc, Win32SysInspect::DXFeatureL const Win32SysInspect::DXFeatureLevel fl = GetFeatureLevel(deviceFeatureLevel); - if (logDeviceInfo) - { - LogDeviceInfo(nAdapter, ad, fl, displaysConnected); - } - if (featureLevel < fl && displaysConnected) { adapterDesc = ad; featureLevel = fl; } - else if (r_overrideDXGIAdapter >= 0) - { - CryLogAlways("No display connected to DXGI adapter override %d. Adapter cannot be used for rendering.", r_overrideDXGIAdapter); - } } SAFE_RELEASE(pDevice); SAFE_RELEASE(pAdapter); } - if (r_overrideDXGIAdapter >= 0) - { - break; - } ++nAdapter; } } @@ -1090,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/CrySizerImpl.cpp b/Code/CryEngine/CrySystem/CrySizerImpl.cpp deleted file mode 100644 index bd26b05b9e..0000000000 --- a/Code/CryEngine/CrySystem/CrySizerImpl.cpp +++ /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. - -#include "CrySystem_precompiled.h" -#include -#include -#include "CrySizerImpl.h" - -CrySizerImpl::CrySizerImpl() - : m_pResourceCollector(0) -{ - m_nFlags = 0; - m_nTotalSize = 0; - // to avoid reallocations during walk through the memory tree, reserve the space for the names - clear(); -} - -CrySizerImpl::~CrySizerImpl() -{ -} - -void CrySizerImpl::Push (const char* szComponentName) -{ - m_stackNames.push_back (getNameIndex(getCurrentName(), szComponentName)); - // if the depth is too deep, something is wrong, perhaps an infinite loop - assert (m_stackNames.size() < 128); -} - -void CrySizerImpl::PushSubcomponent (const char* szSubcomponentName) -{ - Push (szSubcomponentName); -} - - -void CrySizerImpl::Pop () -{ - if (!m_stackNames.empty()) - { - m_stackNames.pop_back(); - } - else - { - assert (0); - } -} - -// returns the index of the current name on the top of the name stack -size_t CrySizerImpl::getCurrentName() const -{ - assert(!m_stackNames.empty()); - return m_stackNames.empty() ? 0 : m_stackNames.back(); -} - - - -// searches for the name in the name array; adds the name if it's not there and returns the index -size_t CrySizerImpl::getNameIndex(size_t nParent, const char* szComponentName) -{ - NameArray::const_iterator it = m_arrNames.begin(), itEnd = it + m_arrNames.size(); - for (; it != itEnd; ++it) - { -#if defined(LINUX) - if (!strcasecmp(it->strName.c_str(), szComponentName) && it->nParent == nParent) -#else - if (!strcmp(it->strName.c_str(), szComponentName) && it->nParent == nParent) -#endif - { - return (size_t)(it - m_arrNames.begin());//it-m_arrNames.begin(); - } - } - - size_t nNewName = m_arrNames.size(); - m_arrNames.resize(nNewName + 1); - - m_arrNames[nNewName].assign(szComponentName, nParent); - - m_arrNames[nParent].arrChildren.push_back(nParent); - - return nNewName; -} - -static NullResCollector s_nullCollector; - -IResourceCollector* CrySizerImpl::GetResourceCollector() -{ - return m_pResourceCollector != 0 ? m_pResourceCollector : &s_nullCollector; -} - -void CrySizerImpl::Reset() -{ - clear(); - - m_nTotalSize = 0; - - //m_arrNames.resize(0); - //m_arrNames.push_back("TOTAL"); // the default name, with index 0 - //m_LastObject.clear(); - ////m_nFlags; - //m_nTotalSize=0; - //if (m_pResourceCollector) - //{ - // m_pResourceCollector->Reset(); - //} - //m_setObjects->clear(); - //m_stackNames.resize(0); - //m_stackNames.push_back(0); -} - - -// adds an object identified by the unique pointer (it needs not be -// the actual object position in the memory, though it would be nice, -// but it must be unique throughout the system and unchanging for this object) -// RETURNS: true if the object has actually been added (for the first time) -// and calculated -bool CrySizerImpl::AddObject (const void* pIdentifier, size_t sizeBytes, int nCount) -{ - if (!pIdentifier || !sizeBytes) - { - return false; // we don't add the NULL objects - } - Object NewObject(pIdentifier, sizeBytes, getCurrentName()); - - // check if the last object was the same - if (NewObject == m_LastObject) - { - assert (m_LastObject.nSize == sizeBytes); - return false; - } - - ObjectSet& rSet = m_setObjects[getHash(pIdentifier)]; - ObjectSet::iterator it = rSet.find (NewObject); - if (it == rSet.end()) - { - // there's no such object in the map, add it - rSet.insert (NewObject); - ComponentName& CompName = m_arrNames[getCurrentName()]; - CompName.numObjects += nCount; - CompName.sizeObjects += sizeBytes; - - m_nTotalSize += sizeBytes; - return true; - } - else - { - Object* pObj = const_cast(&(*it)); - - // if we do an heap check, don't accept the same object twice - if (sizeBytes != pObj->nSize) - { - // if the following assert fails: - // assert (0); - // .. it means we have one object that's added two times with different sizes; that's screws up the whole idea - // we assume there are two different objects that are for some reason assigned the same id - pObj->nSize += sizeBytes; // anyway it's an invalid situation - ComponentName& CompName = m_arrNames[getCurrentName()]; - CompName.sizeObjects += sizeBytes; - return true; // yes we added the object, though there were an error condition - } - - return false; - } -} - -size_t CrySizerImpl::GetObjectCount() -{ - size_t count = m_stackNames.size(); - for (int i = 0; i < g_nHashSize; i++) - { - count += m_setObjects[i].size(); - } - return count; -} - - -// finalizes data collection, should be called after all objects have been added -void CrySizerImpl::End() -{ - // clean up the totals of each name - int i; - for (i = 0; i < m_arrNames.size(); ++i) - { - assert (i == 0 || ((int)m_arrNames[i].nParent < i && m_arrNames[i].nParent >= 0)); - m_arrNames[i].sizeObjectsTotal = m_arrNames[i].sizeObjects; - } - - // add the component's size to the total size of the parent. - // for every component, all their children are put after them in the name array - // we don't include the root because it doesn't belong to any other parent (nowhere further to add) - for (i = m_arrNames.size() - 1; i > 0; --i) - { - // the parent's total size is increased by the _total_ size (already calculated) of this object - m_arrNames[m_arrNames[i].nParent].sizeObjectsTotal += m_arrNames[i].sizeObjectsTotal; - } -} - - -void CrySizerImpl::clear() -{ - for (unsigned i = 0; i < g_nHashSize; ++i) - { - m_setObjects[i].clear(); - } - - m_arrNames.clear(); - m_arrNames.push_back("TOTAL"); // the default name, with index 0 - m_stackNames.clear(); - m_stackNames.push_back(0); - m_LastObject.pId = NULL; - - if (m_pResourceCollector) - { - m_pResourceCollector->Reset(); - } -} - -// hash function for an address; returns value 0..1<> 4) & (g_nHashSize-1); - - // pseudorandomizing transform - ldiv_t Qrem = (ldiv_t)ldiv(((uint32)(UINT_PTR)pId >> 2), 127773); - Qrem.rem = 16807 * Qrem.rem - 2836 * Qrem.quot; - if (Qrem.rem < 0) - { - Qrem.rem += 2147483647; // 0x7FFFFFFF - } - return ((unsigned)Qrem.rem) & (g_nHashSize - 1); -} -unsigned CrySizerImpl::GetDepthLevel(unsigned nCurrent) -{ - uint32 nDepth = 0; - nCurrent = m_arrNames[nCurrent].nParent; - while (nCurrent != 0) - { - nDepth++; - nCurrent = m_arrNames[nCurrent].nParent; - } - return nDepth; -} - diff --git a/Code/CryEngine/CrySystem/CrySizerImpl.h b/Code/CryEngine/CrySystem/CrySizerImpl.h deleted file mode 100644 index f43ee25297..0000000000 --- a/Code/CryEngine/CrySystem/CrySizerImpl.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. - -// Description : Implementation of the ICrySizer interface, which is used to -// calculate the memory usage by the subsystems and components, to help -// the artists keep the memory budged low. - - -#ifndef CRYINCLUDE_CRYSYSTEM_CRYSIZERIMPL_H -#define CRYINCLUDE_CRYSYSTEM_CRYSIZERIMPL_H -#pragma once - - - -// prerequisities - -////////////////////////////////////////////////////////////////////////// -// implementation of interface ICrySizer -// ICrySizer is passed to all subsystems and has a lot of helper functions that -// are compiled in the appropriate subsystems. CrySizerImpl is created in CrySystem -// and is passed to all the other subsystems -class CrySizerImpl - : public ICrySizer -{ -public: - CrySizerImpl(); - ~CrySizerImpl(); - - virtual void Release() { delete this; } - virtual size_t GetTotalSize() { return m_nTotalSize; }; - virtual size_t GetObjectCount(); - - void Reset(); - - // adds an object identified by the unique pointer (it needs not be - // the actual object position in the memory, though it would be nice, - // but it must be unique throughout the system and unchanging for this object) - // RETURNS: true if the object has actually been added (for the first time) - // and calculated - virtual bool AddObject (const void* pIdentifier, size_t nSizeBytes, int nCount = 1); - - virtual IResourceCollector* GetResourceCollector(); - - // finalizes data collection, should be called after all objects have been added - void End(); - - void clear(); - - // Arguments: - // pColl - can be 0 - void SetResourceCollector(IResourceCollector* pColl) { m_pResourceCollector = pColl; } - -protected: - - IResourceCollector* m_pResourceCollector; // - - // these functions must operate on the component name stack - // they are to be only accessible from within class CrySizerComponentNameHelper - // which should be used through macro SIZER_COMPONENT_NAME - virtual void Push (const char* szComponentName); - virtual void PushSubcomponent (const char* szSubcomponentName); - virtual void Pop (); - - // searches for the name in the name array; adds the name if it's not there and returns the index - size_t getNameIndex (size_t nParent, const char* szComponentName); - - // returns the index of the current name on the top of the name stack - size_t getCurrentName() const; - -protected: - friend class CrySizerStatsBuilder; - - // the stack of subsystem names; the indices in the name array are kept, not the names themselves - typedef DynArray NameStack; - NameStack m_stackNames; - - // the array of names; each name ever pushed on the stack is present here - struct ComponentName - { - ComponentName (){} - ComponentName (const char* szName, size_t parent = 0) - : strName (szName) - , nParent (parent) - , numObjects(0) - , sizeObjects (0) - , sizeObjectsTotal (0) - { - } - - void assign (const char* szName, size_t parent = 0) - { - strName = szName; - nParent = parent; - numObjects = 0; - sizeObjects = 0; - sizeObjectsTotal = 0; - arrChildren.clear(); - } - - // the component name, not including the parents' names - string strName; - // the index of the parent, 0 being the root - size_t nParent; - // the number of objects within this component - size_t numObjects; - // the size of the objects belonging to this component, in bytes - size_t sizeObjects; - // the total size of all objects; gets filled by the end() method of the CrySizerImpl - size_t sizeObjectsTotal; - // the children components - DynArray arrChildren; - }; - typedef DynArray NameArray; - NameArray m_arrNames; - - - - // the set of objects and their sizes: the key is the object address/id, - // the value is the size of the object and its name (the index of the name actually) - struct Object - { - const void* pId; // unique pointer identifying the object in memory - size_t nSize; // the size of the object in bytes - size_t nName; // the index of the name in the name array - - Object () - {clear(); } - - Object (const void* id, size_t size = 0, size_t name = 0) - : pId(id) - , nSize(size) - , nName(name) {} - - // the objects are sorted by their Id - bool operator < (const Object& right) const {return (UINT_PTR)pId < (UINT_PTR)right.pId; } - bool operator < (const void* right) const {return (UINT_PTR)pId < (UINT_PTR)right; } - //friend bool operator < (const void* left, const Object& right); - - bool operator == (const Object& right) const {return pId == right.pId; } - - void clear() - { - pId = NULL; - nSize = 0; - nName = 0; - } - }; - typedef std::set ObjectSet; - // 2^g_nHashPower == the number of subsets comprising the hash - - enum - { - g_nHashPower = 12 - }; - - // hash size (number of subsets) - enum - { - g_nHashSize = 1 << g_nHashPower - }; - // hash function for an address; returns value 0..1< 0x10000000 ? 0 : nMinSubcomponentBytes) -{ -} - - -// creates the map of names from old (in the sizer Impl) to new (in the Stats) -void CrySizerStatsBuilder::processNames() -{ - size_t numCompNames = m_pSizer->m_arrNames.size(); - m_pStats->m_arrComponents.reserve (numCompNames); - m_pStats->m_arrComponents.clear(); - - m_mapNames.resize (numCompNames, (size_t)-1); - - // add all root objects - addNameSubtree(0, 0); -} - - -////////////////////////////////////////////////////////////////////////// -// given the name in the old system, adds the subtree of names to the -// name map and components. In case all the subtree is empty, returns false and -// adds nothing -size_t CrySizerStatsBuilder::addNameSubtree (unsigned nDepth, size_t nName) -{ - assert ((int)nName < m_pSizer->m_arrNames.size()); - - CrySizerImpl::ComponentName& rCompName = m_pSizer->m_arrNames[nName]; - size_t sizeObjectsTotal = rCompName.sizeObjectsTotal; - - if (sizeObjectsTotal <= m_nMinSubcomponentBytes) - { - return sizeObjectsTotal; // the subtree didn't pass - } - // the index of the component in the stats object (sorted by the depth-first traverse order) - size_t nNewName = m_pStats->m_arrComponents.size(); - m_pStats->m_arrComponents.resize (nNewName + 1); - - Component& rNewComp = m_pStats->m_arrComponents[nNewName]; - rNewComp.strName = rCompName.strName; - rNewComp.nDepth = nDepth; - rNewComp.numObjects = rCompName.numObjects; - rNewComp.sizeBytes = rCompName.sizeObjects; - rNewComp.sizeBytesTotal = sizeObjectsTotal; - m_mapNames[nName] = nNewName; - - // find the immediate children and sort them by their total size - typedef std::map UintUintMap; - UintUintMap mapSizeName; // total size -> child index (name in old indexation) - - for (int i = nName + 1; i < m_pSizer->m_arrNames.size(); ++i) - { - CrySizerImpl::ComponentName& rChild = m_pSizer->m_arrNames[i]; - if (rChild.nParent == nName && rChild.sizeObjectsTotal > m_nMinSubcomponentBytes) - { - mapSizeName.insert (UintUintMap::value_type(rChild.sizeObjectsTotal, i)); - } - } - - // add the sorted components - /* - for (unsigned i = nName + 1; i < m_pSizer->m_arrNames.size(); ++i) - if (m_pSizer->m_arrNames[i].nParent == nName) - addNameSubtree(nDepth+1,i); - */ - - for (UintUintMap::reverse_iterator it = mapSizeName.rbegin(); it != mapSizeName.rend(); ++it) - { - addNameSubtree(nDepth + 1, it->second); - } - - return sizeObjectsTotal; -} - - -////////////////////////////////////////////////////////////////////////// -// creates the statistics out of the given CrySizerImpl into the given CrySizerStats -// Maps the old to new names according to the depth-walk tree rule -void CrySizerStatsBuilder::build (CrySizerStats* pStats) -{ - m_pStats = pStats; - - m_mapNames.clear(); - - processNames(); - - m_pSizer->clear(); - pStats->refresh(); - pStats->m_nAgeFrames = 0; -} - - -////////////////////////////////////////////////////////////////////////// -// constructs the statistics based on the given cry sizer -CrySizerStats::CrySizerStats (CrySizerImpl* pCrySizer) -{ - CrySizerStatsBuilder builder (pCrySizer); - builder.build(this); -} - -CrySizerStats::CrySizerStats () - : m_nStartRow(0) -{ -} - -void CrySizerStats::updateKeys() -{ - const unsigned int statSize = size(); - //assume 10 pixels for font - unsigned int height = gEnv->pRenderer->GetHeight() / 12; - if (CryGetAsyncKeyState(VK_UP)) - { - if (m_nStartRow > 0) - { - --m_nStartRow; - } - } - if (CryGetAsyncKeyState(VK_DOWN)) - { - if (statSize > height + m_nStartRow) - { - ++m_nStartRow; - } - } - if (CryGetAsyncKeyState(VK_RIGHT) & 1) - { - //assume 10 pixels for font - if (statSize > height) - { - m_nStartRow = statSize - height; - } - } - if (CryGetAsyncKeyState(VK_LEFT) & 1) - { - m_nStartRow = 0; - } -} - -// if there is already such name in the map, then just returns the index -// of the compoentn in the component array; otherwise adds an entry to themap -// and to the component array nad returns its index -CrySizerStatsBuilder::Component& CrySizerStatsBuilder::mapName (unsigned nName) -{ - assert (m_mapNames[nName] != -1); - return m_pStats->m_arrComponents[m_mapNames[nName]]; - /* - IdToIdMap::iterator it = m_mapNames.find (nName); - if (it == m_mapNames.end()) - { - unsigned nNewName = m_arrComponents.size(); - m_mapNames.insert (IdToIdMap::value_type(nName, nNewName)); - m_arrComponents.resize(nNewName + 1); - m_arrComponents[nNewName].strName.swap(m_pSizer->m_arrNames[nName]); - return m_arrComponents.back(); - } - else - { - assert (it->second < m_arrComponents.size()); - return m_arrComponents[it->second]; - } - */ -} - -// refreshes the statistics built after the component array is built -void CrySizerStats::refresh() -{ - m_nMaxNameLength = 0; - for (size_t i = 0; i < m_arrComponents.size(); ++i) - { - size_t nLength = m_arrComponents[i].strName.length() + m_arrComponents[i].nDepth; - if (nLength > m_nMaxNameLength) - { - m_nMaxNameLength = nLength; - } - } -} - - -bool CrySizerStats::Component::GenericOrder::operator () (const Component& left, const Component& right) const -{ - return left.strName < right.strName; -} - - -CrySizerStatsRenderer::CrySizerStatsRenderer (ISystem* pSystem, CrySizerStats* pStats, unsigned nMaxSubcomponentDepth, int nMinSubcomponentBytes) - : m_pStats(pStats) - , m_pRenderer(pSystem->GetIRenderer()) - , m_pLog (pSystem->GetILog()) - , m_pTextModeConsole(pSystem->GetITextModeConsole()) - , m_nMinSubcomponentBytes (nMinSubcomponentBytes < 0 || nMinSubcomponentBytes > 0x10000000 ? 0x8000 : nMinSubcomponentBytes) - , m_nMaxSubcomponentDepth (nMaxSubcomponentDepth) -{ -} - - -static void DrawStatsText(float x, float y, float fScale, float color[4], const char* format, ...) -{ - va_list args; - va_start(args, format); - SDrawTextInfo ti; - ti.xscale = fScale; - ti.yscale = fScale; - ti.color[0] = color[0]; - ti.color[1] = color[1]; - ti.color[2] = color[2]; - ti.color[3] = color[3]; - ti.flags = eDrawText_2D | eDrawText_FixedSize | eDrawText_Monospace; - gEnv->pRenderer->DrawTextQueued(Vec3(x, y, 0.5f), ti, format, args); - va_end(args); -} - -void CrySizerStatsRenderer::render(bool bRefreshMark) -{ - if (!m_pStats->size()) - { - return; - } - - int x, y, dx, dy; - m_pRenderer->GetViewport(&x, &y, &dx, &dy); - - // left coordinate of the text - unsigned nNameWidth = (unsigned)(m_pStats->getMaxNameLength() + 1); - if (nNameWidth < 25) - { - nNameWidth = 25; - } - float fCharScaleX = 1.2f; - float fLeft = 0; - float fTop = 8; - float fVStep = 9; - -#ifdef _DEBUG - const char* szCountStr1 = "count"; - const char* szCountStr2 = "_____"; -#else // _DEBUG - const char* szCountStr1 = "", * szCountStr2 = ""; -#endif // _DEBUG - - float fTextColor[4] = {0.9f, 0.85f, 1, 0.85f}; - DrawStatsText(fLeft, fTop, fCharScaleX, fTextColor, - "%-*s total partial %s", nNameWidth, bRefreshMark ? "Memory usage (refresh*)" : "Memory usage (refresh )", szCountStr1); - DrawStatsText(fLeft, fTop + fVStep * 0.25f, fCharScaleX, fTextColor, - "%*s _____ _______ %s", nNameWidth, "", szCountStr2); - - unsigned nSubgroupDepth = 1; - - // different colors used to paint the statistics subgroups - // a new statistic subgroup starts with a new subtree of depth <= specified - float fGray = 0;//0.45f; - float fLightGray = 0.5f;//0.8f; - float fColors[] = - { - fLightGray, fLightGray, fGray, 1, - 1, 1, 1, 1, - fGray, 1, 1, 1, - 1, fGray, 1, 1, - 1, 1, fGray, 1, - fGray, fLightGray, 1, 1, - fGray, 1, fGray, 1, - 1, fGray, fGray, 1 - }; - float* pColor = fColors; - - unsigned statSize = m_pStats->size(); - unsigned startRow = m_pStats->row(); - unsigned i = 0; - for (; i < startRow; ++i) - { - const Component& rComp = (*m_pStats)[i]; - if (rComp.nDepth <= nSubgroupDepth) - { - //switch the color - pColor += 4; - if (pColor >= fColors + sizeof(fColors) / sizeof(fColors[0])) - { - pColor = fColors; - } - - fTop += fVStep * (0.333333f + (nSubgroupDepth - rComp.nDepth) * 0.15f); - } - } - - for (unsigned r = startRow; i < statSize; ++i) - { - const Component& rComp = (*m_pStats)[i]; - if (rComp.nDepth <= nSubgroupDepth) - { - //switch the color - pColor += 4; - if (pColor >= fColors + sizeof(fColors) / sizeof(fColors[0])) - { - pColor = fColors; - } - - fTop += fVStep * (0.333333f + (nSubgroupDepth - rComp.nDepth) * 0.15f); - } - - if (rComp.sizeBytesTotal <= m_nMinSubcomponentBytes || rComp.nDepth > m_nMaxSubcomponentDepth) - { - continue; - } - - fTop += fVStep; - - char szDepth[32] = " .............................."; - if (rComp.nDepth < sizeof(szDepth)) - { - szDepth[rComp.nDepth] = '\0'; - } - - char szSize[32]; - if (rComp.sizeBytes > 0) - { - if (rComp.sizeBytesTotal > rComp.sizeBytes) - { - azsprintf(szSize, "%7.3f %7.3f", rComp.getTotalSizeMBytes(), rComp.getSizeMBytes()); - } - else - { - azsprintf(szSize, " %7.3f", rComp.getSizeMBytes()); - } - } - else - { - assert (rComp.sizeBytesTotal > 0); - azsprintf(szSize, "%7.3f ", rComp.getTotalSizeMBytes()); - } - char szCount[16]; -#ifdef _DEBUG - if (rComp.numObjects) - { - azsprintf(szCount, "%zd" PRIu64 "", rComp.numObjects); - } - else -#endif - szCount[0] = '\0'; - - DrawStatsText(fLeft, fTop, fCharScaleX, pColor, - "%s%-*s:%s%s", szDepth, nNameWidth - rComp.nDepth, rComp.strName.c_str(), szSize, szCount); - - if (m_pTextModeConsole) - { - string text; - text.Format("%s%-*s:%s%s", szDepth, nNameWidth - rComp.nDepth, rComp.strName.c_str(), szSize, szCount); - m_pTextModeConsole->PutText(0, r++, text.c_str()); - } - } - - float fLTGrayColor[4] = {fLightGray, fLightGray, fLightGray, 1.0f}; - fTop += 0.25f * fVStep; - DrawStatsText(fLeft, fTop, fCharScaleX, fLTGrayColor, - "%-*s %s", nNameWidth, "___________________________", "________________"); - fTop += fVStep; - - const char* szOverheadNames[CrySizerStats::g_numTimers] = - { - ".Collection", - ".Transformation", - ".Cleanup" - }; - bool bOverheadsHeaderPrinted = false; - for (i = 0; i < CrySizerStats::g_numTimers; ++i) - { - float fTime = m_pStats->getTime(i); - if (fTime < 20) - { - continue; - } - // print the header - if (!bOverheadsHeaderPrinted) - { - DrawStatsText(fLeft, fTop, fCharScaleX, fTextColor, - "%-*s", nNameWidth, "Overheads"); - fTop += fVStep; - bOverheadsHeaderPrinted = true; - } - - DrawStatsText(fLeft, fTop, fCharScaleX, fTextColor, - "%-*s:%7.1f ms", nNameWidth, szOverheadNames[i], fTime); - fTop += fVStep; - } -} - -void CrySizerStatsRenderer::dump(bool bUseKB) -{ - if (!m_pStats->size()) - { - return; - } - - unsigned nNameWidth = (unsigned)(m_pStats->getMaxNameLength() + 1); - - // left coordinate of the text - m_pLog->LogToFile ("Memory Statistics: %s", bUseKB ? "KB" : "MB"); - m_pLog->LogToFile("%-*s TOTAL partial count", nNameWidth, ""); - - // different colors used to paint the statistics subgroups - // a new statistic subgroup starts with a new subtree of depth <= specified - - for (unsigned i = 0; i < m_pStats->size(); ++i) - { - const Component& rComp = (*m_pStats)[i]; - - if (rComp.sizeBytesTotal <= m_nMinSubcomponentBytes || rComp.nDepth > m_nMaxSubcomponentDepth) - { - continue; - } - - char szDepth[32] = " .............................."; - if (rComp.nDepth < sizeof(szDepth)) - { - szDepth[rComp.nDepth] = '\0'; - } - - char szSize[32]; - if (rComp.sizeBytes > 0) - { - if (rComp.sizeBytesTotal > rComp.sizeBytes) - { - azsprintf(szSize, bUseKB ? "%7.2f %7.2f" : "%7.3f %7.3f", bUseKB ? rComp.getTotalSizeKBytes() : rComp.getTotalSizeMBytes(), bUseKB ? rComp.getSizeKBytes() : rComp.getSizeMBytes()); - } - else - { - azsprintf(szSize, bUseKB ? " %7.2f" : " %7.3f", bUseKB ? rComp.getSizeKBytes() : rComp.getSizeMBytes()); - } - } - else - { - assert (rComp.sizeBytesTotal > 0); - azsprintf(szSize, bUseKB ? "%7.2f " : "%7.3f ", bUseKB ? rComp.getTotalSizeKBytes() : rComp.getTotalSizeMBytes()); - } - char szCount[16]; - - if (rComp.numObjects) - { - azsprintf(szCount, "%8u", (unsigned int)rComp.numObjects); - } - else - { - szCount[0] = '\0'; - } - - m_pLog->LogToFile ("%s%-*s:%s%s", szDepth, nNameWidth - rComp.nDepth, rComp.strName.c_str(), szSize, szCount); - } -} - - -void CrySizerStats::startTimer(unsigned nTimer, ITimer* pTimer) -{ - assert (nTimer < g_numTimers); - m_fTime[nTimer] = pTimer->GetAsyncCurTime(); -} - -void CrySizerStats::stopTimer(unsigned nTimer, ITimer* pTimer) -{ - assert (nTimer < g_numTimers); - m_fTime[nTimer] = 1000 * (pTimer->GetAsyncCurTime() - m_fTime[nTimer]); -} diff --git a/Code/CryEngine/CrySystem/CrySizerStats.h b/Code/CryEngine/CrySystem/CrySizerStats.h deleted file mode 100644 index fc8c43a7c2..0000000000 --- a/Code/CryEngine/CrySystem/CrySizerStats.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. - -// Description : Declaration of the CrySizerStats class, which is used to -// calculate the memory usage by the subsystems and components, to help -// the artists keep the memory budged low. - -#ifndef CRYINCLUDE_CRYSYSTEM_CRYSIZERSTATS_H -#define CRYINCLUDE_CRYSYSTEM_CRYSIZERSTATS_H -#pragma once - - -class CrySizerImpl; - -////////////////////////////////////////////////////////////////////////// -// This class holds only the necessary statistics data, which can be carried -// over a few frames without significant impact on memory usage -// CrySizerImpl is an implementation of ICrySizer, which is used to collect -// those data; it must be destructed immediately after constructing the Stats -// object to avoid excessive memory usage. -class CrySizerStats -{ -public: - // constructs the statistics based on the given cry sizer - CrySizerStats (CrySizerImpl* pCrySizer); - - CrySizerStats (); - - // this structure describes one component of the memory size statistics - struct Component - { - Component() {clear(); } - Component (const string& name, unsigned size = 0, unsigned num = 0) - : strName(name) - , sizeBytes(size) - , numObjects(num) - , nDepth(0) {} - void clear() - { - strName = ""; - sizeBytes = 0; - numObjects = 0; - nDepth = 0; - } - - // the name of the component, as it appeared in the push() call - string strName; - // the total size, in bytes, of objects in the component - size_t sizeBytes; - // the total size including the subcomponents - size_t sizeBytesTotal; - // the number of objects allocated - size_t numObjects; - unsigned nDepth; - - float getSizeKBytes() const {return sizeBytes / float(1 << 10); } - - float getTotalSizeKBytes () const {return sizeBytesTotal / float(1 << 10); } - - float getSizeMBytes() const {return sizeBytes / float(1 << 20); } - - float getTotalSizeMBytes () const {return sizeBytesTotal / float(1 << 20); } - - struct NameOrder - { - bool operator () (const Component& left, const Component& right) const {return left.strName < right.strName; } - }; - - struct SizeOrder - { - bool operator () (const Component& left, const Component& right) const {return left.sizeBytes < right.sizeBytes; } - }; - - struct GenericOrder - { - bool operator () (const Component& left, const Component& right) const; - }; - }; - - // returns the number of different subsystems/components used - unsigned numComponents() const {return (unsigned)m_arrComponents.size(); } - // returns the name of the i-th component - const Component& getComponent(unsigned nComponent) const {return m_arrComponents[nComponent]; } - - unsigned size() const {return numComponents(); } - const Component& operator [] (unsigned i) const {return getComponent(i); } - const Component& operator [] (signed i) const {return getComponent(i); } - - unsigned row() const {return m_nStartRow; } - void updateKeys(); - - size_t getMaxNameLength() const {return m_nMaxNameLength; } - enum - { - g_numTimers = 3 - }; - - void startTimer(unsigned nTimer, ITimer* pTimer); - void stopTimer(unsigned nTimer, ITimer* pTimer); - float getTime(unsigned nTimer) const {assert (nTimer < g_numTimers); return m_fTime[nTimer]; } - int getAgeFrames() const {return m_nAgeFrames; } - void incAgeFrames() {++m_nAgeFrames; } -protected: - // refreshes the statistics built after the component array is built - void refresh(); -protected: - // the names of the components - typedef std::vector ComponentArray; - ComponentArray m_arrComponents; - - // the maximum length of the component name, in characters - size_t m_nMaxNameLength; - - // the timer that counts the time spent on statistics gathering - float m_fTime[g_numTimers]; - - // the age of the statistics, in frames - int m_nAgeFrames; - - //current row offset inc/dec by cursor keys - unsigned m_nStartRow; - - friend class CrySizerStatsBuilder; -}; - - -////////////////////////////////////////////////////////////////////////// -// this is the constructor for the CrySizerStats -class CrySizerStatsBuilder -{ -public: - CrySizerStatsBuilder (CrySizerImpl* pSizer, int nMinSubcomponentBytes = 0); - - void build (CrySizerStats* pStats); - -protected: - typedef CrySizerStats::Component Component; - // if there is already such name in the map, then just returns the index - // of the compoentn in the component array; otherwise adds an entry to themap - // and to the component array nad returns its index - Component& mapName (unsigned nName); - - // creates the map of names from old to new, and initializes the components themselves - void processNames(); - - // given the name in the old system, adds the subtree of names to the - // name map and components. In case all the subtree is empty, returns 0 and - // adds nothing. Otherwise, returns the total size of objects belonging to the - // subtree - size_t addNameSubtree (unsigned nDepth, size_t nName); - -protected: - CrySizerStats* m_pStats; - CrySizerImpl* m_pSizer; - - // this is the mapping from the old names into the new componentn indices - typedef std::vector IdToIdMap; - // from old to new - IdToIdMap m_mapNames; - - // this is the threshold: if the total number of bytes in the subcomponent - // is less than this, the subcomponent isn't shown - unsigned m_nMinSubcomponentBytes; -}; - - - -////////////////////////////////////////////////////////////////////////// -// Renders the given usage stats; gets created upon every rendering -class CrySizerStatsRenderer -{ -public: - // constructor - CrySizerStatsRenderer (ISystem* pSystem, CrySizerStats* pStats, unsigned nMaxDepth = 2, int nMinSubcomponentBytes = -1); - void render(bool bRefreshMark = false); - // dumps it to log. uses MB as default - void dump (bool bUseKB = false); - -protected: // ------------------------------------------------- - - typedef CrySizerStats::Component Component; - - IRenderer* m_pRenderer; // - ILog* m_pLog; // - CrySizerStats* m_pStats; // - - ITextModeConsole* m_pTextModeConsole; - - // this is the threshold: if the total number of bytes in the subcomponent - // is less than this, the subcomponent isn't shown - unsigned m_nMinSubcomponentBytes; - - // the max depth of the branch to output - unsigned m_nMaxSubcomponentDepth; -}; - -#endif // CRYINCLUDE_CRYSYSTEM_CRYSIZERSTATS_H 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 da3876a422..0000000000 --- a/Code/CryEngine/CrySystem/DebugCallStack.cpp +++ /dev/null @@ -1,949 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS 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); - } - - if (gEnv->pRenderer) - { - ID3DDebugMessage* pMsg = 0; - gEnv->pRenderer->EF_Query(EFQ_GetLastD3DDebugMessage, pMsg); - if (pMsg) - { - const char* pStr = pMsg->GetMessage(); - WriteLineToLog("Last D3D debug message: %s", pStr ? pStr : "#unknown#"); - SAFE_RELEASE(pMsg); - } - } - } - - 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); - - // If in full screen minimize render window - { - ICVar* pFullscreen = (gEnv && gEnv->pConsole) ? gEnv->pConsole->GetCVar("r_Fullscreen") : 0; - if (pFullscreen && pFullscreen->GetIVal() != 0 && gEnv->pRenderer && gEnv->pRenderer->GetHWND()) - { - ::ShowWindow((HWND)gEnv->pRenderer->GetHWND(), SW_MINIMIZE); - } - } - - //hwndException = CreateDialog( gDLLHandle,MAKEINTRESOURCE(IDD_EXCEPTION),NULL,NULL ); - - 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/DefragAllocator.cpp b/Code/CryEngine/CrySystem/DefragAllocator.cpp deleted file mode 100644 index 8858724be1..0000000000 --- a/Code/CryEngine/CrySystem/DefragAllocator.cpp +++ /dev/null @@ -1,1976 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS 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 "DefragAllocator.h" -#include "IRenderAuxGeom.h" - -CDefragAllocatorWalker::CDefragAllocatorWalker(CDefragAllocator& alloc) -{ - m_pAlloc = &alloc; - m_pAlloc->m_lock.Lock(); - - m_nChunkIdx = CDefragAllocator::AddrStartSentinal; -} - -CDefragAllocatorWalker::~CDefragAllocatorWalker() -{ - m_pAlloc->m_lock.Unlock(); -} - -const SDefragAllocChunk* CDefragAllocatorWalker::Next() -{ - m_nChunkIdx = m_pAlloc->m_chunks[m_nChunkIdx].addrNextIdx; - if (m_nChunkIdx == CDefragAllocator::AddrEndSentinal) - { - return NULL; - } - return &m_pAlloc->m_chunks[m_nChunkIdx]; -} - -CDefragAllocator::CDefragAllocator() - : m_isThreadSafe(false) - , m_chunksAreFixed(false) - , m_capacity(0) - , m_available(0) - , m_numAllocs(0) - , m_minAlignment(1) - , m_logMinAlignment(0) - , m_nCancelledMoves(0) -{ -} - -CDefragAllocator::~CDefragAllocator() -{ -} - -void CDefragAllocator::Release(bool bDiscard) -{ - if (!bDiscard) - { - if (m_policy.pDefragPolicy) - { - Defrag_CompletePendingMoves(); - } - - for (PendingMoveVec::iterator it = m_pendingMoves.begin(), itEnd = m_pendingMoves.end(); it != itEnd; ++it) - { - CDBA_ASSERT(it->dstChunkIdx == InvalidChunkIdx); - } - } - - delete this; -} - -void CDefragAllocator::Init(UINT_PTR capacity, UINT_PTR minAlignment, const Policy& policy) -{ - CDBA_ASSERT((capacity & (minAlignment - 1)) == 0); - CDBA_ASSERT((minAlignment & (minAlignment - 1)) == 0); - CDBA_ASSERT(!policy.pDefragPolicy || policy.maxAllocs > 0); - CDBA_ASSERT((capacity / minAlignment) < (1 << SDefragAllocChunkAttr::SizeWidth)); - - uint32 logMinAlignment = (uint32)IntegerLog2(minAlignment); - - capacity >>= logMinAlignment; - - CDBA_ASSERT(capacity <= (uint32) - 1); - - m_isThreadSafe = policy.pDefragPolicy != NULL; - - m_capacity = (uint32)capacity; - m_available = (uint32)capacity; - m_numAllocs = 0; - - m_minAlignment = (uint32)minAlignment; - m_logMinAlignment = logMinAlignment; - - m_chunks.clear(); - m_unusedChunks.clear(); - - m_policy = policy; - if (policy.pDefragPolicy) - { - m_pendingMoves.resize(MaxPendingMoves); - } - - m_chunks.reserve(NumBuckets + 3); - - // Create sentinal chunk for by-address list - { - SDefragAllocChunk addrStartSentinal = {0}; - addrStartSentinal.addrNextIdx = 1; - addrStartSentinal.addrPrevIdx = 1; - addrStartSentinal.attr.SetBusy(true); - addrStartSentinal.ptr = 0; - m_chunks.push_back(addrStartSentinal); - - SDefragAllocChunk addrEndSentinal = {0}; - addrEndSentinal.addrNextIdx = 0; - addrEndSentinal.addrPrevIdx = 0; - addrEndSentinal.attr.SetBusy(true); - addrEndSentinal.ptr = m_capacity; - m_chunks.push_back(addrEndSentinal); - } - - SDefragAllocSegment seg; - seg.address = 0; - seg.capacity = (uint32)capacity; - seg.headSentinalChunkIdx = AddrStartSentinal; - - // Create sentinal chunks for the bucket lists - for (size_t bucketIdx = 0; bucketIdx < NumBuckets; ++bucketIdx) - { - Index chunkIdx = bucketIdx + 2; - - SDefragAllocChunk chunk = {0}; - chunk.attr.SetBusy(true); - chunk.freeNextIdx = chunkIdx; - chunk.freePrevIdx = chunkIdx; - - m_freeBuckets[bucketIdx] = chunkIdx; - m_chunks.push_back(chunk); - } - - Index totalChunkIdx = AllocateChunk(); - SDefragAllocChunk& totalChunk = m_chunks[totalChunkIdx]; - totalChunk.attr.SetSize((unsigned int)capacity); - totalChunk.attr.SetPinCount(0); - totalChunk.attr.SetMoving(0); - LinkAddrChunk(totalChunkIdx, 0); - LinkFreeChunk(totalChunkIdx); - - if (policy.maxAllocs > 0) - { - size_t curChunksSize = m_chunks.size(); - m_chunks.resize(policy.maxAllocs); - for (Index i = (Index)curChunksSize, c = (Index)m_chunks.size(); i < c; ++i) - { - m_unusedChunks.push_back(i); - } - } - - m_chunksAreFixed = policy.pDefragPolicy != NULL; - - m_segments.reserve(policy.maxSegments); - m_segments.push_back(seg); -} - -#ifndef _RELEASE -void CDefragAllocator::DumpState(const char* filename) -{ - CryOptionalAutoLock lock(m_lock, m_isThreadSafe); - - FILE* fp = nullptr; - azfopen(&fp, filename, "wb"); - if (fp) - { - uint32 magic = 0xdef7a6e7; - fwrite(&magic, sizeof(magic), 1, fp); - - fwrite(&m_capacity, sizeof(m_capacity), 1, fp); - fwrite(&m_available, sizeof(m_available), 1, fp); - fwrite(&m_numAllocs, sizeof(m_numAllocs), 1, fp); - fwrite(&m_minAlignment, sizeof(m_minAlignment), 1, fp); - fwrite(&m_logMinAlignment, sizeof(m_logMinAlignment), 1, fp); - fwrite(&m_freeBuckets[0], sizeof(m_freeBuckets), 1, fp); - - uint32 numChunks = (uint32)m_chunks.size(); - fwrite(&numChunks, sizeof(numChunks), 1, fp); - fwrite(&m_chunks[0], sizeof(m_chunks[0]), numChunks, fp); - uint32 numUnused = (uint32)m_unusedChunks.size(); - fwrite(&numUnused, sizeof(numUnused), 1, fp); - fwrite(&m_unusedChunks[0], sizeof(m_unusedChunks[0]), numUnused, fp); - uint32 numPending = (uint32)m_pendingMoves.size(); - fwrite(&numPending, sizeof(numPending), 1, fp); - fwrite(&m_pendingMoves[0], sizeof(m_pendingMoves[0]), numPending, fp); - uint32 numSegs = (uint32)m_segments.size(); - fwrite(&numSegs, sizeof(numSegs), 1, fp); - fwrite(&m_segments[0], sizeof(m_segments[0]), numSegs, fp); - - fclose(fp); - } -} - -void CDefragAllocator::RestoreState(const char* filename) -{ - CryOptionalAutoLock lock(m_lock, m_isThreadSafe); - - FILE* fp = nullptr; - azfopen(&fp, filename, "rb"); - if (fp) - { - uint32 magic; - fread(&magic, sizeof(magic), 1, fp); - - bool bSwap = magic == 0xe7a6f7de; - - fread(&m_capacity, sizeof(m_capacity), 1, fp); - SwapEndian(m_capacity, bSwap); - - fread(&m_available, sizeof(m_available), 1, fp); - SwapEndian(m_available, bSwap); - - fread(&m_numAllocs, sizeof(m_numAllocs), 1, fp); - SwapEndian(m_numAllocs, bSwap); - - fread(&m_minAlignment, sizeof(m_minAlignment), 1, fp); - SwapEndian(m_minAlignment, bSwap); - - fread(&m_logMinAlignment, sizeof(m_logMinAlignment), 1, fp); - SwapEndian(m_logMinAlignment, bSwap); - - fread(&m_freeBuckets[0], sizeof(m_freeBuckets), 1, fp); - SwapEndian(&m_freeBuckets[0], NumBuckets, bSwap); - - uint32 numChunks; - fread(&numChunks, sizeof(numChunks), 1, fp); - SwapEndian(numChunks, bSwap); - - m_chunks.resize(numChunks); - fread(&m_chunks[0], sizeof(m_chunks[0]), numChunks, fp); - if (bSwap) - { - for (size_t ci = 0, cc = m_chunks.size(); ci != cc; ++ci) - { - m_chunks[ci].SwapEndian(); - } - } - - uint32 numUnused; - fread(&numUnused, sizeof(numUnused), 1, fp); - SwapEndian(numUnused, bSwap); - - m_unusedChunks.resize(numUnused); - fread(&m_unusedChunks[0], sizeof(m_unusedChunks[0]), numUnused, fp); - SwapEndian(&m_unusedChunks[0], m_unusedChunks.size(), bSwap); - - uint32 numPending; - fread(&numPending, sizeof(numPending), 1, fp); - SwapEndian(numPending, bSwap); - - m_pendingMoves.resize(numPending); - fread(&m_pendingMoves[0], sizeof(m_pendingMoves[0]), numPending, fp); - if (bSwap) - { - for (size_t pi = 0, pc = m_pendingMoves.size(); pi != pc; ++pi) - { - m_pendingMoves[pi].SwapEndian(); - } - } - - uint32 numSegs; - fread(&numSegs, sizeof(numSegs), 1, fp); - SwapEndian(numSegs, bSwap); - - m_segments.resize(numSegs); - fread(&m_segments[0], sizeof(m_segments[0]), numSegs, fp); - if (bSwap) - { - for (size_t si = 0, sc = m_segments.size(); si != sc; ++si) - { - m_segments[si].SwapEndian(); - } - } - - fclose(fp); - - RebuildFreeLists(); - -#ifdef CDBA_MORE_DEBUG - ValidateAddressChain(); - ValidateFreeLists(); -#endif - } -} -#endif - -bool CDefragAllocator::AppendSegment(UINT_PTR capacity) -{ - CDBA_ASSERT((capacity & (m_minAlignment - 1)) == 0); - - bool bSuccessful = false; - - CryOptionalAutoLock lock(m_lock, m_isThreadSafe); - - capacity >>= m_logMinAlignment; - - // Create a sentinal chunk for the head of the new segment. - Index headSentinalIdx = AllocateChunk(); - if (headSentinalIdx != InvalidChunkIdx) - { - // And a free block. - Index freeBlockIdx = AllocateChunk(); - if (freeBlockIdx != InvalidChunkIdx) - { - SDefragAllocChunk& headSentinalChunk = m_chunks[headSentinalIdx]; - SDefragAllocChunk& freeChunk = m_chunks[freeBlockIdx]; - SDefragAllocChunk& addrEndSentinal = m_chunks[AddrEndSentinal]; - - uint32 allocCapacity = m_capacity; - - headSentinalChunk.ptr = allocCapacity; -#ifndef _RELEASE - headSentinalChunk.source = "Segment Sentinal"; -#endif - headSentinalChunk.attr.SetBusy(true); - headSentinalChunk.attr.SetMoving(false); - headSentinalChunk.attr.SetPinCount(1); - headSentinalChunk.attr.SetSize(0); - - freeChunk.ptr = allocCapacity; - freeChunk.attr.SetBusy(false); - freeChunk.attr.SetMoving(false); - freeChunk.attr.SetPinCount(0); - freeChunk.attr.SetSize((unsigned int)capacity); - - LinkAddrChunk(headSentinalIdx, addrEndSentinal.addrPrevIdx); - LinkAddrChunk(freeBlockIdx, headSentinalIdx); - LinkFreeChunk(freeBlockIdx); - addrEndSentinal.ptr = allocCapacity + (uint32)capacity; - - SDefragAllocSegment seg; - seg.address = allocCapacity; - seg.capacity = (uint32)capacity; - seg.headSentinalChunkIdx = headSentinalIdx; - m_segments.push_back(seg); - - m_capacity = allocCapacity + (uint32)capacity; - m_available += (uint32)capacity; - bSuccessful = true; - -#ifdef CDBA_MORE_DEBUG - ValidateAddressChain(); -#endif - } - else - { - ReleaseChunk(headSentinalIdx); - } - } - - return bSuccessful; -} - -void CDefragAllocator::UnAppendSegment() -{ - CryOptionalAutoLock lock(m_lock, m_isThreadSafe); - - // Can't remove the last segment! - CDBA_ASSERT(m_segments.size() > 1); - - [[maybe_unused]] bool bHasMoves = Defrag_CompletePendingMoves(); - - // All outstanding moves should be completed. - CDBA_ASSERT(!bHasMoves); - - // Move all live chunks from this segment into another. - SyncMoveSegment((uint32)m_segments.size() - 1); - - SDefragAllocSegment& segment = m_segments.back(); - SDefragAllocChunk& headSentinalChunk = m_chunks[segment.headSentinalChunkIdx]; - - // Assert that the segment is empty, and release all chunks within it. - uint32 endAddress = m_capacity; - Index chunkIdx = headSentinalChunk.addrNextIdx; - - UnlinkAddrChunk(segment.headSentinalChunkIdx); - ReleaseChunk(segment.headSentinalChunkIdx); - - SDefragAllocChunk* pChunk = &m_chunks[chunkIdx]; - - while (pChunk->ptr != endAddress) - { - CDBA_ASSERT(!pChunk->attr.IsBusy()); - - Index nextChunkIdx = pChunk->addrNextIdx; - - UnlinkFreeChunk(chunkIdx); - UnlinkAddrChunk(chunkIdx); - ReleaseChunk(chunkIdx); - - chunkIdx = nextChunkIdx; - pChunk = &m_chunks[chunkIdx]; - } - - // chunkIdx/pChunk should be the end of memory sentinal. - CDBA_ASSERT(chunkIdx == AddrEndSentinal && pChunk->attr.IsBusy() && !pChunk->attr.GetSize()); - - pChunk->ptr -= segment.capacity; - - m_capacity -= segment.capacity; - m_available -= segment.capacity; - m_segments.pop_back(); -} - -IDefragAllocator::Hdl CDefragAllocator::Allocate(size_t sz, const char* source, void* pContext) -{ - CDBA_ASSERT((IntegerLog2(NextPower2(Align(sz, m_minAlignment))) - m_logMinAlignment) < (1u << SDefragAllocChunkAttr::SizeWidth)); - - CryOptionalAutoLock lock(m_lock, m_isThreadSafe); - return Allocate_Locked(sz, m_minAlignment, source, pContext); -} - -IDefragAllocator::Hdl CDefragAllocator::AllocateAligned(size_t sz, size_t alignment, const char* source, void* pContext) -{ - alignment = max((size_t)m_minAlignment, alignment); - - // Just to check the alignment can be stored - CDBA_ASSERT((IntegerLog2(alignment) - m_logMinAlignment) < (1u << SDefragAllocChunk::AlignBitCount)); - CDBA_ASSERT((IntegerLog2(NextPower2(Align(sz, alignment))) - m_logMinAlignment) < (1u << SDefragAllocChunkAttr::SizeWidth)); - - CryOptionalAutoLock lock(m_lock, m_isThreadSafe); - return Allocate_Locked(sz, alignment, source, pContext); -} - -IDefragAllocator::AllocatePinnedResult CDefragAllocator::AllocatePinned(size_t sz, const char* source, void* pContext /* = NULL */) -{ - CryOptionalAutoLock lock(m_lock, m_isThreadSafe); - AllocatePinnedResult apr = {0}; - apr.hdl = Allocate_Locked(sz, m_minAlignment, source, pContext); - if (apr.hdl != InvalidHdl) - { - apr.offs = Pin(apr.hdl); - apr.usableSize = CDefragAllocator::UsableSize(apr.hdl); - } - - return apr; -} - -bool CDefragAllocator::Free(Hdl hdl) -{ - CryOptionalAutoLock lock(m_lock, m_isThreadSafe); - - if (hdl != InvalidHdl) - { - // Assume that the allocator now has exclusive ownership of hdl - that is, - // that the caller won't be modifying it externally. - - Index hdlIdx = ChunkIdxFromHdl(hdl); - CDBA_ASSERT(hdlIdx < m_chunks.size()); - - SDefragAllocChunk* chunk = &m_chunks[hdlIdx]; - CDBA_ASSERT(chunk->attr.IsBusy()); - - // Moving state can only be acquired by defrag and released by CancelMove, both own lock as well as Free. - if (chunk->attr.IsMoving()) - { - CancelMove_Locked(hdlIdx, false); - CDBA_ASSERT(!chunk->attr.IsMoving()); - } - - MarkAsFree(*chunk); - MergeFreeBlock(hdlIdx); - - return true; - } - - return false; -} - -void CDefragAllocator::ChangeContext(Hdl hdl, void* pNewContext) -{ - CryOptionalAutoLock lock(m_lock, m_isThreadSafe); - CDBA_ASSERT(hdl != InvalidHdl); - - Index hdlIdx = ChunkIdxFromHdl(hdl); - SDefragAllocChunk& chunk = m_chunks[hdlIdx]; - CDBA_ASSERT(chunk.attr.IsBusy()); - chunk.pContext = pNewContext; -} - -IDefragAllocatorStats CDefragAllocator::GetStats() -{ - CryOptionalAutoLock lock(m_lock, m_isThreadSafe); - - IDefragAllocatorStats stats = {0}; - - stats.nCapacity = static_cast(m_capacity) << m_logMinAlignment; - stats.nInUseSize = static_cast(m_capacity - m_available) << m_logMinAlignment; - stats.nInUseBlocks = m_numAllocs; - - uint32 numFreeBlocks = 0; - uint32 numPinnedBlocks = 0; - uint32 numMovingBlocks = 0; - uint32 maxFreeBlockSize = 0; - uint32 minFreeBlockSize = (uint32) - 1; - - SDefragAllocChunk* pChunks = &m_chunks[0]; - for (Index idx = pChunks[AddrStartSentinal].addrNextIdx; idx != AddrEndSentinal; idx = pChunks[idx].addrNextIdx) - { - SDefragAllocChunk& c = pChunks[idx]; - SDefragAllocChunkAttr ca = c.attr; - - if (ca.IsBusy()) - { - if (ca.IsPinned()) - { - ++numPinnedBlocks; - } - if (ca.IsMoving()) - { - ++numMovingBlocks; - } - } - else - { - maxFreeBlockSize = max(maxFreeBlockSize, ca.GetSize()); - minFreeBlockSize = min(minFreeBlockSize, ca.GetSize()); - ++numFreeBlocks; - } - } - - stats.nFreeBlocks = numFreeBlocks; - stats.nPinnedBlocks = numPinnedBlocks - numMovingBlocks - (int)(m_segments.size() - 1); // Each moving block pins a block for the destination - stats.nMovingBlocks = numMovingBlocks; - stats.nLargestFreeBlockSize = maxFreeBlockSize << m_logMinAlignment; - stats.nSmallestFreeBlockSize = minFreeBlockSize << m_logMinAlignment; - stats.nMeanFreeBlockSize = (numFreeBlocks > 0) - ? ((m_available << m_logMinAlignment) / numFreeBlocks) - : 0; - stats.nCancelledMoveCount = (uint32)m_nCancelledMoves; - - return stats; -} - -size_t CDefragAllocator::DefragmentTick(size_t maxMoves, size_t maxAmount, bool bForce) -{ - if (m_isThreadSafe) - { - if (bForce) - { - m_lock.Lock(); - } - else if (!m_lock.TryLock()) - { - return 0; - } - } - - Defrag_CompletePendingMoves(); - - maxMoves = min(maxMoves, (size_t)MaxPendingMoves); - maxMoves = min(maxMoves, m_unusedChunks.size()); // Assume that each move requires a split - maxAmount >>= m_logMinAlignment; - - PendingMove* moves[MaxPendingMoves]; - size_t numMoves = 0; - size_t curAmount = 0; - -#ifdef CDBA_MORE_DEBUG - Defrag_ValidateFreeBlockIteration(); -#endif - - if (maxMoves > 0) - { - numMoves = Defrag_FindMovesBwd(moves + numMoves, maxMoves - numMoves, curAmount, maxAmount); - if (numMoves < maxMoves) - { - numMoves += Defrag_FindMovesFwd(moves + numMoves, maxMoves - numMoves, curAmount, maxAmount); - } - -#ifdef CDBA_DEBUG - for (size_t moveIdx = 0; moveIdx < numMoves; ++moveIdx) - { - PendingMove& pm = *moves[moveIdx]; - - SDefragAllocChunk& srcChunk = m_chunks[pm.srcChunkIdx]; - SDefragAllocChunk& dstChunk = m_chunks[pm.dstChunkIdx]; - SDefragAllocChunkAttr srcChunkAttr = srcChunk.attr; - SDefragAllocChunkAttr dstChunkAttr = dstChunk.attr; - - CDBA_ASSERT(srcChunkAttr.IsMoving()); - CDBA_ASSERT(dstChunkAttr.IsPinned()); - CDBA_ASSERT(dstChunkAttr.IsBusy()); - CDBA_ASSERT(dstChunkAttr.GetSize() == srcChunkAttr.GetSize()); - } -#endif - } - - if (m_isThreadSafe) - { - m_lock.Unlock(); - } - - return curAmount; -} - -CDefragAllocator::Index CDefragAllocator::AllocateChunk() -{ - Index result = InvalidChunkIdx; - - if (!m_unusedChunks.empty()) - { - result = m_unusedChunks.back(); - m_unusedChunks.pop_back(); - } - else if (!m_chunksAreFixed) - { - m_chunks.push_back(SDefragAllocChunk()); - result = (Index) (m_chunks.size() - 1); - CDBA_ASSERT(result == (m_chunks.size() - 1)); - } - - IF_LIKELY (result != InvalidChunkIdx) - { - SDefragAllocChunk& chunk = m_chunks[result]; - chunk.attr.SetBusy(false); - chunk.attr.SetPinCount(0); - chunk.attr.SetMoving(false); - chunk.pContext = NULL; -#ifndef _RELEASE - chunk.source = ""; -#endif - } - - return result; -} - -void CDefragAllocator::DisplayMemoryUsage([[maybe_unused]] const char* title, [[maybe_unused]] unsigned int allocatorDisplayOffset) -{ -#if !defined(_RELEASE) || defined(PERFORMANCE_BUILD) // We want this vis in Performance builds - if (IRenderAuxGeom* pAuxGeom = gEnv->pRenderer->GetIRenderAuxGeom()) - { - int width = gEnv->pRenderer->GetWidth(); - int height = gEnv->pRenderer->GetHeight(); - - // The height of the bar is 40 pixels, but DrawTriangles is in screen UV coords - const float c_barHeight = 40.0f / height; - - unsigned int currentSize = 0; - unsigned int chunkCount = m_chunks.size(); - AZStd::vector chunkVerts; - chunkVerts.reserve(chunkCount * 4); - AZStd::vector chunkIndices; - chunkIndices.reserve(chunkCount * 6); - AZStd::vector chunkColors; - chunkColors.reserve(chunkCount * 4); - - // Chunks use banded colors to show delineations between adjacent allocations - const ColorB usedColor[2] = { ColorB(255, 0, 0), ColorB(200, 0, 0) }; - const ColorB freeColor[2] = { ColorB(0, 255, 0), ColorB(0, 200, 0) }; - - uint32 i = 0; - float minBarY = 1.0f - allocatorDisplayOffset * c_barHeight; - float maxBarY = 1.0f - (allocatorDisplayOffset + 1) * c_barHeight; - for (size_t idx = m_chunks[0].addrNextIdx; idx != 0; idx = m_chunks[idx].addrNextIdx) - { - SDefragAllocChunk& chunk = m_chunks[idx]; - unsigned int chunkSize = chunk.attr.GetSize(); - if (chunkSize != 0) - { - // Start and end x locations in screen UV coords - float startX = static_cast(currentSize) / m_capacity; - float endX = static_cast(currentSize + chunkSize) / m_capacity; - - // Ensure a valid size is at least one pixel wide - endX = AZStd::max(endX, startX + 1.0f / width); - - chunkVerts.push_back(Vec3(startX, minBarY, 0.0f)); - chunkVerts.push_back(Vec3(endX, minBarY, 0.0f)); - chunkVerts.push_back(Vec3(endX, maxBarY, 0.0f)); - chunkVerts.push_back(Vec3(startX, maxBarY, 0.0f)); - - chunkIndices.push_back(i * 4 + 0); - chunkIndices.push_back(i * 4 + 1); - chunkIndices.push_back(i * 4 + 2); - chunkIndices.push_back(i * 4 + 0); - chunkIndices.push_back(i * 4 + 2); - chunkIndices.push_back(i * 4 + 3); - - if (chunk.attr.IsPinned()) - { - chunkColors.push_back(usedColor[i & 1]); - chunkColors.push_back(usedColor[i & 1]); - chunkColors.push_back(usedColor[i & 1]); - chunkColors.push_back(usedColor[i & 1]); - } - else - { - chunkColors.push_back(freeColor[i & 1]); - chunkColors.push_back(freeColor[i & 1]); - chunkColors.push_back(freeColor[i & 1]); - chunkColors.push_back(freeColor[i & 1]); - } - - currentSize += chunkSize; - i++; - } - } - - SAuxGeomRenderFlags savedFlags = pAuxGeom->GetRenderFlags(); - SAuxGeomRenderFlags tempFlags; - tempFlags.SetMode2D3DFlag(e_Mode2D); - pAuxGeom->SetRenderFlags(tempFlags); - pAuxGeom->DrawTriangles(chunkVerts.data(), chunkVerts.size(), chunkIndices.data(), chunkIndices.size(), chunkColors.data()); - pAuxGeom->SetRenderFlags(savedFlags); - - // Draw other stats about the system - const float statisticsWidth = 384.0f; - float statsXOffset = allocatorDisplayOffset * statisticsWidth; - IDefragAllocatorStats stats = GetStats(); - ColorF statsTextColor(1.0f, 1.0f, 0.5f, 1.0f); - pAuxGeom->Draw2dLabel(10 + statsXOffset, 85, 1.7f, statsTextColor, false, title); - pAuxGeom->Draw2dLabel(20 + statsXOffset, 110, 1.5f, statsTextColor, false, "Capacity (MB): %.2f", stats.nCapacity / 1024.0f / 1024.0f); - pAuxGeom->Draw2dLabel(20 + statsXOffset, 130, 1.5f, statsTextColor, false, "In Use (MB): %.2f", stats.nInUseSize / 1024.0f / 1024.0f); - pAuxGeom->Draw2dLabel(20 + statsXOffset, 150, 1.5f, statsTextColor, false, "In Use Blocks: %u", stats.nInUseBlocks); - pAuxGeom->Draw2dLabel(20 + statsXOffset, 170, 1.5f, statsTextColor, false, "Free Blocks: %u", stats.nFreeBlocks); - pAuxGeom->Draw2dLabel(20 + statsXOffset, 190, 1.5f, statsTextColor, false, "Largest Free Block (B): %u", stats.nLargestFreeBlockSize); - pAuxGeom->Draw2dLabel(20 + statsXOffset, 210, 1.5f, statsTextColor, false, "Smallest Free Block (B): %u", stats.nSmallestFreeBlockSize); - pAuxGeom->Draw2dLabel(20 + statsXOffset, 230, 1.5f, statsTextColor, false, "Mean Free Block (B): %u", stats.nMeanFreeBlockSize); - } -#endif -} - -void CDefragAllocator::ReleaseChunk(Index idx) -{ - m_unusedChunks.push_back(idx); -} - -void CDefragAllocator::LinkFreeChunk(Index idx) -{ - SDefragAllocChunk* pChunks = &m_chunks[0]; - SDefragAllocChunk& chunk = pChunks[idx]; - - CDBA_ASSERT(!chunk.attr.IsBusy()); - - int bucket = BucketForSize(chunk.attr.GetSize()); - - Index rootIdx = m_freeBuckets[bucket]; - Index beforeIdx; - - // Search for the position in the list to insert the new block, maintaining address order - for (beforeIdx = pChunks[rootIdx].freeNextIdx; beforeIdx != rootIdx; beforeIdx = pChunks[beforeIdx].freeNextIdx) - { - if (pChunks[beforeIdx].ptr > chunk.ptr) - { - break; - } - } - - Index afterIdx = pChunks[beforeIdx].freePrevIdx; - SDefragAllocChunk& after = pChunks[afterIdx]; - - chunk.freeNextIdx = after.freeNextIdx; - chunk.freePrevIdx = afterIdx; - pChunks[after.freeNextIdx].freePrevIdx = idx; - after.freeNextIdx = idx; -} - -IDefragAllocator::Hdl CDefragAllocator::Allocate_Locked(size_t sz, size_t alignment, [[maybe_unused]] const char* source, void* pContext) -{ -#if AZ_LEGACY_CRYSYSTEM_TRAIT_USE_BIT64 - CDBA_ASSERT(sz <= (BIT64(NumBuckets))); -#else - CDBA_ASSERT(sz <= (BIT(NumBuckets))); -#endif - - sz = Align(sz, alignment) >> m_logMinAlignment; - alignment >>= m_logMinAlignment; - - if (sz > m_available) - { - return InvalidHdl; - } - - Index bestChunkIdx = InvalidChunkIdx; - switch (m_policy.blockSearchKind) - { - case eBSK_BestFit: - bestChunkIdx = BestFit_FindFreeBlockFor(sz, alignment, 0, ~(uint32)0, true); - break; - case eBSK_FirstFit: - bestChunkIdx = FirstFit_FindFreeBlockFor(sz, alignment, 0, ~(uint32)0, true); - break; - default: - __debugbreak(); - break; - } - - if (bestChunkIdx != InvalidChunkIdx) - { - SplitResult sr = SplitFreeBlock(bestChunkIdx, sz, alignment, true); - - IF_LIKELY (sr.bSuccessful) - { - SDefragAllocChunk& bestChunk = m_chunks[bestChunkIdx]; - CDBA_ASSERT(bestChunk.attr.GetSize() == sz); - - MarkAsInUse(bestChunk); - bestChunk.pContext = pContext; -#ifndef _RELEASE - bestChunk.source = source; -#endif - bestChunk.attr.SetPinCount(0); - bestChunk.attr.SetMoving(false); - - return ChunkHdlFromIdx(bestChunkIdx); - } - } - - return InvalidHdl; -} - -CDefragAllocator::SplitResult CDefragAllocator::SplitFreeBlock(Index fbId, size_t sz, size_t alignment, bool allocateInLowHalf) -{ - CDefragAllocator::SplitResult res; - res.bSuccessful = false; - res.nLeftSplitChunkIdx = InvalidChunkIdx; - res.nRightSplitChunkIdx = InvalidChunkIdx; - - SDefragAllocChunk* allocChunk = &m_chunks[fbId]; - - CDBA_ASSERT(!allocChunk->attr.IsBusy()); - CDBA_ASSERT(sz <= allocChunk->attr.GetSize()); - - if ((allocChunk->ptr & (alignment - 1)) != 0 || allocChunk->attr.GetSize() != sz) - { - // Determine the sizes of the new chunks - UINT_PTR baseAddress = allocChunk->ptr; - UINT_PTR endAddress = allocChunk->ptr + allocChunk->attr.GetSize(); - UINT_PTR allocAddress = allocateInLowHalf - ? Align(baseAddress, alignment) - : ((endAddress - sz) & ~(alignment - 1)); - UINT_PTR allocEndAddress = allocAddress + sz; - - // Allocate split chunks - Index nLeftSplitChunkIdx = InvalidChunkIdx; - if (baseAddress != allocAddress) - { - nLeftSplitChunkIdx = AllocateChunk(); - if (nLeftSplitChunkIdx == InvalidChunkIdx) - { - return res; - } - } - - Index nRightSplitChunkIdx = InvalidChunkIdx; - if (allocEndAddress != endAddress) - { - nRightSplitChunkIdx = AllocateChunk(); - if (nRightSplitChunkIdx == InvalidChunkIdx) - { - if (nLeftSplitChunkIdx != InvalidChunkIdx) - { - ReleaseChunk(nLeftSplitChunkIdx); - } - return res; - } - } - - // Split - UnlinkFreeChunk(fbId); - - allocChunk = &m_chunks[fbId]; - - if (nLeftSplitChunkIdx != InvalidChunkIdx) - { - SDefragAllocChunk& splitChunk = m_chunks[nLeftSplitChunkIdx]; - - splitChunk.ptr = baseAddress; - splitChunk.attr.SetSize((int)(allocAddress - baseAddress)); - LinkAddrChunk(nLeftSplitChunkIdx, allocChunk->addrPrevIdx); - } - - if (nRightSplitChunkIdx != InvalidChunkIdx) - { - SDefragAllocChunk& splitChunk = m_chunks[nRightSplitChunkIdx]; - - splitChunk.ptr = allocEndAddress; - splitChunk.attr.SetSize((int)(endAddress - allocEndAddress)); - LinkAddrChunk(nRightSplitChunkIdx, fbId); - } - - allocChunk->ptr = allocAddress; - allocChunk->attr.SetSize((int)(allocEndAddress - allocAddress)); - allocChunk->logAlign = IntegerLog2(alignment); - - if (nLeftSplitChunkIdx != InvalidChunkIdx) - { - LinkFreeChunk(nLeftSplitChunkIdx); - } - if (nRightSplitChunkIdx != InvalidChunkIdx) - { - LinkFreeChunk(nRightSplitChunkIdx); - } - - res.bSuccessful = true; - res.nLeftSplitChunkIdx = nLeftSplitChunkIdx; - res.nRightSplitChunkIdx = nRightSplitChunkIdx; - } - else - { - // Perfect fit. - UnlinkFreeChunk(fbId); - - res.bSuccessful = true; - } - -#ifdef CDBA_MORE_DEBUG - ValidateFreeLists(); -#endif - - return res; -} - -CDefragAllocator::Index CDefragAllocator::MergeFreeBlock(Index fbId) -{ - SDefragAllocChunk* pChunks = &m_chunks[0]; - - SDefragAllocChunk* chunk = &pChunks[fbId]; - - CDBA_ASSERT(m_available <= m_capacity); - CDBA_ASSERT(!chunk->attr.IsBusy()); - - LinkFreeChunk(fbId); - - Index prevChunkIdx = chunk->addrPrevIdx; - SDefragAllocChunk& prevChunk = pChunks[prevChunkIdx]; - if (!prevChunk.attr.IsBusy()) - { - // Merge with previous chunk - - UnlinkFreeChunk(fbId); - UnlinkFreeChunk(prevChunkIdx); - - prevChunk.attr.AddSize(chunk->attr.GetSize()); - prevChunk.addrNextIdx = chunk->addrNextIdx; - pChunks[chunk->addrNextIdx].addrPrevIdx = prevChunkIdx; - - CDBA_ASSERT(pChunks[prevChunk.addrPrevIdx].ptr + pChunks[prevChunk.addrPrevIdx].attr.GetSize() == prevChunk.ptr); - CDBA_ASSERT(prevChunk.ptr + prevChunk.attr.GetSize() == pChunks[prevChunk.addrNextIdx].ptr); - CDBA_ASSERT(pChunks[prevChunk.addrPrevIdx].addrNextIdx == prevChunkIdx); - CDBA_ASSERT(pChunks[prevChunk.addrNextIdx].addrPrevIdx == prevChunkIdx); - - LinkFreeChunk(prevChunkIdx); - ReleaseChunk(fbId); - - // Pretend the released chunk is the previous one, so the next merge can happen - - fbId = prevChunkIdx; - chunk = &prevChunk; - } - - Index nextChunkIdx = chunk->addrNextIdx; - SDefragAllocChunk& nextChunk = pChunks[nextChunkIdx]; - if (!nextChunk.attr.IsBusy()) - { - // Merge with next chunk - - UnlinkFreeChunk(fbId); - UnlinkFreeChunk(nextChunkIdx); - - chunk->attr.AddSize(nextChunk.attr.GetSize()); - chunk->addrNextIdx = nextChunk.addrNextIdx; - pChunks[chunk->addrNextIdx].addrPrevIdx = fbId; - - CDBA_ASSERT(pChunks[chunk->addrPrevIdx].ptr + pChunks[chunk->addrPrevIdx].attr.GetSize() == chunk->ptr); - CDBA_ASSERT(chunk->ptr + chunk->attr.GetSize() == pChunks[chunk->addrNextIdx].ptr); - CDBA_ASSERT(pChunks[chunk->addrPrevIdx].addrNextIdx == fbId); - CDBA_ASSERT(pChunks[chunk->addrNextIdx].addrPrevIdx == fbId); - - LinkFreeChunk(fbId); - ReleaseChunk(nextChunkIdx); - } - - return fbId; -} - -#ifdef CDBA_MORE_DEBUG -void CDefragAllocator::Defrag_ValidateFreeBlockIteration() -{ - Index freeLists[NumBuckets]; - size_t numFreeLists = 0; - - { - PrepareMergePopPrev(freeLists); - UINT_PTR addr = (UINT_PTR)-1; - - if (numFreeLists) - { - do - { - size_t list = MergePeekPrevChunk(freeLists); - Index chk = freeLists[list]; - UINT_PTR chkAddr = m_chunks[chk].ptr; - CDBA_ASSERT(chkAddr < addr); - addr = chkAddr; - MergePopPrevChunk(freeLists, list); - } while (numFreeLists > 0); - } - } - { - PrepareMergePopNext(freeLists); - UINT_PTR addr = 0; - - if (numFreeLists) - { - do - { - size_t list = MergePeekNextChunk(freeLists); - Index chk = freeLists[list]; - UINT_PTR chkAddr = m_chunks[chk].ptr; - CDBA_ASSERT(chkAddr > addr); - addr = chkAddr; - MergePopNextChunk(freeLists, list); - } while (numFreeLists > 0); - } - } -} -#endif - -CDefragAllocator::Index CDefragAllocator::BestFit_FindFreeBlockForSegment(size_t sz, size_t alignment, uint32 seg) -{ - SDefragAllocSegment& segment = m_segments[seg]; - return BestFit_FindFreeBlockFor(sz, alignment, segment.address, segment.address + segment.capacity, true); -} - -CDefragAllocator::Index CDefragAllocator::BestFit_FindFreeBlockFor(size_t sz, size_t alignment, [[maybe_unused]] UINT_PTR addressMin, UINT_PTR addressMax, bool allocateInLowHalf) -{ - Index bestChunkIdx = InvalidChunkIdx; - UINT_PTR bestWastage = (UINT_PTR)-1; - - for (int bucket = BucketForSize(sz); (bestChunkIdx == InvalidChunkIdx) && (bucket < NumBuckets); ++bucket) - { - size_t rootIdx = m_freeBuckets[bucket]; - SDefragAllocChunk& root = m_chunks[rootIdx]; - - for (size_t idx = root.freeNextIdx; idx != rootIdx; idx = m_chunks[idx].freeNextIdx) - { - SDefragAllocChunk& chunk = m_chunks[idx]; - - CDBA_ASSERT(!chunk.attr.IsBusy()); - CDBA_ASSERT(max(1U, chunk.attr.GetSize()) >= (1U << bucket)); - - if (chunk.ptr < addressMax) - { - UINT_PTR chunkStart = chunk.ptr; - UINT_PTR chunkSize = chunk.attr.GetSize(); - UINT_PTR chunkEnd = chunkStart + chunkSize; - UINT_PTR allocStart = allocateInLowHalf - ? Align(chunkStart, alignment) - : ((chunkEnd - sz) & ~(alignment - 1)); - UINT_PTR allocEnd = allocStart + sz; - - if (chunkStart <= allocStart && allocEnd <= chunkEnd) - { - if (allocStart == chunkStart && chunkSize == sz) - { - bestChunkIdx = idx; - bestWastage = 0; - - break; - } - - UINT_PTR wastage = (allocStart - chunkStart) + (chunkEnd - allocEnd); - if (wastage < bestWastage) - { - bestChunkIdx = idx; - bestWastage = wastage; - } - } - } - else - { - break; - } - } - } - - return bestChunkIdx; -} - -CDefragAllocator::Index CDefragAllocator::FirstFit_FindFreeBlockFor(size_t sz, size_t alignment, [[maybe_unused]] UINT_PTR addressMin, UINT_PTR addressMax, bool allocateInLowHalf) -{ - for (int bucket = BucketForSize(sz); bucket < NumBuckets; ++bucket) - { - size_t rootIdx = m_freeBuckets[bucket]; - SDefragAllocChunk& root = m_chunks[rootIdx]; - for (size_t idx = root.freeNextIdx; idx != rootIdx; idx = m_chunks[idx].freeNextIdx) - { - SDefragAllocChunk& chunk = m_chunks[idx]; - CDBA_ASSERT(!chunk.attr.IsBusy()); - CDBA_ASSERT(max(1U, chunk.attr.GetSize()) >= (1U << bucket)); - if (chunk.ptr < addressMax) - { - UINT_PTR chunkStart = chunk.ptr; - UINT_PTR chunkSize = chunk.attr.GetSize(); - UINT_PTR chunkEnd = chunkStart + chunkSize; - UINT_PTR allocStart = allocateInLowHalf - ? Align(chunkStart, alignment) - : ((chunkEnd - sz) & ~(alignment - 1)); - UINT_PTR allocEnd = allocStart + sz; - if (chunkStart <= allocStart && allocEnd <= chunkEnd) - { - return idx; - } - } - else - { - break; - } - } - } - return InvalidChunkIdx; -} -size_t CDefragAllocator::Defrag_FindMovesBwd(PendingMove** pMoves, size_t maxMoves, size_t& curAmount, size_t maxAmount) -{ - Index freeLists[NumBuckets]; - - size_t numMoves = 0; - bool bIsLast = true; - - PrepareMergePopPrev(freeLists); - - int nSegmentIdx = (int)m_segments.size() - 1; - - // Try and copy a block from the back to the front - do - { - size_t freeChunkList = MergePeekPrevChunk(freeLists); - if (freeChunkList == (size_t)-1) - { - break; - } - - assert(freeChunkList < sizeof(freeLists) / sizeof(freeLists[0])); - Index freeChunkIdx = freeLists[freeChunkList]; - MergePopPrevChunk(freeLists, freeChunkList); - - // Keep track of the last free block in each segment, by watching free blocks - // crossing segment boundaries. - if (nSegmentIdx >= 0) - { - if (m_chunks[freeChunkIdx].ptr < m_segments[nSegmentIdx].address) - { - bIsLast = true; - --nSegmentIdx; - } - } - - // Don't move free block->next blocks if they're at the end of a segment - they're defragged enough. - // TODO - could allow this (and self moves below) if defragging stalls in a bad state - if (!bIsLast) - { - for (Index candidateIdx = m_chunks[freeChunkIdx].addrNextIdx; freeChunkIdx != InvalidChunkIdx && numMoves < maxMoves && curAmount < maxAmount; ) - { - SDefragAllocChunk& freeChunk = m_chunks[freeChunkIdx]; - SDefragAllocChunk& candidateChunk = m_chunks[candidateIdx]; - SDefragAllocChunkAttr candidateChunkAttr = candidateChunk.attr; - - CDBA_ASSERT(!freeChunk.attr.IsBusy()); - - if (IsMoveableCandidate(candidateChunkAttr, 0xffffffff)) - { -#if AZ_LEGACY_CRYSYSTEM_TRAIT_USE_BIT64 - size_t candidateChunkAlign = BIT64(candidateChunk.logAlign); -#else - size_t candidateChunkAlign = BIT(candidateChunk.logAlign); -#endif - - // Try and reallocate this chunk. For the time being, assume that it's going to remain in a valid moveable state. - Index dstChunkIdx = Defrag_Bwd_FindFreeBlockFor(candidateChunkAttr.GetSize(), candidateChunkAlign, freeChunk.ptr);// + freeChunk.attr.GetSize()); - - if (dstChunkIdx != InvalidChunkIdx) - { - PendingMove* pPM = AllocPendingMove(); - IF_UNLIKELY (!pPM) - { - return numMoves; - } - - // Found a possible move, so try and mark the chunk as moveable - as long as it's still a valid candidate. - if (TryMarkAsMoving(candidateChunk, 0xffffffff)) - { - // Chunk has been marked as moveable - can now split the dest chunk and set up the move state. - // If the chunk gets pinned in the meantime, it'll sync (through CancelMove) on the allocator lock. - - if (TryScheduleCopy(candidateChunk, m_chunks[dstChunkIdx], pPM, true)) - { - SplitResult sr = SplitFreeBlock(dstChunkIdx, candidateChunkAttr.GetSize(), candidateChunkAlign, true); - CDBA_ASSERT(sr.bSuccessful); - - MergePatchPrevRemove(freeLists, dstChunkIdx); - - if (sr.nRightSplitChunkIdx != InvalidChunkIdx) - { - MergePatchPrevInsert(freeLists, sr.nRightSplitChunkIdx); - } - - pPM->srcChunkIdx = candidateIdx; - pPM->dstChunkIdx = dstChunkIdx; - - // dstChunk is owned by the allocator, so we don't need to be atomic when changing it's state. - SDefragAllocChunk& dstChunk = m_chunks[dstChunkIdx]; - MarkAsInUse(dstChunk); - dstChunk.attr.SetPinCount(1); - - CDBA_ASSERT(sr.nRightSplitChunkIdx == InvalidChunkIdx || (m_chunks[sr.nRightSplitChunkIdx].ptr > dstChunk.ptr)); - CDBA_ASSERT(dstChunk.ptr < candidateChunk.ptr); - -#ifdef CDBA_MORE_DEBUG - ValidateAddressChain(); -#endif - - pMoves[numMoves++] = pPM; - curAmount += dstChunk.attr.GetSize(); - - candidateIdx = m_chunks[candidateIdx].addrNextIdx; - if (dstChunkIdx == freeChunkIdx) - { - freeChunkIdx = sr.nRightSplitChunkIdx; - } - continue; - } - else - { - MarkAsNotMoving(candidateChunk); - } - } - - // Candidate (probably) got pinned whilst finding a free block, or the copy schedule failed. Nevermind - undo what we need to. - FreePendingMove(pPM); - pPM = NULL; - } - } - - break; - } - } - - if (freeChunkIdx != InvalidChunkIdx) - { - for (Index candidateIdx = m_chunks[freeChunkIdx].addrPrevIdx; numMoves < maxMoves && curAmount < maxAmount; ) - { - SDefragAllocChunk& candidateChunk = m_chunks[candidateIdx]; - SDefragAllocChunkAttr candidateChunkAttr = candidateChunk.attr; - - if (IsMoveableCandidate(candidateChunkAttr, 0xffffffff)) - { -#if AZ_LEGACY_CRYSYSTEM_TRAIT_USE_BIT64 - size_t candidateChunkAlign = BIT64(candidateChunk.logAlign); -#else - size_t candidateChunkAlign = BIT(candidateChunk.logAlign); -#endif - - // Try and reallocate this chunk. For the time being, assume that it's going to remain in a valid moveable state. - Index dstChunkIdx = Defrag_Bwd_FindFreeBlockFor(candidateChunkAttr.GetSize(), candidateChunkAlign, candidateChunk.ptr); - CDBA_ASSERT(dstChunkIdx != freeChunkIdx); - - if (dstChunkIdx != InvalidChunkIdx) - { - PendingMove* pPM = AllocPendingMove(); - IF_UNLIKELY (!pPM) - { - return numMoves; - } - - // Found a possible move, so try and mark the chunk as moveable - as long as it's still a valid candidate. - if (TryMarkAsMoving(candidateChunk, 0xffffffff)) - { - // Chunk has been marked as moveable - can now split the chunk and set up the move state. - // If the chunk gets pinned in the meantime, it'll sync (through CancelMove) on the allocator lock. - - if (TryScheduleCopy(candidateChunk, m_chunks[dstChunkIdx], pPM, true)) - { - SplitResult sr = SplitFreeBlock(dstChunkIdx, candidateChunkAttr.GetSize(), candidateChunkAlign, true); - CDBA_ASSERT(sr.bSuccessful); - - MergePatchPrevRemove(freeLists, dstChunkIdx); - - if (sr.nRightSplitChunkIdx != InvalidChunkIdx) - { - MergePatchPrevInsert(freeLists, sr.nRightSplitChunkIdx); - } - - pPM->srcChunkIdx = candidateIdx; - pPM->dstChunkIdx = dstChunkIdx; - - // dstChunk is owned by the allocator, so don't need to be atomic when changing it's state. - SDefragAllocChunk& dstChunk = m_chunks[dstChunkIdx]; - MarkAsInUse(dstChunk); - dstChunk.attr.SetPinCount(1); - - CDBA_ASSERT(sr.nRightSplitChunkIdx == InvalidChunkIdx || (m_chunks[sr.nRightSplitChunkIdx].ptr > dstChunk.ptr)); - CDBA_ASSERT(dstChunk.ptr < candidateChunk.ptr); - -#ifdef CDBA_MORE_DEBUG - ValidateAddressChain(); -#endif - - pMoves[numMoves++] = pPM; - curAmount += dstChunk.attr.GetSize(); - - candidateIdx = m_chunks[candidateIdx].addrPrevIdx; - continue; - } - else - { - MarkAsNotMoving(candidateChunk); - } - } - - // Candidate (probably) got pinned whilst finding a free block, or the copy schedule failed. Nevermind - undo what we need to. - FreePendingMove(pPM); - pPM = NULL; - } - } - - break; - } - } - bIsLast = false; - } - while (numMoves < maxMoves); - - return numMoves; -} - -size_t CDefragAllocator::Defrag_FindMovesFwd(PendingMove** pMoves, size_t maxMoves, size_t& curAmount, size_t maxAmount) -{ - Index freeLists[NumBuckets]; - - size_t numMoves = 0; - - PrepareMergePopNext(freeLists); - - // Try and copy a block from the front to the back - do - { - size_t freeChunkList = MergePeekNextChunk(freeLists); - if (freeChunkList == (size_t)-1) - { - break; - } - - assert(freeChunkList < sizeof(freeLists) / sizeof(freeLists[0])); - - Index freeChunkIdx = freeLists[freeChunkList]; - MergePopNextChunk(freeLists, freeChunkList); - - CDBA_ASSERT(!m_chunks[freeChunkIdx].attr.IsBusy()); - - for (Index candidateIdx = m_chunks[freeChunkIdx].addrNextIdx; numMoves < maxMoves && curAmount < maxAmount; ) - { - SDefragAllocChunk& freeChunk = m_chunks[freeChunkIdx]; - SDefragAllocChunk& candidateChunk = m_chunks[candidateIdx]; - SDefragAllocChunkAttr candidateChunkAttr = candidateChunk.attr; - - if (IsMoveableCandidate(candidateChunkAttr, 0xffffffff)) - { -#if AZ_LEGACY_CRYSYSTEM_TRAIT_USE_BIT64 - size_t candidateChunkAlign = BIT64(candidateChunk.logAlign); -#else - size_t candidateChunkAlign = BIT(candidateChunk.logAlign); -#endif - - // Try and reallocate this chunk. For the time being, assume that it's going to remain in a valid moveable state. - Index dstChunkIdx = Defrag_Fwd_FindFreeBlockFor(candidateChunkAttr.GetSize(), candidateChunkAlign, freeChunk.ptr + freeChunk.attr.GetSize()); - - CDBA_ASSERT(dstChunkIdx != freeChunkIdx); - - if (dstChunkIdx != InvalidChunkIdx) - { - PendingMove* pPM = AllocPendingMove(); - IF_UNLIKELY (!pPM) - { - return numMoves; - } - - CDBA_ASSERT(!m_chunks[dstChunkIdx].attr.IsBusy()); - CDBA_ASSERT(m_chunks[dstChunkIdx].attr.GetSize() >= candidateChunkAttr.GetSize()); - - // Found a possible move, so try and mark the chunk as moveable - as long as it's still a valid candidate. - if (TryMarkAsMoving(candidateChunk, 0xffffffff)) - { - // Chunk has been marked as moveable - can now split the dest chunk and set up the move state. - // If the chunk gets pinned in the meantime, it'll sync (through CancelMove) on the allocator lock. - - if (TryScheduleCopy(candidateChunk, m_chunks[dstChunkIdx], pPM, false)) - { - SplitResult sr = SplitFreeBlock(dstChunkIdx, candidateChunkAttr.GetSize(), candidateChunkAlign, false); - CDBA_ASSERT(sr.bSuccessful); - - MergePatchNextRemove(freeLists, dstChunkIdx); - - if (sr.nLeftSplitChunkIdx != InvalidChunkIdx) - { - MergePatchNextInsert(freeLists, sr.nLeftSplitChunkIdx); - } - - pPM->srcChunkIdx = candidateIdx; - pPM->dstChunkIdx = dstChunkIdx; - - // dstChunk is owned by the allocator, so we don't need to be atomic when changing it's state. - SDefragAllocChunk& dstChunk = m_chunks[dstChunkIdx]; - MarkAsInUse(dstChunk); - dstChunk.attr.SetPinCount(1); - - CDBA_ASSERT(sr.nLeftSplitChunkIdx == InvalidChunkIdx || (m_chunks[sr.nLeftSplitChunkIdx].ptr < dstChunk.ptr)); - CDBA_ASSERT(dstChunk.ptr > candidateChunk.ptr); - -#ifdef CDBA_MORE_DEBUG - ValidateAddressChain(); -#endif - - pMoves[numMoves++] = pPM; - curAmount += dstChunk.attr.GetSize(); - - candidateIdx = m_chunks[candidateIdx].addrNextIdx; - continue; - } - else - { - MarkAsNotMoving(candidateChunk); - } - } - - // Candidate (probably) got pinned whilst finding a free block, or the copy schedule failed. Nevermind - undo what we need to. - FreePendingMove(pPM); - pPM = NULL; - } - } - - break; - } - } - while (numMoves < maxMoves); - - return numMoves; -} - -bool CDefragAllocator::Defrag_CompletePendingMoves() -{ - CDBA_ASSERT(m_policy.pDefragPolicy); - - bool bHasMoves = false; - - for (DynArray::iterator it = m_pendingMoves.begin(), itEnd = m_pendingMoves.end(); it != itEnd; ++it) - { - if (it->notify.bCancel) - { - // Currently only support cancelling before a move has really begun - // Also assume that there is no copy in flight - the policy has requested it, so it's their responsibility to - // make sure that this is the case - CDBA_ASSERT(!it->relocated); - - MarkAsFree(m_chunks[it->dstChunkIdx]); - MergeFreeBlock(it->dstChunkIdx); - - MarkAsNotMoving(m_chunks[it->srcChunkIdx]); - - FreePendingMove(&*it); - } - else - { - if (it->notify.bDstIsValid) - { - if (!it->relocated) - { - CDBA_ASSERT(it->dstChunkIdx != InvalidChunkIdx); - - if (!it->cancelled) - { - Relocate(it->userMoveId, it->srcChunkIdx, it->dstChunkIdx); - } - - it->relocated = true; - } - - if (it->notify.bSrcIsUnneeded) - { - SDefragAllocChunk& dst = m_chunks[it->dstChunkIdx]; - MarkAsFree(dst); - MergeFreeBlock(it->dstChunkIdx); - - if (!it->cancelled) - { - CDBA_ASSERT(it->srcChunkIdx != InvalidChunkIdx); - - SDefragAllocChunk& src = m_chunks[it->srcChunkIdx]; - - // Should be the last thing to occur during move - MarkAsNotMoving(src); - } - else - { - // Only the destination chunk is now valid - just free it. - CDBA_ASSERT(it->srcChunkIdx == InvalidChunkIdx); - } - - FreePendingMove(&*it); - } - } - - if (it->dstChunkIdx != InvalidChunkIdx) - { - bHasMoves = true; - } - } - } - - return bHasMoves; -} - -CDefragAllocator::Index CDefragAllocator::Defrag_Bwd_FindFreeBlockFor(size_t sz, size_t alignment, UINT_PTR addressLimit) -{ - Index bestChunkIdx = InvalidChunkIdx; - UINT_PTR maxAddress = addressLimit; - - int minBucket = BucketForSize(sz); - - // Search for an exact fit - { - size_t rootIdx = m_freeBuckets[minBucket]; - SDefragAllocChunk& root = m_chunks[rootIdx]; - - for (size_t idx = root.freeNextIdx; idx != rootIdx; idx = m_chunks[idx].freeNextIdx) - { - SDefragAllocChunk& chunk = m_chunks[idx]; - - CDBA_ASSERT(!chunk.attr.IsBusy()); - CDBA_ASSERT(max((uint32)1, (uint32)chunk.attr.GetSize()) >= (1U << minBucket)); - - UINT_PTR chunkBase = chunk.ptr; - UINT_PTR chunkEnd = chunkBase + chunk.attr.GetSize(); - UINT_PTR allocBase = Align(chunkBase, alignment); - UINT_PTR allocEnd = allocBase + sz; - - if (chunk.ptr < maxAddress) - { - if (chunkBase == allocBase && chunkEnd == allocEnd) - { - bestChunkIdx = idx; - maxAddress = chunk.ptr; - break; - } - } - else - { - break; - } - } - } - - for (size_t bucket = minBucket; (bestChunkIdx == InvalidChunkIdx) && (bucket < NumBuckets); ++bucket) - { - size_t rootIdx = m_freeBuckets[bucket]; - SDefragAllocChunk& root = m_chunks[rootIdx]; - - for (size_t idx = root.freeNextIdx; idx != rootIdx; idx = m_chunks[idx].freeNextIdx) - { - SDefragAllocChunk& chunk = m_chunks[idx]; - - CDBA_ASSERT(!chunk.attr.IsBusy()); - CDBA_ASSERT(max((uint32)1, (uint32)chunk.attr.GetSize()) >= (1U << bucket)); - - UINT_PTR chunkBase = chunk.ptr; - UINT_PTR chunkEnd = chunkBase + chunk.attr.GetSize(); - UINT_PTR allocBase = Align(chunkBase, alignment); - UINT_PTR allocEnd = allocBase + sz; - - if (allocEnd <= maxAddress) - { - if (chunkBase <= allocBase && allocEnd <= chunkEnd) - { - bestChunkIdx = idx; - maxAddress = chunkBase; - break; - } - } - else - { - // Chunks are ordered by address. If the maxAddress has been exceeded, there's no point in searching the rest of the list. - break; - } - } - } - - return bestChunkIdx; -} - -CDefragAllocator::Index CDefragAllocator::Defrag_Fwd_FindFreeBlockFor(size_t sz, size_t alignment, UINT_PTR addressLimit) -{ - Index bestChunkIdx = InvalidChunkIdx; - UINT_PTR minAddress = addressLimit; - - int minBucket = BucketForSize(sz); - - // Search for an exact fit - { - size_t rootIdx = m_freeBuckets[minBucket]; - SDefragAllocChunk& root = m_chunks[rootIdx]; - - for (size_t idx = root.freePrevIdx; idx != rootIdx; idx = m_chunks[idx].freePrevIdx) - { - SDefragAllocChunk& chunk = m_chunks[idx]; - - CDBA_ASSERT(!chunk.attr.IsBusy()); - CDBA_ASSERT(max((uint32)1, (uint32)chunk.attr.GetSize()) >= (1U << minBucket)); - - UINT_PTR chunkBase = chunk.ptr; - UINT_PTR chunkEnd = chunkBase + chunk.attr.GetSize(); - UINT_PTR allocBase = (chunkEnd - sz) & ~(alignment - 1); - UINT_PTR allocEnd = allocBase + sz; - - if (chunkBase >= minAddress) - { - if (allocBase == chunkBase && allocEnd == chunkEnd) - { - bestChunkIdx = idx; - minAddress = chunk.ptr; - break; - } - } - else - { - break; - } - } - } - - for (size_t bucket = minBucket; (bestChunkIdx == InvalidChunkIdx) && (bucket < NumBuckets); ++bucket) - { - size_t rootIdx = m_freeBuckets[bucket]; - SDefragAllocChunk& root = m_chunks[rootIdx]; - - for (size_t idx = root.freePrevIdx; idx != rootIdx; idx = m_chunks[idx].freePrevIdx) - { - SDefragAllocChunk& chunk = m_chunks[idx]; - - CDBA_ASSERT(!chunk.attr.IsBusy()); - CDBA_ASSERT(max((uint32)1, (uint32)chunk.attr.GetSize()) >= (1U << bucket)); - - UINT_PTR chunkBase = chunk.ptr; - UINT_PTR chunkEnd = chunkBase + chunk.attr.GetSize(); - UINT_PTR allocBase = (chunkEnd - sz) & ~(alignment - 1); - UINT_PTR allocEnd = allocBase + sz; - - if (chunkBase > minAddress) - { - if (chunkBase <= allocBase && allocEnd <= chunkEnd) - { - bestChunkIdx = idx; - minAddress = chunkBase; - break; - } - } - else - { - // Chunks are ordered by address. If the minAddress has been exceeded, there's no point in searching the rest of the list. - break; - } - } - } - - return bestChunkIdx; -} - -CDefragAllocator::PendingMove* CDefragAllocator::AllocPendingMove() -{ - // Naive - just search for a free slot. - for (PendingMoveVec::iterator it = m_pendingMoves.begin(), itEnd = m_pendingMoves.end(); it != itEnd; ++it) - { - if (it->dstChunkIdx == InvalidChunkIdx) - { - return &*it; - } - } - - return NULL; -} - -void CDefragAllocator::FreePendingMove(PendingMove* pMove) -{ - stl::reconstruct(*pMove); -} - -void CDefragAllocator::CancelMove(Index srcChunkIdx, bool bIsContentNeeded) -{ - CryOptionalAutoLock lock(m_lock, m_isThreadSafe); - CancelMove_Locked(srcChunkIdx, bIsContentNeeded); -} - -void CDefragAllocator::CancelMove_Locked(Index srcChunkIdx, [[maybe_unused]] bool bIsContentNeeded) -{ - SDefragAllocChunk* pChunk = &m_chunks[srcChunkIdx]; - - // In theory CancelMove could get called twice for the same chunk - make sure that - // redundant cancels are ignored - if (pChunk->attr.IsMoving()) - { - // Chunk is being moved. Find the job responsible and cancel it (if it's not complete). - PendingMoveVec::iterator it = std::find_if(m_pendingMoves.begin(), m_pendingMoves.end(), PendingMoveSrcChunkPredicate(srcChunkIdx)); - CDBA_ASSERT(it != m_pendingMoves.end()); - CDBA_ASSERT(it->srcChunkIdx != InvalidChunkIdx); - - if (it->notify.bDstIsValid && it->notify.bSrcIsUnneeded) - { - // Chunk has actually completed, just not finalised. Discard the destination chunk. - MarkAsFree(m_chunks[it->dstChunkIdx]); - MergeFreeBlock(it->dstChunkIdx); - FreePendingMove(&*it); - } - else - { - // Chunk is still in flight. - - // If the content is important, then we can either cancel the copy (if not overlapped), or - // sync and wait for it complete. TODO. - - m_policy.pDefragPolicy->CancelCopy(it->userMoveId, pChunk->pContext, false); - it->srcChunkIdx = InvalidChunkIdx; - it->cancelled = true; - } - - MarkAsNotMoving(*pChunk); - ++m_nCancelledMoves; - } -} - -void CDefragAllocator::Relocate(uint32 userMoveId, Index srcChunkIdx, Index dstChunkIdx) -{ - using std::swap; - - SDefragAllocChunk* pChunks = &m_chunks[0]; - uint32 logAlignment = m_logMinAlignment; - - SDefragAllocChunk& src = pChunks[srcChunkIdx]; - SDefragAllocChunk& dst = pChunks[dstChunkIdx]; - SDefragAllocChunkAttr srcAttr = src.attr; - SDefragAllocChunkAttr dstAttr = dst.attr; - - CDBA_ASSERT(srcAttr.IsMoving()); - CDBA_ASSERT(dstAttr.IsPinned()); - CDBA_ASSERT(!dstAttr.IsMoving()); - CDBA_ASSERT(srcAttr.GetSize() == dstAttr.GetSize()); - - UINT_PTR oldPtr = src.ptr; - UINT_PTR newPtr = dst.ptr; - - // src and dst are linked in the addr chain only - src needs to move where dst is (so user handles remain consistent) - // and the src block be freed. - - SDefragAllocChunk* pA = &dst; - SDefragAllocChunk* pB = &src; - - CDBA_ASSERT(pChunks[pA->addrPrevIdx].ptr + pChunks[pA->addrPrevIdx].attr.GetSize() == pA->ptr); - CDBA_ASSERT(pA->ptr + pA->attr.GetSize() == pChunks[pA->addrNextIdx].ptr); - CDBA_ASSERT(pChunks[pB->addrPrevIdx].ptr + pChunks[pB->addrPrevIdx].attr.GetSize() == pB->ptr); - CDBA_ASSERT(pB->ptr + pB->attr.GetSize() == pChunks[pB->addrNextIdx].ptr); - CDBA_ASSERT(&pChunks[pChunks[pA->addrNextIdx].addrPrevIdx] == pA); - CDBA_ASSERT(&pChunks[pChunks[pA->addrPrevIdx].addrNextIdx] == pA); - CDBA_ASSERT(&pChunks[pChunks[pB->addrNextIdx].addrPrevIdx] == pB); - CDBA_ASSERT(&pChunks[pChunks[pB->addrPrevIdx].addrNextIdx] == pB); - - Index nA = dstChunkIdx; - Index nB = srcChunkIdx; - - if (pA->addrNextIdx == nB) - { - // Neighbours - pB->addrPrevIdx = pA->addrPrevIdx; - pA->addrNextIdx = pB->addrNextIdx; - pA->addrPrevIdx = nB; - pB->addrNextIdx = nA; - pChunks[pB->addrPrevIdx].addrNextIdx = nB; - pChunks[pA->addrNextIdx].addrPrevIdx = nA; - } - else if (pA->addrPrevIdx == nB) - { - // Neighbours - pB->addrNextIdx = pA->addrNextIdx; - pA->addrPrevIdx = pB->addrPrevIdx; - pB->addrPrevIdx = nA; - pA->addrNextIdx = nB; - pChunks[pA->addrPrevIdx].addrNextIdx = nA; - pChunks[pB->addrNextIdx].addrPrevIdx = nB; - } - else - { - swap(pB->addrNextIdx, pA->addrNextIdx); - swap(pA->addrPrevIdx, pB->addrPrevIdx); - pChunks[pA->addrPrevIdx].addrNextIdx = nA; - pChunks[pA->addrNextIdx].addrPrevIdx = nA; - pChunks[pB->addrNextIdx].addrPrevIdx = nB; - pChunks[pB->addrPrevIdx].addrNextIdx = nB; - } - - swap(src.packedPtr, dst.packedPtr); - -#ifdef CDBA_MORE_DEBUG - ValidateAddressChain(); -#endif - - CDBA_ASSERT(pChunks[pA->addrPrevIdx].ptr + pChunks[pA->addrPrevIdx].attr.GetSize() == pA->ptr); - CDBA_ASSERT(pA->ptr + pA->attr.GetSize() == pChunks[pA->addrNextIdx].ptr); - CDBA_ASSERT(pChunks[pB->addrPrevIdx].ptr + pChunks[pB->addrPrevIdx].attr.GetSize() == pB->ptr); - CDBA_ASSERT(pB->ptr + pB->attr.GetSize() == pChunks[pB->addrNextIdx].ptr); - CDBA_ASSERT(&pChunks[pChunks[pA->addrNextIdx].addrPrevIdx] == pA); - CDBA_ASSERT(&pChunks[pChunks[pA->addrPrevIdx].addrNextIdx] == pA); - CDBA_ASSERT(&pChunks[pChunks[pB->addrNextIdx].addrPrevIdx] == pB); - CDBA_ASSERT(&pChunks[pChunks[pB->addrPrevIdx].addrNextIdx] == pB); - - if (userMoveId != IDefragAllocatorPolicy::InvalidUserMoveId) - { - m_policy.pDefragPolicy->Relocate(userMoveId, src.pContext, newPtr << logAlignment, oldPtr << logAlignment, (UINT_PTR)srcAttr.GetSize() << logAlignment); - } -} - -void CDefragAllocator::SyncMoveSegment(uint32 seg) -{ - SDefragAllocSegment& segment = m_segments[seg]; - SDefragAllocChunk& headSentinalChunk = m_chunks[segment.headSentinalChunkIdx]; - - // Assert that the segment is empty. - uint32 endAddress = segment.address + segment.capacity; - - Index chunkIdx = headSentinalChunk.addrNextIdx; - SDefragAllocChunk* pChunk = &m_chunks[chunkIdx]; - - int numValidSegs = seg; - - while (pChunk->ptr != endAddress) - { - if (pChunk->attr.IsBusy()) - { - CDBA_ASSERT(!pChunk->attr.IsMoving()); - CDBA_ASSERT(!pChunk->attr.IsPinned()); - CDBA_ASSERT(m_policy.pDefragPolicy != NULL); - -#if AZ_LEGACY_CRYSYSTEM_TRAIT_USE_BIT64 - size_t chunkAlign = BIT64(pChunk->logAlign); -#else - size_t chunkAlign = BIT(pChunk->logAlign); -#endif - - // Try and synchronously move the allocation - Index destinationChunkIdx = InvalidChunkIdx; - for (int segIdx = 0; destinationChunkIdx == InvalidChunkIdx && segIdx < numValidSegs; ++segIdx) - { - destinationChunkIdx = BestFit_FindFreeBlockForSegment(pChunk->attr.GetSize(), chunkAlign, segIdx); - } - - CDBA_ASSERT(destinationChunkIdx != InvalidChunkIdx); - - SplitResult sr = SplitFreeBlock(destinationChunkIdx, pChunk->attr.GetSize(), chunkAlign, true); - CDBA_ASSERT(sr.bSuccessful); - - SDefragAllocChunk& destinationChunk = m_chunks[destinationChunkIdx]; - MarkAsInUse(destinationChunk); - - Pin(ChunkHdlFromIdx(destinationChunkIdx)); - MarkAsMoving(*pChunk); - - m_policy.pDefragPolicy->SyncCopy(pChunk->pContext, destinationChunk.ptr << m_logMinAlignment, pChunk->ptr << m_logMinAlignment, (UINT_PTR)pChunk->attr.GetSize() << m_logMinAlignment); - Relocate(IDefragAllocatorPolicy::InvalidUserMoveId, chunkIdx, destinationChunkIdx); - - MarkAsNotMoving(*pChunk); - Unpin(ChunkHdlFromIdx(destinationChunkIdx)); - - MarkAsFree(destinationChunk); - destinationChunkIdx = MergeFreeBlock(destinationChunkIdx); - pChunk = &m_chunks[destinationChunkIdx]; - } - - chunkIdx = pChunk->addrNextIdx; - pChunk = &m_chunks[chunkIdx]; - } -} - -void CDefragAllocator::RebuildFreeLists() -{ - for (int bi = 0; bi < NumBuckets; ++bi) - { - Index ci = m_freeBuckets[bi]; - m_chunks[ci].freeNextIdx = ci; - m_chunks[ci].freePrevIdx = ci; - } - - for (Index ci = m_chunks[AddrStartSentinal].addrNextIdx; ci != AddrEndSentinal; ci = m_chunks[ci].addrNextIdx) - { - SDefragAllocChunk& ch = m_chunks[ci]; - if (!ch.attr.IsBusy()) - { - LinkFreeChunk(ci); - } - } - -#ifdef CDBA_MORE_DEBUG - ValidateFreeLists(); -#endif -} - -void CDefragAllocator::ValidateAddressChain() -{ - UINT_PTR p = 0; - - Index hdr = 0; - for (Index ci = m_chunks[hdr].addrNextIdx; ci != hdr; ) - { - SDefragAllocChunk& c = m_chunks[ci]; - - CDBA_ASSERT(p == c.ptr); - p += c.attr.GetSize(); - - ci = c.addrNextIdx; - } - - for (int bi = 0; bi < NumBuckets; ++bi) - { - hdr = m_freeBuckets[bi]; - - for (Index ci = m_chunks[hdr].freeNextIdx; ci != hdr; ) - { - SDefragAllocChunk& c = m_chunks[ci]; - - CDBA_ASSERT(!c.attr.IsBusy()); - - ci = c.freeNextIdx; - } - } -} - -void CDefragAllocator::ValidateFreeLists() -{ -#if defined(CDBA_DEBUG) - for (size_t bucket = 0; bucket < NumBuckets; ++bucket) - { - size_t rootIdx = m_freeBuckets[bucket]; - SDefragAllocChunk& root = m_chunks[rootIdx]; - - for (size_t idx = root.freeNextIdx; idx != rootIdx; idx = m_chunks[idx].freeNextIdx) - { - SDefragAllocChunk& chunk = m_chunks[idx]; - - CDBA_ASSERT(!chunk.attr.IsBusy()); - CDBA_ASSERT(max((uint32)1, (uint32)chunk.attr.GetSize()) >= (1U << bucket)); - CDBA_ASSERT(idx >= NumBuckets + 2); - - CDBA_ASSERT(m_chunks[chunk.freeNextIdx].freePrevIdx == idx); - CDBA_ASSERT(m_chunks[chunk.freePrevIdx].freeNextIdx == idx); - } - - for (size_t idx = root.freePrevIdx; idx != rootIdx; idx = m_chunks[idx].freePrevIdx) - { - SDefragAllocChunk& chunk = m_chunks[idx]; - - CDBA_ASSERT(!chunk.attr.IsBusy()); - CDBA_ASSERT(max((uint32)1, (uint32)chunk.attr.GetSize()) >= (1U << bucket)); - CDBA_ASSERT(idx >= NumBuckets + 2); - - CDBA_ASSERT(m_chunks[chunk.freeNextIdx].freePrevIdx == idx); - CDBA_ASSERT(m_chunks[chunk.freePrevIdx].freeNextIdx == idx); - } - } -#endif -} diff --git a/Code/CryEngine/CrySystem/DefragAllocator.h b/Code/CryEngine/CrySystem/DefragAllocator.h deleted file mode 100644 index 183b10bb7f..0000000000 --- a/Code/CryEngine/CrySystem/DefragAllocator.h +++ /dev/null @@ -1,712 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS 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_DEFRAGALLOCATOR_H -#define CRYINCLUDE_CRYSYSTEM_DEFRAGALLOCATOR_H -#pragma once - - -#include "IDefragAllocator.h" - -#include "System.h" - -#ifndef _RELEASE -#define CDBA_DEBUG -#endif - -//#define CDBA_MORE_DEBUG - -#ifdef CDBA_DEBUG -#define CDBA_ASSERT(x) do { assert(x); if (!(x)) {__debugbreak(); } \ -} while (0) -#else -#define CDBA_ASSERT(x) assert(x) -#endif - -union SDefragAllocChunkAttr -{ - enum - { - SizeWidth = 27, - SizeMask = (1 << SizeWidth) - 1, - BusyMask = 1 << 27, - MovingMask = 1 << 28, - MaxPinCount = 7, - PinnedCountShift = 29, - PinnedIncMask = 1 << PinnedCountShift, - PinnedCountMask = MaxPinCount << PinnedCountShift, - }; - - uint32 ui; - - ILINE unsigned int GetSize() const { return ui & SizeMask; } - ILINE void SetSize(unsigned int size) { ui = (ui & ~SizeMask) | size; } - ILINE void AddSize(int size) { ui += size; } - ILINE bool IsBusy() const { return (ui & BusyMask) != 0; } - ILINE void SetBusy(bool b) { ui = b ? (ui | BusyMask) : (ui & ~BusyMask); } - ILINE bool IsMoving() const { return (ui & MovingMask) != 0; } - ILINE void SetMoving(bool m) { ui = m ? (ui | MovingMask) : (ui & ~MovingMask); } - ILINE void IncPinCount() { ui += PinnedIncMask; } - ILINE void DecPinCount() { ui -= PinnedIncMask; } - ILINE bool IsPinned() const { return (ui & PinnedCountMask) != 0; } - ILINE unsigned int GetPinCount() const { return (ui & PinnedCountMask) >> PinnedCountShift; } - ILINE void SetPinCount(unsigned int p) { ui = (ui & ~PinnedCountMask) | (p << PinnedCountShift); } -}; - -struct SDefragAllocChunk -{ - enum - { - AlignBitCount = 4, - }; - typedef IDefragAllocator::Hdl Index; - - Index addrPrevIdx; - Index addrNextIdx; - - union - { - struct - { - UINT_PTR ptr : sizeof(UINT_PTR) * 8 - AlignBitCount; - UINT_PTR logAlign: AlignBitCount; - }; - UINT_PTR packedPtr; - }; - SDefragAllocChunkAttr attr; - - union - { - void* pContext; - struct - { - Index freePrevIdx; - Index freeNextIdx; - }; - }; - -#ifndef _RELEASE - const char* source; -#endif - - void SwapEndian() - { - ::SwapEndian(addrPrevIdx, true); - ::SwapEndian(addrNextIdx, true); - ::SwapEndian(packedPtr, true); - ::SwapEndian(attr.ui, true); - - if (attr.IsBusy()) - { - ::SwapEndian(pContext, true); - } - else - { - ::SwapEndian(freePrevIdx, true); - ::SwapEndian(freeNextIdx, true); - } - -#ifndef _RELEASE - ::SwapEndian(source, true); -#endif - } -}; - -struct SDefragAllocSegment -{ - uint32 address; - uint32 capacity; - SDefragAllocChunk::Index headSentinalChunkIdx; - - void SwapEndian() - { - ::SwapEndian(address, true); - ::SwapEndian(capacity, true); - ::SwapEndian(headSentinalChunkIdx, true); - } -}; - -class CDefragAllocator; - -class CDefragAllocatorWalker -{ -public: - explicit CDefragAllocatorWalker(CDefragAllocator& alloc); - ~CDefragAllocatorWalker(); - - const SDefragAllocChunk* Next(); - -private: - CDefragAllocatorWalker(const CDefragAllocatorWalker&); - CDefragAllocatorWalker& operator = (const CDefragAllocatorWalker&); - -private: - CDefragAllocator* m_pAlloc; - SDefragAllocChunk::Index m_nChunkIdx; -}; - -class CDefragAllocator - : public IDefragAllocator -{ - friend class CDefragAllocatorWalker; - typedef SDefragAllocChunk::Index Index; - -public: - CDefragAllocator(); - - void Release(bool bDiscard); - - void Init(UINT_PTR capacity, UINT_PTR minAlignment, const Policy& policy); - -#ifndef _RELEASE - void DumpState(const char* filename); - void RestoreState(const char* filename); -#endif - - // allocatorDisplayOffset will offset the statistics for the allocator depending on the index. - // 0 means no offset and default location, 1 means bar will be rendered above the 0th bar and stats to the right of the 0th stats - void DisplayMemoryUsage(const char* title, unsigned int allocatorDisplayOffset = 0); - - bool AppendSegment(UINT_PTR capacity); - void UnAppendSegment(); - - Hdl Allocate(size_t sz, const char* source, void* pContext = NULL); - Hdl AllocateAligned(size_t sz, size_t alignment, const char* source, void* pContext = NULL); - AllocatePinnedResult AllocatePinned(size_t sz, const char* source, void* pContext = NULL); - bool Free(Hdl hdl); - - void ChangeContext(Hdl hdl, void* pNewContext); - - size_t GetAllocated() const { return (size_t)(m_capacity - m_available) << m_logMinAlignment; } - IDefragAllocatorStats GetStats(); - - size_t DefragmentTick(size_t maxMoves, size_t maxAmount, bool bForce); - - ILINE UINT_PTR UsableSize(Hdl hdl) - { - Index chunkIdx = ChunkIdxFromHdl(hdl); - CDBA_ASSERT(chunkIdx < m_chunks.size()); - - SDefragAllocChunk& chunk = m_chunks[chunkIdx]; - SDefragAllocChunkAttr attr = chunk.attr; - - CDBA_ASSERT(attr.IsBusy()); - return (UINT_PTR)attr.GetSize() << m_logMinAlignment; - } - - // Pin the chunk until the next defrag tick, when it will be automatically unpinned - ILINE UINT_PTR WeakPin(Hdl hdl) - { - Index chunkIdx = ChunkIdxFromHdl(hdl); - CDBA_ASSERT(chunkIdx < m_chunks.size()); - - SDefragAllocChunk& chunk = m_chunks[chunkIdx]; - SDefragAllocChunkAttr attr = chunk.attr; - CDBA_ASSERT(attr.IsBusy()); - - if (attr.IsMoving()) - { - CancelMove(chunkIdx, true); - } - - return chunk.ptr << m_logMinAlignment; - } - - // Pin the chunk until Unpin is called - ILINE UINT_PTR Pin(Hdl hdl) - { - Index chunkIdx = ChunkIdxFromHdl(hdl); - - SDefragAllocChunk& chunk = m_chunks[chunkIdx]; - SDefragAllocChunkAttr attr; - SDefragAllocChunkAttr newAttr; - - do - { - attr.ui = const_cast(chunk.attr.ui); - newAttr.ui = attr.ui; - - CDBA_ASSERT(attr.GetPinCount() < SDefragAllocChunkAttr::MaxPinCount); - CDBA_ASSERT(attr.IsBusy()); - - newAttr.IncPinCount(); - } - while (CryInterlockedCompareExchange(alias_cast(&chunk.attr.ui), newAttr.ui, attr.ui) != attr.ui); - - // Potentially a Relocate could be in progress here. Either the Relocate is mid-way, in which case 'IsMoving()' will - // still be set, and CancelMove will sync and all is well. - - // If 'IsMoving()' is not set, the Relocate should have just completed, in which case ptr should validly point - // to the new location. - - if (attr.IsMoving()) - { - CancelMove(chunkIdx, true); - } - - return chunk.ptr << m_logMinAlignment; - } - - ILINE void Unpin(Hdl hdl) - { - SDefragAllocChunk& chunk = m_chunks[ChunkIdxFromHdl(hdl)]; - SDefragAllocChunkAttr attr; - SDefragAllocChunkAttr newAttr; - do - { - attr.ui = const_cast(chunk.attr.ui); - newAttr.ui = attr.ui; - - CDBA_ASSERT(attr.IsPinned()); - CDBA_ASSERT(attr.IsBusy()); - - newAttr.DecPinCount(); - } - while (CryInterlockedCompareExchange(alias_cast(&chunk.attr.ui), newAttr.ui, attr.ui) != attr.ui); - } - - ILINE const char* GetSourceOf([[maybe_unused]] Hdl hdl) - { -#ifndef _RELEASE - return m_chunks[ChunkIdxFromHdl(hdl)].source; -#else - return ""; -#endif - } - -private: - enum - { - NumBuckets = 31, // 2GB - MaxPendingMoves = 64, - - AddrStartSentinal = 0, - AddrEndSentinal = 1, - }; - - struct SplitResult - { - bool bSuccessful; - Index nLeftSplitChunkIdx; - Index nRightSplitChunkIdx; - }; - - struct PendingMove - { - PendingMove() - : srcChunkIdx(InvalidChunkIdx) - , dstChunkIdx(InvalidChunkIdx) - , userMoveId(0) - , relocated(false) - , cancelled(false) - { - } - - Index srcChunkIdx; - Index dstChunkIdx; - uint32 userMoveId; - IDefragAllocatorCopyNotification notify; - bool relocated; - bool cancelled; - - void SwapEndian() - { - ::SwapEndian(srcChunkIdx, true); - ::SwapEndian(dstChunkIdx, true); - ::SwapEndian(userMoveId, true); - } - }; - - struct PendingMoveSrcChunkPredicate - { - PendingMoveSrcChunkPredicate(Index ci) - : m_ci(ci) {} - bool operator () (const PendingMove& pm) const { return pm.srcChunkIdx == m_ci; } - Index m_ci; - }; - - typedef DynArray PendingMoveVec; - typedef std::vector SegmentVec; - - static const Index InvalidChunkIdx = (Index) - 1; - -private: - static ILINE Index ChunkIdxFromHdl(Hdl id) { return id - 1; } - static ILINE Hdl ChunkHdlFromIdx(Index idx) { return idx + 1; } - -private: - ~CDefragAllocator(); - - Index AllocateChunk(); - void ReleaseChunk(Index idx); - - ILINE void MarkAsInUse(SDefragAllocChunk& chunk) - { - CDBA_ASSERT(!chunk.attr.IsBusy()); - - chunk.attr.SetBusy(true); - m_available -= chunk.attr.GetSize(); - ++m_numAllocs; - - // m_available is unsigned, so check for underflow - CDBA_ASSERT(m_available <= m_capacity); - } - - ILINE void MarkAsFree(SDefragAllocChunk& chunk) - { - CDBA_ASSERT(chunk.attr.IsBusy()); - - chunk.attr.SetPinCount(0); - chunk.attr.SetMoving(false); - chunk.attr.SetBusy(0); - m_available += chunk.attr.GetSize(); - --m_numAllocs; - - // m_available is unsigned, so check for underflow - CDBA_ASSERT(m_available <= m_capacity); - } - - void LinkFreeChunk(Index idx); - void UnlinkFreeChunk(Index idx) - { - SDefragAllocChunk& chunk = m_chunks[idx]; - m_chunks[chunk.freePrevIdx].freeNextIdx = chunk.freeNextIdx; - m_chunks[chunk.freeNextIdx].freePrevIdx = chunk.freePrevIdx; - } - - void LinkAddrChunk(Index idx, Index afterIdx) - { - SDefragAllocChunk& chunk = m_chunks[idx]; - SDefragAllocChunk& afterChunk = m_chunks[afterIdx]; - - chunk.addrNextIdx = afterChunk.addrNextIdx; - chunk.addrPrevIdx = afterIdx; - m_chunks[chunk.addrNextIdx].addrPrevIdx = idx; - afterChunk.addrNextIdx = idx; - } - - void UnlinkAddrChunk(Index id) - { - SDefragAllocChunk& chunk = m_chunks[id]; - - m_chunks[chunk.addrPrevIdx].addrNextIdx = chunk.addrNextIdx; - m_chunks[chunk.addrNextIdx].addrPrevIdx = chunk.addrPrevIdx; - } - - void PrepareMergePopNext(Index* pLists) - { - for (int bucketIdx = 0; bucketIdx < NumBuckets; ++bucketIdx) - { - Index hdrChunkId = m_freeBuckets[bucketIdx]; - Index nextId = m_chunks[hdrChunkId].freeNextIdx; - if (nextId != hdrChunkId) - { - pLists[bucketIdx] = nextId; - } - else - { - pLists[bucketIdx] = InvalidChunkIdx; - } - } - } - - size_t MergePeekNextChunk(Index* pLists) - { - size_t farList = (size_t)-1; - UINT_PTR farPtr = (UINT_PTR)-1; - - for (size_t listIdx = 0; listIdx < NumBuckets; ++listIdx) - { - Index chunkIdx = pLists[listIdx]; - if (chunkIdx != InvalidChunkIdx) - { - SDefragAllocChunk& chunk = m_chunks[chunkIdx]; - if (chunk.ptr < farPtr) - { - farPtr = chunk.ptr; - farList = listIdx; - } - } - } - - return farList; - } - - void MergePopNextChunk(Index* pLists, size_t list) - { - using std::swap; - - Index fni = m_chunks[pLists[list]].freeNextIdx; - pLists[list] = fni; - if (m_chunks[fni].attr.IsBusy()) - { - // End of the list - pLists[list] = InvalidChunkIdx; - } - } - - void MergePatchNextRemove(Index* pLists, Index removeIdx) - { - for (int bucketIdx = 0; bucketIdx < NumBuckets; ++bucketIdx) - { - if (pLists[bucketIdx] == removeIdx) - { - Index nextIdx = m_chunks[removeIdx].freeNextIdx; - if (!m_chunks[nextIdx].attr.IsBusy()) - { - pLists[bucketIdx] = nextIdx; - } - else - { - pLists[bucketIdx] = InvalidChunkIdx; - } - } - } - } - - void MergePatchNextInsert(Index* pLists, Index insertIdx) - { - SDefragAllocChunk& insertChunk = m_chunks[insertIdx]; - int bucket = BucketForSize(insertChunk.attr.GetSize()); - - if (pLists[bucket] != InvalidChunkIdx) - { - SDefragAllocChunk& listChunk = m_chunks[pLists[bucket]]; - if (listChunk.ptr > insertChunk.ptr) - { - pLists[bucket] = insertIdx; - } - } - } - - void PrepareMergePopPrev(Index* pLists) - { - for (int bucketIdx = 0; bucketIdx < NumBuckets; ++bucketIdx) - { - Index hdrChunkId = m_freeBuckets[bucketIdx]; - Index prevIdx = m_chunks[hdrChunkId].freePrevIdx; - if (prevIdx != hdrChunkId) - { - pLists[bucketIdx] = prevIdx; - } - else - { - pLists[bucketIdx] = InvalidChunkIdx; - } - } - } - - size_t MergePeekPrevChunk(Index* pLists) - { - size_t farList = (size_t)-1; - UINT_PTR farPtr = 0; - - for (size_t listIdx = 0; listIdx < NumBuckets; ++listIdx) - { - Index chunkIdx = pLists[listIdx]; - if (chunkIdx != InvalidChunkIdx) - { - SDefragAllocChunk& chunk = m_chunks[chunkIdx]; - if (chunk.ptr >= farPtr) - { - farPtr = chunk.ptr; - farList = listIdx; - } - } - } - - return farList; - } - - void MergePopPrevChunk(Index* pLists, size_t list) - { - using std::swap; - - Index fpi = m_chunks[pLists[list]].freePrevIdx; - pLists[list] = fpi; - if (m_chunks[fpi].attr.IsBusy()) - { - // End of the list - pLists[list] = InvalidChunkIdx; - } - } - - void MergePatchPrevInsert(Index* pLists, Index insertIdx) - { - SDefragAllocChunk& insertChunk = m_chunks[insertIdx]; - int bucket = BucketForSize(insertChunk.attr.GetSize()); - - if (pLists[bucket] != InvalidChunkIdx) - { - SDefragAllocChunk& listChunk = m_chunks[pLists[bucket]]; - if (listChunk.ptr < insertChunk.ptr) - { - pLists[bucket] = insertIdx; - } - } - } - - void MergePatchPrevRemove(Index* pLists, Index removeIdx) - { - for (int bucketIdx = 0; bucketIdx < NumBuckets; ++bucketIdx) - { - if (pLists[bucketIdx] == removeIdx) - { - Index nextIdx = m_chunks[removeIdx].freePrevIdx; - if (!m_chunks[nextIdx].attr.IsBusy()) - { - pLists[bucketIdx] = nextIdx; - } - else - { - pLists[bucketIdx] = InvalidChunkIdx; - } - } - } - } - - void MarkAsMoving(SDefragAllocChunk& src) - { - SDefragAllocChunkAttr srcAttr, srcNewAttr; - do - { - srcAttr.ui = const_cast(src.attr.ui); - srcNewAttr.ui = srcAttr.ui; - srcNewAttr.SetMoving(true); - } - while (CryInterlockedCompareExchange(alias_cast(&src.attr.ui), srcNewAttr.ui, srcAttr.ui) != srcAttr.ui); - } - - void MarkAsNotMoving(SDefragAllocChunk& src) - { - SDefragAllocChunkAttr srcAttr, srcNewAttr; - do - { - srcAttr.ui = const_cast(src.attr.ui); - srcNewAttr.ui = srcAttr.ui; - srcNewAttr.SetMoving(false); - } - while (CryInterlockedCompareExchange(alias_cast(&src.attr.ui), srcNewAttr.ui, srcAttr.ui) != srcAttr.ui); - } - - ILINE bool IsMoveableCandidate(const SDefragAllocChunkAttr& a, uint32 sizeUpperBound) - { - return a.IsBusy() && !a.IsPinned() && !a.IsMoving() && (0 < a.GetSize()) && (a.GetSize() <= sizeUpperBound); - } - - bool TryMarkAsMoving(SDefragAllocChunk& src, uint32 sizeUpperBound) - { - SDefragAllocChunkAttr srcAttr, srcNewAttr; - do - { - srcAttr.ui = const_cast(src.attr.ui); - srcNewAttr.ui = srcAttr.ui; - if (!IsMoveableCandidate(srcAttr, sizeUpperBound)) - { - return false; - } - srcNewAttr.SetMoving(true); - } - while (CryInterlockedCompareExchange(alias_cast(&src.attr.ui), srcNewAttr.ui, srcAttr.ui) != srcAttr.ui); - return true; - } - - bool TryScheduleCopy(SDefragAllocChunk& srcChunk, SDefragAllocChunk& dstChunk, PendingMove* pPM, bool bLowHalf) - { - UINT_PTR dstChunkBase = dstChunk.ptr; - UINT_PTR dstChunkEnd = dstChunkBase + dstChunk.attr.GetSize(); -#if AZ_LEGACY_CRYSYSTEM_TRAIT_USE_BIT64 - UINT_PTR allocAlign = BIT64(srcChunk.logAlign); -#else - UINT_PTR allocAlign = BIT(srcChunk.logAlign); -#endif - UINT_PTR allocSize = srcChunk.attr.GetSize(); - UINT_PTR dstAllocBase = bLowHalf - ? Align(dstChunkBase, allocAlign) - : ((dstChunkEnd - allocSize) & ~(allocAlign - 1)); - - uint32 userId = m_policy.pDefragPolicy->BeginCopy( - srcChunk.pContext, - dstAllocBase << m_logMinAlignment, - srcChunk.ptr << m_logMinAlignment, - allocSize << m_logMinAlignment, - &pPM->notify); - pPM->userMoveId = userId; - - return userId != 0; - } - - Hdl Allocate_Locked(size_t sz, size_t alignment, const char* source, void* pContext); - SplitResult SplitFreeBlock(Index fbId, size_t sz, size_t alignment, bool allocateInLowHalf); - Index MergeFreeBlock(Index fbId); - -#ifdef CDBA_MORE_DEBUG - void Defrag_ValidateFreeBlockIteration(); -#endif - - Index BestFit_FindFreeBlockForSegment(size_t sz, size_t alignment, uint32 nSegment); - Index BestFit_FindFreeBlockFor(size_t sz, size_t alignment, UINT_PTR addressMin, UINT_PTR addressMax, bool allocateInLowHalf); - Index FirstFit_FindFreeBlockFor(size_t sz, size_t alignment, UINT_PTR addressMin, UINT_PTR addressMax, bool allocateInLowHalf); - - size_t Defrag_FindMovesBwd(PendingMove** pMoves, size_t maxMoves, size_t& curAmount, size_t maxAmount); - size_t Defrag_FindMovesFwd(PendingMove** pMoves, size_t maxMoves, size_t& curAmount, size_t maxAmount); - bool Defrag_CompletePendingMoves(); - Index Defrag_Bwd_FindFreeBlockFor(size_t sz, size_t alignment, UINT_PTR addressLimit); - Index Defrag_Fwd_FindFreeBlockFor(size_t sz, size_t alignment, UINT_PTR addressLimit); - - PendingMove* AllocPendingMove(); - void FreePendingMove(PendingMove* pMove); - - void CancelMove(Index srcChunkIdx, bool bIsContentNeeded); - void CancelMove_Locked(Index srcChunkIdx, bool bIsContentNeeded); - void Relocate(uint32 userMoveId, Index srcChunkIdx, Index dstChunkIdx); - - void SyncMoveSegment(uint32 seg); - - void RebuildFreeLists(); - void ValidateAddressChain(); - void ValidateFreeLists(); - - int BucketForSize(size_t sz) const - { - return sz > 0 - ? static_cast(IntegerLog2(sz)) - : 0; - } - -private: - bool m_isThreadSafe; - bool m_chunksAreFixed; - - CryCriticalSection m_lock; - - uint32 m_capacity; - uint32 m_available; - Index m_numAllocs; - - uint16 m_minAlignment; - uint16 m_logMinAlignment; - - Index m_freeBuckets[NumBuckets]; - - std::vector m_chunks; - std::vector m_unusedChunks; - PendingMoveVec m_pendingMoves; - SegmentVec m_segments; - - uint32 m_nCancelledMoves; - - Policy m_policy; -}; - -#endif // CRYINCLUDE_CRYSYSTEM_DEFRAGALLOCATOR_H diff --git a/Code/CryEngine/CrySystem/DllMain.cpp b/Code/CryEngine/CrySystem/DllMain.cpp index aba39fb9fb..c3a15812ce 100644 --- a/Code/CryEngine/CrySystem/DllMain.cpp +++ b/Code/CryEngine/CrySystem/DllMain.cpp @@ -14,11 +14,6 @@ #include "CrySystem_precompiled.h" #include "System.h" #include -#include "DebugCallStack.h" -#if defined(AZ_MONOLITHIC_BUILD) -#include -#include -#endif #if defined(AZ_RESTRICTED_PLATFORM) #undef AZ_RESTRICTED_SECTION @@ -76,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: { @@ -91,7 +82,6 @@ public: { CryCleanup(); STLALLOCATOR_CLEANUP; - gEnv->pSystem->SetThreadState(ESubsys_Physics, true); break; } } @@ -132,31 +122,13 @@ 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) { 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; @@ -178,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/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/HMDCVars.cpp b/Code/CryEngine/CrySystem/HMDCVars.cpp deleted file mode 100644 index 4ef08db729..0000000000 --- a/Code/CryEngine/CrySystem/HMDCVars.cpp +++ /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. - -#include "CrySystem_precompiled.h" -#include "HMDCVars.h" -#include -#include - -namespace AZ -{ -namespace VR -{ - -void HMDCVars::OnHMDRecenter([[maybe_unused]] IConsoleCmdArgs* args) -{ - EBUS_EVENT(AZ::VR::HMDDeviceRequestBus, RecenterPose); -} - -void HMDCVars::OnHMDTrackingLevelChange(IConsoleCmdArgs* args) -{ - if (args->GetArgCount() != 2) - { - // First arg should be the command itself, second arg should be the requested tracking level. - return; - } - - // Read the new tracking level. - int argVal = 0; - std::stringstream stream(args->GetArg(1)); - stream >> argVal; - - AZ::VR::HMDTrackingLevel level = static_cast(argVal); - EBUS_EVENT(AZ::VR::HMDDeviceRequestBus, SetTrackingLevel, level); -} - -void HMDCVars::OnOutputToHMDChanged(ICVar* var) -{ - // Set the necessary cvars for turning on/off output to an HMD. - ICVar* mode = gEnv->pConsole->GetCVar("r_StereoMode"); - ICVar* output = gEnv->pConsole->GetCVar("r_StereoOutput"); - ICVar* height = gEnv->pConsole->GetCVar("r_height"); - ICVar* width = gEnv->pConsole->GetCVar("r_width"); - - if (!mode || !output || !height || !width) - { - return; - } - - bool enable = (var->GetIVal() == 1); - if (enable) - { - // Auto-set the resolution. - { - const AZ::VR::HMDDeviceInfo* deviceInfo = nullptr; - EBUS_EVENT_RESULT(deviceInfo, AZ::VR::HMDDeviceRequestBus, GetDeviceInfo); - - // If the device info exists then there is a VR device connected and working. - if (deviceInfo) - { - mode->Set(EStereoMode::STEREO_MODE_DUAL_RENDERING); - output->Set(EStereoOutput::STEREO_OUTPUT_HMD); - - width->Set(static_cast(deviceInfo->renderWidth)); - height->Set(static_cast(deviceInfo->renderHeight)); - } - } - } - else - { - mode->Set(EStereoMode::STEREO_MODE_NO_STEREO); - output->Set(EStereoOutput::STEREO_OUTPUT_STANDARD); - } -} - -void HMDCVars::OnHMDDebugInfo(ICVar* var) -{ - bool enable = (var->GetIVal() == 1); - EBUS_EVENT(AZ::VR::HMDDebuggerRequestBus, EnableInfo, enable); -} - -void HMDCVars::OnHMDDebugCamera(ICVar* var) -{ - bool enable = (var->GetIVal() == 1); - EBUS_EVENT(AZ::VR::HMDDebuggerRequestBus, EnableCamera, enable); -} - -int HMDCVars::hmd_social_screen = static_cast(HMDSocialScreen::UndistortedLeftEye); -int HMDCVars::hmd_debug_info = 0; -int HMDCVars::hmd_debug_camera = 0; - -} // namespace VR -} // namespace AZ diff --git a/Code/CryEngine/CrySystem/HMDCVars.h b/Code/CryEngine/CrySystem/HMDCVars.h deleted file mode 100644 index f449bb0725..0000000000 --- a/Code/CryEngine/CrySystem/HMDCVars.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 -#include - -namespace AZ -{ - namespace VR - { - class HMDCVars - { - public: - - static int hmd_social_screen; - static int hmd_debug_info; - static int hmd_debug_camera; - - static void Register() - { - REGISTER_CVAR2("hmd_social_screen", &hmd_social_screen, hmd_social_screen, - VF_NULL, "Selects the social screen mode: \n" - "-1- Off\n" - "0 - Undistorted left eye\n" - "1 - Undistorted right eye\n" - ); - - REGISTER_INT_CB("hmd_debug_info", 0, VF_ALWAYSONCHANGE, - "Enable/disable HMD and VR controller debug info/rendering", - OnHMDDebugInfo); - - REGISTER_INT_CB("hmd_debug_camera", 0, VF_ALWAYSONCHANGE, - "Enable/disable HMD debug camera", - OnHMDDebugCamera); - - REGISTER_COMMAND("hmd_tracking_level", &OnHMDTrackingLevelChange, - VF_NULL, "Set the HMD center reference point.\n" - "0 - Camera (Actor's head)\n" - "1 - Actor's feet (floor)\n"); - - REGISTER_COMMAND("hmd_recenter_pose", &OnHMDRecenter, - VF_NULL, "Re-centers sensor orientation of the HMD."); - - REGISTER_INT_CB("output_to_hmd", 0, VF_ALWAYSONCHANGE, - "Enable/disable output to any connected HMD (for VR)", - OnOutputToHMDChanged); - } - - private: - - static void OnHMDRecenter(IConsoleCmdArgs* args); - static void OnHMDTrackingLevelChange(IConsoleCmdArgs* args); - static void OnOutputToHMDChanged(ICVar* var); - static void OnHMDDebugInfo(ICVar* var); - static void OnHMDDebugCamera(ICVar* var); - }; - } // namespace VR -} // namespace AZ diff --git a/Code/CryEngine/CrySystem/IDebugCallStack.cpp b/Code/CryEngine/CrySystem/IDebugCallStack.cpp deleted file mode 100644 index d73d70ab8b..0000000000 --- a/Code/CryEngine/CrySystem/IDebugCallStack.cpp +++ /dev/null @@ -1,300 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS 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::Screenshot(const char* szFileName) -{ - WriteLineToLog("Attempting to create error screenshot \"%s\"", szFileName); - - static int g_numScreenshots = 0; - if (gEnv->pRenderer && !g_numScreenshots++) - { - if (gEnv->pRenderer->ScreenShot(szFileName)) - { - WriteLineToLog("Successfully created screenshot."); - } - else - { - WriteLineToLog("Error creating screenshot."); - } - } - else - { - WriteLineToLog("Ignoring multiple calls to Screenshot"); - } -} - -////////////////////////////////////////////////////////////////////////// -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 7b54c0cac0..0000000000 --- a/Code/CryEngine/CrySystem/IDebugCallStack.h +++ /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. - -// 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); - - static void Screenshot(const char* szFileName); - - 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 8818dfa0d9..0af52d8cc4 100644 --- a/Code/CryEngine/CrySystem/LevelSystem/LevelSystem.cpp +++ b/Code/CryEngine/CrySystem/LevelSystem/LevelSystem.cpp @@ -17,10 +17,8 @@ #include "LevelSystem.h" #include #include "IMovieSystem.h" -#include "IMaterialEffects.h" #include #include -#include "IDeferredCollisionEvent.h" #include "CryPath.h" #include @@ -649,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) @@ -769,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; } @@ -846,11 +828,6 @@ void CLevelSystem::OnLoadingError(const char* levelName, const char* error) return; } - if (gEnv->pRenderer) - { - gEnv->pRenderer->SetTexturePrecaching(false); - } - for (AZStd::vector::const_iterator it = m_listeners.begin(); it != m_listeners.end(); ++it) { (*it)->OnLoadingError(levelName, error); @@ -968,33 +945,6 @@ void CLevelSystem::UnloadLevel() CTimeValue tBegin = gEnv->pTimer->GetAsyncTime(); - //AM: Flush render thread (Flush is not exposed - using EndFrame()) - //We are about to delete resources that could be in use - if (gEnv->pRenderer) - { - gEnv->pRenderer->EndFrame(); - - - bool isLoadScreenPlaying = false; -#if AZ_LOADSCREENCOMPONENT_ENABLED - LoadScreenBus::BroadcastResult(isLoadScreenPlaying, &LoadScreenBus::Events::IsPlaying); -#endif // if AZ_LOADSCREENCOMPONENT_ENABLED - - // force a black screen as last render command. - //if load screen is playing do not call this draw as it may lead to a crash due to UI loading code getting - //pumped while loading the shaders for this draw. - if (!isLoadScreenPlaying) - { - gEnv->pRenderer->BeginFrame(); - gEnv->pRenderer->SetState(GS_BLSRC_SRCALPHA | GS_BLDST_ONEMINUSSRCALPHA | GS_NODEPTHTEST); - gEnv->pRenderer->Draw2dImage(0, 0, 800, 600, -1, 0.0f, 0.0f, 1.0f, 1.0f, 0.f, 0.0f, 0.0f, 0.0f, 1.0, 0.f); - gEnv->pRenderer->EndFrame(); - } - - //flush any outstanding texture requests - gEnv->pRenderer->FlushPendingTextureTasks(); - } - // Clear level entities and prefab instances. EBUS_EVENT(AzFramework::GameEntityContextRequestBus, ResetGameContext); @@ -1045,27 +995,6 @@ void CLevelSystem::UnloadLevel() // Normally the GC step is triggered at the end of this method (by the ESYSTEM_EVENT_LEVEL_POST_UNLOAD event). EBUS_EVENT(AZ::ScriptSystemRequestBus, GarbageCollect); - // Force to clean render resources left after deleting all objects and materials. - IRenderer* pRenderer = gEnv->pRenderer; - if (pRenderer) - { - pRenderer->FlushRTCommands(true, true, true); - - CryComment("Deleting Render meshes, render resources and flush texture streaming"); - // This may also release some of the materials. - int flags = FRR_DELETED_MESHES | FRR_FLUSH_TEXTURESTREAMING | FRR_OBJECTS | FRR_RENDERELEMENTS | FRR_RP_BUFFERS | FRR_POST_EFFECTS; - - // Always keep the system resources around in the editor. - // If a level load fails for any reason, then do not unload the system resources, otherwise we will not have any system resources to continue rendering the console and debug output text. - if (!gEnv->IsEditor() && !GetLevelLoadFailed()) - { - flags |= FRR_SYSTEM_RESOURCES; - } - - pRenderer->FreeResources(flags); - CryComment("done"); - } - // Perform level unload procedures for the LyShine UI system if (gEnv && gEnv->pLyShine) { diff --git a/Code/CryEngine/CrySystem/LevelSystem/SpawnableLevelSystem.cpp b/Code/CryEngine/CrySystem/LevelSystem/SpawnableLevelSystem.cpp index 4b6e210522..8b3c75cce2 100644 --- a/Code/CryEngine/CrySystem/LevelSystem/SpawnableLevelSystem.cpp +++ b/Code/CryEngine/CrySystem/LevelSystem/SpawnableLevelSystem.cpp @@ -15,7 +15,6 @@ #include #include "IMovieSystem.h" #include -#include "IDeferredCollisionEvent.h" #include @@ -248,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) @@ -344,8 +341,6 @@ namespace LegacyLevelSystem gEnv->pSystem->GetISystemEventDispatcher()->OnSystemEvent(ESYSTEM_EVENT_LEVEL_PRECACHE_START, 0, 0); - m_pSystem->SetThreadState(ESubsys_Physics, true); - return true; } @@ -423,11 +418,6 @@ namespace LegacyLevelSystem { AZ_Error("LevelSystem", false, "Error loading level '%s': %s\n", levelName, error); - if (gEnv->pRenderer) - { - gEnv->pRenderer->SetTexturePrecaching(false); - } - for (auto& listener : m_listeners) { listener->OnLoadingError(levelName, error); @@ -541,32 +531,6 @@ namespace LegacyLevelSystem CTimeValue tBegin = gEnv->pTimer->GetAsyncTime(); - // AM: Flush render thread (Flush is not exposed - using EndFrame()) - // We are about to delete resources that could be in use - if (gEnv->pRenderer) - { - gEnv->pRenderer->EndFrame(); - - bool isLoadScreenPlaying = false; - #if AZ_LOADSCREENCOMPONENT_ENABLED - LoadScreenBus::BroadcastResult(isLoadScreenPlaying, &LoadScreenBus::Events::IsPlaying); - #endif // if AZ_LOADSCREENCOMPONENT_ENABLED - - // force a black screen as last render command. - // if load screen is playing do not call this draw as it may lead to a crash due to UI loading code getting - // pumped while loading the shaders for this draw. - if (!isLoadScreenPlaying) - { - gEnv->pRenderer->BeginFrame(); - gEnv->pRenderer->SetState(GS_BLSRC_SRCALPHA | GS_BLDST_ONEMINUSSRCALPHA | GS_NODEPTHTEST); - gEnv->pRenderer->Draw2dImage(0, 0, 800, 600, -1, 0.0f, 0.0f, 1.0f, 1.0f, 0.f, 0.0f, 0.0f, 0.0f, 1.0, 0.f); - gEnv->pRenderer->EndFrame(); - } - - // flush any outstanding texture requests - gEnv->pRenderer->FlushPendingTextureTasks(); - } - // Clear level entities and prefab instances. EBUS_EVENT(AzFramework::GameEntityContextRequestBus, ResetGameContext); @@ -608,28 +572,6 @@ namespace LegacyLevelSystem // Normally the GC step is triggered at the end of this method (by the ESYSTEM_EVENT_LEVEL_POST_UNLOAD event). EBUS_EVENT(AZ::ScriptSystemRequestBus, GarbageCollect); - // Force to clean render resources left after deleting all objects and materials. - IRenderer* pRenderer = gEnv->pRenderer; - if (pRenderer) - { - pRenderer->FlushRTCommands(true, true, true); - - CryComment("Deleting Render meshes, render resources and flush texture streaming"); - // This may also release some of the materials. - int flags = FRR_DELETED_MESHES | FRR_FLUSH_TEXTURESTREAMING | FRR_OBJECTS | FRR_RENDERELEMENTS | FRR_RP_BUFFERS | FRR_POST_EFFECTS; - - // Always keep the system resources around in the editor. - // If a level load fails for any reason, then do not unload the system resources, otherwise we will not have any system resources to - // continue rendering the console and debug output text. - if (!gEnv->IsEditor() && !GetLevelLoadFailed()) - { - flags |= FRR_SYSTEM_RESOURCES; - } - - pRenderer->FreeResources(flags); - CryComment("done"); - } - // Perform level unload procedures for the LyShine UI system if (gEnv && gEnv->pLyShine) { diff --git a/Code/CryEngine/CrySystem/LocalizedStringManager.cpp b/Code/CryEngine/CrySystem/LocalizedStringManager.cpp index a11e068a9b..7a2ad51e8b 100644 --- a/Code/CryEngine/CrySystem/LocalizedStringManager.cpp +++ b/Code/CryEngine/CrySystem/LocalizedStringManager.cpp @@ -32,9 +32,6 @@ #include #include -#if !defined(_RELEASE) -#include "CrySizerImpl.h" -#endif //#if !defined(_RELEASE) #define MAX_CELL_COUNT 32 @@ -165,52 +162,6 @@ static void TestFormatMessage ([[maybe_unused]] IConsoleCmdArgs* pArgs) } #endif //#if !defined(_RELEASE) - -////////////////////////////////////////////////////////////////////////// -#if !defined(_RELEASE) -void CLocalizedStringsManager::LocalizationDumpLoadedInfo([[maybe_unused]] IConsoleCmdArgs* pArgs) -{ - CLocalizedStringsManager* pLoca = (CLocalizedStringsManager*) gEnv->pSystem->GetLocalizationManager(); - - for (TTagFileNames::iterator tagit = pLoca->m_tagFileNames.begin(); tagit != pLoca->m_tagFileNames.end(); ++tagit) - { - CryLogAlways("Tag %s (%d)", tagit->first.c_str(), tagit->second.id); - - int entries = 0; - CrySizerImpl* pSizer = new CrySizerImpl(); - - for (tmapFilenames::iterator it = pLoca->m_loadedTables.begin(); it != pLoca->m_loadedTables.end(); it++) - { - if (tagit->second.id == it->second.nTagID) - { - CryLogAlways("\t%s", it->first.c_str()); - } - - if (pLoca->m_pLanguage) - { - const uint32 numEntries = pLoca->m_pLanguage->m_vLocalizedStrings.size(); - for (int32 i = numEntries - 1; i >= 0; i--) - { - SLocalizedStringEntry* entry = pLoca->m_pLanguage->m_vLocalizedStrings[i]; - if (tagit->second.id == entry->nTagID) - { - entries++; - entry->GetMemoryUsage((ICrySizer*) pSizer); - } - } - } - } - - // This line messes up Uncrustify so turn it off: *INDENT-OFF* - CryLogAlways("\t\tEntries %d, Approx Size %" PRISIZE_T "Kb", entries, pSizer->GetTotalSize() / 1024); - // turn it back on again: *INDENT-ON* - - SAFE_RELEASE(pSizer); - } -} - -#endif //#if !defined(_RELEASE) - ////////////////////////////////////////////////////////////////////// // Construction/Destruction ////////////////////////////////////////////////////////////////////// @@ -249,9 +200,6 @@ CLocalizedStringsManager::CLocalizedStringsManager(ISystem* pSystem) "0: No encoding, store as wide strings\n" "1: Huffman encode translated text, saves approx 30% with a small runtime performance cost\n" "Default is 1."); - - - REGISTER_COMMAND("LocalizationDumpLoadedInfo", LocalizationDumpLoadedInfo, VF_NULL, "Dump out into about the loaded localization files"); #endif //#if !defined(_RELEASE) REGISTER_CVAR2(c_sys_localization_format, &m_cvarLocalizationFormat, 1, VF_NULL, diff --git a/Code/CryEngine/CrySystem/LocalizedStringManager.h b/Code/CryEngine/CrySystem/LocalizedStringManager.h index 6b7ef6060b..1f18ba5c4a 100644 --- a/Code/CryEngine/CrySystem/LocalizedStringManager.h +++ b/Code/CryEngine/CrySystem/LocalizedStringManager.h @@ -96,10 +96,6 @@ public: void GetLoadedTags(TLocalizationTagVec& tagVec); void FreeLocalizationData(); -#if !defined(_RELEASE) - static void LocalizationDumpLoadedInfo(IConsoleCmdArgs* pArgs); -#endif //#if !defined(_RELEASE) - private: void SetAvailableLocalizationsBitfield(const ILocalizationManager::TLocalizationBitfield availableLocalizations); 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/MemoryFragmentationProfiler.h b/Code/CryEngine/CrySystem/MemoryFragmentationProfiler.h deleted file mode 100644 index 7d373bb472..0000000000 --- a/Code/CryEngine/CrySystem/MemoryFragmentationProfiler.h +++ /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. - -#ifndef CRYINCLUDE_CRYSYSTEM_MEMORYFRAGMENTATIONPROFILER_H -#define CRYINCLUDE_CRYSYSTEM_MEMORYFRAGMENTATIONPROFILER_H -#pragma once - - -// useful class to investigate memory fragmentation -// every time you call this from the console: -// -// #System.DumpMemoryCoverage() -// -// it adds a line to "MemoryCoverage.bmp" (generated the first time, there is a max line count) -// blue stripes mark some special positions (DLL positions) - -// Dependencies: only CryLog() - - -#include // STL vector<> - - -#if defined(WIN32) || defined(WIN64) - -class CMemoryFragmentationProfiler -{ -public: - - // constructor - clean file - CMemoryFragmentationProfiler() - : m_dwLine(0xffffffff) // 0xffffffff means not initialized yet - { - } - - // call this if you want to add one line (on first call the file is generated) - void DumpMemoryCoverage() - { - if (m_dwLine == 0xffffffff) - { - Init(); - } - - const size_t nMinMemoryPerUnit = 4 * 1024; // down to a few KB - const size_t nUnitsPerLine = 1024 * 8; // amount of bits, should only occupy a few KB memory - - const size_t nMaxMemoryPerUnit = 0x100000000 / nUnitsPerLine; // 4GB in total - - static std::vector vCoverage; - - vCoverage.clear(); - vCoverage.resize(nUnitsPerLine, 0); // should occupy nUnitsPerLine/8 bytes (vector is specialized) - - size_t nAvailableMem = 0, nUsedMem = 0; - - const size_t nMallocOverhead = 24; // depends on used runtime (debug:32, release:24) - - size_t nCurrentUnitSize = 256 * 1024 * 1024; // start with 256 MB blocks - - void** pMemoryBlocks = 0; // linked list of memory blocks (to free them) - - size_t nUnits = 0; - uint32 dwAllocCnt = 0, dwFreeCnt = 0; - - while (nCurrentUnitSize >= nMinMemoryPerUnit) - { - size_t nLocalUnits = 0; - - for (;; ) - { - void** pMem = (void**)::malloc(nCurrentUnitSize - nMallocOverhead); - - if (!pMem) - { - break; - } - - ++dwAllocCnt; - - // update coverage (conservative) - { - size_t nStartUnit = ((size_t)pMem + nMaxMemoryPerUnit - 1) / (nMaxMemoryPerUnit); - size_t nEndUnit = ((size_t)pMem + nCurrentUnitSize) / (nMaxMemoryPerUnit); - - if (nStartUnit > nUnitsPerLine) - { - nStartUnit = nUnitsPerLine; - } - - if (nEndUnit > nUnitsPerLine) - { - nEndUnit = nUnitsPerLine; - } - - for (size_t i = nStartUnit; i < nEndUnit; ++i) - { - vCoverage[i] = 1; - } - } - - ++nLocalUnits; - - // insert in linked list - *pMem = pMemoryBlocks; - pMemoryBlocks = pMem; - } - - nUnits += nLocalUnits; - nAvailableMem += nLocalUnits * nCurrentUnitSize; - - nCurrentUnitSize /= 2; - nUnits *= 2; - } - - // free all memory blocks allocated - while (pMemoryBlocks) - { - void* pNext = *pMemoryBlocks; - - ::free(pMemoryBlocks); - ++dwFreeCnt; - - pMemoryBlocks = (void**)pNext; - } - - - // _heapmin(); - - CryLog("CMemoryFragmentationProfiler Y=%d, available memory=%d MB, used memory=%d MB", - m_dwLine, (nAvailableMem + 1024 * 1024 - 1) / (1024 * 1024), (nUsedMem + 1024 * 1024 - 1) / (1024 * 1024)); - - LogCoverage(vCoverage); - - DumpToRAWCoverage(vCoverage); - } - -private: // ------------------------------------------------------------------ - - void Init() - { - FILE* out = nullptr; - azfopen(&out, "MemoryCoverage.bmp", "wb"); - - if (out) - { - BITMAPFILEHEADER pHeader; - BITMAPINFOHEADER pInfoHeader; - - memset(&pHeader, 0, sizeof(BITMAPFILEHEADER)); - memset(&pInfoHeader, 0, sizeof(BITMAPINFOHEADER)); - - pHeader.bfType = 0x4D42; - pHeader.bfSize = sizeof(BITMAPFILEHEADER) + sizeof(BITMAPINFOHEADER) + m_nPixelsPerLine * m_nLineCount * 3; - pHeader.bfOffBits = sizeof(BITMAPFILEHEADER) + sizeof(BITMAPINFOHEADER); - - pInfoHeader.biSize = sizeof(BITMAPINFOHEADER); - pInfoHeader.biWidth = m_nPixelsPerLine; - pInfoHeader.biHeight = m_nLineCount; - pInfoHeader.biPlanes = 1; - pInfoHeader.biBitCount = 24; - pInfoHeader.biCompression = 0; - pInfoHeader.biSizeImage = m_nPixelsPerLine * m_nLineCount; - - fwrite(&pHeader, 1, sizeof(BITMAPFILEHEADER), out); - fwrite(&pInfoHeader, 1, sizeof(BITMAPINFOHEADER), out); - - for (int y = 0; y < m_nLineCount; y++) // amount of lines - { - for (int x = 0; x < m_nPixelsPerLine; x++) - { - size_t nAddress = x * (0x100000000 / m_nPixelsPerLine); - - if (nAddress == 0x30000000 - || nAddress == 0x30500000 - || nAddress == 0x31000000 - || nAddress == 0x31500000 - || nAddress == 0x32000000 - || nAddress == 0x32500000 - || nAddress == 0x33500000 - || nAddress == 0x34000000 - || nAddress == 0x35000000 - || nAddress == 0x35500000 - || nAddress == 0x36000000 - || nAddress == 0x36500000 - || nAddress == 0x38000000 - || nAddress == 0x39000000) - { - putc((unsigned char)100, out); // blue DLL start - } - else - { - putc((unsigned char)0, out); // black - } - putc((unsigned char)0, out); - putc((unsigned char)0, out); - } - } - - fclose(out); - m_dwLine = 0; - } - } - - void LogCoverage(std::vector& vCov) - { - const size_t nCharPerLine = 128; // readable amount - - char szResult[nCharPerLine + 1], * pCursor = szResult; - - szResult[nCharPerLine] = 0; // zero termination - - size_t nSize = vCov.size(); - size_t nUnitsPerChar = nSize / nCharPerLine; - - for (size_t i = 0; i < nSize; ) - { - unsigned int nLocalCov = 0; - - for (size_t e = 0; e < nUnitsPerChar; ++e, ++i) - { - if (vCov[i]) - { - ++nLocalCov; - } - } - - if (nLocalCov == 0) - { - *pCursor++ = '#'; // occupied - } - else if (nLocalCov == nUnitsPerChar) - { - *pCursor++ = '.'; // free - } - else - { - *pCursor++ = '+'; // partly - } - } - - CryLog(" Coverage=%s", szResult); - } - - - void DumpToRAWCoverage(std::vector& vCov) - { - FILE* out = nullptr; - azfopen(&out, "MemoryCoverage.bmp", "rb+"); - - if (!out) - { - return; - } - - if (fseek(out, sizeof(BITMAPFILEHEADER) + sizeof(BITMAPINFOHEADER) + 3 * (m_nLineCount - 1 - m_dwLine) * m_nPixelsPerLine, SEEK_SET) != 0) - { - fclose(out); - return; - } - - size_t nSize = vCov.size(); - size_t nUnitsPerChar = nSize / m_nPixelsPerLine; - - for (size_t i = 0; i < nSize; ) - { - unsigned int nLocalCov = 0; - - for (size_t e = 0; e < nUnitsPerChar; ++e, ++i) - { - if (vCov[i]) - { - ++nLocalCov; - } - } - - size_t Val = 256 - (256 * nLocalCov) / nUnitsPerChar; - - if (Val > 0) - { - Val = 127 + Val / 2; - } - - putc((unsigned char)Val, out); - putc((unsigned char)Val, out); - putc((unsigned char)Val, out); // grey - } - - fclose(out); - - ++m_dwLine; - } - - - - unsigned int m_dwLine; // [0..m_nLineCount-1], m_nLineCount means bitmap is full, 0xffffffff means not initialized yet - static const size_t m_nPixelsPerLine = 1024; // bitmap width - static const size_t m_nLineCount = 128; // -}; - - -#else // defined(WIN32) || defined(WIN64) - - -class CMemoryFragmentationProfiler -{ -public: - void DumpMemoryCoverage() {} -}; - -#endif // defined(WIN32) || defined(WIN64) - - - -#endif // CRYINCLUDE_CRYSYSTEM_MEMORYFRAGMENTATIONPROFILER_H - - diff --git a/Code/CryEngine/CrySystem/MemoryManager.cpp b/Code/CryEngine/CrySystem/MemoryManager.cpp index 4704d2f5fe..3021d68539 100644 --- a/Code/CryEngine/CrySystem/MemoryManager.cpp +++ b/Code/CryEngine/CrySystem/MemoryManager.cpp @@ -17,7 +17,6 @@ #include "CustomMemoryHeap.h" #include "GeneralMemoryHeap.h" #include "PageMappingHeap.h" -#include "DefragAllocator.h" #if defined(AZ_RESTRICTED_PLATFORM) @@ -217,11 +216,6 @@ IPageMappingHeap* CCryMemoryManager::CreatePageMappingHeap(size_t addressSpace, return new CPageMappingHeap(addressSpace, sName); } -IDefragAllocator* CCryMemoryManager::CreateDefragAllocator() -{ - return new CDefragAllocator(); -} - extern "C" { CRYMEMORYMANAGER_API void CryGetIMemoryManagerInterface(void** pIMemoryManager) diff --git a/Code/CryEngine/CrySystem/MemoryManager.h b/Code/CryEngine/CrySystem/MemoryManager.h index e9d748e481..e29d5404d8 100644 --- a/Code/CryEngine/CrySystem/MemoryManager.h +++ b/Code/CryEngine/CrySystem/MemoryManager.h @@ -44,8 +44,6 @@ public: virtual IMemoryAddressRange* ReserveAddressRange(size_t capacity, const char* sName); virtual IPageMappingHeap* CreatePageMappingHeap(size_t addressSpace, const char* sName); - - virtual IDefragAllocator* CreateDefragAllocator(); }; #else typedef IMemoryManager CCryMemoryManager; diff --git a/Code/CryEngine/CrySystem/MiniGUI/DrawContext.cpp b/Code/CryEngine/CrySystem/MiniGUI/DrawContext.cpp deleted file mode 100644 index a45fde272b..0000000000 --- a/Code/CryEngine/CrySystem/MiniGUI/DrawContext.cpp +++ /dev/null @@ -1,160 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS 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 "DrawContext.h" -#include -#include -#include - -MINIGUI_BEGIN - -////////////////////////////////////////////////////////////////////////// -CDrawContext::CDrawContext(SMetrics* pMetrics) -{ - m_currentStackLevel = 0; - m_x = 0; - m_y = 0; - m_pMetrics = pMetrics; - m_color = ColorB(0, 0, 0, 0); - m_defaultZ = 0.0f; - m_pAuxRender = gEnv->pRenderer->GetIRenderAuxGeom(); - - m_frameWidth = (float)gEnv->pRenderer->GetWidth(); - m_frameHeight = (float)gEnv->pRenderer->GetHeight(); -} - -////////////////////////////////////////////////////////////////////////// -void CDrawContext::SetColor(ColorB color) -{ - m_color = color; -} - -////////////////////////////////////////////////////////////////////////// -void CDrawContext::DrawLine(float x0, float y0, float x1, float y1, float thickness /*= 1.0f */) -{ - m_pAuxRender->DrawLine(Vec3(m_x + x0, m_y + y0, m_defaultZ), m_color, Vec3(m_x + x1, m_y + y1, m_defaultZ), m_color, thickness); -} - -////////////////////////////////////////////////////////////////////////// -void CDrawContext::DrawTriangle(float x0, float y0, float x1, float y1, float x2, float y2) -{ - m_pAuxRender->DrawTriangle(Vec3(m_x + x0, m_y + y0, m_defaultZ), m_color, Vec3(m_x + x1, m_y + y1, m_defaultZ), m_color, Vec3(m_x + x2, m_y + y2, m_defaultZ), m_color); -} - -////////////////////////////////////////////////////////////////////////// -void CDrawContext::DrawRect(const Rect& rc) -{ - m_pAuxRender->DrawTriangle(Vec3(m_x + rc.left, m_y + rc.top, m_defaultZ), m_color, Vec3(m_x + rc.left, m_y + rc.bottom, m_defaultZ), m_color, Vec3(m_x + rc.right, m_y + rc.top, m_defaultZ), m_color); - m_pAuxRender->DrawTriangle(Vec3(m_x + rc.left, m_y + rc.bottom, m_defaultZ), m_color, Vec3(m_x + rc.right, m_y + rc.bottom, m_defaultZ), m_color, Vec3(m_x + rc.right, m_y + rc.top, m_defaultZ), m_color); -} - -////////////////////////////////////////////////////////////////////////// -void CDrawContext::DrawFrame(const Rect& rc, ColorB lineColor, ColorB solidColor, float thickness) -{ - ColorB prevColor = m_color; - - SetColor(solidColor); - DrawRect(rc); - - SetColor(lineColor); - - uint32 curFlags = m_pAuxRender->GetRenderFlags().m_renderFlags; - m_pAuxRender->SetRenderFlags(curFlags | e_DrawInFrontOn); - DrawLine(rc.left, rc.top, rc.right, rc.top, thickness); - DrawLine(rc.right, rc.top, rc.right, rc.bottom, thickness); - DrawLine(rc.left, rc.top, rc.left, rc.bottom, thickness); - DrawLine(rc.left, rc.bottom, rc.right, rc.bottom, thickness); - m_pAuxRender->SetRenderFlags(curFlags); - - m_color = prevColor; -} - -////////////////////////////////////////////////////////////////////////// -void CDrawContext::StartDrawing() -{ - uint32 width = gEnv->pRenderer->GetWidth(); - uint32 height = gEnv->pRenderer->GetHeight(); - - gEnv->pRenderer->Set2DMode(width, height, m_backupSceneMatrices); - - m_prevRenderFlags = m_pAuxRender->GetRenderFlags().m_renderFlags; - m_pAuxRender->SetRenderFlags(e_Mode3D | e_AlphaBlended | e_FillModeSolid | e_CullModeBack | e_DepthWriteOff | e_DepthTestOff); -} - -////////////////////////////////////////////////////////////////////////// -void CDrawContext::StopDrawing() -{ - // Restore old flags that where set before our draw context. - m_pAuxRender->SetRenderFlags(m_prevRenderFlags); - - gEnv->pRenderer->Unset2DMode(m_backupSceneMatrices); -} - -////////////////////////////////////////////////////////////////////////// -void CDrawContext::DrawString(float x, float y, float font_size, ETextAlign align, const char* format, ...) -{ - //text will be off screen - if (y > m_frameHeight || x > m_frameWidth) - { - return; - } - - va_list args; - va_start(args, format); - SDrawTextInfo ti; - ti.xscale = ti.yscale = font_size / 12.0f; // font size in pixels to text scale. - - ti.flags = eDrawText_Monospace | eDrawText_2D | eDrawText_FixedSize | eDrawText_IgnoreOverscan; - if (align == eTextAlign_Left) - { - } - else if (align == eTextAlign_Right) - { - ti.flags |= eDrawText_Right; - } - else if (align == eTextAlign_Center) - { - ti.flags |= eDrawText_Center; - } - ti.color[0] = (float)m_color.r / 255.0f; - ti.color[1] = (float)m_color.g / 255.0f; - ti.color[2] = (float)m_color.b / 255.0f; - ti.color[3] = (float)m_color.a / 255.0f; - gEnv->pRenderer->DrawTextQueued(Vec3(m_x + x, m_y + y, m_defaultZ), ti, format, args); - va_end(args); -} - -////////////////////////////////////////////////////////////////////////// -void CDrawContext::PushClientRect(const Rect& rc) -{ - m_currentStackLevel++; - assert(m_currentStackLevel < MAX_ORIGIN_STACK); - m_clientRectStack[m_currentStackLevel] = rc; - m_x += rc.left; - m_y += rc.top; -} - -////////////////////////////////////////////////////////////////////////// -void CDrawContext::PopClientRect() -{ - if (m_currentStackLevel > 0) - { - Rect& rc = m_clientRectStack[m_currentStackLevel]; - m_x -= rc.left; - m_y -= rc.top; - - m_currentStackLevel--; - } -} -MINIGUI_END diff --git a/Code/CryEngine/CrySystem/MiniGUI/DrawContext.h b/Code/CryEngine/CrySystem/MiniGUI/DrawContext.h deleted file mode 100644 index 6b1b8000ae..0000000000 --- a/Code/CryEngine/CrySystem/MiniGUI/DrawContext.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. - -// Description : DrawContext helper class for MiniGUI - - -#ifndef CRYINCLUDE_CRYSYSTEM_MINIGUI_DRAWCONTEXT_H -#define CRYINCLUDE_CRYSYSTEM_MINIGUI_DRAWCONTEXT_H -#pragma once - - -#include "ICryMiniGUI.h" -#include - -struct IRenderAuxGeom; - -MINIGUI_BEGIN - -enum ETextAlign -{ - eTextAlign_Left, - eTextAlign_Right, - eTextAlign_Center -}; - -////////////////////////////////////////////////////////////////////////// -// Context of MiniGUI drawing. -////////////////////////////////////////////////////////////////////////// -class CDrawContext -{ -public: - CDrawContext(SMetrics* pMetrics); - - // Must be called before any drawing happens - void StartDrawing(); - // Must be called after all drawing have been complete. - void StopDrawing(); - - void PushClientRect(const Rect& rc); - void PopClientRect(); - - SMetrics& Metrics() { return *m_pMetrics; } - void SetColor(ColorB color); - - void DrawLine(float x0, float y0, float x1, float y1, float thickness = 1.0f); - void DrawTriangle(float x0, float y0, float x1, float y1, float x2, float y2); - void DrawRect(const Rect& rc); - void DrawFrame(const Rect& rc, ColorB lineColor, ColorB solidColor, float thickness = 1.0f); - - void DrawString(float x, float y, float font_size, ETextAlign align, const char* format, ...); - - -protected: - SMetrics* m_pMetrics; - - ColorB m_color; - float m_defaultZ; - IRenderAuxGeom* m_pAuxRender; - uint32 m_prevRenderFlags; - - enum - { - MAX_ORIGIN_STACK = 16 - }; - - int m_currentStackLevel; - float m_x, m_y; // Reference X,Y positions - Rect m_clientRectStack[MAX_ORIGIN_STACK]; - - float m_frameWidth; - float m_frameHeight; - -private: - TransformationMatrices m_backupSceneMatrices; -}; - -MINIGUI_END - -#endif // CRYINCLUDE_CRYSYSTEM_MINIGUI_DRAWCONTEXT_H diff --git a/Code/CryEngine/CrySystem/MiniGUI/MiniButton.cpp b/Code/CryEngine/CrySystem/MiniGUI/MiniButton.cpp deleted file mode 100644 index cbedfe1eae..0000000000 --- a/Code/CryEngine/CrySystem/MiniGUI/MiniButton.cpp +++ /dev/null @@ -1,316 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS 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 : Button implementation in the MiniGUI - - -#include "CrySystem_precompiled.h" -#include "MiniButton.h" -#include "DrawContext.h" -#include -#include - -MINIGUI_BEGIN - - -CMiniButton::CMiniButton() -{ - m_pCVar = NULL; - m_fCVarValue[0] = 0; - m_fCVarValue[1] = 1; - m_saveStateOn = false; - m_clickCallback = NULL; - m_pCallbackData = NULL; - m_pConnectedCtrl = NULL; -} - -////////////////////////////////////////////////////////////////////////// -void CMiniButton::Reset() -{ - /*if (m_pCVar) - { - pCVar->Set( m_fCVarValue[0] ); - }*/ - - /*if(m_pConnectedCtrl) - { - m_pConnectedCtrl->SetVisible(false); - }*/ - - clear_flag(eCtrl_Checked); -} - -////////////////////////////////////////////////////////////////////////// -void CMiniButton::SaveState() -{ - if (is_flag(eCtrl_Checked)) - { - if (m_pConnectedCtrl && m_pConnectedCtrl->CheckFlag(eCtrl_Hidden)) - { - m_saveStateOn = false; - } - else - { - m_saveStateOn = true; - } - } - else - { - m_saveStateOn = false; - } -} - -////////////////////////////////////////////////////////////////////////// -void CMiniButton::RestoreState() -{ - if (m_pCVar) - { - if (m_pCVar->GetFVal() == m_fCVarValue[1]) - { - set_flag(eCtrl_Checked); - - - //Restoring CVars has caused a few issues, especially when the user is changing - //CVars through the console while perfHud is active, removing for now - //pCVar->Set( m_saveStateOn ? m_fCVarValue[1] : m_fCVarValue[0] ); - } - else - { - clear_flag(eCtrl_Checked); - } - } - else - { - //connected controls (tables / info boxes etc) now look after themselves - /*if(m_pConnectedCtrl) - { - m_pConnectedCtrl->SetVisible(m_saveStateOn); - }*/ - - if (CheckFlag(eCtrl_CheckButton)) - { - if (m_saveStateOn) - { - set_flag(eCtrl_Checked); - } - else - { - clear_flag(eCtrl_Checked); - } - } - } -} - -////////////////////////////////////////////////////////////////////////// -void CMiniButton::OnPaint(CDrawContext& dc) -{ - ColorB bkgColor = dc.Metrics().clrBackground; - - if (is_flag(eCtrl_Highlight)) - { - bkgColor = dc.Metrics().clrBackgroundHighlight; - } - else if (is_flag(eCtrl_Checked)) - { - //if connected control has been hidden, this button should not be checked - if (m_pConnectedCtrl && m_pConnectedCtrl->CheckFlag(eCtrl_Hidden)) - { - clear_flag(eCtrl_Checked); - } - else - { - bkgColor = dc.Metrics().clrBackgroundSelected; - } - } - - float borderThickness = 1.0f; - - if (is_flag(eCtrl_Focus)) - { - borderThickness = 3.0f; - } - - ColorB borderCol = dc.Metrics().clrFrameBorder; - - if (!m_pGUI->InFocus()) - { - borderCol = dc.Metrics().clrFrameBorderOutOfFocus; - bkgColor.a = dc.Metrics().outOfFocusAlpha; - } - - dc.DrawFrame(m_rect, borderCol, bkgColor, borderThickness); - - ColorB textColor = dc.Metrics().clrText; - - if (is_flag(eCtrl_Checked | eCtrl_Highlight)) - { - textColor = dc.Metrics().clrTextSelected; - } - - dc.SetColor(textColor); - - ETextAlign align; - float startX; - - if (is_flag(eCtrl_TextAlignCentre)) - { - startX = (m_rect.left + m_rect.right) / 2.f; - align = eTextAlign_Center; - } - else - { - startX = m_rect.left + 5.f; - align = eTextAlign_Left; - } - - dc.DrawString(startX, m_rect.top, dc.Metrics().fTitleSize, align, GetTitle()); - - //Check not very obvious -#if 0 - if (is_flag(eCtrl_Checked)) - { - // Draw checked mark. - float checkX = m_rect.left + 4; - float checkY = (m_rect.bottom + m_rect.top) * 0.5f; - dc.SetColor(dc.Metrics().clrChecked); - dc.DrawLine(checkX, checkY, checkX + 3, checkY + 3); - dc.DrawLine(checkX + 3, checkY + 3, checkX + 7, checkY - 6); - } -#endif -} - -////////////////////////////////////////////////////////////////////////// -void CMiniButton::SetRect(const Rect& rc) -{ - Rect newrc = rc; - newrc.bottom = newrc.top + m_pGUI->Metrics().fTitleSize + 2; - CMiniCtrl::SetRect(newrc); -} - -////////////////////////////////////////////////////////////////////////// -void CMiniButton::OnEvent(float x, float y, EMiniCtrlEvent event) -{ - switch (event) - { - case eCtrlEvent_LButtonDown: - { - SCommand cmd; - - if (CheckFlag(eCtrl_CheckButton)) - { - if (!CheckFlag(eCtrl_Checked)) - { - cmd.command = eCommand_ButtonChecked; - } - else - { - cmd.command = eCommand_ButtonUnchecked; - } - } - else - { - cmd.command = eCommand_ButtonPress; - } - - cmd.nCtrlID = GetId(); - cmd.pCtrl = this; - GetGUI()->OnCommand(cmd); - - if (CheckFlag(eCtrl_CheckButton)) - { - bool bOn = false; - - if (CheckFlag(eCtrl_Checked)) - { - bOn = false; - ClearFlag(eCtrl_Checked); - } - else - { - bOn = true; - SetFlag(eCtrl_Checked); - } - - if (m_pCVar) - { - m_pCVar->Set(m_fCVarValue[bOn ? 1 : 0]); - } - - if (m_pConnectedCtrl) - { - m_pConnectedCtrl->SetVisible(bOn); - } - } - else - { - //cross button behavior - if (m_pConnectedCtrl) - { - m_pConnectedCtrl->SetVisible(false); - } - } - - if (m_clickCallback) - { - m_clickCallback(m_pCallbackData, true); - } - } - break; - case eCtrlEvent_MouseOff: - { - if (m_pParent) - { - m_pParent->OnEvent(x, y, eCtrlEvent_MouseOff); - } - } - break; - } -} - -////////////////////////////////////////////////////////////////////////// -bool CMiniButton::SetControlCVar(const char* sCVarName, float fOffValue, float fOnValue) -{ - m_pCVar = GetISystem()->GetIConsole()->GetCVar(sCVarName); - - if (!m_pCVar) - { - CryLogAlways("failed to find CVar: %s\n", sCVarName); - } - - m_fCVarValue[0] = fOffValue; - m_fCVarValue[1] = fOnValue; - - if (m_pCVar && m_pCVar->GetFVal() == fOnValue) - { - set_flag(eCtrl_Checked); - } - - return true; -} - -////////////////////////////////////////////////////////////////////////// -bool CMiniButton::SetClickCallback(ClickCallback callback, void* pCallbackData) -{ - m_clickCallback = callback; - m_pCallbackData = pCallbackData; - return true; -} - -////////////////////////////////////////////////////////////////////////// -bool CMiniButton::SetConnectedCtrl(IMiniCtrl* pConnectedCtrl) -{ - m_pConnectedCtrl = pConnectedCtrl; - return true; -} - -MINIGUI_END diff --git a/Code/CryEngine/CrySystem/MiniGUI/MiniButton.h b/Code/CryEngine/CrySystem/MiniGUI/MiniButton.h deleted file mode 100644 index 3e45f6b4e4..0000000000 --- a/Code/CryEngine/CrySystem/MiniGUI/MiniButton.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. - -// Description : Button implementation in the MiniGUI - - -#ifndef CRYINCLUDE_CRYSYSTEM_MINIGUI_MINIBUTTON_H -#define CRYINCLUDE_CRYSYSTEM_MINIGUI_MINIBUTTON_H -#pragma once - - -#include "MiniGUI.h" - -MINIGUI_BEGIN - -////////////////////////////////////////////////////////////////////////// -// Root window all other controls derive from -class CMiniButton - : public CMiniCtrl -{ -public: - CMiniButton(); - - ////////////////////////////////////////////////////////////////////////// - // CMiniCtrl interface implementation. - ////////////////////////////////////////////////////////////////////////// - virtual EMiniCtrlType GetType() const { return eCtrlType_Button; } - virtual void SetRect(const Rect& rc); - virtual void OnPaint(CDrawContext& dc); - virtual void OnEvent(float x, float y, EMiniCtrlEvent event); - virtual void Reset(); - virtual void SaveState(); - virtual void RestoreState(); - ////////////////////////////////////////////////////////////////////////// - - virtual bool SetControlCVar(const char* sCVarName, float fOffValue, float fOnValue); - virtual bool SetClickCallback(ClickCallback callback, void* pCallbackData); - virtual bool SetConnectedCtrl(IMiniCtrl* pConnectedCtrl); - -protected: - ICVar* m_pCVar; - float m_fCVarValue[2]; - ClickCallback m_clickCallback; - void* m_pCallbackData; - IMiniCtrl* m_pConnectedCtrl; -}; - -MINIGUI_END - -#endif // CRYINCLUDE_CRYSYSTEM_MINIGUI_MINIBUTTON_H diff --git a/Code/CryEngine/CrySystem/MiniGUI/MiniGUI.cpp b/Code/CryEngine/CrySystem/MiniGUI/MiniGUI.cpp deleted file mode 100644 index 9b074ce537..0000000000 --- a/Code/CryEngine/CrySystem/MiniGUI/MiniGUI.cpp +++ /dev/null @@ -1,862 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS 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 MiniGUI class - - -#include "CrySystem_precompiled.h" -#include "MiniGUI.h" -#include "DrawContext.h" - -#include "MiniButton.h" -#include "MiniMenu.h" -#include "MiniInfoBox.h" -#include "MiniTable.h" - -#include -#include - -#include -#include -#include - -namespace minigui -{ - CRYREGISTER_SINGLETON_CLASS(CMiniGUI) -} - - -MINIGUI_BEGIN - -////////////////////////////////////////////////////////////////////////// -void CMiniGUI::InitMetrics() -{ - m_metrics.clrText = ColorB(255, 255, 255, 255); - m_metrics.clrTextSelected = ColorB(0, 255, 0, 255); - m_metrics.fTextSize = 12.0f; - - m_metrics.clrTitle = ColorB(255, 255, 255, 255); - - m_metrics.fTitleSize = 14.0f; - - const int backgroundAlpha = 255; - - m_metrics.clrBackground = ColorB(20, 20, 20, backgroundAlpha); - m_metrics.clrBackgroundHighlight = ColorB(10, 10, 150, backgroundAlpha); - m_metrics.clrBackgroundSelected = ColorB(10, 120, 10, backgroundAlpha); - - m_metrics.clrFrameBorder = ColorB(255, 0, 0, 255); - m_metrics.clrFrameBorderHighlight = ColorB(255, 255, 0, 255); - m_metrics.clrFrameBorderOutOfFocus = ColorB(0, 0, 0, 255); - - m_metrics.clrChecked = ColorB(0, 0, 0, 255); - m_metrics.outOfFocusAlpha = 32; -} - -class CMiniCtrlRoot - : public CMiniCtrl -{ -public: - CMiniCtrlRoot() {}; - virtual EMiniCtrlType GetType() const { return eCtrlType_Unknown; }; - virtual void OnPaint([[maybe_unused]] class CDrawContext& dc) {}; -}; - -////////////////////////////////////////////////////////////////////////// -CMiniGUI::CMiniGUI() - : m_enabled(false) - , m_inFocus(true) - , m_pDPadMenu(NULL) - , m_pMovingCtrl(NULL) -{ -} - -////////////////////////////////////////////////////////////////////////// -CMiniGUI::~CMiniGUI() -{ -} - -////////////////////////////////////////////////////////////////////////// -void CMiniGUI::Init() -{ - m_pEventListener = NULL; - InitMetrics(); - - AzFramework::InputChannelEventListener::Connect(); - - m_pRootCtrl = new CMiniCtrlRoot; -} - -////////////////////////////////////////////////////////////////////////// -void CMiniGUI::Reset() -{ - m_pRootCtrl->Reset(); -} - -////////////////////////////////////////////////////////////////////////// -void CMiniGUI::SaveState() -{ - m_pRootCtrl->SaveState(); -} - -////////////////////////////////////////////////////////////////////////// -void CMiniGUI::RestoreState() -{ - m_pRootCtrl->RestoreState(); -} - -////////////////////////////////////////////////////////////////////////// -void CMiniGUI::SetEnabled(bool status) -{ - m_enabled = status; -} - -////////////////////////////////////////////////////////////////////////// -void CMiniGUI::SetInFocus(bool status) -{ - if (status) - { - m_inFocus = true; - } - else - { - CloseDPadMenu(); - m_inFocus = false; - } -} - -////////////////////////////////////////////////////////////////////////// -void CMiniGUI::Done() -{ - AzFramework::InputChannelEventListener::Disconnect(); -} - - -////////////////////////////////////////////////////////////////////////// -void CMiniGUI::Draw() -{ - FUNCTION_PROFILER_FAST(GetISystem(), PROFILE_SYSTEM, g_bProfilerEnabled); - - // When console opened hide MiniGui - bool bConsoleOpened = gEnv->pConsole->IsOpened(); - if (m_enabled && !bConsoleOpened) - { - ProcessInput(); - - CDrawContext dc(&m_metrics); - dc.StartDrawing(); - { - // Draw all controls. - m_pRootCtrl->DrawCtrl(dc); - } - dc.StopDrawing(); - } -} - -////////////////////////////////////////////////////////////////////////// -void CMiniGUI::ProcessInput() -{ - //check we are not in digital selection mode - if (!m_pDPadMenu) - { - float mx(0), my(0); - AZ::Vector2 systemCursorPositionNormalized = AZ::Vector2::CreateZero(); - AzFramework::InputSystemCursorRequestBus::EventResult(systemCursorPositionNormalized, - AzFramework::InputDeviceMouse::Id, - &AzFramework::InputSystemCursorRequests::GetSystemCursorPositionNormalized); - mx = systemCursorPositionNormalized.GetX() * gEnv->pRenderer->GetWidth(); - my = systemCursorPositionNormalized.GetY() * gEnv->pRenderer->GetHeight(); - - //update moving control - if (m_pMovingCtrl) - { - m_pMovingCtrl->Move(mx, my); - } - - IMiniCtrl* pCtrl = GetCtrlFromPoint(mx, my); - if (pCtrl) - { - SetHighlight(pCtrl, true, mx, my); - } - else - { - SetHighlight(m_highlightedCtrl, false, mx, my); - } - } -} - -////////////////////////////////////////////////////////////////////////// -IMiniCtrl* CMiniGUI::GetCtrlFromPoint(float x, float y) const -{ - // Draw all controls. - return m_pRootCtrl->GetCtrlFromPoint(x, y); -} - -////////////////////////////////////////////////////////////////////////// -void CMiniGUI::SetHighlight(IMiniCtrl* pCtrl, bool bEnable, float x, float y) -{ - if (pCtrl) - { - if (m_highlightedCtrl && m_highlightedCtrl != pCtrl) - { - m_highlightedCtrl->OnEvent(x, y, eCtrlEvent_MouseOff); - m_highlightedCtrl->ClearFlag(eCtrl_Highlight); - } - - if (bEnable) - { - pCtrl->OnEvent(x, y, eCtrlEvent_MouseOver); - pCtrl->SetFlag(eCtrl_Highlight); - - m_highlightedCtrl = pCtrl; - } - else - { - pCtrl->OnEvent(x, y, eCtrlEvent_MouseOff); - pCtrl->ClearFlag(eCtrl_Highlight); - m_highlightedCtrl = NULL; - } - } - else - { - assert(bEnable == false); - - if (m_highlightedCtrl) - { - m_highlightedCtrl->OnEvent(x, y, eCtrlEvent_MouseOff); - m_highlightedCtrl->ClearFlag(eCtrl_Highlight); - m_highlightedCtrl = NULL; - } - } -} - -////////////////////////////////////////////////////////////////////////// -void CMiniGUI::SetFocus(IMiniCtrl* pCtrl, bool bEnable) -{ - if (m_focusCtrl) - { - m_focusCtrl->ClearFlag(eCtrl_Focus); - } - m_focusCtrl = pCtrl; - if (m_focusCtrl) - { - if (bEnable) - { - m_focusCtrl->SetFlag(eCtrl_Focus); - } - else - { - m_focusCtrl->ClearFlag(eCtrl_Focus); - } - } -} - -////////////////////////////////////////////////////////////////////////// -SMetrics& CMiniGUI::Metrics() -{ - return m_metrics; -} - -////////////////////////////////////////////////////////////////////////// -IMiniCtrl* CMiniGUI::CreateCtrl(IMiniCtrl* pParentCtrl, int nCtrlID, EMiniCtrlType type, int nCtrlFlags, const Rect& rc, const char* title) -{ - CMiniCtrl* pCtrl = 0; - // Test code. - switch (type) - { - case eCtrlType_Button: - pCtrl = new CMiniButton; - break; - case eCtrlType_Menu: - pCtrl = new CMiniMenu; - break; - case eCtrlType_InfoBox: - pCtrl = new CMiniInfoBox; - break; - case eCtrlType_Table: - pCtrl = new CMiniTable; - break; - default: - assert(0 && "Unknown MiniGUI control type"); - break; - } - ; - if (pCtrl) - { - pCtrl->SetGUI(this); - pCtrl->SetFlag(nCtrlFlags); - pCtrl->SetTitle(title); - pCtrl->SetRect(rc); - pCtrl->SetId(nCtrlID); - - if (pCtrl->CheckFlag(eCtrl_AutoResize)) - { - pCtrl->AutoResize(); - } - - if (pCtrl->CheckFlag(eCtrl_CloseButton)) - { - pCtrl->CreateCloseButton(); - } - - if (pParentCtrl) - { - pParentCtrl->AddSubCtrl(pCtrl); - } - else - { - m_pRootCtrl->AddSubCtrl(pCtrl); - } - - if (type == eCtrlType_Menu && pParentCtrl == NULL) - { - m_rootMenus.push_back(pCtrl); - } - } - return pCtrl; -} - -////////////////////////////////////////////////////////////////////////// -void CMiniGUI::OnCommand(SCommand& cmd) -{ - if (m_pEventListener) - { - m_pEventListener->OnCommand(cmd); - } -} - -////////////////////////////////////////////////////////////////////////// -void CMiniGUI::OnMouseInputEvent(const AzFramework::InputChannel& inputChannel) -{ - if (!m_inFocus || !m_enabled) - { - return; - } - - const AzFramework::InputChannel::PositionData2D* positionData2D = inputChannel.GetCustomData(); - if (!positionData2D) - { - return; - } - const float mx = positionData2D->m_normalizedPosition.GetX() * gEnv->pRenderer->GetWidth(); - const float my = positionData2D->m_normalizedPosition.GetY() * gEnv->pRenderer->GetHeight(); - IMiniCtrl* pCtrl = GetCtrlFromPoint(mx, my); - if (pCtrl) - { - const AzFramework::InputChannelId& channelId = inputChannel.GetInputChannelId(); - if (channelId == AzFramework::InputDeviceMouse::Button::Left) - { - if (inputChannel.IsStateBegan()) - { - pCtrl->OnEvent(mx, my, eCtrlEvent_LButtonDown); - } - else if (inputChannel.IsStateEnded()) - { - pCtrl->OnEvent(mx, my, eCtrlEvent_LButtonUp); - } - } - } -} - -void CMiniGUI::SetDPadMenu(IMiniCtrl* pMenu) -{ - m_pDPadMenu = (CMiniMenu*)pMenu; - UiCursorBus::Broadcast(&UiCursorInterface::DecrementVisibleCounter); -} - -void CMiniGUI::CloseDPadMenu() -{ - if (m_pDPadMenu) - { - CMiniMenu* closeMenu = m_pDPadMenu; - - //close menu and all parent menus - do - { - closeMenu->Close(); - closeMenu = (CMiniMenu*)closeMenu->GetParent(); - } while (closeMenu->GetType() == eCtrlType_Menu); - - m_pDPadMenu->ClearFlag(eCtrl_Highlight); - m_pDPadMenu = NULL; - UiCursorBus::Broadcast(&UiCursorInterface::IncrementVisibleCounter); - } -} - -void CMiniGUI::UpdateDPadMenu(const AzFramework::InputChannel& inputChannel) -{ - const AzFramework::InputChannelId& channelId = inputChannel.GetInputChannelId(); - const bool isPressed = inputChannel.IsStateBegan(); - - if (m_pDPadMenu) - { - if (channelId == AzFramework::InputDeviceGamepad::Button::B) - { - CloseDPadMenu(); - return; - } - - if (isPressed) - { - if (channelId == AzFramework::InputDeviceGamepad::Button::DD || - channelId == AzFramework::InputDeviceGamepad::ThumbStickDirection::LD) - { - m_pDPadMenu = m_pDPadMenu->UpdateSelection(eCtrlEvent_DPadDown); - } - else if (channelId == AzFramework::InputDeviceGamepad::Button::DU || - channelId == AzFramework::InputDeviceGamepad::ThumbStickDirection::LU) - { - m_pDPadMenu = m_pDPadMenu->UpdateSelection(eCtrlEvent_DPadUp); - } - else if (channelId == AzFramework::InputDeviceGamepad::Button::DL || - channelId == AzFramework::InputDeviceGamepad::ThumbStickDirection::LL) - { - CMiniMenu* pNewMenu = m_pDPadMenu->UpdateSelection(eCtrlEvent_DPadLeft); - - //get previous root menu - if (pNewMenu == NULL) - { - int i = 0, nRootMenus = m_rootMenus.size(); - - for (i = 0; i < nRootMenus; i++) - { - if (m_rootMenus[i] == m_pDPadMenu) - { - break; - } - } - - if (i > 0) - { - m_pDPadMenu->Close(); - m_pDPadMenu->ClearFlag(eCtrl_Highlight); - - m_pDPadMenu = (CMiniMenu*)m_rootMenus[i - 1]; - m_pDPadMenu->Open(); - m_pDPadMenu->SetFlag(eCtrl_Highlight); - } - //else selected menu remains the same - } - else - { - m_pDPadMenu = pNewMenu; - } - } - else if (channelId == AzFramework::InputDeviceGamepad::Button::DR || - channelId == AzFramework::InputDeviceGamepad::ThumbStickDirection::LR) - { - CMiniMenu* pNewMenu = m_pDPadMenu->UpdateSelection(eCtrlEvent_DPadRight); - - //get next root menu - if (pNewMenu == NULL) - { - int i = 0, nRootMenus = m_rootMenus.size(); - - for (i = 0; i < nRootMenus; i++) - { - if (m_rootMenus[i] == m_pDPadMenu) - { - break; - } - } - - if (i < nRootMenus - 1) - { - m_pDPadMenu->Close(); - m_pDPadMenu->ClearFlag(eCtrl_Highlight); - - m_pDPadMenu = (CMiniMenu*)m_rootMenus[i + 1]; - m_pDPadMenu->Open(); - m_pDPadMenu->SetFlag(eCtrl_Highlight); - } - //else selected menu remains the same - } - else - { - m_pDPadMenu = pNewMenu; - } - } - else if (channelId == AzFramework::InputDeviceGamepad::Button::A) - { - m_pDPadMenu = m_pDPadMenu->UpdateSelection(eCtrlEvent_LButtonDown); - } - } - } -} - -bool CMiniGUI::OnInputChannelEventFiltered(const AzFramework::InputChannel& inputChannel) -{ - const AzFramework::InputDeviceId& deviceId = inputChannel.GetInputDevice().GetInputDeviceId(); - if (AzFramework::InputDeviceMouse::IsMouseDevice(deviceId)) - { - OnMouseInputEvent(inputChannel); - return false; - } - - if (!m_inFocus) - { - return false; - } - - if (!AzFramework::InputDeviceGamepad::IsGamepadDevice(deviceId)) - { - return false; - } - - if (m_pDPadMenu) - { - UpdateDPadMenu(inputChannel); - } - else - { - float posX = 0.0f; - float posY = 0.0f; - const AzFramework::InputChannel::PositionData2D* positionData2D = inputChannel.GetCustomData(); - if (positionData2D) - { - posX = positionData2D->m_normalizedPosition.GetX() * gEnv->pRenderer->GetWidth(); - posY = positionData2D->m_normalizedPosition.GetY() * gEnv->pRenderer->GetHeight(); - } - - IMiniCtrl* pCtrl = GetCtrlFromPoint(posX, posY); - - if (pCtrl) - { - const AzFramework::InputChannelId& channelId = inputChannel.GetInputChannelId(); - if (channelId == AzFramework::InputDeviceGamepad::Button::A) - { - switch (inputChannel.GetState()) - { - case AzFramework::InputChannel::State::Began: - pCtrl->OnEvent(posX, posY, eCtrlEvent_LButtonDown); - break; - - case AzFramework::InputChannel::State::Ended: - pCtrl->OnEvent(posX, posY, eCtrlEvent_LButtonUp); - break; - - case AzFramework::InputChannel::State::Updated: - pCtrl->OnEvent(posX, posY, eCtrlEvent_LButtonPressed); - - //if we've clicked on a menu, enter menu selection mode, disable mouse - if (pCtrl->GetType() == eCtrlType_Menu) - { - SetDPadMenu(pCtrl); - } - - break; - } - } - } - } - - return false; -} - -////////////////////////////////////////////////////////////////////////// -void CMiniGUI::SetEventListener(IMiniGUIEventListener* pListener) -{ - m_pEventListener = pListener; -} - -////////////////////////////////////////////////////////////////////////// -void CMiniGUI::RemoveAllCtrl() -{ - m_highlightedCtrl = NULL; - - //reset all console variables to default state - Reset(); - - m_pRootCtrl->RemoveAllSubCtrl(); -} - -////////////////////////////////////////////////////////////////////////// -//CMiniCtrl -////////////////////////////////////////////////////////////////////////// - -////////////////////////////////////////////////////////////////////////// -void CMiniCtrl::Reset() -{ - for (int i = 0, num = GetSubCtrlCount(); i < num; i++) - { - IMiniCtrl* pSubCtrl = GetSubCtrl(i); - pSubCtrl->Reset(); - } -} - -////////////////////////////////////////////////////////////////////////// -void CMiniCtrl::SaveState() -{ - for (int i = 0, num = GetSubCtrlCount(); i < num; i++) - { - IMiniCtrl* pSubCtrl = GetSubCtrl(i); - pSubCtrl->SaveState(); - } -} - -////////////////////////////////////////////////////////////////////////// -void CMiniCtrl::RestoreState() -{ - for (int i = 0, num = GetSubCtrlCount(); i < num; i++) - { - IMiniCtrl* pSubCtrl = GetSubCtrl(i); - pSubCtrl->RestoreState(); - } -} - -////////////////////////////////////////////////////////////////////////// -void CMiniCtrl::AddSubCtrl(IMiniCtrl* pCtrl) -{ - assert(pCtrl); - _smart_ptr pTempCtrl(pCtrl); - IMiniCtrl* pParent = pCtrl->GetParent(); - if (pParent) - { - pParent->RemoveSubCtrl(pCtrl); - } - - static_cast(pCtrl)->m_pParent = this; - m_subCtrls.push_back(pCtrl); -} - -////////////////////////////////////////////////////////////////////////// -void CMiniCtrl::RemoveSubCtrl(IMiniCtrl* pCtrl) -{ - assert(pCtrl); - _smart_ptr pTempCtrl(pCtrl); - IMiniCtrl* pParent = pCtrl->GetParent(); - if (pParent == this) - { - static_cast(pCtrl)->m_pParent = 0; - for (int i = 0, num = (int)m_subCtrls.size(); i < num; i++) - { - if (m_subCtrls[i] == pCtrl) - { - m_subCtrls.erase(m_subCtrls.begin() + i); - break; - } - } - } -} - -////////////////////////////////////////////////////////////////////////// -void CMiniCtrl::RemoveAllSubCtrl() -{ - int nSubCtrls = m_subCtrls.size(); - - if (nSubCtrls) - { - for (int i = 0; i < nSubCtrls; i++) - { - IMiniCtrl* pSubCtrl = m_subCtrls[i].get(); - pSubCtrl->RemoveAllSubCtrl(); - } - - m_subCtrls.clear(); - } -} - -////////////////////////////////////////////////////////////////////////// -IMiniCtrl* CMiniCtrl::GetCtrlFromPoint(float x, float y) -{ - if (is_flag(eCtrl_Hidden)) - { - return 0; - } - - for (int i = 0, num = (int)m_subCtrls.size(); i < num; i++) - { - float lx = x - m_rect.left; - float ly = y - m_rect.top; - IMiniCtrl* pHit = m_subCtrls[i]->GetCtrlFromPoint(lx, ly); - if (pHit) - { - return pHit; - } - } - if (m_rect.IsPointInside(x, y)) - { - return this; - } - - return 0; -} - -////////////////////////////////////////////////////////////////////////// -void CMiniCtrl::DrawCtrl(CDrawContext& dc) -{ - OnPaint(dc); - - dc.PushClientRect(m_rect); - - for (int i = 0, num = (int)m_subCtrls.size(); i < num; i++) - { - CMiniCtrl* pCtrl = static_cast((IMiniCtrl*)m_subCtrls[i]); - if (!pCtrl->is_flag(eCtrl_Hidden)) - { - pCtrl->DrawCtrl(dc); - } - } - - dc.PopClientRect(); -} - -////////////////////////////////////////////////////////////////////////// -int CMiniCtrl::GetSubCtrlCount() const -{ - return (int)m_subCtrls.size(); -} - -////////////////////////////////////////////////////////////////////////// -IMiniCtrl* CMiniCtrl::GetSubCtrl(int nIndex) const -{ - assert(nIndex >= 0 && nIndex < (int)m_subCtrls.size()); - return m_subCtrls[nIndex]; -} - -////////////////////////////////////////////////////////////////////////// -void CMiniCtrl::SetRect(const Rect& rc) -{ - m_rect = rc; - - if (m_pCloseButton) - { - float width = rc.Width(); - - //relative position of cross box - Rect closeRect(width - 20.f, 0.f, width, 20.f); - m_pCloseButton->SetRect(closeRect); - } -} - -////////////////////////////////////////////////////////////////////////// -void CMiniCtrl::SetVisible(bool state) -{ - if (state) - { - clear_flag(eCtrl_Hidden); - } - else - { - set_flag(eCtrl_Hidden); - } - - if (m_pCloseButton) - { - m_pCloseButton->SetVisible(state); - } -} - -////////////////////////////////////////////////////////////////////////// -void CMiniCtrl::AutoResize() -{ - uint32 stringLen = m_title.length(); - - if (stringLen) - { - //just an approximation for now - should take into account font size / kerning - m_rect.right = m_rect.left + (8.5f * stringLen); - } - - m_requiresResize = false; -} - -////////////////////////////////////////////////////////////////////////// -void CMiniCtrl::StartMoving(float x, float y) -{ - if (!m_moving) - { - m_prevX = x; - m_prevY = y; - m_moving = true; - - m_pGUI->SetMovingCtrl(this); - } -} - -////////////////////////////////////////////////////////////////////////// -void CMiniCtrl::StopMoving() -{ - if (m_moving) - { - m_moving = false; - m_pGUI->SetMovingCtrl(NULL); - } -} - -////////////////////////////////////////////////////////////////////////// -void CMiniCtrl::Move(float x, float y) -{ - if (m_moving) - { - float moveX = x - m_prevX; - float moveY = y - m_prevY; - - m_rect.top += moveY; - m_rect.bottom += moveY; - - m_rect.left += moveX; - m_rect.right += moveX; - - m_prevX = x; - m_prevY = y; - } -} - -////////////////////////////////////////////////////////////////////////// -void CMiniCtrl::OnEvent(float x, float y, EMiniCtrlEvent event) -{ - switch (event) - { - case eCtrlEvent_LButtonDown: - { - if (is_flag(eCtrl_Highlight | eCtrl_Moveable)) - { - StartMoving(x, y); - } - } - break; - - case eCtrlEvent_LButtonUp: - if (m_moving) - { - StopMoving(); - } - break; - - case eCtrlEvent_MouseOver: - break; - } -} - -////////////////////////////////////////////////////////////////////////// -void CMiniCtrl::CreateCloseButton() -{ - if (m_pGUI) - { - m_pCloseButton = m_pGUI->CreateCtrl(this, 100, eCtrlType_Button, 0, Rect(0, 0, 100, 20), "X"); - - if (m_pCloseButton) - { - m_pCloseButton->SetConnectedCtrl(this); - - float width = m_rect.Width(); - - //relative position of cross box - Rect closeRect(width - 20.f, 0.f, width, 20.f); - m_pCloseButton->SetRect(closeRect); - } - } -} - -MINIGUI_END diff --git a/Code/CryEngine/CrySystem/MiniGUI/MiniGUI.h b/Code/CryEngine/CrySystem/MiniGUI/MiniGUI.h deleted file mode 100644 index a4db53070f..0000000000 --- a/Code/CryEngine/CrySystem/MiniGUI/MiniGUI.h +++ /dev/null @@ -1,219 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS 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 Mini GUI subsystem - - -#ifndef CRYINCLUDE_CRYSYSTEM_MINIGUI_MINIGUI_H -#define CRYINCLUDE_CRYSYSTEM_MINIGUI_MINIGUI_H -#pragma once - - -#include "ICryMiniGUI.h" -#include - -#include - -#include - -MINIGUI_BEGIN - -class CMiniMenu; - -////////////////////////////////////////////////////////////////////////// -// Root window all other controls derive from -class CMiniCtrl - : public IMiniCtrl -{ -public: - - CMiniCtrl() - : m_nFlags(0) - , m_id(0) - , m_renderCallback(NULL) - , m_fTextSize(12.f) - , m_prevX(0.f) - , m_prevY(0.f) - , m_moving(false) - , m_requiresResize(false) - , m_pCloseButton(NULL) - , m_saveStateOn(false) - {}; - - ////////////////////////////////////////////////////////////////////////// - // IMiniCtrl interface implementation. - ////////////////////////////////////////////////////////////////////////// - virtual void Reset(); - virtual void SaveState(); - virtual void RestoreState(); - - virtual void SetGUI(IMiniGUI* pGUI) { m_pGUI = pGUI; }; - virtual IMiniGUI* GetGUI() const { return m_pGUI; }; - - virtual int GetId() const { return m_id; }; - virtual void SetId(int id) { m_id = id; }; - - virtual const char* GetTitle() const { return m_title; }; - virtual void SetTitle(const char* title) { m_title = title; }; - - virtual Rect GetRect() const { return m_rect; } - virtual void SetRect(const Rect& rc); - - virtual void SetFlag(uint32 flag) { set_flag(flag); } - virtual void ClearFlag(uint32 flag) { clear_flag(flag); }; - virtual bool CheckFlag(uint32 flag) const { return is_flag(flag); } - - virtual void AddSubCtrl(IMiniCtrl* pCtrl); - virtual void RemoveSubCtrl(IMiniCtrl* pCtrl); - virtual void RemoveAllSubCtrl(); - virtual int GetSubCtrlCount() const; - virtual IMiniCtrl* GetSubCtrl(int nIndex) const; - virtual IMiniCtrl* GetParent() const { return m_pParent; }; - - virtual IMiniCtrl* GetCtrlFromPoint(float x, float y); - - virtual void SetVisible(bool state); - - virtual void OnEvent(float x, float y, EMiniCtrlEvent); - - virtual bool SetRenderCallback(RenderCallback callback) { m_renderCallback = callback; return true; }; - - - // Not implemented in base control - virtual bool SetControlCVar([[maybe_unused]] const char* sCVarName, [[maybe_unused]] float fOffValue, [[maybe_unused]] float fOnValue) { assert(0); return false; }; - virtual bool SetClickCallback([[maybe_unused]] ClickCallback callback, [[maybe_unused]] void* pCallbackData) { assert(0); return false; }; - virtual bool SetConnectedCtrl([[maybe_unused]] IMiniCtrl* pConnectedCtrl) { assert(0); return false; }; - - ////////////////////////////////////////////////////////////////////////// - - ////////////////////////////////////////////////////////////////////////// - virtual void AutoResize(); - - ////////////////////////////////////////////////////////////////////////// - virtual void CreateCloseButton(); - - void DrawCtrl(CDrawContext& dc); - - virtual void Move(float x, float y); - -protected: - void set_flag(uint32 flag) { m_nFlags |= flag; } - void clear_flag(uint32 flag) { m_nFlags &= ~flag; }; - bool is_flag(uint32 flag) const { return (m_nFlags & flag) == flag; } - - //dynamic movement - void StartMoving(float x, float y); - void StopMoving(); - -protected: - int m_id; - IMiniGUI* m_pGUI; - uint32 m_nFlags; - CryFixedStringT<32> m_title; - Rect m_rect; - _smart_ptr m_pParent; - std::vector m_subCtrls; - RenderCallback m_renderCallback; - float m_fTextSize; - - //optional close 'X' button on controls, ref counted by m_subCtrls - IMiniCtrl* m_pCloseButton; - - //dynamic movement - float m_prevX; - float m_prevY; - bool m_moving; - bool m_requiresResize; - bool m_saveStateOn; -}; - -////////////////////////////////////////////////////////////////////////// -class CMiniGUI - : public IMiniGUI - , public AzFramework::InputChannelEventListener -{ -public: - CRYINTERFACE_BEGIN() - CRYINTERFACE_ADD(IMiniGUI) - CRYINTERFACE_END() - CRYGENERATE_SINGLETONCLASS(CMiniGUI, "MiniGUI", 0x1a049b879a4e4b58, 0xac14026e17e6255e) - -public: - void InitMetrics(); - void ProcessInput(); - - ////////////////////////////////////////////////////////////////////////// - // IMiniGUI interface implementation. - ////////////////////////////////////////////////////////////////////////// - virtual void Init(); - virtual void Done(); - virtual void Draw(); - virtual void Reset(); - virtual void SaveState(); - virtual void RestoreState(); - virtual void SetEnabled(bool status); - virtual void SetInFocus(bool status); - virtual bool InFocus() {return m_inFocus; } - - virtual void SetEventListener(IMiniGUIEventListener* pListener); - - virtual SMetrics& Metrics(); - - virtual void OnCommand(SCommand& cmd); - - virtual void RemoveAllCtrl(); - virtual IMiniCtrl* CreateCtrl(IMiniCtrl* pParentCtrl, int nCtrlID, EMiniCtrlType type, int nCtrlFlags, const Rect& rc, const char* title); - - virtual IMiniCtrl* GetCtrlFromPoint(float x, float y) const; - - void SetHighlight(IMiniCtrl* pCtrl, bool bEnable, float x, float y); - void SetFocus(IMiniCtrl* pCtrl, bool bEnable); - - // AzFramework::InputChannelEventListener - bool OnInputChannelEventFiltered(const AzFramework::InputChannel& inputChannel) override; - AZ::s32 GetPriority() const override { return AzFramework::InputChannelEventListener::GetPriorityUI(); } - - virtual void SetMovingCtrl(IMiniCtrl* pCtrl) - { - m_pMovingCtrl = pCtrl; - } - -protected: - void OnMouseInputEvent(const AzFramework::InputChannel& inputChannel); - - //DPad menu navigation - void UpdateDPadMenu(const AzFramework::InputChannel& inputChannel); - void SetDPadMenu(IMiniCtrl* pMenu); - void CloseDPadMenu(); - -protected: - bool m_enabled; - bool m_inFocus; - - SMetrics m_metrics; - - _smart_ptr m_pRootCtrl; - - _smart_ptr m_highlightedCtrl; - _smart_ptr m_focusCtrl; - - IMiniGUIEventListener* m_pEventListener; - - CMiniMenu* m_pDPadMenu; - IMiniCtrl* m_pMovingCtrl; - std::vector m_rootMenus; -}; - -MINIGUI_END - -#endif // CRYINCLUDE_CRYSYSTEM_MINIGUI_MINIGUI_H diff --git a/Code/CryEngine/CrySystem/MiniGUI/MiniInfoBox.cpp b/Code/CryEngine/CrySystem/MiniGUI/MiniInfoBox.cpp deleted file mode 100644 index 74114b9156..0000000000 --- a/Code/CryEngine/CrySystem/MiniGUI/MiniInfoBox.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. - -// Description : Button implementation in the MiniGUI - - -#include "CrySystem_precompiled.h" -#include "MiniInfoBox.h" -#include "DrawContext.h" -#include - -MINIGUI_BEGIN - - -CMiniInfoBox::CMiniInfoBox() - : m_fTextIndent(4) -{ -} - -////////////////////////////////////////////////////////////////////////// -void CMiniInfoBox::SaveState() -{ - if (CheckFlag(eCtrl_Hidden)) - { - m_saveStateOn = false; - } - else - { - m_saveStateOn = true; - } -} - -////////////////////////////////////////////////////////////////////////// -void CMiniInfoBox::Reset() -{ - SetFlag(eCtrl_Hidden); -} - -////////////////////////////////////////////////////////////////////////// -void CMiniInfoBox::RestoreState() -{ - if (m_saveStateOn) - { - ClearFlag(eCtrl_Hidden); - } -} - -////////////////////////////////////////////////////////////////////////// -void CMiniInfoBox::OnPaint(CDrawContext& dc) -{ - if (m_requiresResize) - { - AutoResize(); - } - - ColorB borderCol = dc.Metrics().clrFrameBorder; - ColorB backgroundCol = dc.Metrics().clrBackground; - - if (!m_pGUI->InFocus()) - { - borderCol = dc.Metrics().clrFrameBorderOutOfFocus; - backgroundCol.a = dc.Metrics().outOfFocusAlpha; - } - else if (m_moving) - { - borderCol = dc.Metrics().clrFrameBorderHighlight; - } - - dc.DrawFrame(m_rect, borderCol, backgroundCol); - - dc.SetColor(dc.Metrics().clrTitle); - dc.DrawString(m_rect.left + 4, m_rect.top, dc.Metrics().fTitleSize, eTextAlign_Left, GetTitle()); - - float fTextSize = m_fTextSize; - if (fTextSize == 0) - { - fTextSize = dc.Metrics().fTextSize; - } - - float x = m_fTextIndent + m_rect.left + 8; - float y = m_rect.top + fTextSize + fTextSize; - // Draw entries. - for (int i = 0, num = (int)m_entries.size(); i < num; i++) - { - SInfoEntry& info = m_entries[i]; - dc.SetColor(info.color); - dc.DrawString(x, y, info.textSize, eTextAlign_Left, info.text); - y += info.textSize * 0.8f; - if (y + info.textSize > m_rect.bottom) - { - break; - } - } - - if (m_renderCallback) - { - m_renderCallback(m_rect.left, m_rect.top); - } -} - - -////////////////////////////////////////////////////////////////////////// -void CMiniInfoBox::OnEvent(float x, float y, EMiniCtrlEvent event) -{ - CMiniCtrl::OnEvent(x, y, event); -} - -void CMiniInfoBox::AddEntry(const char* str, ColorB col, float textSize) -{ - SInfoEntry info; - - info.color = col; - info.textSize = textSize; - cry_strcpy(info.text, str); - - m_entries.push_back(info); - - if (CheckFlag(eCtrl_AutoResize)) - { - //set dirty flag instead of resizing for every elem - m_requiresResize = true; //AutoResize(); - } -} - -void CMiniInfoBox::ClearEntries() -{ - m_entries.clear(); - m_requiresResize = true; -} - -////////////////////////////////////////////////////////////////////////// -void CMiniInfoBox::AutoResize() -{ - float width = 0.f; - float height = 32.f; - - //must be at least the size of title and cross box - width = m_fTextIndent + ((float)m_title.size() * 14.f) + 30.f; - - for (int i = 0, num = (int)m_entries.size(); i < num; i++) - { - SInfoEntry& info = m_entries[i]; - - uint32 strLength = strlen(info.text); - - float strSize = info.textSize * strLength; - - width = max(strSize, width); - height += info.textSize * 0.8f; - } - - //scale width, could do with kerning info - width *= 0.6f; - - Rect newRect = m_rect; - newRect.right = newRect.left + width; - newRect.bottom = newRect.top + height; - - SetRect(newRect); - - m_requiresResize = false; -} - -MINIGUI_END diff --git a/Code/CryEngine/CrySystem/MiniGUI/MiniInfoBox.h b/Code/CryEngine/CrySystem/MiniGUI/MiniInfoBox.h deleted file mode 100644 index dbe8a668d6..0000000000 --- a/Code/CryEngine/CrySystem/MiniGUI/MiniInfoBox.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. - -// Description : Button implementation in the MiniGUI - -#ifndef CRYINCLUDE_CRYSYSTEM_MINIGUI_MINIINFOBOX_H -#define CRYINCLUDE_CRYSYSTEM_MINIGUI_MINIINFOBOX_H -#pragma once - - -#include "MiniGUI.h" - -MINIGUI_BEGIN - -////////////////////////////////////////////////////////////////////////// -// Root window all other controls derive from -class CMiniInfoBox - : public CMiniCtrl - , public IMiniInfoBox -{ -public: - CMiniInfoBox(); - - ////////////////////////////////////////////////////////////////////////// - // CMiniCtrl interface implementation. - ////////////////////////////////////////////////////////////////////////// - virtual EMiniCtrlType GetType() const { return eCtrlType_InfoBox; } - virtual void OnPaint(CDrawContext& dc); - virtual void OnEvent(float x, float y, EMiniCtrlEvent event); - virtual void Reset(); - virtual void SaveState(); - virtual void RestoreState(); - virtual void AutoResize(); - ////////////////////////////////////////////////////////////////////////// - - virtual void SetTextIndent(float x) { m_fTextIndent = x; } - virtual void SetTextSize(float sz) { m_fTextSize = sz; } - virtual void ClearEntries(); - virtual void AddEntry(const char* str, ColorB col, float textSize); - - ////////////////////////////////////////////////////////////////////////// - // IMiniTable interface implementation. - ////////////////////////////////////////////////////////////////////////// - virtual bool IsHidden() { return CheckFlag(eCtrl_Hidden); } - virtual void Hide(bool stat) { SetVisible(!stat); } - -public: - - ////////////////////////////////////////////////////////////////////////// - - static const int MAX_TEXT_LENGTH = 64; - - struct SInfoEntry - { - char text[MAX_TEXT_LENGTH]; - ColorB color; - float textSize; - }; - ////////////////////////////////////////////////////////////////////////// - -protected: - - std::vector m_entries; - float m_fTextIndent; -}; - -MINIGUI_END - -#endif // CRYINCLUDE_CRYSYSTEM_MINIGUI_MINIINFOBOX_H diff --git a/Code/CryEngine/CrySystem/MiniGUI/MiniMenu.cpp b/Code/CryEngine/CrySystem/MiniGUI/MiniMenu.cpp deleted file mode 100644 index f905f0f998..0000000000 --- a/Code/CryEngine/CrySystem/MiniGUI/MiniMenu.cpp +++ /dev/null @@ -1,364 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -// Description : Button implementation in the MiniGUI - - -#include "CrySystem_precompiled.h" -#include "MiniMenu.h" -#include "DrawContext.h" - -MINIGUI_BEGIN - - -CMiniMenu::CMiniMenu() -{ - m_bVisible = false; - m_bSubMenu = false; - m_menuWidth = 0.f; - m_selectionIndex = -1; -} - -////////////////////////////////////////////////////////////////////////// -void CMiniMenu::OnPaint(CDrawContext& dc) -{ - CMiniButton::OnPaint(dc); - - if (m_bSubMenu) - { - // Draw checked mark. - float x1 = m_rect.right - 12; - float y1 = m_rect.top + 3; - - float x2 = m_rect.right - 3; - float y2 = (m_rect.bottom + m_rect.top) / 2; - - float x3 = m_rect.right - 12; - float y3 = m_rect.bottom - 3; - - dc.SetColor(ColorB(0, 0, 0, 255)); - - dc.DrawLine(x1, y1, x2, y2, 2.f); - dc.DrawLine(x2, y2, x3, y3, 2.f); - - x1 -= 1; - x2 -= 1; - x3 -= 1; - y1 -= 1; - y2 -= 1; - y3 -= 1; - - dc.SetColor(ColorB(255, 255, 255, 255)); - - dc.DrawLine(x1, y1, x2, y2, 2.f); - dc.DrawLine(x2, y2, x3, y3, 2.f); - } - - - //dc.DrawFrame( m_rect,dc.Metrics().clrFrameBorder,dc.Metrics().clrBackground ); -} - -////////////////////////////////////////////////////////////////////////// -void CMiniMenu::SetRect(const Rect& rc) -{ - Rect newrc = rc; - newrc.bottom = newrc.top + m_pGUI->Metrics().fTitleSize + 2; - CMiniCtrl::SetRect(newrc); -} - -////////////////////////////////////////////////////////////////////////// -void CMiniMenu::OnEvent(float x, float y, EMiniCtrlEvent event) -{ - switch (event) - { - case eCtrlEvent_LButtonDown: - { - if (m_bVisible) - { - Close(); - } - else - { - Open(); - } - } - break; - case eCtrlEvent_MouseOff: - { - bool closeMenu = true; - IMiniCtrl* pCtrl = m_pGUI->GetCtrlFromPoint(x, y); - - //check if the cursor is still in one of the menu's children - if (pCtrl) - { - for (int i = 0, num = GetSubCtrlCount(); i < num; i++) - { - if (pCtrl == GetSubCtrl(i)) - { - closeMenu = false; - break; - } - } - } - - if (closeMenu) - { - Close(); - - if (m_pParent) - { - m_pParent->OnEvent(x, y, eCtrlEvent_MouseOff); - } - } - } - break; - } -} - -CMiniMenu* CMiniMenu::UpdateSelection(EMiniCtrlEvent event) -{ - CMiniMenu* pNewMenu = this; - IMiniCtrl* pCurrentSelection = NULL; - - if (m_selectionIndex != -1) - { - pCurrentSelection = m_subCtrls[m_selectionIndex]; - } - - switch (event) - { - case eCtrlEvent_DPadLeft: //move to parent - if (!pCurrentSelection) - { - //move to previous root menu - pNewMenu = NULL; - } - else if (m_bSubMenu) - { - Close(); - pNewMenu = (CMiniMenu*)m_pParent.get(); - //pNewMenu->SetFlag(eCtrl_Highlight); - } - break; - - case eCtrlEvent_DPadRight: //move to child - if (!pCurrentSelection) - { - //move to next root menu - pNewMenu = NULL; - } - else if (pCurrentSelection->GetType() == eCtrlType_Menu) - { - pNewMenu = (CMiniMenu*)pCurrentSelection; - pNewMenu->Open(); - pNewMenu->ClearFlag(eCtrl_Highlight); - } - break; - - case eCtrlEvent_DPadUp: //move up list - if (m_bSubMenu) - { - if (m_selectionIndex > 0) - { - m_selectionIndex--; - } - } - else - { - if (m_selectionIndex >= 0) - { - m_selectionIndex--; - - if (m_selectionIndex == -1) - { - SetFlag(eCtrl_Highlight); - } - } - } - break; - - case eCtrlEvent_DPadDown: //move down the list - if (m_selectionIndex < (int)(m_subCtrls.size() - 1)) - { - if (m_selectionIndex == -1) - { - ClearFlag(eCtrl_Highlight); - } - m_selectionIndex++; - } - break; - - case eCtrlEvent_LButtonDown: //pass on button press - { - if (pCurrentSelection) - { - if (pCurrentSelection->GetType() == eCtrlType_Menu) - { - pNewMenu = (CMiniMenu*)pCurrentSelection; - } - pCurrentSelection->OnEvent(0, 0, eCtrlEvent_LButtonDown); - } - else - { - OnEvent(0, 0, eCtrlEvent_LButtonDown); - } - } - break; - } - - if (pCurrentSelection) - { - pCurrentSelection->ClearFlag(eCtrl_Highlight); - } - - if (m_selectionIndex >= 0) - { - m_subCtrls[m_selectionIndex]->SetFlag(eCtrl_Highlight); - } - - return pNewMenu; -} - -////////////////////////////////////////////////////////////////////////// -void CMiniMenu::Open() -{ - m_bVisible = true; - - Rect rc(0, 0, m_menuWidth, 1); - - //render sub menu to the right - if (m_bSubMenu) - { - CMiniMenu* pParent = static_cast(m_pParent.get()); - rc.left = pParent->m_menuWidth; //rcParent.right; - rc.right = rc.left + m_menuWidth; - } - else - { - Rect rcThis = GetRect(); - rc.top = rcThis.Height(); - } - - for (int i = 0, num = GetSubCtrlCount(); i < num; i++) - { - IMiniCtrl* pSubCtrl = GetSubCtrl(i); - pSubCtrl->ClearFlag(eCtrl_Hidden); - float h = pSubCtrl->GetRect().Height(); - Rect rcCtrl = rc; - rcCtrl.top = rc.top; - rcCtrl.bottom = rcCtrl.top + h; - pSubCtrl->SetRect(rcCtrl); - rc.top += h; - } - - //highlight first item when opened - if (m_bSubMenu) - { - m_selectionIndex = 0; - m_subCtrls[m_selectionIndex]->SetFlag(eCtrl_Highlight); - } -} - -////////////////////////////////////////////////////////////////////////// -void CMiniMenu::Close() -{ - m_bVisible = false; - - for (int i = 0, num = GetSubCtrlCount(); i < num; i++) - { - IMiniCtrl* pSubCtrl = GetSubCtrl(i); - pSubCtrl->SetFlag(eCtrl_Hidden); - } - - if (m_selectionIndex != -1) - { - m_subCtrls[m_selectionIndex]->ClearFlag(eCtrl_Highlight); - } - m_selectionIndex = -1; -} - -////////////////////////////////////////////////////////////////////////// -void CMiniMenu::Reset() -{ - m_bVisible = false; - - for (int i = 0, num = GetSubCtrlCount(); i < num; i++) - { - IMiniCtrl* pSubCtrl = GetSubCtrl(i); - pSubCtrl->Reset(); - } -} - -////////////////////////////////////////////////////////////////////////// -void CMiniMenu::SaveState() -{ - for (int i = 0, num = GetSubCtrlCount(); i < num; i++) - { - IMiniCtrl* pSubCtrl = GetSubCtrl(i); - pSubCtrl->SaveState(); - } -} - -////////////////////////////////////////////////////////////////////////// -void CMiniMenu::RestoreState() -{ - for (int i = 0, num = GetSubCtrlCount(); i < num; i++) - { - IMiniCtrl* pSubCtrl = GetSubCtrl(i); - pSubCtrl->RestoreState(); - } -} - -////////////////////////////////////////////////////////////////////////// -void CMiniMenu::AddSubCtrl(IMiniCtrl* pCtrl) -{ - assert(pCtrl); - pCtrl->SetFlag(eCtrl_Hidden); - pCtrl->SetFlag(eCtrl_NoBorder); - - bool bSubMenu = false; - - if (pCtrl->GetType() == eCtrlType_Menu) - { - CMiniMenu* pSubMenu = static_cast(pCtrl); - pSubMenu->m_bSubMenu = true; - bSubMenu = true; - } - - if (!m_bSubMenu) - { - //menu is at least the size of title bar - m_menuWidth = max(m_menuWidth, strlen(GetTitle()) * 8.5f); - } - - const char* title = pCtrl->GetTitle(); - - if (title) - { - uint32 titleLen = strlen(title); - - float width = (float)titleLen * 8.5f; - - if (bSubMenu) - { - //increase width for submenu arrow - width += 10.f; - } - - m_menuWidth = max(m_menuWidth, width); - } - - // Call parent - CMiniButton::AddSubCtrl(pCtrl); -} -MINIGUI_END diff --git a/Code/CryEngine/CrySystem/MiniGUI/MiniMenu.h b/Code/CryEngine/CrySystem/MiniGUI/MiniMenu.h deleted file mode 100644 index c288d840df..0000000000 --- a/Code/CryEngine/CrySystem/MiniGUI/MiniMenu.h +++ /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. - -// Description : Button implementation in the MiniGUI - - -#ifndef CRYINCLUDE_CRYSYSTEM_MINIGUI_MINIMENU_H -#define CRYINCLUDE_CRYSYSTEM_MINIGUI_MINIMENU_H -#pragma once - - -#include "MiniGUI.h" -#include "MiniButton.h" - -MINIGUI_BEGIN - -////////////////////////////////////////////////////////////////////////// -// Root window all other controls derive from -class CMiniMenu - : public CMiniButton -{ -public: - CMiniMenu(); - - ////////////////////////////////////////////////////////////////////////// - // CMiniCtrl interface implementation. - ////////////////////////////////////////////////////////////////////////// - virtual EMiniCtrlType GetType() const { return eCtrlType_Menu; } - virtual void SetRect(const Rect& rc); - virtual void OnPaint(CDrawContext& dc); - virtual void OnEvent(float x, float y, EMiniCtrlEvent event); - virtual void AddSubCtrl(IMiniCtrl* pCtrl); - virtual void Reset(); - virtual void SaveState(); - virtual void RestoreState(); - ////////////////////////////////////////////////////////////////////////// - - //digital selection funcs - CMiniMenu* UpdateSelection(EMiniCtrlEvent event); - - void Open(); - void Close(); - -protected: - -protected: - bool m_bVisible; - bool m_bSubMenu; - float m_menuWidth; - - int m_selectionIndex; -}; - -MINIGUI_END - -#endif // CRYINCLUDE_CRYSYSTEM_MINIGUI_MINIMENU_H diff --git a/Code/CryEngine/CrySystem/MiniGUI/MiniTable.cpp b/Code/CryEngine/CrySystem/MiniGUI/MiniTable.cpp deleted file mode 100644 index 6a306a2f9e..0000000000 --- a/Code/CryEngine/CrySystem/MiniGUI/MiniTable.cpp +++ /dev/null @@ -1,336 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS 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 : Table implementation in the MiniGUI - - -#include "CrySystem_precompiled.h" -#include "MiniTable.h" -#include "DrawContext.h" - -#include - -MINIGUI_BEGIN - -CMiniTable::CMiniTable() -{ - m_fTextSize = 15.f; - m_pageNum = 0; - m_pageSize = 35; -} - -void CMiniTable::OnPaint(CDrawContext& dc) -{ - if (m_requiresResize) - { - AutoResize(); - } - - ColorB borderCol; - ColorB backgroundCol = dc.Metrics().clrBackground; - - if (m_pGUI->InFocus()) - { - if (m_moving) - { - borderCol = dc.Metrics().clrFrameBorderHighlight; - } - else - { - borderCol = dc.Metrics().clrFrameBorder; - } - } - else - { - borderCol = dc.Metrics().clrFrameBorderOutOfFocus; - backgroundCol.a = dc.Metrics().outOfFocusAlpha; - } - - dc.DrawFrame(m_rect, borderCol, backgroundCol); - - float fTextSize = m_fTextSize; - if (fTextSize == 0) - { - fTextSize = dc.Metrics().fTextSize; - } - - float indent = 4.f; - - float x = m_rect.left + indent; - float y = m_rect.top + indent; - - const int nColumns = m_columns.size(); - int numEntries = nColumns > 0 ? m_columns[0].cells.size() : 0; - - int startIdx = 0; - int endIdx = numEntries; - - //Page number - if (nColumns) - { - int numPages = numEntries / m_pageSize; - - if (numPages) - { - startIdx = m_pageNum * m_pageSize; - endIdx = min(startIdx + m_pageSize, numEntries); - dc.SetColor(ColorB(255, 255, 255, 255)); - - //print page details (adjust for zero indexed) - dc.DrawString(x, y, fTextSize, eTextAlign_Left, "Page %d of %d (Page Up / Page Down)", m_pageNum + 1, numPages + 1); - y += fTextSize; - } - } - - float topOfTable = y; - - for (int i = 0; i < nColumns; i++) - { - SColumn& column = m_columns[i]; - - y = topOfTable; - - dc.SetColor(ColorB(32, 32, 255, 255)); - - dc.DrawString(x, y, fTextSize, eTextAlign_Left, column.name); - y += fTextSize + indent; - - ColorB currentCol(255, 255, 255, 255); - - dc.SetColor(currentCol); - - const int nCells = column.cells.size(); - - for (int j = startIdx; j < endIdx && j < nCells; j++) - { - if (column.cells[j].col != currentCol) - { - dc.SetColor(column.cells[j].col); - currentCol = column.cells[j].col; - } - - dc.DrawString(x, y, fTextSize, eTextAlign_Left, column.cells[j].text); - y += fTextSize; - } - - x += column.width; - } -} - -void CMiniTable::OnEvent(float x, float y, EMiniCtrlEvent event) -{ - //movement - CMiniCtrl::OnEvent(x, y, event); -} - -void CMiniTable::AutoResize() -{ - //must be at least the size of cross box - float tableWidth = 30.f; - - float tableHeight = 0.f; - const float widthScale = 0.6f; - const int nColumns = m_columns.size(); - - int startIdx = 0; - int endIdx = 0; - - bool bPageHeader = false; - - //Update Page index - if (nColumns) - { - int numEntries = m_columns[0].cells.size(); - - //page index is now invalid, cap at max - if ((m_pageNum * m_pageSize) > numEntries) - { - m_pageNum = (numEntries / m_pageSize); - } - - startIdx = m_pageNum * m_pageSize; - endIdx = min(startIdx + m_pageSize, numEntries); - - if (numEntries > m_pageSize) - { - bPageHeader = true; - } - } - - for (int i = 0; i < nColumns; i++) - { - SColumn& column = m_columns[i]; - - float width = strlen(column.name) * m_fTextSize; - - int nCells = column.cells.size(); - - for (int j = startIdx; j < endIdx && j < nCells; j++) - { - width = max(width, strlen(column.cells[j].text) * m_fTextSize); - } - - width *= widthScale; - - column.width = width; - tableWidth += width; - tableHeight = max(tableHeight, min(endIdx - startIdx, m_pageSize) * m_fTextSize); - } - - tableHeight += m_fTextSize * 2.f; - - //Page index - if (bPageHeader) - { - tableHeight += m_fTextSize; - } - - Rect newRect = m_rect; - - newRect.right = newRect.left + tableWidth; - newRect.bottom = newRect.top + tableHeight; - - SetRect(newRect); - - m_requiresResize = false; -} - -void CMiniTable::Reset() -{ - SetFlag(eCtrl_Hidden); - - m_pageNum = 0; -} - -void CMiniTable::SaveState() -{ - if (CheckFlag(eCtrl_Hidden)) - { - m_saveStateOn = false; - } - else - { - m_saveStateOn = true; - } -} - -void CMiniTable::RestoreState() -{ - if (m_saveStateOn) - { - ClearFlag(eCtrl_Hidden); - } -} - -int CMiniTable::AddColumn(const char* name) -{ - assert(name); - - SColumn col; - - cry_strcpy(col.name, name); - col.width = strlen(col.name) * 8.f; - - m_columns.push_back(col); - - m_requiresResize = true; - - return m_columns.size() - 1; -} - -void CMiniTable::RemoveColumns() -{ - m_columns.clear(); -} - -int CMiniTable::AddData(int columnIndex, ColorB col, const char* format, ...) -{ - assert(columnIndex < (int)m_columns.size()); - - SCell cell; - - va_list args; - va_start(args, format); - int written = vsnprintf_s(cell.text, MAX_TEXT_LENGTH, MAX_TEXT_LENGTH - 1, format, args); - va_end(args); - - if (written == -1) - { - cell.text[MAX_TEXT_LENGTH - 1] = '\0'; - } - - cell.col = col; - - m_columns[columnIndex].cells.push_back(cell); - - m_requiresResize = true; - - return m_columns[columnIndex].cells.size() - 1; -} - -void CMiniTable::ClearTable() -{ - const int nColumns = m_columns.size(); - - for (int i = 0; i < nColumns; i++) - { - m_columns[i].cells.clear(); - } -} - -void CMiniTable::SetVisible(bool state) -{ - if (state) - { - clear_flag(eCtrl_Hidden); - AzFramework::InputChannelEventListener::Connect(); - } - else - { - set_flag(eCtrl_Hidden); - AzFramework::InputChannelEventListener::Disconnect(); - } - - if (m_pCloseButton) - { - m_pCloseButton->SetVisible(state); - } -} - -void CMiniTable::Hide(bool stat) -{ - SetVisible(!stat); -} - -bool CMiniTable::OnInputChannelEventFiltered(const AzFramework::InputChannel& inputChannel) -{ - if (!IsHidden() && inputChannel.IsStateBegan()) - { - const AzFramework::InputChannelId& channelId = inputChannel.GetInputChannelId(); - if (channelId == AzFramework::InputDeviceKeyboard::Key::NavigationPageUp) - { - m_pageNum++; - m_requiresResize = true; - } - else if (channelId == AzFramework::InputDeviceKeyboard::Key::NavigationPageDown) - { - if (m_pageNum > 0) - { - m_pageNum--; - m_requiresResize = true; - } - } - } - return false; -} -MINIGUI_END diff --git a/Code/CryEngine/CrySystem/MiniGUI/MiniTable.h b/Code/CryEngine/CrySystem/MiniGUI/MiniTable.h deleted file mode 100644 index fb89aca2dc..0000000000 --- a/Code/CryEngine/CrySystem/MiniGUI/MiniTable.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 : Table implementation in the MiniGUI - - -#ifndef CRYINCLUDE_CRYSYSTEM_MINIGUI_MINITABLE_H -#define CRYINCLUDE_CRYSYSTEM_MINIGUI_MINITABLE_H -#pragma once - - -#include "MiniGUI.h" - -MINIGUI_BEGIN - -class CMiniTable - : public CMiniCtrl - , public IMiniTable - , public AzFramework::InputChannelEventListener -{ -public: - CMiniTable(); - - ////////////////////////////////////////////////////////////////////////// - // CMiniCtrl interface implementation. - ////////////////////////////////////////////////////////////////////////// - virtual EMiniCtrlType GetType() const { return eCtrlType_Table; } - virtual void OnPaint(CDrawContext& dc); - virtual void OnEvent(float x, float y, EMiniCtrlEvent event); - virtual void Reset(); - virtual void SaveState(); - virtual void RestoreState(); - virtual void AutoResize(); - virtual void SetVisible(bool state); - - ////////////////////////////////////////////////////////////////////////// - - ////////////////////////////////////////////////////////////////////////// - // IMiniTable interface implementation. - ////////////////////////////////////////////////////////////////////////// - - //Add a new column to the table, return column index - virtual int AddColumn(const char* name); - - //Remove all columns an associated data - virtual void RemoveColumns(); - - //Add data to specified column (add onto the end), return row index - virtual int AddData(int columnIndex, ColorB col, const char* format, ...); - - //Clear all data from table - virtual void ClearTable(); - - virtual bool IsHidden() { return CheckFlag(eCtrl_Hidden); } - - virtual void Hide(bool stat); - - // AzFramework::InputChannelEventListener - bool OnInputChannelEventFiltered(const AzFramework::InputChannel& inputChannel) override; - AZ::s32 GetPriority() const override { return AzFramework::InputChannelEventListener::GetPriorityUI(); } - - static const int MAX_TEXT_LENGTH = 64; - -protected: - - struct SCell - { - char text[MAX_TEXT_LENGTH]; - ColorB col; - }; - - struct SColumn - { - char name[MAX_TEXT_LENGTH]; - float width; - std::vector cells; - }; - - std::vector m_columns; - int m_pageSize; - int m_pageNum; -}; - -MINIGUI_END - -#endif // CRYINCLUDE_CRYSYSTEM_MINIGUI_MINITABLE_H 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/OverloadSceneManager/OverloadSceneManager.cpp b/Code/CryEngine/CrySystem/OverloadSceneManager/OverloadSceneManager.cpp deleted file mode 100644 index 044d44fade..0000000000 --- a/Code/CryEngine/CrySystem/OverloadSceneManager/OverloadSceneManager.cpp +++ /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. - -// Description : Manages overload values (eg CPU,GPU etc) -// 1.0="everything is ok" 0.0="very bad frame rate" -// various systems can use this information and control what is currently in the scene - - -#include "CrySystem_precompiled.h" -#include "OverloadSceneManager.h" - -//-------------------------------------------------------------------------------------------------- -// Name: COverloadSceneManager -// Desc: Constructor -//-------------------------------------------------------------------------------------------------- -COverloadSceneManager::COverloadSceneManager() -{ - InitialiseCVars(); - - m_currentFrameStat = 0; - - ResetDefaultValues(); -}//------------------------------------------------------------------------------------------------- - -//-------------------------------------------------------------------------------------------------- -// Desc: static console callback functions -//-------------------------------------------------------------------------------------------------- -static void OnChange_osm_enabled(ICVar* pCVar) -{ - if (pCVar->GetIVal() == 0) - { - gEnv->pOverloadSceneManager->Reset(); - //gEnv->pRenderer->EnablePipelineProfiler(false); // would need push/pop since something else might have enabled it - } - else if (pCVar->GetIVal() == 1) - { - gEnv->pRenderer->EnablePipelineProfiler(true); - } -} - -static void cmd_setFBScale(IConsoleCmdArgs* pParams) -{ - int argCount = pParams->GetArgCount(); - - Vec2 newScale = Vec2(0.0f, 0.0f); - gEnv->pRenderer->EF_Query(EFQ_GetViewportDownscaleFactor, newScale); - - if (argCount > 1) - { - newScale.x = clamp_tpl((float)atof(pParams->GetArg(1)), 0.0f, 1.0f); - - if (argCount > 2) - { - newScale.y = clamp_tpl((float)atof(pParams->GetArg(2)), 0.0f, 1.0f); - } - else - { - newScale.y = newScale.x; - } - - newScale = gEnv->pRenderer->SetViewportDownscale(newScale.x, newScale.y); - } - - int nWidth = gEnv->pRenderer->GetWidth(); - int nHeight = gEnv->pRenderer->GetHeight(); - - gEnv->pLog->LogWithType(ILog::eInputResponse, "Current Viewport Resolution: %dx%d", - int(nWidth * newScale.x), int(nHeight * newScale.y)); -} - -//-------------------------------------------------------------------------------------------------- -// Name: InitialiseCVars -// Desc: Initialises CVars -//-------------------------------------------------------------------------------------------------- -void COverloadSceneManager::InitialiseCVars() -{ - // depending on final requirements, these could be made into const cvars - REGISTER_CVAR_CB(osm_enabled, 0, VF_NULL, "Enables/disables overload scene manager", &OnChange_osm_enabled); - REGISTER_CVAR(osm_historyLength, 5, VF_NULL, "Overload scene manager number of frames to record stats for"); - REGISTER_CVAR(osm_targetFPS, 28.0f, VF_NULL, "Overload scene manager target frame rate"); - REGISTER_CVAR(osm_targetFPSTolerance, 1.0f, VF_NULL, "The overload scene manager will make adjustments if fps is outside targetFPS +/- this value"); - REGISTER_CVAR(osm_fbScaleDeltaDown, 5.0f, VF_NULL, "The speed multiplier for the overload scene manager frame buffer scaling down"); - REGISTER_CVAR(osm_fbScaleDeltaUp, 1.0f, VF_NULL, "The speed multiplier for the overload scene manager frame buffer scaling up"); - REGISTER_CVAR(osm_fbMinScale, 0.66f, VF_NULL, "The minimum scale factor the overload scene manager will drop to"); - - REGISTER_COMMAND("osm_setFBScale", cmd_setFBScale, VF_NULL, "Sets the framebuffer scale to either a single scale on both X and Y, or independent scales.\n" - "NOTE: Will be overridden immediately if Overload scene manager is still enabled - see osm_enabled"); -}//------------------------------------------------------------------------------------------------- - -//-------------------------------------------------------------------------------------------------- -// Name: Reset -// Desc: Resets overload scene manager outputs to sensible defaults -//-------------------------------------------------------------------------------------------------- -void COverloadSceneManager::Reset() -{ - ResetDefaultValues(); - - gEnv->pRenderer->SetViewportDownscale(m_fbScale, m_fbScale); -} - -void COverloadSceneManager::ResetDefaultValues() -{ - m_fbScale = 1.0f; - m_scaleState = FBSCALE_AUTO; - m_lerpOverride.m_start = m_lerpOverride.m_length = 1.0f; - m_lerpOverride.m_reversed = false; - m_lerpAuto.m_start = m_lerpAuto.m_length = 1.0f; - m_lerpAuto.m_reversed = true; - m_fbAutoScale = m_fbOverrideDestScale = m_fbOverrideCurScale = 1.0f; - - // completely reset history - for (int i = 0; i < osm_historyLength; i++) - { - SScenePerformanceStats& stats = m_sceneStats[i]; - stats.frameRate = stats.gpuFrameRate = osm_targetFPS; - } - - m_smoothedSceneStats.frameRate = m_smoothedSceneStats.gpuFrameRate = osm_targetFPS; -} -//------------------------------------------------------------------------------------------------- - -//-------------------------------------------------------------------------------------------------- -// Name: Update -// Desc: Updates overload scene manager -//-------------------------------------------------------------------------------------------------- -void COverloadSceneManager::Update() -{ - if (!osm_enabled) - { - return; - } - - UpdateStats(); - ResizeFB(); -}//------------------------------------------------------------------------------------------------- - -//-------------------------------------------------------------------------------------------------- -// Name: OverrideScale and ResetScale -// Desc: sets up appropriate members for lerping between automatic framebuffer scale and manual -// overrides. -//-------------------------------------------------------------------------------------------------- -void COverloadSceneManager::OverrideScale(float frameScale, float dt) -{ - dt = max(dt, 1.0f / 1000.0f); - - float curTime = gEnv->pTimer->GetCurrTime(); - - frameScale = clamp_tpl(frameScale, osm_fbMinScale, 1.0f); - - m_fbOverrideDestScale = frameScale; - - if (m_scaleState == FBSCALE_AUTO) - { - // remove any override lerp - we want to lerp straight from auto to the given value. - m_lerpOverride.m_start = m_lerpOverride.m_length = 1.0f; - m_lerpOverride.m_reversed = false; - m_fbOverrideCurScale = frameScale; - - m_lerpAuto.m_start = curTime; - m_lerpAuto.m_length = dt; - m_lerpAuto.m_reversed = false; - } - else if (m_scaleState == FBSCALE_OVERRIDE) - { - m_lerpOverride.m_start = curTime; - m_lerpOverride.m_length = dt; - m_lerpOverride.m_reversed = false; - - m_fbOverrideCurScale = m_fbScale; - } - - m_scaleState = FBSCALE_OVERRIDE; -} - -void COverloadSceneManager::ResetScale(float dt) -{ - dt = max(dt, 1.0f / 1000.0f); - - float curTime = gEnv->pTimer->GetCurrTime(); - - // remove any override lerp - we want to lerp straight to auto - m_lerpOverride.m_start = m_lerpOverride.m_length = 1.0f; - m_lerpOverride.m_reversed = false; - m_fbOverrideCurScale = m_fbOverrideDestScale = m_fbScale; - - m_lerpAuto.m_start = curTime; - m_lerpAuto.m_length = dt; - m_lerpAuto.m_reversed = true; // want to lerp back to auto mode - - m_scaleState = FBSCALE_AUTO; -}//------------------------------------------------------------------------------------------------- - -//-------------------------------------------------------------------------------------------------- -// Name: UpdateStats -// Desc: Updates overload stats -//-------------------------------------------------------------------------------------------------- -void COverloadSceneManager::UpdateStats() -{ - m_currentFrameStat++; - - if (m_currentFrameStat >= osm_historyLength) - { - m_currentFrameStat = 0; - } - - SScenePerformanceStats& currentStats = m_sceneStats[m_currentFrameStat]; - const float frameLength = gEnv->pTimer->GetRealFrameTime() * 1000.0f; - const float gpuFrameLength = gEnv->pRenderer->GetGPUFrameTime() * 1000.0f; - - currentStats.frameRate = frameLength > 0.0f ? 1000.0f / frameLength : 0.0f; - currentStats.gpuFrameRate = gpuFrameLength > 0.0f ? 1000.0f / gpuFrameLength : 0.0f; - - CalculateSmoothedStats(); -}//------------------------------------------------------------------------------------------------- - -void COverloadSceneManager::CalculateSmoothedStats() -{ - m_smoothedSceneStats.Reset(); - - for (int i = 0; i < osm_historyLength; i++) - { - SScenePerformanceStats& stats = m_sceneStats[i]; - m_smoothedSceneStats.frameRate += stats.frameRate; - m_smoothedSceneStats.gpuFrameRate += stats.gpuFrameRate; - } - - m_smoothedSceneStats.frameRate /= osm_historyLength; - m_smoothedSceneStats.gpuFrameRate /= osm_historyLength; -} - -float COverloadSceneManager::CalcFBScale() -{ - float curTime = gEnv->pTimer->GetCurrTime(); - - // first calculate delta of the override lerp - float delta = clamp_tpl((curTime - m_lerpOverride.m_start) / m_lerpOverride.m_length, 0.0f, 1.0f); - if (m_lerpOverride.m_reversed) - { - delta = 1.0f - delta; - } - - // get the current target override - float curOverrideScale = LERP(m_fbOverrideCurScale, m_fbOverrideDestScale, delta); - - // calculate the delta from (or two) automatic scaling - delta = clamp_tpl((curTime - m_lerpAuto.m_start) / m_lerpAuto.m_length, 0.0f, 1.0f); - if (m_lerpAuto.m_reversed) - { - delta = 1.0f - delta; - } - - // final lerp from automatic to current override - return LERP(m_fbAutoScale, curOverrideScale, delta); -} - -void COverloadSceneManager::ResizeFB() -{ - // don't do anything for invalid framerates - if (m_smoothedSceneStats.gpuFrameRate < 5.0f || m_smoothedSceneStats.gpuFrameRate > 100.0f) - { - return; - } - - float fpsDiff = fabsf(m_smoothedSceneStats.gpuFrameRate - osm_targetFPS); - - if (m_smoothedSceneStats.gpuFrameRate < osm_targetFPS - osm_targetFPSTolerance) - { - m_fbAutoScale -= osm_fbScaleDeltaDown / 1000.0f * fpsDiff; - } - else if (m_smoothedSceneStats.gpuFrameRate > osm_targetFPS + osm_targetFPSTolerance) - { - m_fbAutoScale += osm_fbScaleDeltaUp / 1000.0f * fpsDiff; - } - - m_fbAutoScale = clamp_tpl(m_fbAutoScale, osm_fbMinScale, 1.0f); - - m_fbScale = clamp_tpl(CalcFBScale(), osm_fbMinScale, 1.0f); - - gEnv->pRenderer->SetViewportDownscale(m_fbScale, m_fbScale); -} diff --git a/Code/CryEngine/CrySystem/OverloadSceneManager/OverloadSceneManager.h b/Code/CryEngine/CrySystem/OverloadSceneManager/OverloadSceneManager.h deleted file mode 100644 index 06a901b3df..0000000000 --- a/Code/CryEngine/CrySystem/OverloadSceneManager/OverloadSceneManager.h +++ /dev/null @@ -1,127 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS 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_OVERLOADSCENEMANAGER_OVERLOADSCENEMANAGER_H -#define CRYINCLUDE_CRYSYSTEM_OVERLOADSCENEMANAGER_OVERLOADSCENEMANAGER_H -#pragma once - - -// Includes -#include "IOverloadSceneManager.h" - -#define SCENE_PERFORMANCE_FRAME_HISTORY 64 - -//================================================================================================== -// Name: SOverloadSceneStats -// Desc: Overload scene stats -// Author: James Chilvers -//================================================================================================== -struct SScenePerformanceStats -{ - SScenePerformanceStats() - { - Reset(); - } - - void Reset() - { - frameRate = 0.0f; - gpuFrameRate = 0.0f; - } - - float frameRate; - float gpuFrameRate; -};//------------------------------------------------------------------------------------------------ - -//================================================================================================== -// Name: COverloadSceneManager -// Desc: Manages overload values (eg CPU,GPU etc) -// 1.0="everything is ok" 0.0="very bad frame rate" -// various systems can use this information and control what is currently in the scene -// Author: James Chilvers -//================================================================================================== -class COverloadSceneManager - : public IOverloadSceneManager -{ - friend class COverloadDG; - -public: - - COverloadSceneManager(); - ~COverloadSceneManager() override = default; - - virtual void Reset(); - - virtual void Update(); - - virtual void OverrideScale(float frameScale, float dt); - virtual void ResetScale(float dt); - -private: - - void ResetDefaultValues(); - void InitialiseCVars(); - void UpdateStats(); - void CalculateSmoothedStats(); - void ResizeFB(); - - float CalcFBScale(); // performs all lerping and returns final framebuffer scale - - // cvars - int osm_enabled; - int osm_historyLength; - float osm_targetFPS; - float osm_targetFPSTolerance; - float osm_fbScaleDeltaUp, osm_fbScaleDeltaDown; - float osm_fbMinScale; - - SScenePerformanceStats m_smoothedSceneStats; - SScenePerformanceStats m_sceneStats[SCENE_PERFORMANCE_FRAME_HISTORY]; - int m_currentFrameStat; - - // current output scale, set to the renderer - float m_fbScale; - - // Lerping behaviour is to lerp from autoscale to (lerp between cur/dest override) - // - // m_fbOverrideCurScale - // | - // | - // m_fbAutoScale ---- m_lerpAuto ---> m_lerpOverride - // | - // v - // m_fbOverrideDestScale - - // framebuffer scales to support lerping & overriding of calculated scale - float m_fbAutoScale, m_fbOverrideCurScale, m_fbOverrideDestScale; - - struct ScaleLerp - { - bool m_reversed; // Normally lerp is 0 -> 1. If reversed it's 1 -> 0 - float m_start; // time in seconds - float m_length; // time in seconds - }; - - // lerpAuto is the lerp between auto scale and whatever override is. - // lerpOverride is the lerp between m_fbOverrideCurScale and m_fbOverrideDestScale - ScaleLerp m_lerpAuto, m_lerpOverride; - - // State is the current destination of any lerps. - enum ScaleState - { - FBSCALE_AUTO, - FBSCALE_OVERRIDE, - } m_scaleState; -};//------------------------------------------------------------------------------------------------ - -#endif // CRYINCLUDE_CRYSYSTEM_OVERLOADSCENEMANAGER_OVERLOADSCENEMANAGER_H diff --git a/Code/CryEngine/CrySystem/PerfHUD.cpp b/Code/CryEngine/CrySystem/PerfHUD.cpp deleted file mode 100644 index 2aeabe2650..0000000000 --- a/Code/CryEngine/CrySystem/PerfHUD.cpp +++ /dev/null @@ -1,2166 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS 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 : Button implementation in the MiniGUI - -#include "CrySystem_precompiled.h" - -#ifdef USE_PERFHUD - -#include "PerfHUD.h" -#include "MiniGUI/MiniInfoBox.h" -#include "MiniGUI/MiniMenu.h" -#include "MiniGUI/MiniTable.h" -#include -#include -#include "System.h" - -#include - -#include - -#include -#include - -#include - -#define PERFHUD_CONFIG_FILE "Config/PerfHud_PC.xml" - -using namespace minigui; - -const float CPerfHUD::OVERSCAN_X = 15; -const float CPerfHUD::OVERSCAN_Y = 15; - -const ColorB CPerfHUD::COL_NORM = ColorB(255, 255, 255, 255); -const ColorB CPerfHUD::COL_WARN = ColorB(255, 255, 0, 255); -const ColorB CPerfHUD::COL_ERROR = ColorB(255, 0, 0, 255); - -const float CPerfHUD::TEXT_SIZE_NORM = 14.f; -const float CPerfHUD::TEXT_SIZE_WARN = 18.f; -const float CPerfHUD::TEXT_SIZE_ERROR = 26.f; - -const float CPerfHUD::ACTIVATE_TIME_FROM_GAME = 1.f; -const float CPerfHUD::ACTIVATE_TIME_FROM_HUD = 0.1f; - -CRYREGISTER_SINGLETON_CLASS(CPerfHUD) -CPerfHUD::CPerfHUD() - : m_menuStartX(OVERSCAN_X) - , m_menuStartY(OVERSCAN_Y) - , m_hudCreated(false) - , m_L1Pressed(false) - , m_L2Pressed(false) - , m_R1Pressed(false) - , m_R2Pressed(false) - , m_changingState(false) - , m_hwMouseEnabled(false) - , m_triggersDownStartTime(-1.f) - , m_hudState(eHudOff) - , m_hudLastState(eHudOff) -{ - m_widgets.reserve(ICryPerfHUDWidget::eWidget_Num); -} - -CPerfHUD::~CPerfHUD() {} - -void CPerfHUD::Destroy() -{ - m_widgets.clear(); - - m_rootMenus.clear(); - - IMiniGUIPtr pGUI; - if (CryCreateClassInstanceForInterface(cryiidof(), pGUI)) - { - pGUI->RemoveAllCtrl(); - } -} - -// -// CONSOLE COMMAND CALLBACKS -// - -int CPerfHUD::m_sys_perfhud = 0; -int CPerfHUD::m_sys_perfhud_pause = 0; - -void CPerfHUD::CVarChangeCallback(ICVar* pCvar) -{ - ICryPerfHUD* pPerfHud = gEnv->pSystem->GetPerfHUD(); - - if (pPerfHud) - { - int val = pCvar->GetIVal(); - //Check for invalid value - if (val >= 0 && val < eHudNumStates) - { - pPerfHud->SetState((EHudState)val); - } - } -} - -SET_WIDGET_DEF(Warnings, eWidget_Warnings) -SET_WIDGET_DEF(RenderSummary, eWidget_RenderStats) -SET_WIDGET_DEF(RenderBatchStats, eWidget_RenderBatchStats) -SET_WIDGET_DEF(FpsBuckets, eWidget_FpsBuckets) -SET_WIDGET_DEF(Particles, eWidget_Particles) -SET_WIDGET_DEF(PakFile, eWidget_PakFile) - -////////////////////////////////////////////////////////////////////////// -void CPerfHUD::Init() -{ - m_sys_perfhud_prev = 0; - - if (gEnv->pConsole) - { - REGISTER_CVAR2_CB("sys_perfhud", &m_sys_perfhud, 0, VF_ALWAYSONCHANGE, "PerfHUD 0:off, 1:In focus, 2:Out of focus", CVarChangeCallback); - - REGISTER_CVAR2("sys_perfhud_pause", &m_sys_perfhud_pause, 0, VF_NULL, "Toggle FPS Buckets exclusive / inclusive"); - - SET_WIDGET_COMMAND("stats_Warnings", Warnings); - SET_WIDGET_COMMAND("stats_RenderSummary", RenderSummary); - SET_WIDGET_COMMAND("stats_RenderBatchStats", RenderBatchStats); - SET_WIDGET_COMMAND("stats_FpsBuckets", FpsBuckets); - SET_WIDGET_COMMAND("stats_Particles", Particles); - SET_WIDGET_COMMAND("stats_PakFile", PakFile); - } - - AzFramework::InputChannelEventListener::Connect(); - - IMiniGUIPtr pGUI; - if (CryCreateClassInstanceForInterface(cryiidof(), pGUI)) - { - InitUI(pGUI.get()); - } -} - -////////////////////////////////////////////////////////////////////////// -void CPerfHUD::LoadBudgets() -{ - XmlNodeRef budgets = gEnv->pSystem->LoadXmlFromFile(PERFHUD_CONFIG_FILE); - - if (budgets) - { - const int nWidgets = m_widgets.size(); - - for (int i = 0; i < nWidgets; i++) - { - m_widgets[i]->LoadBudgets(budgets); - } - } -} - -////////////////////////////////////////////////////////////////////////// -void CPerfHUD::SaveStats(const char* filename) -{ - XmlNodeRef rootNode = GetISystem()->CreateXmlNode("PerfHudStats"); - - if (rootNode) - { - const int nWidgets = m_widgets.size(); - - for (int i = 0; i < nWidgets; i++) - { - m_widgets[i]->SaveStats(rootNode); - } - - if (!filename) - { - filename = "PerfHudStats.xml"; - } - rootNode->saveToFile(filename); - } -} - -////////////////////////////////////////////////////////////////////////// -void CPerfHUD::ResetWidgets() -{ - TWidgetIterator itWidget; - for (itWidget = m_widgets.begin(); itWidget != m_widgets.end(); ++itWidget) - { - (*itWidget)->Reset(); - } -} - -void CPerfHUD::AddWidget(ICryPerfHUDWidget* pWidget) -{ - assert(pWidget); - static int s_widgetUID = ICryPerfHUDWidget::eWidget_Num; - - if (pWidget->m_id == -1) - { - pWidget->m_id = s_widgetUID++; - } - - m_widgets.push_back(pWidget); -} - -void CPerfHUD::RemoveWidget(ICryPerfHUDWidget* pWidget) -{ - TWidgetIterator widgetIter = m_widgets.begin(); - TWidgetIterator widgetEnd = m_widgets.end(); - - while (widgetIter != widgetEnd) - { - if (pWidget == (*widgetIter).get()) - { - m_widgets.erase(widgetIter); - break; - } - ++widgetIter; - } -} - -////////////////////////////////////////////////////////////////////////// -void CPerfHUD::Done() -{ - AzFramework::InputChannelEventListener::Disconnect(); -} - -////////////////////////////////////////////////////////////////////////// -void CPerfHUD::Draw() -{ - FUNCTION_PROFILER_FAST(GetISystem(), PROFILE_SYSTEM, g_bProfilerEnabled); - - if (m_hudState != m_hudLastState) - { - //restore gui state if the last state was off - bool bRestoreState = (m_hudLastState == eHudOff); - - Show(bRestoreState); - m_hudLastState = m_hudState; - } - - if (m_hudState != eHudOff) - { - //Pause - if (m_sys_perfhud_pause) - { - if ((gEnv->pRenderer->GetFrameID(false) % 40) < 20) - { - float col[4] = {1.f, 1.f, 0.f, 1.f}; - gEnv->pRenderer->Draw2dLabel(500.f, 220.f, 2.f, col, false, "PefHUD Paused"); - } - } - else //Update - { - const int nWidgets = m_widgets.size(); - - for (int i = 0; i < nWidgets; i++) - { - if (m_widgets[i]->ShouldUpdate()) - { - m_widgets[i]->Update(); - } - } - } - } -} - -////////////////////////////////////////////////////////////////////////// -void CPerfHUD::Show(bool bRestoreState) -{ - IMiniGUIPtr pGUI; - if (!CryCreateClassInstanceForInterface(cryiidof(), pGUI)) - { - return; - } - - switch (m_hudState) - { - case eHudInFocus: - { - pGUI->SetEventListener(this); - - if (!m_hudCreated) - { - InitUI(pGUI.get()); - } - else if (bRestoreState) - { - pGUI->RestoreState(); - } - pGUI->SetEnabled(true); - pGUI->SetInFocus(true); - - int nRootMenus = m_rootMenus.size(); - for (int i = 0; i < nRootMenus; i++) - { - m_rootMenus[i]->SetVisible(1); - } - } - break; - - case eHudOutOfFocus: - { - if (bRestoreState) - { - pGUI->RestoreState(); - } - - int nRootMenus = m_rootMenus.size(); - for (int i = 0; i < nRootMenus; i++) - { - m_rootMenus[i]->SetVisible(0); - } - - pGUI->SetEventListener(0); - pGUI->SetEnabled(true); - pGUI->SetInFocus(false); - } - break; - - case eHudOff: - { - pGUI->SaveState(); - pGUI->Reset(); - pGUI->SetEnabled(false); - } - break; - - default: - break; - } -} - -////////////////////////////////////////////////////////////////////////// -void CPerfHUD::InitUI(IMiniGUI* pGUI) -{ - assert(m_hudCreated == false); - - IMiniCtrl* pMenu; - XmlNodeRef perfXML = gEnv->pSystem->LoadXmlFromFile(PERFHUD_CONFIG_FILE); - - // - // RENDERING MENU - // - pMenu = CreateMenu("Rendering"); - - IMiniCtrl* pDebugMenu = CreateMenu("Debug", pMenu); - CreateCVarMenuItem(pDebugMenu, "Wireframe", "r_wireframe", 0, 1); - CreateCVarMenuItem(pDebugMenu, "Overdraw", "r_MeasureOverdrawScale", 0, 1); - CreateCVarMenuItem(pDebugMenu, "Freeze Camera", "e_CameraFreeze", 0, 1); - CreateCVarMenuItem(pDebugMenu, "Post Effects", "r_PostProcessEffects", 0, 1); - CreateCVarMenuItem(pDebugMenu, "Deferred decals debug", "r_deferredDecalsDebug", 0, 1); - CreateCVarMenuItem(pDebugMenu, "Shadows", "e_Shadows", 0, 1); - CreateCVarMenuItem(pDebugMenu, "Ocean", "e_WaterOcean", 0, 1); - CreateCVarMenuItem(pDebugMenu, "Characters", "ca_DrawChr", 0, 1); - CreateCVarMenuItem(pDebugMenu, "Coverage Buffer", "e_CoverageBuffer", 0, 1); - CreateCVarMenuItem(pDebugMenu, "Sun", "e_Sun", 0, 1); - CreateCVarMenuItem(pDebugMenu, "Unlit", "r_Unlit", 0, 1); - CreateCVarMenuItem(pDebugMenu, "Disable Normal Maps", "r_texbindmode", 0, 5); - CreateCVarMenuItem(pDebugMenu, "Env Probes", "r_deferredShadingEnvProbes", 0, 1); - CreateCVarMenuItem(pDebugMenu, "Lighting View", "r_texbindmode", 0, 11); - CreateCVarMenuItem(pDebugMenu, "Normal and Lighting View", "r_texbindmode", 0, 6); - CreateCVarMenuItem(pDebugMenu, "Default Material", "e_defaultMaterial", 0, 1); - - //this cvar is not created when perfHUD is initialised - so it doesn't work - //CreateCVarMenuItem(pDebugMenu, "MFX visual debug", "mfx_DebugVisual", 0, 1 ); - - - IMiniCtrl* pStatsMenu = CreateMenu("Stats", pMenu); - //Render Info - CRenderStatsWidget* pRenderStats = new CRenderStatsWidget(pStatsMenu, this); - - if (pRenderStats) - { - if (perfXML) - { - pRenderStats->LoadBudgets(perfXML); - } - m_widgets.push_back(pRenderStats); - } - - CRenderBatchWidget* pRenderBatchStats = new CRenderBatchWidget(pStatsMenu, this); - - if (pRenderBatchStats) - { - m_widgets.push_back(pRenderBatchStats); - } - -#ifndef _RELEASE - CreateCVarMenuItem(pStatsMenu, "Debug Gun", "e_debugDraw", 0, 16); -#endif - CreateCVarMenuItem(pStatsMenu, "Poly / Lod info", "e_debugDraw", 0, 1); - CreateCVarMenuItem(pStatsMenu, "Texture Memory Usage", "e_debugDraw", 0, 4); - CreateCVarMenuItem(pStatsMenu, "Detailed Render Stats", "r_Stats", 0, 1); - CreateCVarMenuItem(pStatsMenu, "Shader Stats", "r_ProfileShaders", 0, 1); - - // - // SYSTEM MENU - // - pMenu = CreateMenu("System"); - - //FPS Buckets - CWarningsWidget* pWarningsWidget = new CWarningsWidget(pMenu, this); - - if (pWarningsWidget) - { - m_widgets.push_back(pWarningsWidget); - } - - CreateCVarMenuItem(pMenu, "Profiler", "profile", 0, 1); - CreateCVarMenuItem(pMenu, "Thread Summary", "r_showmt", 0, 1); - CreateCVarMenuItem(pMenu, "Track File Access", "sys_PakLogInvalidFileAccess", 0, 1); - - //FPS Buckets - CFpsWidget* pFpsBuckets = new CFpsWidget(pMenu, this); - - if (pFpsBuckets) - { - if (perfXML) - { - pFpsBuckets->LoadBudgets(perfXML); - } - m_widgets.push_back(pFpsBuckets); - } - - // - // STREAMING MENU - // - pMenu = CreateMenu("Streaming"); - CreateCVarMenuItem(pMenu, "Streaming Debug", "sys_streaming_debug", 0, 1); - CreateCVarMenuItem(pMenu, "Loaded Geometry Info", "e_streamcgfdebug", 0, 3); - CreateCVarMenuItem(pMenu, "Texture Load/Unload Debug", "r_TexBindMode", 0, 9); - CreateCVarMenuItem(pMenu, "Textures by Size", "r_TexturesStreamingDebug", 0, 4); - CreateCVarMenuItem(pMenu, "Textures by Prio", "r_TexturesStreamingDebug", 0, 5); - - // - // SETUP MENU - // - pMenu = CreateMenu("Setup"); - CreateCallbackMenuItem(pMenu, "Reset HUD", CPerfHUD::ResetCallback, NULL); - CreateCallbackMenuItem(pMenu, "Reload Budgets", CPerfHUD::ReloadBudgetsCallback, NULL); - CreateCallbackMenuItem(pMenu, "Save Stats", CPerfHUD::SaveStatsCallback, NULL); - CreateCVarMenuItem(pMenu, "Pause PerfHUD", "sys_perfhud_pause", 0, 1); - - //save default windows - pGUI->SaveState(); - - m_hudCreated = true; -} -////////////////////////////////////////////////////////////////////////// -// GUI CREATION HELPER FUNCS -////////////////////////////////////////////////////////////////////////// - -IMiniCtrl* CPerfHUD::CreateMenu(const char* name, IMiniCtrl* pParent) -{ - assert(name); - - IMiniGUIPtr pGUI; - if (CryCreateClassInstanceForInterface(cryiidof(), pGUI)) - { - bool subMenu = false; - - if (pParent) - { - assert(pParent->GetType() == eCtrlType_Menu); - subMenu = true; - } - - const float ButtonWidth = 10.f; //arbitrary, button will be scaled based on contained text - - int ctrlFlags = 0; - - if (!subMenu) - { - ctrlFlags = eCtrl_TextAlignCentre | eCtrl_AutoResize; - } - - Rect rcMenuBtn = Rect(m_menuStartX, m_menuStartY, m_menuStartX + ButtonWidth, m_menuStartY + 20); - - IMiniCtrl* pMenu = pGUI->CreateCtrl(pParent, 1, eCtrlType_Menu, ctrlFlags, rcMenuBtn, name); - - if (pMenu && !subMenu) - { - const float MenuBtnSepration = 10.f; - - //Update Menu Positions - rcMenuBtn = pMenu->GetRect(); - m_menuStartX = rcMenuBtn.right + MenuBtnSepration; - m_menuStartY = rcMenuBtn.top; - - m_rootMenus.push_back(pMenu); - } - - return pMenu; - } - return NULL; -} - -////////////////////////////////////////////////////////////////////////// -bool CPerfHUD::CreateCVarMenuItem(IMiniCtrl* pMenu, const char* name, const char* controlVar, float controlVarOff, float controlVarOn) -{ - assert(pMenu && name && controlVar); - assert(pMenu->GetType() == eCtrlType_Menu); - - IMiniGUIPtr pGUI; - if (CryCreateClassInstanceForInterface(cryiidof(), pGUI)) - { - IMiniCtrl* pCtrl = pGUI->CreateCtrl(pMenu, 100, eCtrlType_Button, eCtrl_CheckButton, Rect(0, 0, 100, 20), name); - - if (pCtrl) - { - if (controlVar) - { - pCtrl->SetControlCVar(controlVar, controlVarOff, controlVarOn); - } - return true; - } - } - return false; -} - -////////////////////////////////////////////////////////////////////////// -bool CPerfHUD::CreateCallbackMenuItem(IMiniCtrl* pMenu, const char* name, ClickCallback clickCallback, void* pCallbackData) -{ - assert(pMenu && name && clickCallback); - assert(pMenu->GetType() == eCtrlType_Menu); - - IMiniGUIPtr pGUI; - if (CryCreateClassInstanceForInterface(cryiidof(), pGUI)) - { - IMiniCtrl* pCtrl = pGUI->CreateCtrl(pMenu, 100, eCtrlType_Button, 0 /*eCtrl_CheckButton*/, Rect(0, 0, 100, 20), name); - - if (pCtrl) - { - pCtrl->SetClickCallback(clickCallback, pCallbackData); - return true; - } - } - return false; -} - -////////////////////////////////////////////////////////////////////////// -IMiniInfoBox* CPerfHUD::CreateInfoMenuItem(IMiniCtrl* pMenu, const char* name, RenderCallback renderCallback, const Rect& rect, bool onAtStart) -{ - assert(pMenu->GetType() == eCtrlType_Menu); - - IMiniGUIPtr pGUI; - if (CryCreateClassInstanceForInterface(cryiidof(), pGUI)) - { - IMiniCtrl* pCtrl = pGUI->CreateCtrl(pMenu, 100, eCtrlType_Button, eCtrl_CheckButton, Rect(0, 0, 100, 20), name); - - int infoFlags = eCtrl_Moveable | eCtrl_CloseButton; - - if (!renderCallback) - { - infoFlags |= eCtrl_AutoResize; - } - - CMiniInfoBox* pInfo = (CMiniInfoBox*)pGUI->CreateCtrl(NULL, 200, eCtrlType_InfoBox, infoFlags, rect, name); - - if (pCtrl) - { - pCtrl->SetConnectedCtrl(pInfo); - - if (onAtStart) - { - pCtrl->SetFlag(eCtrl_Checked); - } - else - { - pInfo->SetVisible(false); - } - - if (renderCallback) - { - pInfo->SetRenderCallback(renderCallback); - } - - return pInfo; - } - } - return NULL; -} - -////////////////////////////////////////////////////////////////////////// -IMiniTable* CPerfHUD::CreateTableMenuItem(IMiniCtrl* pMenu, const char* name) -{ - assert(pMenu && name); - assert(pMenu->GetType() == eCtrlType_Menu); - - IMiniGUIPtr pGUI; - if (CryCreateClassInstanceForInterface(cryiidof(), pGUI)) - { - CMiniTable* pTable = (CMiniTable*)pGUI->CreateCtrl(NULL, 200, eCtrlType_Table, eCtrl_AutoResize | eCtrl_Moveable | eCtrl_CloseButton, Rect(50, 100, 400, 350), name); - - if (pTable) - { - IMiniCtrl* pCtrl = pGUI->CreateCtrl(pMenu, 100, eCtrlType_Button, eCtrl_CheckButton, Rect(0, 0, 100, 20), name); - - if (pCtrl) - { - pCtrl->SetConnectedCtrl(pTable); - - pTable->SetVisible(false); - - return pTable; - } - } - } - return NULL; -} - -IMiniCtrl* CPerfHUD::GetMenu(const char* name) -{ - int nRootMenus = m_rootMenus.size(); - - for (int i = 0; i < nRootMenus; i++) - { - if (strcmp(m_rootMenus[i]->GetTitle(), name) == 0) - { - return m_rootMenus[i]; - } - } - return NULL; -} - -////////////////////////////////////////////////////////////////////////// -void CPerfHUD::OnCommand([[maybe_unused]] SCommand& cmd) -{ - //CryLog( "Button Clicked = %d",cmd.nCtrlID ); -} - -////////////////////////////////////////////////////////////////////////// -bool CPerfHUD::OnInputChannelEventFiltered(const AzFramework::InputChannel& inputChannel) -{ - const AzFramework::InputChannelId& channelId = inputChannel.GetInputChannelId(); - const AzFramework::InputDeviceId& deviceId = inputChannel.GetInputDevice().GetInputDeviceId(); - if (AzFramework::InputDeviceKeyboard::IsKeyboardDevice(deviceId) && inputChannel.IsStateBegan()) - { - if (channelId == AzFramework::InputDeviceKeyboard::Key::WindowsSystemPrint) - { - //Cycle modes - const AzFramework::ModifierKeyStates* customData = inputChannel.GetCustomData(); - const AzFramework::ModifierKeyStates modifierKeyStates = customData ? *customData : AzFramework::ModifierKeyStates(); - const bool isAltModifierActive = modifierKeyStates.IsActive(AzFramework::ModifierKeyMask::AltAny); - const bool isCtrlModifierActive = modifierKeyStates.IsActive(AzFramework::ModifierKeyMask::CtrlAny); - if (isAltModifierActive || isCtrlModifierActive) - { - SetNextState(); - } - } - else if (channelId == AzFramework::InputDeviceKeyboard::Key::WindowsSystemScrollLock) - { - //toggle pause - m_sys_perfhud_pause ^= 1; - } - } - - - if (deviceId == AzFramework::InputDeviceGamepad::IdForIndex0) - { - if (inputChannel.IsStateBegan()) - { - bool checkState = false; - - if (channelId == AzFramework::InputDeviceGamepad::Button::L1) - { - m_L1Pressed = true; - checkState = true; - } - else if (channelId == AzFramework::InputDeviceGamepad::Button::R1) - { - m_R1Pressed = true; - checkState = true; - } - else if (channelId == AzFramework::InputDeviceGamepad::Button::X) - { - if (m_changingState) - { - SetNextState(); - } - } - - //if(checkState&&m_L1Pressed&&m_L2Pressed&&m_R1Pressed&&m_R2Pressed) - if (checkState && m_L1Pressed && m_R1Pressed) - { - m_triggersDownStartTime = gEnv->pTimer->GetAsyncCurTime(); - } - } - else if (inputChannel.IsStateUpdated()) - { - float activateTime = (m_hudState == eHudOff) ? ACTIVATE_TIME_FROM_GAME : ACTIVATE_TIME_FROM_HUD; - - if (m_triggersDownStartTime > 0.f && gEnv->pTimer->GetAsyncCurTime() - m_triggersDownStartTime > activateTime) - { - m_changingState = true; - - const char* hudStateStr = NULL; - - switch (m_hudState) - { - case eHudInFocus: - hudStateStr = "CryPerfHUD Edit Mode"; - break; - - case eHudOutOfFocus: - hudStateStr = "CryPerfHUD Game Mode"; - break; - - case eHudOff: - hudStateStr = "CryPerfHUD Off"; - break; - - default: - hudStateStr = "CryPerfHud unknown"; - break; - } - - float col[4] = {1.f, 1.f, 1.f, 1.f}; - gEnv->pRenderer->Draw2dLabel(450.f, 200.f, 2.f, col, false, hudStateStr); - gEnv->pRenderer->Draw2dLabel(450.f, 220.f, 2.f, col, false, "Press X to change Mode"); - } - } - else if (inputChannel.IsStateEnded()) - { - bool triggerReleased = false; - - if (channelId == AzFramework::InputDeviceGamepad::Button::L1) - { - m_L1Pressed = false; - triggerReleased = true; - } - else if (channelId == AzFramework::InputDeviceGamepad::Button::R1) - { - m_R1Pressed = false; - triggerReleased = true; - } - - if (triggerReleased) - { - m_triggersDownStartTime = 0.f; - - if (m_changingState) - { - m_changingState = false; - - //workaround: hardware mouse resets all input states when enabled - //this breaks perfhud selection mode (as triggers are released) - //don't enable mouse until we've finished selection mode - if (m_hudState == eHudInFocus) - { - if (!m_hwMouseEnabled) - { - UiCursorBus::Broadcast(&UiCursorInterface::IncrementVisibleCounter); - m_hwMouseEnabled = true; - } - } - else if (m_hwMouseEnabled) - { - UiCursorBus::Broadcast(&UiCursorInterface::DecrementVisibleCounter); - m_hwMouseEnabled = false; - } - } - } - } - - if (m_hudState == eHudInFocus) - { - //PerfHUD takes control of the input - return true; - } - } - return false; -} - -void CPerfHUD::SetNextState() -{ - if (m_sys_perfhud != eHudOff) - { - m_hudState = (EHudState)((m_hudState + 1) % eHudNumStates); - //CryLogAlways("Setting new HUD state: %d", m_hudState); - - //what to do about cvar? - //ICVar *pPerfCVar = GetISystem()->GetIConsole()->GetCVar("sys_perfhud"); - //pPerfCVar->Set( 1 ); - } -} - -void CPerfHUD::SetState(EHudState state) -{ - if (state != m_hudState) - { - if (m_hwMouseEnabled) - { - if (state != eHudInFocus) - { - UiCursorBus::Broadcast(&UiCursorInterface::DecrementVisibleCounter); - m_hwMouseEnabled = false; - } - } - else if (state == eHudInFocus) - { - UiCursorBus::Broadcast(&UiCursorInterface::IncrementVisibleCounter); - m_hwMouseEnabled = true; - } - - m_hudState = state; - } -} - -void CPerfHUD::Reset() -{ - IMiniGUIPtr pGUI; - if (CryCreateClassInstanceForInterface(cryiidof(), pGUI)) - { - pGUI->Reset(); - } -} - -////////////////////////////////////////////////////////////////////////// -// CLICK CALLBACKS -////////////////////////////////////////////////////////////////////////// - -void CPerfHUD::ResetCallback([[maybe_unused]] void* data, [[maybe_unused]] bool status) -{ - ICryPerfHUDPtr pPerfHUD; - if (CryCreateClassInstanceForInterface(cryiidof(), pPerfHUD)) - { - pPerfHUD->Reset(); - } -} - -void CPerfHUD::ReloadBudgetsCallback([[maybe_unused]] void* data, [[maybe_unused]] bool status) -{ - ICryPerfHUDPtr pPerfHUD; - if (CryCreateClassInstanceForInterface(cryiidof(), pPerfHUD)) - { - pPerfHUD->LoadBudgets(); - } -} - -void CPerfHUD::SaveStatsCallback([[maybe_unused]] void* data, [[maybe_unused]] bool status) -{ - ICryPerfHUDPtr pPerfHUD; - if (CryCreateClassInstanceForInterface(cryiidof(), pPerfHUD)) - { - pPerfHUD->SaveStats(); - } -} - -////////////////////////////////////////////////////////////////////////// -// RENDER CALLBACKS -////////////////////////////////////////////////////////////////////////// - -void CPerfHUD::EnableWidget(ICryPerfHUDWidget::EWidgetID id, int mode) -{ - const int nWidgets = m_widgets.size(); - - for (int i = 0; i < nWidgets; i++) - { - if (m_widgets[i]->m_id == id) - { - m_widgets[i]->Enable(mode); - return; - } - } -} - -void CPerfHUD::DisableWidget(ICryPerfHUDWidget::EWidgetID id) -{ - const int nWidgets = m_widgets.size(); - - for (int i = 0; i < nWidgets; i++) - { - if (m_widgets[i]->m_id == id) - { - m_widgets[i]->Disable(); - return; - } - } -} - -////////////////////////////////////////////////////////////////////////// -// Widget Specific Interface -////////////////////////////////////////////////////////////////////////// -void CPerfHUD::AddWarning(float duration, const char* fmt, va_list argList) -{ - if (m_hudState != eHudOff) - { - //could cache warnings window ptr for efficiency - const int nWidgets = m_widgets.size(); - - for (int i = 0; i < nWidgets; i++) - { - if (m_widgets[i]->m_id == ICryPerfHUDWidget::eWidget_Warnings) - { - CWarningsWidget* warnings = (CWarningsWidget*)m_widgets[i].get(); - - if (warnings->ShouldUpdate()) - { - warnings->AddWarningV(duration, fmt, argList); - break; - } - } - } - } -} - -bool CPerfHUD::WarningsWindowEnabled() const -{ - const int nWidgets = m_widgets.size(); - - for (int i = 0; i < nWidgets; i++) - { - if (m_widgets[i]->m_id == ICryPerfHUDWidget::eWidget_Warnings) - { - return m_widgets[i]->ShouldUpdate(); - } - } - - return false; -} - -const std::vector* CPerfHUD::GetFpsBuckets(float& totalTime) const -{ - const int nWidgets = m_widgets.size(); - - for (int i = 0; i < nWidgets; i++) - { - if (m_widgets[i]->m_id == ICryPerfHUDWidget::eWidget_FpsBuckets) - { - return ((CFpsWidget*)m_widgets[i].get())->GetFpsBuckets(totalTime); - } - } - - return NULL; -} - -////////////////////////////////////////////////////////////////////////// -//FPS Buckets Widget -////////////////////////////////////////////////////////////////////////// - -int CFpsWidget::m_cvarPerfHudFpsExclusive = 0; - -CFpsWidget::CFpsWidget(IMiniCtrl* pParentMenu, ICryPerfHUD* pPerfHud) - : ICryPerfHUDWidget(eWidget_FpsBuckets) -{ - m_fpsBucketSize = 5.f; - m_fpsBudget = 30.f; - m_dpBudget = 2500.f; - m_dpBucketSize = 250.f; - - //FPS Buckets - IMiniCtrl* pFPSMenu = pPerfHud->CreateMenu("FPS", pParentMenu); - m_pInfoBox = pPerfHud->CreateInfoMenuItem(pFPSMenu, "FPS Buckets", NULL, Rect(850, 395, 860, 405)); - pPerfHud->CreateCallbackMenuItem(pFPSMenu, "Reset Buckets", CFpsWidget::ResetCallback, this); - - //Display framerates buckets as inclusive or exclusive - REGISTER_CVAR2("sys_perfhud_fpsBucketsExclusive", &m_cvarPerfHudFpsExclusive, 0, VF_CHEAT, "Toggle FPS Buckets exclusive / inclusive"); - - Init(); -} - -void CFpsWidget::LoadBudgets(XmlNodeRef PerfXML) -{ - if (PerfXML) - { - XmlNodeRef xmlNode; - - //FPS / GPU - explicit bucket values - if ((xmlNode = PerfXML->findChild("fpsBucketValues"))) - { - m_perfBuckets[BUCKET_FPS].buckets.clear(); - m_perfBuckets[BUCKET_GPU].buckets.clear(); - - uint32 nBuckets = xmlNode->getChildCount(); - - for (uint32 i = 0; i < nBuckets; i++) - { - XmlNodeRef bucketVal = xmlNode->getChild(i); - - float target; - bucketVal->getAttr("value", target); - - ICryPerfHUD::PerfBucket bucket(target); - - m_perfBuckets[BUCKET_FPS].buckets.push_back(bucket); - m_perfBuckets[BUCKET_GPU].buckets.push_back(bucket); - } - - m_perfBuckets[BUCKET_FPS].totalTime = 0.f; - m_perfBuckets[BUCKET_GPU].totalTime = 0.f; - } - //Auto generated buckets based on max fps and bucket size - else if ((xmlNode = PerfXML->findChild("fpsBucketMax"))) - { - xmlNode->getAttr("value", m_fpsBudget); - - if ((xmlNode = PerfXML->findChild("fpsBucketSize"))) - { - xmlNode->getAttr("value", m_fpsBucketSize); - } - else - { - m_fpsBucketSize = 5; - } - - m_perfBuckets[BUCKET_FPS].buckets.clear(); - m_perfBuckets[BUCKET_GPU].buckets.clear(); - - float targetFPS = m_fpsBudget; - - for (uint32 i = 0; i < NUM_FPS_BUCKETS_DEFAULT; i++) - { - ICryPerfHUD::PerfBucket bucket(targetFPS); - - m_perfBuckets[BUCKET_FPS].buckets.push_back(bucket); - m_perfBuckets[BUCKET_GPU].buckets.push_back(bucket); - - targetFPS -= m_fpsBucketSize; - } - - m_perfBuckets[BUCKET_FPS].totalTime = 0.f; - m_perfBuckets[BUCKET_GPU].totalTime = 0.f; - } - - //DP buckets - explicit bucket values - if ((xmlNode = PerfXML->findChild("dpBucketValues"))) - { - m_perfBuckets[BUCKET_DP].buckets.clear(); - - uint32 nBuckets = xmlNode->getChildCount(); - - for (uint32 i = 0; i < nBuckets; i++) - { - XmlNodeRef bucketVal = xmlNode->getChild(i); - - float target; - bucketVal->getAttr("value", target); - - ICryPerfHUD::PerfBucket bucket(target); - - m_perfBuckets[BUCKET_DP].buckets.push_back(bucket); - } - m_perfBuckets[BUCKET_DP].totalTime = 0.f; - } - //DPs auto values - else if ((xmlNode = PerfXML->findChild("drawPrimBucketMax"))) - { - xmlNode->getAttr("value", m_dpBudget); - - //Auto generated buckets based on max dp and bucket size - if ((xmlNode = PerfXML->findChild("dpBucketSize"))) - { - xmlNode->getAttr("value", m_dpBucketSize); - } - else - { - m_dpBucketSize = 250.f; - } - - m_perfBuckets[BUCKET_DP].buckets.clear(); - - float nDPs = m_dpBudget - ((NUM_FPS_BUCKETS_DEFAULT - 1) * m_dpBucketSize); - - for (uint32 i = 0; i < NUM_FPS_BUCKETS_DEFAULT; i++) - { - ICryPerfHUD::PerfBucket bucket(nDPs); - - m_perfBuckets[BUCKET_DP].buckets.push_back(bucket); - - nDPs += m_dpBucketSize; - } - m_perfBuckets[BUCKET_DP].totalTime = 0.f; - } - } -} - -template -void CFpsWidget::UpdateBuckets(PerfBucketsStat& bucketStat, float frameTime, const char* name, float stat) -{ - char entryBuffer[CMiniInfoBox::MAX_TEXT_LENGTH] = {0}; - - const uint32 numBuckets = bucketStat.buckets.size(); - - if (frameTime > 0.f) - { - bucketStat.totalTime += frameTime; - - for (uint32 i = 0; i < numBuckets; i++) - { - if (LESS_THAN) - { - if (stat <= bucketStat.buckets[i].target) - { - bucketStat.buckets[i].timeAtTarget += frameTime; - } - } - else - { - if (stat >= bucketStat.buckets[i].target) - { - bucketStat.buckets[i].timeAtTarget += frameTime; - } - } - } - } - - if (bucketStat.totalTime > 0.f) - { - sprintf_s(entryBuffer, CMiniInfoBox::MAX_TEXT_LENGTH, "%s: %.2f", name, stat); - m_pInfoBox->AddEntry(entryBuffer, CPerfHUD::COL_NORM, CPerfHUD::TEXT_SIZE_NORM); - - //render exclusive stats - if (m_cvarPerfHudFpsExclusive) - { - for (uint32 i = 0; i < numBuckets; i++) - { - //inclusive time - float timeAtTarget = bucketStat.buckets[i].timeAtTarget; - - if (i > 0) - { - //exclusive time - timeAtTarget -= bucketStat.buckets[i - 1].timeAtTarget; - - //Add info to gui - float percentAtTarget = 100.f * (timeAtTarget / bucketStat.totalTime); - sprintf_s(entryBuffer, CMiniInfoBox::MAX_TEXT_LENGTH, "%.2f%%%% of time %.1f -> %.1f FPS", percentAtTarget, bucketStat.buckets[i].target, bucketStat.buckets[i - 1].target); - } - else - { - float percentAtTarget = 100.f * (bucketStat.buckets[i].timeAtTarget / bucketStat.totalTime); - sprintf_s(entryBuffer, CMiniInfoBox::MAX_TEXT_LENGTH, "%.2f%%%% of time >= %.1f FPS", percentAtTarget, bucketStat.buckets[i].target); - } - m_pInfoBox->AddEntry(entryBuffer, CPerfHUD::COL_NORM, CPerfHUD::TEXT_SIZE_NORM); - } - } - else //render inclusive stats - { - for (uint32 i = 0; i < numBuckets; i++) - { - float percentAtTarget = 100.f * (bucketStat.buckets[i].timeAtTarget / bucketStat.totalTime); - sprintf_s(entryBuffer, CMiniInfoBox::MAX_TEXT_LENGTH, "%.2f%%%% of time %s %.1f", percentAtTarget, LESS_THAN ? "<=" : ">=", bucketStat.buckets[i].target); - m_pInfoBox->AddEntry(entryBuffer, CPerfHUD::COL_NORM, CPerfHUD::TEXT_SIZE_NORM); - } - } - } -} - -void CFpsWidget::Update() -{ - m_pInfoBox->ClearEntries(); - - // - // FPS - // - { - float frameTime = gEnv->pTimer->GetRealFrameTime(); - UpdateBuckets(m_perfBuckets[BUCKET_FPS], frameTime, "FPS", 1.f / frameTime); - } - - // - // GPU FPS - // - { - float gpuFrameTime = gEnv->pRenderer->GetGPUFrameTime(); - - if (gpuFrameTime > 0.f) - { - m_pInfoBox->AddEntry("", CPerfHUD::COL_NORM, CPerfHUD::TEXT_SIZE_NORM); - UpdateBuckets(m_perfBuckets[BUCKET_GPU], gpuFrameTime, "GPU FPS", 1.f / gpuFrameTime); - } - } - - // - // Draw Call - // - { - //ugly, but buckets are float only at the moment - float nDPs = (float)gEnv->pRenderer->GetCurrentNumberOfDrawCalls(); - m_pInfoBox->AddEntry("", CPerfHUD::COL_NORM, CPerfHUD::TEXT_SIZE_NORM); - UpdateBuckets(m_perfBuckets[BUCKET_DP], 1.f, "DPs", nDPs); - } -} - -//Init buckets with default values -void CFpsWidget::Init() -{ - float targetFPS = m_fpsBudget; - float nDPs = m_dpBudget - ((NUM_FPS_BUCKETS_DEFAULT - 1) * m_dpBucketSize); - - for (uint32 i = 0; i < NUM_FPS_BUCKETS_DEFAULT; i++) - { - ICryPerfHUD::PerfBucket bucket(targetFPS); - - m_perfBuckets[BUCKET_FPS].buckets.push_back(bucket); - m_perfBuckets[BUCKET_GPU].buckets.push_back(bucket); - - bucket.target = (float)nDPs; - - m_perfBuckets[BUCKET_DP].buckets.push_back(bucket); - - targetFPS -= m_fpsBucketSize; - nDPs += m_dpBucketSize; - } - - for (uint32 i = 0; i < BUCKET_TYPE_NUM; i++) - { - m_perfBuckets[i].totalTime = 0.f; - } -} - -//Clear bucket totals -void CFpsWidget::Reset() -{ - for (uint32 i = 0; i < BUCKET_TYPE_NUM; i++) - { - PerfBucketsStat& stat = m_perfBuckets[i]; - - const uint32 nBuckets = stat.buckets.size(); - - //Init fps buckets - for (uint32 j = 0; j < nBuckets; j++) - { - stat.buckets[j].timeAtTarget = 0.f; - } - - stat.totalTime = 0.f; - } -} - -void CFpsWidget::ResetCallback(void* data, [[maybe_unused]] bool status) -{ - assert(data); - ((CFpsWidget*)data)->Reset(); -} - -bool CFpsWidget::ShouldUpdate() -{ - return !m_pInfoBox->IsHidden(); -} - -//TODO -void CFpsWidget::SaveStats(XmlNodeRef statsXML) -{ - if (statsXML) - { - const char* perfBucketTypeStr[] = - { - "BUCKET_FPS", - "BUCKET_GPU", - "BUCKET_DP", - }; - - XmlNodeRef fpsNode; - - for (int i = 0; i < BUCKET_TYPE_NUM; i++) - { - PerfBucketsStat& perfBucket = m_perfBuckets[i]; - - if (perfBucket.totalTime > 0.f) - { - if ((fpsNode = statsXML->newChild(perfBucketTypeStr[i]))) - { - XmlNodeRef child; - - const uint32 numBuckets = perfBucket.buckets.size(); - - for (uint32 j = 0; j < numBuckets; j++) - { - float percentAtTarget = 100.f * (perfBucket.buckets[j].timeAtTarget / perfBucket.totalTime); - - if ((child = fpsNode->newChild("bucket"))) - { - child->setAttr("target", perfBucket.buckets[j].target); - } - - if ((child = fpsNode->newChild("percentAtTime"))) - { - child->setAttr("value", percentAtTarget); - } - } - } - } - } - } -} - -const std::vector* CFpsWidget::GetFpsBuckets(float& totalTime) const -{ - totalTime = m_perfBuckets[BUCKET_FPS].totalTime; - return &m_perfBuckets[BUCKET_FPS].buckets; -} - -////////////////////////////////////////////////////////////////////////// -//Render Stats Widget -////////////////////////////////////////////////////////////////////////// - -CRenderStatsWidget::CRenderStatsWidget(IMiniCtrl* pParentMenu, ICryPerfHUD* pPerfHud) - : ICryPerfHUDWidget(eWidget_RenderStats) -{ - m_pPerfHUD = pPerfHud; - m_fpsBudget = 30.f; - m_dpBudget = 2000; - m_polyBudget = 500000; - m_postEffectBudget = 3; - m_shadowCastBudget = 2; - m_particlesBudget = 1000; - m_pInfoBox = NULL; - m_buildNum = 0; - - ZeroStruct(m_runtimeData); - - m_pInfoBox = pPerfHud->CreateInfoMenuItem(pParentMenu, "Scene Summary", NULL, Rect(45, 350, 100, 400) /*, true*/); - - //Get build number from BuildName.txt - //FILE *buildFile = fxopen("BuildName.txt", "r"); - CCryFile buildFile; - - if (buildFile.Open("./BuildName.txt", "rb", AZ::IO::IArchive::FOPEN_ONDISK | AZ::IO::IArchive::FOPEN_HINT_QUIET)) - { - size_t fileSize = buildFile.GetLength(); - - if (fileSize > 0 && fileSize < 64) - { - char buffer[64] = {0}; - - buildFile.ReadRaw(buffer, fileSize); - - if (buffer[0]) - { - const char* ptr = strchr(buffer, '('); - - if (ptr) - { - ptr++; - m_buildNum = atoi(ptr); - } - } - } - } -} - -void CRenderStatsWidget::Update() -{ - IRenderer* pRenderer = gEnv->pRenderer; - - char entryBuffer[CMiniInfoBox::MAX_TEXT_LENGTH] = {0}; - - //Clear old entries - m_pInfoBox->ClearEntries(); - ZeroStruct(m_runtimeData); - - // - // FPS - // - m_runtimeData.fps = min(9999.f, gEnv->pTimer->GetFrameRate()); - - sprintf_s(entryBuffer, CMiniInfoBox::MAX_TEXT_LENGTH, "FPS: %.2f (%.2f)", m_runtimeData.fps, m_fpsBudget); - - if (m_runtimeData.fps >= m_fpsBudget) - { - m_pInfoBox->AddEntry(entryBuffer, CPerfHUD::COL_NORM, CPerfHUD::TEXT_SIZE_NORM); - } - else - { - m_pInfoBox->AddEntry(entryBuffer, CPerfHUD::COL_ERROR, CPerfHUD::TEXT_SIZE_NORM); - CryPerfHUDWarning(1.f, "FPS Too Low: %.2f", m_runtimeData.fps); - - //PerfHud / AuxRenderer causes us to be RenderThread limited - //Need to investigate vertex buffer locks in AuxRenderer before enabling - - /* - // Fran: please call me before re-enabling this code - - SRenderTimes renderTimes; - pRenderer->GetRenderTimes(renderTimes); - - //wait for main is never 0 - if(renderTimes.fWaitForMain>renderTimes.fWaitForRender && renderTimes.fWaitForMain>renderTimes.fWaitForGPU) - { - m_pInfoBox->AddEntry("Main Thread Limited", CPerfHUD::COL_ERROR, CPerfHUD::TEXT_SIZE_ERROR); - m_pPerfHud->AddWarning("Main Thread Limited",1.f); - } - else if(renderTimes.fWaitForRender>renderTimes.fWaitForGPU) - { - m_pInfoBox->AddEntry("Render Thread Limited", CPerfHUD::COL_ERROR, CPerfHUD::TEXT_SIZE_ERROR); - m_pPerfHud->AddWarning("Render Thread Limited",1.f); - } - else - { - m_pInfoBox->AddEntry("GPU Limited", CPerfHUD::COL_ERROR, CPerfHUD::TEXT_SIZE_ERROR); - m_pPerfHud->AddWarning("GPU Limited",1.f); - }*/ - } - - // - // GPU Time - // - float gpuTime = pRenderer->GetGPUFrameTime(); - - if (gpuTime > 0.f) - { - float gpuFPS = 1.f / gpuTime; - - sprintf_s(entryBuffer, CMiniInfoBox::MAX_TEXT_LENGTH, "GPU FPS: %.2f (%.2f)", gpuFPS, m_fpsBudget); - if (gpuFPS >= m_fpsBudget) - { - m_pInfoBox->AddEntry(entryBuffer, CPerfHUD::COL_NORM, CPerfHUD::TEXT_SIZE_NORM); - } - else - { - m_pInfoBox->AddEntry(entryBuffer, CPerfHUD::COL_ERROR, CPerfHUD::TEXT_SIZE_NORM); - CryPerfHUDWarning(1.f, "GPU FPS Too Low: %.2f", gpuFPS); - } - } - - - // - // HDR - // - bool bHDRModeEnabled = false; - pRenderer->EF_Query(EFQ_HDRModeEnabled, bHDRModeEnabled); - if (bHDRModeEnabled) - { - m_runtimeData.hdrEnabled = true; - if (!m_runtimeData.hdrEnabled) - { - CryPerfHUDWarning(1.f, "HDR Disabled"); - } - } - - if (!gEnv->IsEditor()) - { - // - // Render Thread - // - static ICVar* pMultiThreaded = gEnv->pConsole->GetCVar("r_MultiThreaded"); - if (pMultiThreaded && pMultiThreaded->GetIVal() > 0) - { - //sprintf_s(entryBuffer, CMiniInfoBox::MAX_TEXT_LENGTH, "Render Thread Enabled"); - //m_pInfoBox->AddEntry(entryBuffer, CPerfHUD::COL_NORM, CPerfHUD::TEXT_SIZE_NORM); - m_runtimeData.renderThreadEnabled = true; - } - else - { - sprintf_s(entryBuffer, CMiniInfoBox::MAX_TEXT_LENGTH, "Render Thread Disabled"); - m_pInfoBox->AddEntry(entryBuffer, CPerfHUD::COL_ERROR, CPerfHUD::TEXT_SIZE_NORM); - m_runtimeData.renderThreadEnabled = false; - CryPerfHUDWarning(1.f, "Render Thread Disabled"); - } - } - - - // - // Camera - // - Matrix33 m = Matrix33(pRenderer->GetCamera().GetMatrix()); - m_runtimeData.cameraRot = RAD2DEG(Ang3::GetAnglesXYZ(m)); - m_runtimeData.cameraPos = pRenderer->GetCamera().GetPosition(); - - - // - // Polys / Draw Prims - // - int nShadowVolPolys; - int nPolys; - pRenderer->GetPolyCount(nPolys, nShadowVolPolys); - m_runtimeData.nPolys = nPolys; - m_runtimeData.nDrawPrims = pRenderer->GetCurrentNumberOfDrawCalls(); - - sprintf_s(entryBuffer, CMiniInfoBox::MAX_TEXT_LENGTH, "Draw Calls: %d (%d)", m_runtimeData.nDrawPrims, m_dpBudget); - - if (m_runtimeData.nDrawPrims <= m_dpBudget) - { - m_pInfoBox->AddEntry(entryBuffer, CPerfHUD::COL_NORM, CPerfHUD::TEXT_SIZE_NORM); - } - else - { - m_pInfoBox->AddEntry(entryBuffer, CPerfHUD::COL_ERROR, CPerfHUD::TEXT_SIZE_NORM); - CryPerfHUDWarning(1.f, "Too Many Draw Calls: %d", m_runtimeData.nDrawPrims); - } - - sprintf_s(entryBuffer, CMiniInfoBox::MAX_TEXT_LENGTH, "Num Tris: %d (%d)", m_runtimeData.nPolys, m_polyBudget); - - if (m_runtimeData.nPolys <= m_polyBudget) - { - m_pInfoBox->AddEntry(entryBuffer, CPerfHUD::COL_NORM, CPerfHUD::TEXT_SIZE_NORM); - } - else - { - m_pInfoBox->AddEntry(entryBuffer, CPerfHUD::COL_ERROR, CPerfHUD::TEXT_SIZE_NORM); - CryPerfHUDWarning(1.f, "Too Many Tris: %d", m_runtimeData.nPolys); - } - - // - // Post Effects - // - - gEnv->pRenderer->EF_Query(EFQ_NumActivePostEffects, m_runtimeData.nPostEffects); - sprintf_s(entryBuffer, CMiniInfoBox::MAX_TEXT_LENGTH, "Num Post Effects: %d (%d)", m_runtimeData.nPostEffects, m_postEffectBudget); - - if (m_runtimeData.nPostEffects <= m_postEffectBudget) - { - m_pInfoBox->AddEntry(entryBuffer, CPerfHUD::COL_NORM, CPerfHUD::TEXT_SIZE_NORM); - } - else - { - m_pInfoBox->AddEntry(entryBuffer, CPerfHUD::COL_ERROR, CPerfHUD::TEXT_SIZE_NORM); - CryPerfHUDWarning(1.f, "Too Many Post Effects: %d", m_runtimeData.nPostEffects); - } - - m_runtimeData.nFwdLights = 0; - m_runtimeData.nFwdShadowLights = 0; - - ////////////////////////////////////////////////////////////////////////// - if (gEnv->pRenderer) - { - STextureStreamingStats textureStats(true); - gEnv->pRenderer->EF_Query(EFQ_GetTexStreamingInfo, textureStats); - - float fTexRequiredMB = (float)(textureStats.nRequiredStreamedTexturesSize) / (1024 * 1024); - sprintf_s(entryBuffer, "Textures Required: %.2f (%dMB)", fTexRequiredMB, azlossy_cast(textureStats.nMaxPoolSize / (1024 * 1024))); - if (fTexRequiredMB < textureStats.nMaxPoolSize) - { - m_pInfoBox->AddEntry(entryBuffer, CPerfHUD::COL_NORM, CPerfHUD::TEXT_SIZE_NORM); - } - else - { - m_pInfoBox->AddEntry(entryBuffer, CPerfHUD::COL_ERROR, CPerfHUD::TEXT_SIZE_NORM); - CryPerfHUDWarning(1.f, "Too Many Textures: %.2fMB", fTexRequiredMB); - } - } -} -bool CRenderStatsWidget::ShouldUpdate() -{ - if (!m_pInfoBox->IsHidden() || - m_pPerfHUD->WarningsWindowEnabled()) - { - return true; - } - return false; -} - -void CRenderStatsWidget::LoadBudgets(XmlNodeRef perfXML) -{ - if (perfXML) - { - XmlNodeRef xmlNode; - - if ((xmlNode = perfXML->findChild("fps"))) - { - xmlNode->getAttr("value", m_fpsBudget); - } - - if ((xmlNode = perfXML->findChild("drawPrim"))) - { - xmlNode->getAttr("value", m_dpBudget); - } - - if ((xmlNode = perfXML->findChild("tris"))) - { - xmlNode->getAttr("value", m_polyBudget); - } - - if ((xmlNode = perfXML->findChild("postEffects"))) - { - xmlNode->getAttr("value", m_postEffectBudget); - } - - if ((xmlNode = perfXML->findChild("shadowCastingLights"))) - { - xmlNode->getAttr("value", m_shadowCastBudget); - } - - if ((xmlNode = perfXML->findChild("particles"))) - { - xmlNode->getAttr("value", m_particlesBudget); - } - } -} - -void CRenderStatsWidget::SaveStats(XmlNodeRef statsXML) -{ - if (!ShouldUpdate()) - { - //Force update of stats, widget may not be currently enabled - Update(); - } - - if (statsXML) - { - XmlNodeRef renderNode; - - if ((renderNode = statsXML->newChild("RenderStats"))) - { - XmlNodeRef child; - - if ((child = renderNode->newChild("fps"))) - { - child->setAttr("value", m_runtimeData.fps); - } - - if ((child = renderNode->newChild("hdr"))) - { - child->setAttr("value", m_runtimeData.hdrEnabled); - } - - if ((child = renderNode->newChild("renderThread"))) - { - child->setAttr("value", m_runtimeData.renderThreadEnabled); - } - - if ((child = renderNode->newChild("cameraPos"))) - { - child->setAttr("x", m_runtimeData.cameraPos.x); - child->setAttr("y", m_runtimeData.cameraPos.y); - child->setAttr("z", m_runtimeData.cameraPos.z); - } - - if ((child = renderNode->newChild("cameraRot"))) - { - child->setAttr("x", m_runtimeData.cameraRot.x); - child->setAttr("y", m_runtimeData.cameraRot.y); - child->setAttr("z", m_runtimeData.cameraRot.z); - } - - if ((child = renderNode->newChild("drawPrims"))) - { - child->setAttr("value", m_runtimeData.nDrawPrims); - } - - if ((child = renderNode->newChild("numPolys"))) - { - child->setAttr("value", m_runtimeData.nPolys); - } - - if ((child = renderNode->newChild("numPostEffects"))) - { - child->setAttr("value", m_runtimeData.nPostEffects); - } - - if ((child = renderNode->newChild("numFwdLights"))) - { - child->setAttr("value", m_runtimeData.nFwdLights); - } - - if ((child = renderNode->newChild("numFwdShadowLights"))) - { - child->setAttr("value", m_runtimeData.nFwdShadowLights); - } - - if ((child = renderNode->newChild("numDefLights"))) - { - child->setAttr("value", m_runtimeData.nDefLights); - } - - if ((child = renderNode->newChild("numDefShadowLights"))) - { - child->setAttr("value", m_runtimeData.nDefShadowLights); - } - - if ((child = renderNode->newChild("numDefCubeMaps"))) - { - child->setAttr("value", m_runtimeData.nDefCubeMaps); - } - - if ((child = renderNode->newChild("numParticles"))) - { - child->setAttr("value", m_runtimeData.nParticles); - } - } - } -} - -////////////////////////////////////////////////////////////////////////// -//Streaming Stats Widget -////////////////////////////////////////////////////////////////////////// - -CStreamingStatsWidget::CStreamingStatsWidget(IMiniCtrl* pParentMenu, ICryPerfHUD* pPerfHud) - : ICryPerfHUDWidget(eWidget_StreamingStats) -{ - m_pPerfHUD = pPerfHud; - m_pInfoBox = pPerfHud->CreateInfoMenuItem(pParentMenu, "Streaming", NULL, Rect(45, 200, 100, 300), true); - - //m_maxMeshSizeArroundMB = 0; - //m_maxTextureSizeArroundMB = 0; -} - -////////////////////////////////////////////////////////////////////////// -void CStreamingStatsWidget::Update() -{ -} - -////////////////////////////////////////////////////////////////////////// -bool CStreamingStatsWidget::ShouldUpdate() -{ - if (!m_pInfoBox->IsHidden() || - m_pPerfHUD->WarningsWindowEnabled()) - { - return true; - } - return false; -} - -////////////////////////////////////////////////////////////////////////// -void CStreamingStatsWidget::LoadBudgets(XmlNodeRef perfXML) -{ - /* -if(perfXML) -{ -XmlNodeRef xmlNode; -if( (xmlNode=perfXML->findChild("MeshSizeArround")) ) -{ - xmlNode->getAttr("value", m_maxMeshSizeArroundMB); -} -if( (xmlNode=perfXML->findChild("TextureSizeArround")) ) -{ - xmlNode->getAttr("value", m_maxTextureSizeArroundMB); -} -} -*/ -} - -////////////////////////////////////////////////////////////////////////// -//Warnings Widget -////////////////////////////////////////////////////////////////////////// - -CWarningsWidget::CWarningsWidget(IMiniCtrl* pParentMenu, ICryPerfHUD* pPerfHud) - : ICryPerfHUDWidget(eWidget_Warnings) -{ - m_pInfoBox = pPerfHud->CreateInfoMenuItem(pParentMenu, "Warnings", NULL, Rect(890, 150, 900, 200) /*, true*/); - - m_nMainThreadId = CryGetCurrentThreadId(); -} - -void CWarningsWidget::Reset() -{ - m_warnings.clear(); -} - -void CWarningsWidget::Update() -{ - //must be Main thread for MT warnings to work - assert(CryGetCurrentThreadId() == m_nMainThreadId); - - //Update from multithreaded queue - while (!m_threadWarnings.empty()) - { - SWarning warning; - if (m_threadWarnings.try_pop(warning)) - { - AddWarning(warning.remainingDuration, warning.text); - } - } - - float frameTime = gEnv->pTimer->GetRealFrameTime(); - - //delete old warnings - // [K01]: fixing Linux crash - TSWarnings::iterator iter = m_warnings.begin(); - while (iter != m_warnings.end()) - { - SWarning* pW = &(*iter); - pW->remainingDuration -= frameTime; - - if (pW->remainingDuration <= 0.f) - { - iter = m_warnings.erase(iter); - } - else - { - ++iter; - } - } - - int nWarnings = m_warnings.size(); - m_pInfoBox->ClearEntries(); - - //display warnings - for (int i = 0; i < nWarnings; i++) - { - m_pInfoBox->AddEntry(m_warnings[i].text, CPerfHUD::COL_ERROR, CPerfHUD::TEXT_SIZE_WARN); - } -} - -bool CWarningsWidget::ShouldUpdate() -{ - return !m_pInfoBox->IsHidden(); -} - -void CWarningsWidget::SaveStats(XmlNodeRef statsXML) -{ - if (statsXML) - { - const int nWarnings = m_warnings.size(); - - if (nWarnings > 0) - { - XmlNodeRef warningNode; - - if ((warningNode = statsXML->newChild("warnings"))) - { - XmlNodeRef child; - - for (int i = 0; i < nWarnings; i++) - { - if ((child = warningNode->newChild("warning"))) - { - child->setAttr("value", m_warnings[i].text); - } - } - } - } - } -} - -void CWarningsWidget::AddWarningV(float duration, const char* fmt, va_list argList) -{ - char warningText[WARNING_LENGTH]; - - int written = vsnprintf_s(warningText, WARNING_LENGTH, WARNING_LENGTH - 1, fmt, argList); - - if (written == -1) - { - warningText[WARNING_LENGTH - 1] = '\0'; - } - - AddWarning(duration, warningText); -} - -void CWarningsWidget::AddWarning(float duration, const char* warning) -{ - if (CryGetCurrentThreadId() == m_nMainThreadId) - { - const size_t nWarnings = m_warnings.size(); - bool bNewWarning = true; - - ptrdiff_t nCompareLen = strlen(warning); - const char* s = strchr(warning, ':'); - if (s) - { - nCompareLen = s - warning; - } - - for (size_t i = 0; i < nWarnings; i++) - { - if (strncmp(m_warnings[i].text, warning, nCompareLen) == 0) - { - //warning already exists, update duration - m_warnings[i].remainingDuration = duration; - cry_strcpy(m_warnings[i].text, warning); - bNewWarning = false; - break; - } - } - - if (bNewWarning) - { - SWarning newWarning; - newWarning.remainingDuration = duration; - cry_strcpy(newWarning.text, warning); - - m_warnings.push_back(newWarning); - } - } - else - { - //add to thread safe queue, warning will be added next update - SWarning newWarning; - newWarning.remainingDuration = duration; - cry_strcpy(newWarning.text, warning); - m_threadWarnings.push(newWarning); - } -} - -////////////////////////////////////////////////////////////////////////// -//Render Batch Stats Widget -////////////////////////////////////////////////////////////////////////// - -CRenderBatchWidget::CRenderBatchWidget(IMiniCtrl* pParentMenu, ICryPerfHUD* pPerfHud) - : ICryPerfHUDWidget(eWidget_RenderBatchStats) -{ - m_pTable = pPerfHud->CreateTableMenuItem(pParentMenu, "Render Batch Stats"); - - m_pRStatsCVar = GetISystem()->GetIConsole()->GetCVar("r_stats"); - - m_displayMode = DISPLAY_MODE_BATCH_STATS; - - m_pTable->RemoveColumns(); - m_pTable->AddColumn("Name"); - m_pTable->AddColumn("DPs"); - m_pTable->AddColumn("Instances"); - m_pTable->AddColumn("ZPass"); - m_pTable->AddColumn("Shadows"); - m_pTable->AddColumn("General"); - m_pTable->AddColumn("Transparent"); - m_pTable->AddColumn("Misc"); -} - -void CRenderBatchWidget::Reset() -{ -} - -void CRenderBatchWidget::SaveStats(XmlNodeRef statsXML) -{ -} - -void CRenderBatchWidget::Enable(int mode) -{ - mode = min(mode, DISPLAY_MODE_NUM - 1); - EDisplayMode newMode = (EDisplayMode)mode; - - if (m_displayMode != newMode) - { - //workaround for now, - //since we poke renderer in order to gather stats - switch (m_displayMode) - { - case DISPLAY_MODE_BATCH_STATS: - gEnv->pRenderer->CollectDrawCallsInfo(false); - break; - - case DISPLAY_MODE_GPU_TIMES: - m_pRStatsCVar->Set(0); - break; - } - - switch (newMode) - { - case DISPLAY_MODE_BATCH_STATS: - m_pTable->RemoveColumns(); - m_pTable->AddColumn("Name"); - m_pTable->AddColumn("DPs"); - m_pTable->AddColumn("Instances"); - m_pTable->AddColumn("ZPass"); - m_pTable->AddColumn("Shadows"); - m_pTable->AddColumn("General"); - m_pTable->AddColumn("Transparent"); - m_pTable->AddColumn("Misc"); - m_displayMode = newMode; - break; - - case DISPLAY_MODE_GPU_TIMES: - m_pTable->RemoveColumns(); - m_pTable->AddColumn("Name"); - m_pTable->AddColumn("Num Batches"); - m_pTable->AddColumn("Num Verts"); - m_pTable->AddColumn("Num Tris"); - m_displayMode = newMode; - break; - - default: - CryLogAlways("[Render Batch Stats] Attempting to set incorrect display mode set: %d", mode); - break; - } - } - - m_pTable->Hide(false); -} - -void CRenderBatchWidget::Disable() -{ - //ensure renderer is not doing unnecessary work - m_pRStatsCVar->Set(0); - gEnv->pRenderer->CollectDrawCallsInfo(false); - m_pTable->Hide(true); -} - - -bool CRenderBatchWidget::ShouldUpdate() -{ - return !m_pTable->IsHidden(); -} - -void CRenderBatchWidget::Update() -{ - switch (m_displayMode) - { - case DISPLAY_MODE_BATCH_STATS: - Update_ModeBatchStats(); - break; - case DISPLAY_MODE_GPU_TIMES: - Update_ModeGpuTimes(); - break; - default: - CryLogAlways("[Render Batch Stats]Incorrect Display mode set: %d", m_displayMode); - break; - } -} - -void CRenderBatchWidget::Update_ModeBatchStats() -{ -#if !defined(_RELEASE) - IRenderer* pRenderer = gEnv->pRenderer; - - pRenderer->CollectDrawCallsInfo(true); - - typedef std::map BatchMap; - typedef std::map::iterator BatchMapItor; - - //sorted Map elements - std::vector sortedBatchList; - - BatchMap batchMap; - - //mesh totals - static const char* strMeshTotals = "TOTAL (Mesh)"; - BatchInfoPerPass totalsMesh; - totalsMesh.col.set(255, 255, 255, 255); - totalsMesh.name = strMeshTotals; - - int nDPs = gEnv->pRenderer->GetCurrentNumberOfDrawCalls(); - - //scene totals - static const char* strSceneTotals = "TOTAL (Scene)"; - - BatchInfoPerPass totalsScene; - totalsScene.col.set(0, 255, 255, 255); - totalsScene.name = strSceneTotals; - totalsScene.nBatches = nDPs; - - int unknownDPs = nDPs; - - m_pTable->ClearTable(); - - IRenderer::RNDrawcallsMapMesh& drawCallsInfo = gEnv->pRenderer->GetDrawCallsInfoPerMesh(); - - IRenderer::RNDrawcallsMapMeshItor pEnd = drawCallsInfo.end(); - IRenderer::RNDrawcallsMapMeshItor pItor = drawCallsInfo.begin(); - - //Per RenderNode Stats - for (; pItor != pEnd; ++pItor) - { - IRenderer::SDrawCallCountInfo& drawInfo = pItor->second; - - uint32 nDrawcalls = drawInfo.nShadows + drawInfo.nZpass + drawInfo.nGeneral + drawInfo.nTransparent + drawInfo.nMisc; - - const char* pRenderNodeName = drawInfo.meshName; - const char* pNameShort = strrchr(pRenderNodeName, '/'); - - if (pNameShort) - { - pRenderNodeName = pNameShort + 1; - } - - BatchInfoPerPass batch; - - batch.name = pRenderNodeName; - batch.nBatches = nDrawcalls; - batch.nInstances = 1; - batch.nZpass = drawInfo.nZpass; - batch.nShadows = drawInfo.nShadows; - batch.nGeneral = drawInfo.nGeneral; - batch.nTransparent = drawInfo.nTransparent; - batch.nMisc = drawInfo.nMisc; - - BatchMapItor batchIter = batchMap.find(string(pRenderNodeName)); - - //already an entry for this stat obj - append details - if (batchIter != batchMap.end()) - { - BatchInfoPerPass& currentBatch = batchIter->second; - currentBatch += batch; - } - else - { - //insert new entry into map - std::pair newElem = batchMap.insert(BatchMapItor::value_type(string(pRenderNodeName), batch)); - BatchInfoPerPass& newBatch = newElem.first->second; - sortedBatchList.push_back(&newBatch); - } - - totalsMesh += batch; - } - - unknownDPs -= totalsMesh.nBatches; - - // - // Unknown counts (sceneDP - sum of batches) - // - //could be -ve or +ve (-ve for conditional rendering) - if (unknownDPs != 0) - { - static const char* s_strUnknown = "Unknown"; - static BatchInfoPerPass s_unknownBatch; - s_unknownBatch.Reset(); - s_unknownBatch.name = s_strUnknown; - s_unknownBatch.nBatches = max(0, unknownDPs); - s_unknownBatch.col.set(255, 255, 0, 255); - sortedBatchList.push_back(&s_unknownBatch); - } - - //Scene Totals - m_pTable->AddData(0, totalsScene.col, totalsScene.name); - m_pTable->AddData(1, totalsScene.col, "%d", totalsScene.nBatches); - m_pTable->AddData(2, totalsScene.col, "%d", totalsScene.nInstances); - m_pTable->AddData(3, totalsScene.col, "%d", totalsScene.nZpass); - m_pTable->AddData(4, totalsScene.col, "%d", totalsScene.nShadows); - m_pTable->AddData(5, totalsScene.col, "%d", totalsScene.nGeneral); - m_pTable->AddData(6, totalsScene.col, "%d", totalsScene.nTransparent); - m_pTable->AddData(7, totalsScene.col, "%d", totalsScene.nMisc); - - //Mesh Totals - m_pTable->AddData(0, totalsMesh.col, totalsMesh.name); - m_pTable->AddData(1, totalsMesh.col, "%d", totalsMesh.nBatches); - m_pTable->AddData(2, totalsMesh.col, "%d", totalsMesh.nInstances); - m_pTable->AddData(3, totalsMesh.col, "%d", totalsMesh.nZpass); - m_pTable->AddData(4, totalsMesh.col, "%d", totalsMesh.nShadows); - m_pTable->AddData(5, totalsMesh.col, "%d", totalsMesh.nGeneral); - m_pTable->AddData(6, totalsMesh.col, "%d", totalsMesh.nTransparent); - m_pTable->AddData(7, totalsMesh.col, "%d", totalsMesh.nMisc); - - - if (int nBatches = sortedBatchList.size()) - { - std::sort(sortedBatchList.begin(), sortedBatchList.end(), BatchInfoSortPerPass()); - - for (int i = 0; i < nBatches; i++) - { - BatchInfoPerPass* batch = sortedBatchList[i]; - - int nInstances = max(1, (int)batch->nInstances); - - m_pTable->AddData(0, batch->col, batch->name); - - //Due to different render meshes with the same name, averaged - //stats are a bit confusing, disabling for now - if constexpr (0 && batch->nInstances > 1) - { - m_pTable->AddData(1, batch->col, "%d (%d)", batch->nBatches, batch->nBatches / nInstances); - m_pTable->AddData(2, batch->col, "%d", batch->nInstances); - m_pTable->AddData(3, batch->col, "%d (%d)", batch->nZpass, batch->nZpass / nInstances); - m_pTable->AddData(4, batch->col, "%d (%d)", batch->nShadows, batch->nShadows / nInstances); - m_pTable->AddData(5, batch->col, "%d (%d)", batch->nGeneral, batch->nGeneral / nInstances); - m_pTable->AddData(6, batch->col, "%d (%d)", batch->nTransparent, batch->nTransparent / nInstances); - m_pTable->AddData(7, batch->col, "%d (%d)", batch->nMisc, batch->nMisc / nInstances); - } - else - { - m_pTable->AddData(1, batch->col, "%d", batch->nBatches); - m_pTable->AddData(2, batch->col, "%d", batch->nInstances); - m_pTable->AddData(3, batch->col, "%d", batch->nZpass); - m_pTable->AddData(4, batch->col, "%d", batch->nShadows); - m_pTable->AddData(5, batch->col, "%d", batch->nGeneral); - m_pTable->AddData(6, batch->col, "%d", batch->nTransparent); - m_pTable->AddData(7, batch->col, "%d", batch->nMisc); - } - } - } -#else - m_pTable->ClearTable(); - m_pTable->AddData(0, ColorB(255, 0, 0, 255), "Not supported in Release builds"); -#endif//RELEASE (DO_RENDERSTATS - not available in CrySystem) -} - -void CRenderBatchWidget::Update_ModeGpuTimes() -{ - m_pTable->ClearTable(); - m_pTable->AddData(0, ColorB(255, 0, 0, 255), "Not supported for this platform"); -} - - -#endif //USE_PERFHUD - diff --git a/Code/CryEngine/CrySystem/PerfHUD.h b/Code/CryEngine/CrySystem/PerfHUD.h deleted file mode 100644 index 27078eb3c6..0000000000 --- a/Code/CryEngine/CrySystem/PerfHUD.h +++ /dev/null @@ -1,478 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS 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 : Button implementation in the MiniGUI - - -#ifndef CRYINCLUDE_CRYSYSTEM_PERFHUD_H -#define CRYINCLUDE_CRYSYSTEM_PERFHUD_H -#pragma once - - -#include - -#ifdef USE_PERFHUD - -#include -#include "MiniGUI/MiniInfoBox.h" -#include "MiniGUI/MiniTable.h" - -//Macros for console based widget control - -#define SET_WIDGET_DECL(WIDGET_NAME) \ - static int s_cvar_##WIDGET_NAME; \ - static void Set_##WIDGET_NAME##_Widget(ICVar * pCvar); - -#define SET_WIDGET_DEF(WIDGET_NAME, WIDGET_ID) \ - int CPerfHUD::s_cvar_##WIDGET_NAME = 0; \ - void CPerfHUD::Set_##WIDGET_NAME##_Widget(ICVar * pCvar) \ - { \ - ICryPerfHUD* pPerfHud = gEnv->pSystem->GetPerfHUD(); \ - if (pPerfHud) \ - { \ - int val = pCvar->GetIVal(); \ - if (val) \ - { \ - pPerfHud->SetState(eHudOutOfFocus); \ - pPerfHud->EnableWidget(ICryPerfHUDWidget::WIDGET_ID, val); \ - } \ - else \ - { \ - pPerfHud->DisableWidget(ICryPerfHUDWidget::WIDGET_ID); \ - } \ - } \ - } - -#define SET_WIDGET_COMMAND(COMMAND_NAME, WIDGET_NAME) \ - REGISTER_CVAR2_CB(COMMAND_NAME, &s_cvar_##WIDGET_NAME, 0, VF_ALWAYSONCHANGE, "", Set_##WIDGET_NAME##_Widget); - -////////////////////////////////////////////////////////////////////////// -// Root window all other controls derive from -class CPerfHUD - : public ICryPerfHUD - , public minigui::IMiniGUIEventListener - , public AzFramework::InputChannelEventListener -{ -public: - CRYINTERFACE_BEGIN() - CRYINTERFACE_ADD(ICryPerfHUD) - CRYINTERFACE_END() - CRYGENERATE_SINGLETONCLASS(CPerfHUD, "PerfHUD", 0x006945f9985e4ce2, 0x872120bfdec09ca5) - -public: - ////////////////////////////////////////////////////////////////////////// - // ICryPerfHUD implementation - ////////////////////////////////////////////////////////////////////////// - virtual void Init(); - virtual void Done(); - virtual void Draw(); - virtual void LoadBudgets(); - virtual void SaveStats(const char* filename); - virtual void ResetWidgets(); - virtual void Reset(); - virtual void Destroy(); - - //Set state through code (rather than using joypad input) - virtual void SetState(EHudState state); - - virtual void Show(bool bRestoreState); - - virtual void AddWidget(ICryPerfHUDWidget* pWidget); - virtual void RemoveWidget(ICryPerfHUDWidget* pWidget); - - ////////////////////////////////////////////////////////////////////////// - // Gui Creation helper funcs - ////////////////////////////////////////////////////////////////////////// - virtual minigui::IMiniCtrl* CreateMenu(const char* name, minigui::IMiniCtrl* pParent = NULL); - virtual bool CreateCVarMenuItem(minigui::IMiniCtrl* pMenu, const char* name, const char* controlVar, float controlVarOn, float controlVarOff); - virtual bool CreateCallbackMenuItem(minigui::IMiniCtrl* pMenu, const char* name, minigui::ClickCallback callback, void* pCallbackData); - virtual minigui::IMiniInfoBox* CreateInfoMenuItem(minigui::IMiniCtrl* pMenu, const char* name, minigui::RenderCallback renderCallback, const minigui::Rect& rect, bool onAtStart = false); - virtual minigui::IMiniTable* CreateTableMenuItem(minigui::IMiniCtrl* pMenu, const char* name); - - virtual minigui::IMiniCtrl* GetMenu(const char* name); - - virtual void EnableWidget(ICryPerfHUDWidget::EWidgetID id, int mode); - virtual void DisableWidget(ICryPerfHUDWidget::EWidgetID id); - - ////////////////////////////////////////////////////////////////////////// - // WARNINGS - Widget Specific Interface - ////////////////////////////////////////////////////////////////////////// - virtual void AddWarning(float duration, const char* fmt, va_list argList); - virtual bool WarningsWindowEnabled() const; - - ////////////////////////////////////////////////////////////////////////// - // FPS - Widget Specific Interface - ////////////////////////////////////////////////////////////////////////// - virtual const std::vector* GetFpsBuckets(float& totalTime) const; - - ////////////////////////////////////////////////////////////////////////// - // IMiniGUIEventListener implementation - ////////////////////////////////////////////////////////////////////////// - virtual void OnCommand(minigui::SCommand& cmd); - ////////////////////////////////////////////////////////////////////////// - - // AzFramework::InputChannelEventListener - bool OnInputChannelEventFiltered(const AzFramework::InputChannel& inputChannel) override; - AZ::s32 GetPriority() const override { return AzFramework::InputChannelEventListener::GetPriorityUI(); } - - ////////////////////////////////////////////////////////////////////////// - // CLICK CALLBACKS - ////////////////////////////////////////////////////////////////////////// - - static void ResetCallback(void* data, bool status); - static void ReloadBudgetsCallback(void* data, bool status); - static void SaveStatsCallback(void* data, bool status); - - ////////////////////////////////////////////////////////////////////////// - // RENDER CALLBACKS - ////////////////////////////////////////////////////////////////////////// - - static void DisplayRenderInfoCallback(const minigui::Rect& rect); - - ////////////////////////////////////////////////////////////////////////// - // CVAR CALLBACK - ////////////////////////////////////////////////////////////////////////// - - static void CVarChangeCallback(ICVar* pCvar); - - SET_WIDGET_DECL(Warnings); - SET_WIDGET_DECL(RenderSummary); - SET_WIDGET_DECL(RenderBatchStats); - SET_WIDGET_DECL(FpsBuckets); - SET_WIDGET_DECL(Particles); - SET_WIDGET_DECL(PakFile); - - ////////////////////////////////////////////////////////////////////////// - // Static Data - ////////////////////////////////////////////////////////////////////////// - - static const float OVERSCAN_X; - static const float OVERSCAN_Y; - - static const ColorB COL_NORM; - static const ColorB COL_WARN; - static const ColorB COL_ERROR; - - static const float TEXT_SIZE_NORM; - static const float TEXT_SIZE_WARN; - static const float TEXT_SIZE_ERROR; - - static const float ACTIVATE_TIME_FROM_GAME; - static const float ACTIVATE_TIME_FROM_HUD; - -protected: - void InitUI(minigui::IMiniGUI* pGUI); - void SetNextState(); - -protected: - - static int m_sys_perfhud; - static int m_sys_perfhud_pause; - - int m_sys_perfhud_prev; - - //record last menu position - float m_menuStartX; - float m_menuStartY; - - bool m_hudCreated; - - bool m_L1Pressed; - bool m_L2Pressed; - bool m_R1Pressed; - bool m_R2Pressed; - bool m_changingState; - bool m_hwMouseEnabled; - - float m_triggersDownStartTime; - - EHudState m_hudState; - EHudState m_hudLastState; - - typedef std::vector< _smart_ptr, stl::STLGlobalAllocator<_smart_ptr > >::iterator TWidgetIterator; - - std::vector< _smart_ptr, stl::STLGlobalAllocator<_smart_ptr > > m_widgets; - std::vector > m_rootMenus; -}; - -class CFpsWidget - : public ICryPerfHUDWidget -{ -public: - - CFpsWidget(minigui::IMiniCtrl* pParentMenu, ICryPerfHUD* pPerfHud); - - virtual void Reset(); - virtual void Update(); - virtual bool ShouldUpdate(); - virtual void LoadBudgets(XmlNodeRef perfXML); - virtual void SaveStats(XmlNodeRef statsXML); - virtual void Enable([[maybe_unused]] int mode) { m_pInfoBox->Hide(false); } - virtual void Disable() { m_pInfoBox->Hide(true); } - - void Init(); - - const std::vector* GetFpsBuckets(float& totalTime) const; - - static void ResetCallback(void* data, bool status); - -protected: - - static const uint32 NUM_FPS_BUCKETS_DEFAULT = 6; - - struct PerfBucketsStat - { - std::vector buckets; - float totalTime; - }; - - template - void UpdateBuckets(PerfBucketsStat& buckets, float frameTime, const char* name, float stat); - - // Data - static int m_cvarPerfHudFpsExclusive; - - enum EPerfBucketType - { - BUCKET_FPS = 0, - BUCKET_GPU, - BUCKET_DP, - BUCKET_TYPE_NUM - }; - - - PerfBucketsStat m_perfBuckets[BUCKET_TYPE_NUM]; - - float m_fpsBucketSize; - float m_fpsBudget; - float m_dpBudget; - float m_dpBucketSize; - - minigui::IMiniInfoBox* m_pInfoBox; -}; - -class CRenderStatsWidget - : public ICryPerfHUDWidget -{ -public: - - CRenderStatsWidget(minigui::IMiniCtrl* pParentMenu, ICryPerfHUD* pPerfHud); - - virtual void Reset() {} - virtual void Update(); - virtual bool ShouldUpdate(); - virtual void LoadBudgets(XmlNodeRef perfXML); - virtual void SaveStats(XmlNodeRef statsXML); - virtual void Enable([[maybe_unused]] int mode) { m_pInfoBox->Hide(false); } - virtual void Disable() { m_pInfoBox->Hide(true); } - -protected: - - //budgets - float m_fpsBudget; - uint32 m_dpBudget; - uint32 m_polyBudget; - uint32 m_postEffectBudget; - uint32 m_shadowCastBudget; - uint32 m_particlesBudget; - - //runtime data - struct SRuntimeData - { - Vec3 cameraPos; - Ang3 cameraRot; - float fps; - uint32 nDrawPrims; - uint32 nPolys; - uint32 nPostEffects; - uint32 nFwdLights; - uint32 nFwdShadowLights; - uint32 nDefLights; - uint32 nDefShadowLights; - uint32 nDefCubeMaps; - int nParticles; - bool hdrEnabled; - bool renderThreadEnabled; - }; - - SRuntimeData m_runtimeData; - minigui::IMiniInfoBox* m_pInfoBox; - ICryPerfHUD* m_pPerfHUD; - uint32 m_buildNum; -}; - -class CStreamingStatsWidget - : public ICryPerfHUDWidget -{ -public: - - CStreamingStatsWidget(minigui::IMiniCtrl* pParentMenu, ICryPerfHUD* pPerfHud); - - virtual void Reset() {} - virtual void Update(); - virtual bool ShouldUpdate(); - virtual void LoadBudgets(XmlNodeRef perfXML); - virtual void SaveStats(XmlNodeRef statsXML) {}; - virtual void Enable([[maybe_unused]] int mode) { m_pInfoBox->Hide(false); } - virtual void Disable() { m_pInfoBox->Hide(true); } - -protected: - //float m_maxMeshSizeArroundMB; - //float m_maxTextureSizeArroundMB; - minigui::IMiniInfoBox* m_pInfoBox; - ICryPerfHUD* m_pPerfHUD; -}; - - -class CWarningsWidget - : public ICryPerfHUDWidget -{ -public: - - CWarningsWidget(minigui::IMiniCtrl* pParentMenu, ICryPerfHUD* pPerfHud); - - virtual void Reset(); - virtual void Update(); - virtual bool ShouldUpdate(); - virtual void LoadBudgets(XmlNodeRef perfXML) {}; - virtual void SaveStats(XmlNodeRef statsXML); - virtual void Enable([[maybe_unused]] int mode) { m_pInfoBox->Hide(false); } - virtual void Disable() { m_pInfoBox->Hide(true); } - - void AddWarningV(float duration, const char* fmt, va_list argList); - void AddWarning(float duration, const char* warning); - -protected: - - static const uint32 WARNING_LENGTH = 64; - - struct SWarning - { - char text[WARNING_LENGTH]; - float remainingDuration; - }; - - minigui::IMiniInfoBox* m_pInfoBox; - - typedef std::vector< SWarning > TSWarnings; - - TSWarnings m_warnings; - - CryMT::queue m_threadWarnings; - - threadID m_nMainThreadId; -}; - -class CRenderBatchWidget - : public ICryPerfHUDWidget -{ -public: - - CRenderBatchWidget(minigui::IMiniCtrl* pParentMenu, ICryPerfHUD* pPerfHud); - - virtual void Reset(); - virtual void Update(); - virtual bool ShouldUpdate(); - virtual void LoadBudgets(XmlNodeRef perfXML) {}; - virtual void SaveStats(XmlNodeRef statsXML); - virtual void Enable(int mode); - virtual void Disable(); - - void Update_ModeGpuTimes(); - void Update_ModeBatchStats(); - -protected: - - struct BatchInfoGpuTimes - { - const char* name; - uint32 nBatches; - float gpuTime; - int numVerts; - int numIndices; - }; - - struct BatchInfoSortGpuTimes - { - inline bool operator() (const BatchInfoGpuTimes& lhs, const BatchInfoGpuTimes& rhs) const - { - return lhs.gpuTime > rhs.gpuTime; - } - }; - - struct BatchInfoPerPass - { - const char* name; - uint16 nBatches; - uint16 nInstances; - uint16 nZpass; - uint16 nShadows; - uint16 nGeneral; - uint16 nTransparent; - uint16 nMisc; - ColorB col; - - BatchInfoPerPass() - { - Reset(); - } - - void Reset() - { - name = NULL; - nBatches = 0; - nInstances = 0; - nZpass = 0; - nShadows = 0; - nGeneral = 0; - nTransparent = 0; - nMisc = 0; - col.set(255, 255, 255, 255); - } - - void operator += (const BatchInfoPerPass& rhs) - { - nBatches += rhs.nBatches; - nInstances += rhs.nInstances; - nZpass += rhs.nZpass; - nShadows += rhs.nShadows; - nGeneral += rhs.nGeneral; - nTransparent += rhs.nTransparent; - nMisc += rhs.nMisc; - } - }; - - struct BatchInfoSortPerPass - { - inline bool operator() (const BatchInfoPerPass* lhs, const BatchInfoPerPass* rhs) const - { - return lhs->nBatches > rhs->nBatches; - } - }; - - enum EDisplayMode - { - DISPLAY_MODE_NONE = 0, - DISPLAY_MODE_BATCH_STATS, - DISPLAY_MODE_GPU_TIMES, - DISPLAY_MODE_NUM, - }; - - minigui::IMiniTable* m_pTable; - ICVar* m_pRStatsCVar; - EDisplayMode m_displayMode; -}; - -#endif //USE_PERFHUD - -#endif // CRYINCLUDE_CRYSYSTEM_PERFHUD_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/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/ResourceManager.cpp b/Code/CryEngine/CrySystem/ResourceManager.cpp index 08a674136d..5e9477a99c 100644 --- a/Code/CryEngine/CrySystem/ResourceManager.cpp +++ b/Code/CryEngine/CrySystem/ResourceManager.cpp @@ -320,7 +320,6 @@ bool CResourceManager::LoadFastLoadPaks(bool bToMemory) } const char* const assetsDir = "@assets@"; - const char* shaderPakPath = "ShaderCacheStartup.pak"; #if defined(AZ_RESTRICTED_PLATFORM) #define AZ_RESTRICTED_SECTION RESOURCEMANAGER_CPP_SECTION_2 @@ -328,7 +327,6 @@ bool CResourceManager::LoadFastLoadPaks(bool bToMemory) #endif gEnv->pCryPak->OpenPacks(assetsDir, AZ::IO::PathString(FAST_LOADING_PAKS_SRC_FOLDER) + "*.pak", nPakPreloadFlags, &m_fastLoadPakPaths); - gEnv->pCryPak->OpenPack(assetsDir, shaderPakPath, AZ::IO::IArchive::FLAGS_PAK_IN_MEMORY | AZ::IO::INestedArchive::FLAGS_OVERRIDE_PAK); gEnv->pCryPak->OpenPack(assetsDir, "Engine.pak", AZ::IO::IArchive::FLAGS_PAK_IN_MEMORY); return !m_fastLoadPakPaths.empty(); } @@ -343,11 +341,6 @@ void CResourceManager::UnloadFastLoadPaks() gEnv->pCryPak->ClosePack(m_fastLoadPakPaths[i].c_str(), AZ::IO::IArchive::FLAGS_PATH_REAL); } m_fastLoadPakPaths.clear(); - - if (gEnv && gEnv->pRenderer) - { - gEnv->pRenderer->UnloadShaderStartupCache(); - } } ////////////////////////////////////////////////////////////////////////// @@ -706,37 +699,18 @@ 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); } } - //Load and precache frontend shader cache - if (g_cvars.archiveVars.nLoadFrontendShaderCache) - { - gEnv->pRenderer->LoadShaderLevelCache(); - gEnv->pRenderer->EF_Query(EFQ_SetShaderCombinations); - } - break; } case ESYSTEM_EVENT_LEVEL_LOAD_PREPARE: { - if (g_cvars.archiveVars.nLoadFrontendShaderCache) - { - gEnv->pRenderer->UnloadShaderLevelCache(); - } - - 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/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/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/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/StreamEngine/StreamEngine.cpp b/Code/CryEngine/CrySystem/StreamEngine/StreamEngine.cpp index 37a7de8391..7f8c75b2a8 100644 --- a/Code/CryEngine/CrySystem/StreamEngine/StreamEngine.cpp +++ b/Code/CryEngine/CrySystem/StreamEngine/StreamEngine.cpp @@ -1211,20 +1211,9 @@ void CStreamEngine::TempFree(void* p, size_t nSize) namespace { #ifdef STREAMENGINE_ENABLE_STATS - void DrawText(const float x, const float y, ColorF c, const char* format, ...) + void DrawText(const float, const float, ColorF, const char*, ...) { - va_list args; - va_start(args, format); - - SDrawTextInfo ti; - ti.flags = eDrawText_FixedSize | eDrawText_2D | eDrawText_Monospace; - ti.xscale = ti.yscale = 1.2f; - ti.color[0] = c.r; - ti.color[1] = c.g; - ti.color[2] = c.b; - ti.color[3] = c.a; - gEnv->pRenderer->DrawTextQueued(Vec3(x, y, 1.0f), ti, format, args); - va_end(args); + // ToDo: Remove whole file with SPEC-343, or update to draw with Atom? Likely the former as I think this whole system is dead. } #endif diff --git a/Code/CryEngine/CrySystem/System.cpp b/Code/CryEngine/CrySystem/System.cpp index af9b674f6a..9016ea99f1 100644 --- a/Code/CryEngine/CrySystem/System.cpp +++ b/Code/CryEngine/CrySystem/System.cpp @@ -121,13 +121,9 @@ LRESULT WINAPI WndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam) #include #include -#include #include #include #include -#include -#include -#include "VisRegTest.h" #include #include @@ -135,10 +131,6 @@ LRESULT WINAPI WndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam) #include #include "XConsole.h" #include "Log.h" -#include "CrySizerStats.h" -#include "CrySizerImpl.h" -#include "NotificationNetwork.h" -#include "ProfileLog.h" #include "XML/xml.h" #include "XML/ReadWriteXMLSink.h" @@ -148,13 +140,10 @@ 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" #include "HMDBus.h" -#include "OverloadSceneManager/OverloadSceneManager.h" -#include #include "IZLibCompressor.h" #include "IZlibDecompressor.h" @@ -273,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. ////////////////////////////////////////////////////////////////////////// @@ -318,11 +291,6 @@ CSystem::CSystem(SharedEnvironmentInstance* pSharedEnvironment) m_pSystemEventDispatcher->RegisterListener(this); } -#ifdef WIN32 - m_hInst = NULL; - m_hWnd = NULL; -#endif - ////////////////////////////////////////////////////////////////////////// // Clear environment. ////////////////////////////////////////////////////////////////////////// @@ -333,31 +301,16 @@ 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; - m_pVisRegTest = NULL; m_rWidth = NULL; m_rHeight = NULL; m_rWidthAndHeightAsFractionOfScreenSize = NULL; @@ -368,7 +321,6 @@ CSystem::CSystem(SharedEnvironmentInstance* pSharedEnvironment) m_cvSSInfo = NULL; m_rStencilBits = NULL; m_rFullscreen = NULL; - m_rDriver = NULL; m_sysNoUpdate = NULL; m_pMemoryManager = NULL; m_pProcess = NULL; @@ -383,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) @@ -391,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; @@ -413,7 +358,6 @@ CSystem::CSystem(SharedEnvironmentInstance* pSharedEnvironment) m_pCpu = NULL; m_bInitializedSuccessfully = false; - m_bShaderCacheGenMode = false; m_bRelaunch = false; m_iLoadingMode = 0; m_bTestMode = false; @@ -423,16 +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 - - // no mem stats at the moment - m_pMemStats = NULL; - m_pSizer = NULL; m_pCVarQuit = NULL; m_bForceNonDevMode = false; @@ -446,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; @@ -460,17 +387,10 @@ CSystem::CSystem(SharedEnvironmentInstance* pSharedEnvironment) m_pXMLUtils = new CXmlUtils(this); - m_pArchiveHost = Serialization::CreateArchiveHost(); m_pMemoryManager = CryGetIMemoryManager(); - m_pThreadTaskManager = new CThreadTaskManager; m_pResourceManager = new CResourceManager; m_pTextModeConsole = NULL; - InitThreadSystem(); - - m_pMiniGUI = NULL; - m_pPerfHUD = NULL; - g_pPakHeap = new CMTSafeHeap; if (!AZ::AllocatorInstance::IsReady()) @@ -485,7 +405,6 @@ CSystem::CSystem(SharedEnvironmentInstance* pSharedEnvironment) AZ::Debug::Trace::Instance().Init(); } - m_UpdateTimesIdx = 0U; m_bNeedDoWorkDuringOcclusionChecks = false; m_eRuntimeState = ESYSTEM_EVENT_LEVEL_UNLOAD; @@ -499,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 @@ -516,19 +432,9 @@ CSystem::~CSystem() CRY_ASSERT(m_windowMessageHandlers.empty() && "There exists a dangling window message handler somewhere"); - SAFE_DELETE(m_pVisRegTest); SAFE_DELETE(m_pXMLUtils); - SAFE_DELETE(m_pArchiveHost); - 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); @@ -640,8 +546,6 @@ void CSystem::ShutDown() SAFE_DELETE(m_pTextModeConsole); - KillPhysicsThread(); - if (m_sys_firstlaunch) { m_sys_firstlaunch->Set("0"); @@ -687,10 +591,7 @@ void CSystem::ShutDown() gEnv->pLyShine = nullptr; } - 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) @@ -704,13 +605,6 @@ void CSystem::ShutDown() SAFE_RELEASE(m_pViewSystem); SAFE_RELEASE(m_pLevelSystem); - //Can't kill renderer before we delete CryFont, 3DEngine, etc - if (GetIRenderer()) - { - GetIRenderer()->ShutDown(); - SAFE_RELEASE(m_env.pRenderer); - } - if (m_env.pLog) { m_env.pLog->UnregisterConsoleVariables(); @@ -731,14 +625,12 @@ void CSystem::ShutDown() SAFE_RELEASE(m_cvSSInfo); SAFE_RELEASE(m_rStencilBits); SAFE_RELEASE(m_rFullscreen); - SAFE_RELEASE(m_rDriver); SAFE_RELEASE(m_sysWarnings); SAFE_RELEASE(m_sysKeyboard); 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 @@ -748,16 +640,9 @@ 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_pMemStats); - SAFE_DELETE(m_pSizer); SAFE_DELETE(m_pDefaultValidator); m_pValidator = nullptr; - SAFE_DELETE(m_env.pOverloadSceneManager); - SAFE_DELETE(m_pLocalizationManager); //DebugStats(false, false);//true); @@ -779,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(); @@ -788,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); @@ -816,11 +696,6 @@ void CSystem::Quit() m_pUserCallback->OnQuit(); } - if (GetIRenderer()) - { - GetIRenderer()->RestoreGamma(); - } - gEnv->pLog->FlushAndClose(); // Latest possible place to flush any pending messages to disk before the forceful termination. @@ -882,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() { @@ -1221,16 +829,10 @@ 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 - gEnv->pOverloadSceneManager->Update(); - #ifdef WIN32 // enable/disable SSE fp exceptions (#nan and /0) // need to do it each frame since sometimes they are being reset @@ -1242,15 +844,6 @@ bool CSystem::UpdatePreTickBus(int updateFlags, int nPauseMode) m_nUpdateCounter++; #ifndef EXCLUDE_UPDATE_ON_CONSOLE - if (!m_sDelayedScreeenshot.empty()) - { - gEnv->pRenderer->ScreenShot(m_sDelayedScreeenshot.c_str()); - m_sDelayedScreeenshot.clear(); - } - - // Check if game needs to be sleeping when not active. - SleepIfInactive(); - if (m_pUserCallback) { m_pUserCallback->OnUpdate(); @@ -1265,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 ////////////////////////////////////////////////////////////////////////// @@ -1278,27 +870,6 @@ bool CSystem::UpdatePreTickBus(int updateFlags, int nPauseMode) #ifdef USE_REMOTE_CONSOLE GetIRemoteConsole()->Update(); #endif - - if (!gEnv->IsEditor() && gEnv->pRenderer) - { - // If the dimensions of the render target change, - // or are different from the camera defaults, - // we need to update the camera frustum. - CCamera& viewCamera = GetViewCamera(); - const int renderTargetWidth = m_rWidth->GetIVal(); - const int renderTargetHeight = m_rHeight->GetIVal(); - - if (renderTargetWidth != viewCamera.GetViewSurfaceX() || - renderTargetHeight != viewCamera.GetViewSurfaceZ()) - { - viewCamera.SetFrustum(renderTargetWidth, - renderTargetHeight, - viewCamera.GetFov(), - viewCamera.GetNearPlane(), - viewCamera.GetFarPlane(), - gEnv->pRenderer->GetPixelAspectRatio()); - } - } if (nPauseMode != 0) { m_bPaused = true; @@ -1333,66 +904,12 @@ 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); m_pStreamEngine->Update(); } - if (g_cvars.az_streaming_stats) - { - SDrawTextInfo ti; - ti.flags = eDrawText_FixedSize | eDrawText_2D | eDrawText_Monospace; - ti.xscale = ti.yscale = 1.2f; - - const int viewportHeight = GetViewCamera().GetViewSurfaceZ(); - -#if defined(AZ_RESTRICTED_PLATFORM) - #define AZ_RESTRICTED_SECTION SYSTEM_CPP_SECTION_8 -#include AZ_RESTRICTED_FILE(System_cpp) -#else - float y = static_cast(viewportHeight) - 85.0f; -#endif - - AZStd::vector stats; - AZ::Interface::Get()->CollectStatistics(stats); - - for (AZ::IO::Statistic& stat : stats) - { - switch (stat.GetType()) - { - case AZ::IO::Statistic::Type::FloatingPoint: - gEnv->pRenderer->DrawTextQueued(Vec3(10, y, 1.0f), ti, - AZStd::string::format("%s/%s: %.3f", stat.GetOwner().data(), stat.GetName().data(), stat.GetFloatValue()).c_str()); - break; - case AZ::IO::Statistic::Type::Integer: - gEnv->pRenderer->DrawTextQueued(Vec3(10, y, 1.0f), ti, - AZStd::string::format("%s/%s: %lli", stat.GetOwner().data(), stat.GetName().data(), stat.GetIntegerValue()).c_str()); - break; - case AZ::IO::Statistic::Type::Percentage: - gEnv->pRenderer->DrawTextQueued(Vec3(10, y, 1.0f), ti, - AZStd::string::format("%s/%s: %.2f (percent)", stat.GetOwner().data(), stat.GetName().data(), stat.GetPercentage()).c_str()); - break; - default: - gEnv->pRenderer->DrawTextQueued(Vec3(10, y, 1.0f), ti, AZStd::string::format("Unsupported stat type: %i", static_cast(stat.GetType())).c_str()); - break; - } - y -= 12.0f; - if (y < 0.0f) - { - //Exit the loop because there's no purpose on rendering text outside of the visible area. - break; - } - } - } - #ifndef EXCLUDE_UPDATE_ON_CONSOLE if (m_bIgnoreUpdates) { @@ -1407,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; @@ -1476,12 +992,6 @@ bool CSystem::UpdatePreTickBus(int updateFlags, int nPauseMode) m_pServerThrottle->Update(); } - ////////////////////////////////////////////////////////////////////////// - if (m_env.pRenderer && m_env.pRenderer->GetIStereoRenderer()->IsRenderingToHMD()) - { - EBUS_EVENT(AZ::VR::HMDDeviceRequestBus, UpdateInternalState); - } - ////////////////////////////////////////////////////////////////////// //update console system if (m_env.pConsole) @@ -1496,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()) @@ -1524,14 +1024,6 @@ bool CSystem::UpdatePreTickBus(int updateFlags, int nPauseMode) } } - ////////////////////////////////////////////////////////////////////////// - // Update Threads Task Manager. - ////////////////////////////////////////////////////////////////////////// - { - FRAME_PROFILER("SysUpdate:ThreadTaskManager", this, PROFILE_SYSTEM); - m_pThreadTaskManager->OnUpdate(); - } - ////////////////////////////////////////////////////////////////////////// // Update Resource Manager. ////////////////////////////////////////////////////////////////////////// @@ -1540,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); @@ -1672,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(); @@ -2000,12 +1419,6 @@ void CSystem::Relaunch(bool bRelaunch) SaveConfiguration(); } -////////////////////////////////////////////////////////////////////////// -ICrySizer* CSystem::CreateSizer() -{ - return new CrySizerImpl; -} - ////////////////////////////////////////////////////////////////////////// uint32 CSystem::GetUsedMemory() { @@ -2018,12 +1431,6 @@ ILocalizationManager* CSystem::GetLocalizationManager() return m_pLocalizationManager; } -////////////////////////////////////////////////////////////////////////// -IThreadTaskManager* CSystem::GetIThreadTaskManager() -{ - return m_pThreadTaskManager; -} - ////////////////////////////////////////////////////////////////////////// IResourceManager* CSystem::GetIResourceManager() { @@ -2088,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()) { @@ -2101,23 +1504,12 @@ 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 } } //gEnv->pConsole->ExecuteString("sys_RestoreSpec test*"); // to get useful debugging information about current spec settings to the log file } -void CSystem::DumpMemoryCoverage() -{ - m_MemoryFragmentationProfiler.DumpMemoryCoverage(); -} - ITextModeConsole* CSystem::GetITextModeConsole() { if (m_bDedicatedServer) @@ -2211,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 f5235f2ea8..e27dfe4866 100644 --- a/Code/CryEngine/CrySystem/System.h +++ b/Code/CryEngine/CrySystem/System.h @@ -26,15 +26,12 @@ #include "MTSafeAllocator.h" #include "CPUDetect.h" #include -#include "MemoryFragmentationProfiler.h" // CMemoryFragmentationProfiler -#include "ThreadTask.h" #include "RenderBus.h" #include #include #include -#include namespace AzFramework { @@ -43,16 +40,8 @@ namespace AzFramework struct IConsoleCmdArgs; class CServerThrottle; -struct ICryFactoryRegistryImpl; struct IZLibCompressor; class CWatchdogThread; -class CThreadManager; - -struct ICryPerfHUD; -namespace minigui -{ - struct IMiniGUI; -} #if defined(AZ_RESTRICTED_PLATFORM) #undef AZ_RESTRICTED_SECTION @@ -191,8 +180,6 @@ namespace minigui #include "CryLibrary.h" #endif -#define NUM_UPDATE_TIMES (128U) - #ifdef WIN32 typedef void* WIN_HMODULE; #else @@ -214,7 +201,6 @@ namespace Audio } // namespace Audio struct SDefaultValidator; struct IDataProbe; -class CVisRegTest; #define PHSYICS_OBJECT_ENTITY 0 @@ -227,7 +213,6 @@ extern VTuneFunction VTPause; struct SSystemCVars { - int az_streaming_stats; int sys_streaming_requests_grouping_time_period; int sys_streaming_sleep; int sys_streaming_memory_budget; @@ -251,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; @@ -270,15 +254,6 @@ struct SSystemCVars int sys_error_debugbreak; int sys_FilesystemCaseSensitivity; - int sys_rendersplashscreen; - const char* sys_splashscreen; - - enum SplashScreenScaleMode - { - SplashScreenScaleMode_Fit = 0, - SplashScreenScaleMode_Fill - }; - int sys_splashScreenScaleMode; int sys_deferAudioUpdateOptim; #if USE_STEAM @@ -361,7 +336,6 @@ class CSystem , public IWindowMessageHandler , public AZ::RenderNotificationsBus::Handler , public CrySystemRequestBus::Handler - , private AzFramework::Terrain::TerrainDataNotificationBus::Handler { public: @@ -416,24 +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(); - virtual void DumpMemoryUsageStatistics(bool bUseKB); - virtual void DumpMemoryCoverage(); - void CollectMemInfo(SCryEngineStatsGlobalMemInfo&); - -#ifndef _RELEASE - virtual void GetCheckpointData(ICheckpointData& data); - virtual void IncreaseCheckpointLoadCount(); - virtual void SetLoadOrigin(LevelLoadOrigin origin); -#endif - virtual bool SteamInit(); void Relaunch(bool bRelaunch); @@ -444,22 +402,17 @@ public: void Quit(); bool IsQuitting() const; void ShutdownFileSystem(); // used to cleanup any file resources, such as cache handle. - bool IsShaderCacheGenMode() const { return m_bShaderCacheGenMode; } void SetAffinity(); virtual const char* GetUserName(); virtual int GetApplicationInstance(); int GetApplicationLogInstance(const char* logFilePath) override; - virtual sUpdateTimes& GetCurrentUpdateTimeStats(); - virtual const sUpdateTimes* GetUpdateTimeStats(uint32&, uint32&); - IRenderer* GetIRenderer(){ return m_env.pRenderer; } ITimer* GetITimer(){ return m_env.pTimer; } AZ::IO::IArchive* GetIPak() { return m_env.pCryPak; }; IConsole* GetIConsole() { return m_env.pConsole; }; 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; } @@ -469,38 +422,18 @@ public: IViewSystem* GetIViewSystem(); ILevelSystem* GetILevelSystem(); ISystemEventDispatcher* GetISystemEventDispatcher() { return m_pSystemEventDispatcher; } - IThreadTaskManager* GetIThreadTaskManager(); IResourceManager* GetIResourceManager(); ITextModeConsole* GetITextModeConsole(); - IFileChangeMonitor* GetIFileChangeMonitor() { return m_env.pFileChangeMonitor; } - IVisualLog* GetIVisualLog() { return m_env.pVisualLog; } - INotificationNetwork* GetINotificationNetwork() { return m_pNotificationNetwork; } IProfilingSystem* GetIProfilingSystem() { return &m_ProfilingSystem; } - ICryPerfHUD* GetPerfHUD() { return m_pPerfHUD; } IZLibCompressor* GetIZLibCompressor() { return m_pIZLibCompressor; } IZLibDecompressor* GetIZLibDecompressor() { return m_pIZLibDecompressor; } ILZ4Decompressor* GetLZ4Decompressor() { return m_pILZ4Decompressor; } IZStdDecompressor* GetZStdDecompressor() { return m_pIZStdDecompressor; } - WIN_HWND GetHWND(){ return m_hWnd; } ////////////////////////////////////////////////////////////////////////// // retrieves the perlin noise singleton instance 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 SetIFileChangeMonitor(IFileChangeMonitor* pFileChangeMonitor) { m_env.pFileChangeMonitor = pFileChangeMonitor; } - void SetIVisualLog(IVisualLog* pVisualLog) { m_env.pVisualLog = pVisualLog; } void DetectGameFolderAccessRights(); virtual void ExecuteCommandLine(bool deferred=true); @@ -514,8 +447,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; } @@ -585,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(); @@ -602,8 +527,6 @@ public: virtual void SetConfigPlatform(ESystemConfigPlatform platform); ////////////////////////////////////////////////////////////////////////// - virtual int SetThreadState(ESubsystem subsys, bool bActive); - virtual ICrySizer* CreateSizer(); virtual bool IsPaused() const { return m_bPaused; }; virtual ILocalizationManager* GetLocalizationManager(); @@ -613,27 +536,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: - // this enumeration describes the purpose for which the statistics is gathered. - // if it's gathered to be dumped, then some different rules may be applied - enum MemStatsPurposeEnum - { - nMSP_ForDisplay, nMSP_ForDump, nMSP_ForCrashLog, nMSP_ForBudget - }; - // collects the whole memory statistics into the given sizer object - void CollectMemStats (class ICrySizer* pSizer, MemStatsPurposeEnum nPurpose = nMSP_ForDisplay, std::vector* pStats = 0); - void GetExeSizes (ICrySizer* pSizer, MemStatsPurposeEnum nPurpose = nMSP_ForDisplay); - //! refreshes the m_pMemStats if necessary; creates it if it's not created - void TickMemStats(MemStatsPurposeEnum nPurpose = nMSP_ForDisplay, IResourceCollector* pResourceCollector = 0); - #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(); @@ -656,8 +563,6 @@ private: // Release all resources. void ShutDown(); - void SleepIfInactive(); - bool LoadEngineDLLs(); //! @name Initialization routines @@ -671,16 +576,9 @@ private: //@} - ////////////////////////////////////////////////////////////////////////// - // Threading functions. - ////////////////////////////////////////////////////////////////////////// - void InitThreadSystem(); - void ShutDownThreadSystem(); - ////////////////////////////////////////////////////////////////////////// // Helper functions. ////////////////////////////////////////////////////////////////////////// - void CreateRendererVars(const SSystemInitParams& startupParams); void CreateSystemVars(); void CreateAudioVars(); @@ -694,9 +592,6 @@ private: void LogBuildInfo(); void SetDevMode(bool bEnable); - void CreatePhysicsThread(); - void KillPhysicsThread(); - #ifndef _RELEASE static void SystemVersionChanged(ICVar* pCVar); #endif // #ifndef _RELEASE @@ -725,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, "\\")) @@ -755,23 +649,9 @@ public: CCpuFeatures* GetCPUFeatures() { return m_pCpu; }; - string& GetDelayedScreeenshot() {return m_sDelayedScreeenshot; } - - CVisRegTest*& GetVisRegTestPtrRef() {return m_pVisRegTest; } - const CTimeValue& GetLastTickTime(void) const { return m_lastTickTime; } const ICVar* GetDedicatedMaxRate(void) const { return m_svDedicatedMaxRate; } - const char* GetRenderingDriverName(void) const - { - if(m_rDriver) - { - return m_rDriver->GetString(); - } - return nullptr; - } - - std::shared_ptr CreateLocalFileIO(); // Gets the dimensions (in pixels) of the primary physical display. @@ -787,11 +667,9 @@ private: // ------------------------------------------------------ CTimer m_Time; //!< CCamera m_ViewCamera; //!< bool m_bInitializedSuccessfully; //!< true if the system completed all initialization steps - bool m_bShaderCacheGenMode;//!< true if the application runs in shader cache generation mode 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; @@ -804,19 +682,8 @@ private: // ------------------------------------------------------ bool m_bInDevMode; //!< Set to true if was in dev mode. bool m_bGameFolderWritable;//!< True when verified that current game folder have write access. SDefaultValidator* m_pDefaultValidator; //!< - string m_sDelayedScreeenshot;//!< to delay a screenshot call for a frame 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 +734,6 @@ private: // ------------------------------------------------------ // XML Utils interface. class CXmlUtils* m_pXMLUtils; - Serialization::IArchiveHost* m_pArchiveHost; - int m_iApplicationInstance; //! to hold the values stored in system.cfg @@ -917,7 +782,6 @@ private: // ------------------------------------------------------ ICVar* m_rFullscreen; ICVar* m_rFullscreenWindow; ICVar* m_rFullscreenNativeRes; - ICVar* m_rDriver; ICVar* m_rDisplayInfo; ICVar* m_rOverscanBordersDrawDebugView; ICVar* m_sysNoUpdate; @@ -935,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) @@ -959,26 +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) - - WIN_HWND m_hWnd; - WIN_HINSTANCE m_hInst; - - // this is the memory statistics that is retained in memory between frames - // in which it's not gathered - class CrySizerStats* m_pMemStats; - class CrySizerImpl* m_pSizer; - - ICryPerfHUD* m_pPerfHUD; - minigui::IMiniGUI* m_pMiniGUI; - - //int m_nCurrentLogVerbosity; - SFileVersion m_fileVersion; SFileVersion m_productVersion; SFileVersion m_buildVersion; @@ -989,8 +831,6 @@ private: // ------------------------------------------------------ // Name table. CNameTable m_nameTable; - IThreadTask* m_PhysThread; - ESystemConfigSpec m_nServerConfigSpec; ESystemConfigSpec m_nMaxConfigSpec; ESystemConfigPlatform m_ConfigPlatform; @@ -998,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; @@ -1070,35 +908,20 @@ 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; - CVisRegTest* m_pVisRegTest; - 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 std::vector< std::pair > m_updateTimes; - CMemoryFragmentationProfiler m_MemoryFragmentationProfiler; - struct SErrorMessage { string m_Message; diff --git a/Code/CryEngine/CrySystem/SystemInit.cpp b/Code/CryEngine/CrySystem/SystemInit.cpp index 22445ec4a5..48cb5e0d9e 100644 --- a/Code/CryEngine/CrySystem/SystemInit.cpp +++ b/Code/CryEngine/CrySystem/SystemInit.cpp @@ -35,19 +35,13 @@ #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 -#include -#include #include // for AZ_MAX_PATH_LEN #include #include @@ -95,7 +89,6 @@ #include #include #include -#include "HMDCVars.h" #include #include @@ -106,26 +99,16 @@ #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 "VisRegTest.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 "OverloadSceneManager/OverloadSceneManager.h" -#include "ServiceNetwork.h" -#include "RemoteCommand.h" #include "LevelSystem/LevelSystem.h" #include "LevelSystem/SpawnableLevelSystem.h" #include "ViewSystem/ViewSystem.h" @@ -134,9 +117,6 @@ #include #include -#include "PerfHUD.h" -#include "MiniGUI/MiniGUI.h" - #if USE_STEAM #include "Steamworks/public/steam/steam_api.h" #include "Steamworks/public/steam/isteamremotestorage.h" @@ -158,8 +138,6 @@ #include "MobileDetectSpec.h" #endif -#include "IDebugCallStack.h" - #include "WindowsConsole.h" #if defined(EXTERNAL_CRASH_REPORTING) @@ -175,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 @@ -412,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; } @@ -740,28 +707,6 @@ static void LoadDetectedSpec(ICVar* pVar) GetISystem()->LoadConfiguration("editor.cfg"); } - bool bMultiGPUEnabled = false; - if (gEnv->pRenderer) - { - gEnv->pRenderer->EF_Query(EFQ_MultiGPUEnabled, bMultiGPUEnabled); - -#if defined(AZ_PLATFORM_ANDROID) - AZStd::string gpuConfigFile; - const AZStd::string& adapterDesc = gEnv->pRenderer->GetAdapterDescription(); - const AZStd::string& apiver = gEnv->pRenderer->GetApiVersion(); - - if (!adapterDesc.empty()) - { - MobileSysInspect::GetSpecForGPUAndAPI(adapterDesc, apiver, gpuConfigFile); - GetISystem()->LoadConfiguration(gpuConfigFile.c_str(), pSysSpecOverrideSinkConsole); - } -#endif - } - if (bMultiGPUEnabled) - { - GetISystem()->LoadConfiguration("mgpu.cfg"); - } - // override cvars just loaded based on current API version/GPU GetISystem()->SetConfigSpec(static_cast(spec), platform, false); @@ -884,148 +829,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() { @@ -1204,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(); @@ -1279,12 +1081,11 @@ void CSystem::ShutdownFileSystem() } ///////////////////////////////////////////////////////////////////////////////// -bool CSystem::InitFileSystem_LoadEngineFolders(const SSystemInitParams& initParams) +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()); } @@ -1294,13 +1095,6 @@ bool CSystem::InitFileSystem_LoadEngineFolders(const SSystemInitParams& initPara 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()); @@ -1320,10 +1114,6 @@ bool CSystem::InitFileSystem_LoadEngineFolders(const SSystemInitParams& initPara static const char* g_additionalConfig = gEnv->IsDedicated() ? "server_cfg" : "client_cfg"; LoadConfiguration(g_additionalConfig, nullptr, false); - if (initParams.bShaderCacheGen) - { - LoadConfiguration("shadercachegen.cfg"); - } // We do not use CVar groups on the consoles AddCVarGroupDirectory("Config/CVarGroups"); @@ -1359,8 +1149,6 @@ bool CSystem::InitAudioSystem(const SSystemInitParams& initParams) bool useRealAudioSystem = false; if (!initParams.bPreview - && !initParams.bShaderCacheGen - && !initParams.bMinimal && !m_bDedicatedServer && m_sys_audio_disable->GetIVal() == 0) { @@ -1853,13 +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_bShaderCacheGenMode = startupParams.bShaderCacheGen; + m_env.bNoAssertDialog = false; m_bNoCrashDialog = gEnv->IsDedicated(); @@ -1906,12 +1689,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 { @@ -1938,23 +1715,14 @@ AZ_POP_DISABLE_WARNING QueryVersionInfo(); DetectGameFolderAccessRights(); - m_hInst = (WIN_HINSTANCE)startupParams.hInstance; - m_hWnd = (WIN_HWND)startupParams.hWnd; - m_bEditor = startupParams.bEditor; 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); @@ -1962,7 +1730,6 @@ AZ_POP_DISABLE_WARNING #endif m_env.SetToolMode(startupParams.bToolMode); - m_env.bIsOutOfMemory = false; if (m_bEditor) { @@ -2126,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) @@ -2158,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 ////////////////////////////////////////////////////////////////////////// @@ -2226,11 +1960,6 @@ AZ_POP_DISABLE_WARNING InlineInitializationProcessing("CSystem::Init Create console"); - if (!startupParams.bSkipRenderer) - { - CreateRendererVars(startupParams); - } - // Need to load the engine.pak that includes the config files needed during initialization m_env.pCryPak->OpenPack("@assets@", "Engine.pak"); #if defined(AZ_PLATFORM_ANDROID) || defined(AZ_PLATFORM_IOS) @@ -2247,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)) @@ -2298,28 +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); - - if (!startupParams.bSkipRenderer) - { - // Load the hmd.cfg if it exists. This will enable optional stereo rendering. - LoadConfiguration("hmd.cfg"); - } - - if (startupParams.bShaderCacheGen) - { - LoadConfiguration("shadercachegen.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 } @@ -2365,32 +2079,8 @@ AZ_POP_DISABLE_WARNING InlineInitializationProcessing("CSystem::Init LoadConfigurations"); - m_env.pOverloadSceneManager = new COverloadSceneManager; - - if (m_bDedicatedServer && m_rDriver) - { - m_sSavedRDriver = m_rDriver->GetString(); - m_rDriver->Set("NULL"); - } - -#if defined(WIN32) || defined(WIN64) - if (!startupParams.bSkipRenderer) - { - if (azstricmp(m_rDriver->GetString(), "Auto") == 0) - { - m_rDriver->Set("DX11"); - } - } - - if (gEnv->IsEditor() && azstricmp(m_rDriver->GetString(), "DX12") == 0) - { - AZ_Warning(AZ_TRACE_SYSTEM_WINDOW, false, "DX12 mode is not supported in the editor. Reverting to DX11 mode."); - m_rDriver->Set("DX11"); - } -#endif - #ifdef WIN32 - if ((g_cvars.sys_WER) && (!startupParams.bMinimal)) + if ((g_cvars.sys_WER)) { SetUnhandledExceptionFilter(CryEngineExceptionFilterWER); } @@ -2400,7 +2090,6 @@ AZ_POP_DISABLE_WARNING ////////////////////////////////////////////////////////////////////////// // Localization ////////////////////////////////////////////////////////////////////////// - if (!startupParams.bMinimal) { InitLocalization(); } @@ -2410,72 +2099,6 @@ AZ_POP_DISABLE_WARNING m_thermalInfoHandler = AZStd::make_unique(); #endif - if (g_cvars.sys_rendersplashscreen && !startupParams.bEditor && !startupParams.bShaderCacheGen) - { - if (m_env.pRenderer) - { - LOADING_TIME_PROFILE_SECTION_NAMED("Rendering Splash Screen"); - ITexture* pTex = m_env.pRenderer->EF_LoadTexture(g_cvars.sys_splashscreen, FT_DONT_STREAM | FT_NOMIPS | FT_USAGE_ALLOWREADSRGB); - //check the width and height as extra verification hack. This texture is loaded before the replace me, so there is - //no backup if it fails to load. - if (pTex && pTex->GetWidth() && pTex->GetHeight()) - { - const int splashWidth = pTex->GetWidth(); - const int splashHeight = pTex->GetHeight(); - - const int screenWidth = m_env.pRenderer->GetOverlayWidth(); - const int screenHeight = m_env.pRenderer->GetOverlayHeight(); - - const float scaleX = (float)screenWidth / (float)splashWidth; - const float scaleY = (float)screenHeight / (float)splashHeight; - - float scale = 1.0f; - switch (g_cvars.sys_splashScreenScaleMode) - { - case SSystemCVars::SplashScreenScaleMode_Fit: - { - scale = AZStd::GetMin(scaleX, scaleY); - } - break; - case SSystemCVars::SplashScreenScaleMode_Fill: - { - scale = AZStd::GetMax(scaleX, scaleY); - } - break; - } - - const float w = splashWidth * scale; - const float h = splashHeight * scale; - const float x = (screenWidth - w) * 0.5f; - const float y = (screenHeight - h) * 0.5f; - - const float vx = (800.0f / (float) screenWidth); - const float vy = (600.0f / (float) screenHeight); - - m_env.pRenderer->SetViewport(0, 0, screenWidth, screenHeight); - -#if defined(AZ_PLATFORM_IOS) || defined(AZ_PLATFORM_MAC) - // Pump system events in order to update the screen - AzFramework::ApplicationRequests::Bus::Broadcast(&AzFramework::ApplicationRequests::PumpSystemEventLoopUntilEmpty); -#endif - - pTex->Release(); - } - - #if defined(AZ_PLATFORM_ANDROID) - bool engineSplashEnabled = (g_cvars.sys_rendersplashscreen != 0); - if (engineSplashEnabled) - { - AZ::Android::Utils::DismissSplashScreen(); - } - #endif - } - else - { - AZ_Warning(AZ_TRACE_SYSTEM_WINDOW, false, "Could not load startscreen image: %s.", g_cvars.sys_splashscreen); - } - } - ////////////////////////////////////////////////////////////////////////// // Open basic pak files after intro movie playback started ////////////////////////////////////////////////////////////////////////// @@ -2484,7 +2107,6 @@ AZ_POP_DISABLE_WARNING ////////////////////////////////////////////////////////////////////////// // AUDIO ////////////////////////////////////////////////////////////////////////// - if (!startupParams.bMinimal) { if (InitAudioSystem(startupParams)) { @@ -2507,27 +2129,6 @@ AZ_POP_DISABLE_WARNING m_pUserCallback->OnInitProgress("First time asset processing - may take a minute..."); } - ////////////////////////////////////////////////////////////////////////// - // POST RENDERER - ////////////////////////////////////////////////////////////////////////// - if (!startupParams.bSkipRenderer && m_env.pRenderer) - { - m_env.pRenderer->PostInit(); - - if (!startupParams.bShaderCacheGen) - { - // try to do a flush to keep the renderer busy during loading - m_env.pRenderer->TryFlush(); - } - } - InlineInitializationProcessing("CSystem::Init Renderer::PostInit"); - -#ifdef SOFTCODE_SYSTEM_ENABLED - m_env.pSoftCodeMgr = new SoftCodeMgr(); -#else - m_env.pSoftCodeMgr = nullptr; -#endif - ////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////// // System cursor @@ -2537,10 +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() && - m_env.pRenderer && - !gEnv->IsEditor() && - !startupParams.bTesting && - !m_pCmdLine->FindArg(eCLAT_Pre, "nomouse")) + !gEnv->IsEditor()) { AzFramework::InputSystemCursorRequestBus::Event(AzFramework::InputDeviceMouse::Id, &AzFramework::InputSystemCursorRequests::SetSystemCursorState, @@ -2561,7 +2159,7 @@ AZ_POP_DISABLE_WARNING ////////////////////////////////////////////////////////////////////////// // UI. Should be after input and hardware mouse ////////////////////////////////////////////////////////////////////////// - if (!startupParams.bShaderCacheGen && !m_bDedicatedServer) + if (!m_bDedicatedServer) { AZ_Printf(AZ_TRACE_SYSTEM_WINDOW, "UI system initialization"); INDENT_LOG_DURING_SCOPE(); @@ -2572,23 +2170,6 @@ AZ_POP_DISABLE_WARNING } InlineInitializationProcessing("CSystem::Init InitShine"); - - ////////////////////////////////////////////////////////////////////////// - // Create MiniGUI - ////////////////////////////////////////////////////////////////////////// - if (!startupParams.bMinimal) - { - minigui::IMiniGUIPtr pMiniGUI; - if (CryCreateClassInstanceForInterface(cryiidof(), pMiniGUI)) - { - m_pMiniGUI = pMiniGUI.get(); - m_pMiniGUI->Init(); - } - } - - InlineInitializationProcessing("CSystem::Init InitMiniGUI"); - - ////////////////////////////////////////////////////////////////////////// // CONSOLE ////////////////////////////////////////////////////////////////////////// if (!InitConsole()) @@ -2596,78 +2177,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(); - } - - ////////////////////////////////////////////////////////////////////////// - - ////////////////////////////////////////////////////////////////////////// - // VR SYSTEM INITIALIZATION - ////////////////////////////////////////////////////////////////////////// - if ((!startupParams.bSkipRenderer) && (!startupParams.bMinimal)) - { - if (m_pUserCallback) - { - m_pUserCallback->OnInitProgress("Initializing VR Systems..."); - } - - AZStd::vector devices; - AZ::VR::HMDInitRequestBus::EnumerateHandlers([&devices](AZ::VR::HMDInitBus* device) - { - devices.emplace_back(device); - return true; - }); - - // Order the devices so that devices that only support one type of HMD are ordered first as we want - // to use any device-specific drivers over more general ones. - std::sort(devices.begin(), devices.end(), [](AZ::VR::HMDInitBus* left, AZ::VR::HMDInitBus* right) - { - return left->GetInitPriority() > right->GetInitPriority(); - }); - - //Start up a job to init the HMDs since they may take a while to start up - AZ::JobContext* jobContext = nullptr; - EBUS_EVENT_RESULT(jobContext, AZ::JobManagerBus, GetGlobalContext); - AZ::Job* hmdJob = AZ::CreateJobFunction([devices]() - { - // Loop through the attached devices and attempt to initialize them. We'll use the first - // one that succeeds since we currently only support a single HMD. - for (AZ::VR::HMDInitBus* device : devices) - { - if (device->AttemptInit()) - { - // At this point if any device connected to the HMDDeviceRequestBus then we are good to go for VR. - EBUS_EVENT(AZ::VR::HMDDeviceRequestBus, OutputHMDInfo); - EBUS_EVENT(AZ::VR::HMDDeviceRequestBus, EnableDebugging, false); - - // Since this was a job and we may have beaten the level's output_to_hmd cvar initialization - // We just want to retrigger the callback to this cvar - ICVar* outputToHMD = gEnv->pConsole->GetCVar("output_to_hmd"); - if (outputToHMD != nullptr) - { - int outputToHMDVal = gEnv->pConsole->GetCVar("output_to_hmd")->GetIVal(); - gEnv->pConsole->GetCVar("output_to_hmd")->Set(outputToHMDVal); - } - break; - } - } - }, true, jobContext); - hmdJob->Start(); - } - if (m_pUserCallback) { m_pUserCallback->OnInitProgress("Initializing additional systems..."); @@ -2724,45 +2233,6 @@ AZ_POP_DISABLE_WARNING m_pIZStdDecompressor = new CZStdDecompressor(); InlineInitializationProcessing("CSystem::Init ZStdDecompressor"); - ////////////////////////////////////////////////////////////////////////// - // Create PerfHUD - ////////////////////////////////////////////////////////////////////////// - -#if defined(USE_PERFHUD) - if (!gEnv->bTesting && !gEnv->IsInToolMode()) - { - //Create late in Init so that associated CVars have already been created - ICryPerfHUDPtr pPerfHUD; - if (CryCreateClassInstanceForInterface(cryiidof(), pPerfHUD)) - { - m_pPerfHUD = pPerfHUD.get(); - m_pPerfHUD->Init(); - } - } -#endif - - - ////////////////////////////////////////////////////////////////////////// - // Initialize task threads. - ////////////////////////////////////////////////////////////////////////// - if (!startupParams.bSkipRenderer) - { - 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) { @@ -2775,12 +2245,6 @@ AZ_POP_DISABLE_WARNING AZ::Interface::Get()->VisitRegisteredFunctors([](AZ::ConsoleFunctorBase* functor) { AzConsoleToCryConsoleBinder::Visit(functor); }); AzConsoleToCryConsoleBinder::s_commandRegisteredHandler.Connect(AZ::Interface::Get()->GetConsoleCommandRegisteredEvent()); - // final tryflush to be sure that all framework init request have been processed - if (!startupParams.bShaderCacheGen && m_env.pRenderer) - { - m_env.pRenderer->TryFlush(); - } - if (g_cvars.sys_float_exceptions > 0) { if (g_cvars.sys_float_exceptions == 3 && gEnv->IsEditor()) // Turn off float exceptions in editor if sys_float_exceptions = 3 @@ -2793,8 +2257,6 @@ AZ_POP_DISABLE_WARNING } } EnableFloatExceptions(g_cvars.sys_float_exceptions); - - MarkThisThreadForDebugging("Main"); } InlineInitializationProcessing("CSystem::Init End"); @@ -2849,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)); } @@ -2874,99 +2335,6 @@ static string ConcatPath(const char* szPart1, const char* szPart2) return ret; } -static void ScreenshotCmd(IConsoleCmdArgs* pParams) -{ - assert(pParams); - - uint32 dwCnt = pParams->GetArgCount(); - - if (dwCnt <= 1) - { - if (!gEnv->IsEditing()) - { - // open console one line only - - //line should lie within title safe area, so calculate overscan border - Vec2 overscanBorders = Vec2(0.0f, 0.0f); - gEnv->pRenderer->EF_Query(EFQ_OverscanBorders, overscanBorders); - float yDelta = /*((float)gEnv->pRenderer->GetHeight())*/ 600.0f * overscanBorders.y; - - //set console height depending on top/bottom overscan border - gEnv->pConsole->ShowConsole(true, (int)(16 + yDelta)); - gEnv->pConsole->SetInputLine("Screenshot "); - } - else - { - gEnv->pLog->LogWithType(ILog::eInputResponse, "Screenshot missing - no screenshot was done"); - } - } - else - { - static int iScreenshotNumber = -1; - - const char* szPrefix = "Screenshot"; - uint32 dwPrefixSize = strlen(szPrefix); - - char path[AZ::IO::IArchive::MaxPath]; - path[sizeof(path) - 1] = 0; - gEnv->pCryPak->AdjustFileName("@user@/ScreenShots", path, AZ_ARRAY_SIZE(path), AZ::IO::IArchive::FLAGS_PATH_REAL | AZ::IO::IArchive::FLAGS_FOR_WRITING); - - if (iScreenshotNumber == -1) // first time - find max number to start - { - auto pCryPak = gEnv->pCryPak; - - AZ::IO::ArchiveFileIterator handle = pCryPak->FindFirst((string(path) + "/*").c_str()); // mastercd folder - if (handle) - { - do - { - int iCurScreenshotNumber; - - if (_strnicmp(handle.m_filename.data(), szPrefix, dwPrefixSize) == 0) - { - int iCnt = azsscanf(handle.m_filename.data() + dwPrefixSize, "%d", &iCurScreenshotNumber); - - if (iCnt) - { - iScreenshotNumber = max(iCurScreenshotNumber, iScreenshotNumber); - } - } - - handle = pCryPak->FindNext(handle); - } while (handle); - pCryPak->FindClose(handle); - } - } - - ++iScreenshotNumber; - - char szNumber[16]; - azsprintf(szNumber, "%.4d ", iScreenshotNumber); - - string sScreenshotName = string(szPrefix) + szNumber; - - for (uint32 dwI = 1; dwI < dwCnt; ++dwI) - { - if (dwI > 1) - { - sScreenshotName += "_"; - } - - sScreenshotName += pParams->GetArg(dwI); - } - - sScreenshotName.replace("\\", "_"); - sScreenshotName.replace("/", "_"); - sScreenshotName.replace(":", "_"); - sScreenshotName.replace(".", "_"); - - gEnv->pConsole->ShowConsole(false); - - CSystem* pCSystem = (CSystem*)(gEnv->pSystem); - pCSystem->GetDelayedScreeenshot() = string(path) + "/" + sScreenshotName;// to delay a screenshot call for a frame - } -} - // Helper to maintain backwards compatibility with our CVar but not force our new code to // pull in CryCommon by routing through an environment variable void CmdSetAwsLogLevel(IConsoleCmdArgs* pArgs) @@ -3168,32 +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(); - } -} - -static void VisRegTest(IConsoleCmdArgs* pParams) -{ - CSystem* pCSystem = (CSystem*)(gEnv->pSystem); - CVisRegTest*& visRegTest = pCSystem->GetVisRegTestPtrRef(); - if (!visRegTest) - { - visRegTest = new CVisRegTest(); - } - - visRegTest->Init(pParams); -} - ////////////////////////////////////////////////////////////////////////// void CSystem::CreateSystemVars() { @@ -3251,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" @@ -3278,28 +2617,10 @@ void CSystem::CreateSystemVars() attachVariable("sys_PakLogAllFileAccess", &g_cvars.archiveVars.nLogAllFileAccess, "Log all file access allowing you to easily see whether a file has been loaded directly, or which pak file."); #endif attachVariable("sys_PakValidateFileHash", &g_cvars.archiveVars.nValidateFileHashes, "Validate file hashes in pak files for collisions"); - attachVariable("sys_LoadFrontendShaderCache", &g_cvars.archiveVars.nLoadFrontendShaderCache, "Load frontend shader cache (on/off)"); attachVariable("sys_UncachedStreamReads", &g_cvars.archiveVars.nUncachedStreamReads, "Enable stream reads via an uncached file handle"); attachVariable("sys_PakDisableNonLevelRelatedPaks", &g_cvars.archiveVars.nDisableNonLevelRelatedPaks, "Disables all paks that are not required by specific level; This is used with per level splitted assets."); attachVariable("sys_PakWarnOnPakAccessFailures", &g_cvars.archiveVars.nWarnOnPakAccessFails, "If 1, access failure for Paks is treated as a warning, if zero it is only a log message."); - - { - int nDefaultRenderSplashScreen = 1; -#if defined(AZ_RESTRICTED_PLATFORM) -#define AZ_RESTRICTED_SECTION SYSTEMINIT_CPP_SECTION_10 -#include AZ_RESTRICTED_FILE(SystemInit_cpp) -#endif - REGISTER_CVAR2("sys_rendersplashscreen", &g_cvars.sys_rendersplashscreen, nDefaultRenderSplashScreen, VF_NULL, - "Render the splash screen during game initialization"); - REGISTER_CVAR2("sys_splashscreenscalemode", &g_cvars.sys_splashScreenScaleMode, static_cast(SSystemCVars::SplashScreenScaleMode_Fill), VF_NULL, - "0 - scale to fit (letterbox)\n" - "1 - scale to fill (cropped)\n" - "Default is 1"); - REGISTER_CVAR2("sys_splashscreen", &g_cvars.sys_splashscreen, "EngineAssets/Textures/startscreen.tif", VF_NULL, - "The splash screen to render during game initialization"); - } - static const int fileSystemCaseSensitivityDefault = 0; REGISTER_CVAR2("sys_FilesystemCaseSensitivity", &g_cvars.sys_FilesystemCaseSensitivity, fileSystemCaseSensitivityDefault, VF_NULL, "0 - CryPak lowercases all input file names\n" @@ -3410,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) @@ -3452,10 +2763,6 @@ void CSystem::CreateSystemVars() REGISTER_CVAR2("sys_streaming_max_finalize_per_frame", &g_cvars.sys_streaming_max_finalize_per_frame, 0, VF_NULL, "Maximum stream finalizing calls per frame to reduce the CPU impact on main thread (0 to disable)"); REGISTER_CVAR2("sys_streaming_max_bandwidth", &g_cvars.sys_streaming_max_bandwidth, 0, VF_NULL, "Enables capping of max streaming bandwidth in MB/s"); - REGISTER_CVAR2("az_streaming_stats", &g_cvars.az_streaming_stats, 0, VF_NULL, "Show stats from AZ::IO::Streamer\n" - "0=off\n" - "1=on\n" - ); REGISTER_CVAR2("sys_streaming_debug", &g_cvars.sys_streaming_debug, 0, VF_NULL, "Enable streaming debug information\n" "0=off\n" "1=Streaming Stats\n" @@ -3580,12 +2887,6 @@ void CSystem::CreateSystemVars() m_env.pConsole->CreateKeyBind("alt_keyboard_key_function_F12", "Screenshot"); m_env.pConsole->CreateKeyBind("alt_keyboard_key_function_F11", "RecordClip"); - // screenshot functionality in system as console - REGISTER_COMMAND("Screenshot", &ScreenshotCmd, VF_BLOCKFRAME, - "Create a screenshot with annotation\n" - "e.g. Screenshot beach scene with shark\n" - "Usage: Screenshot "); - /* // experimental feature? - needs to be created very early m_sys_filecache = REGISTER_INT("sys_FileCache",0,0, @@ -3593,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"); @@ -3606,9 +2906,6 @@ void CSystem::CreateSystemVars() "'test*' and 'info' log to the log file only\n" "Usage: sys_RestoreSpec [test|test*|apply|info]"); - REGISTER_COMMAND("VisRegTest", &VisRegTest, 0, "Run visual regression test.\n" - "Usage: VisRegTest [=test] [=visregtest.xml] [quit=false]"); - #if defined(WIN32) REGISTER_CVAR2("sys_display_threads", &g_cvars.sys_display_threads, 0, 0, "Displays Thread info"); #elif defined(AZ_RESTRICTED_PLATFORM) @@ -3629,15 +2926,8 @@ void CSystem::CreateSystemVars() REGISTER_CVAR2("sys_error_debugbreak", &g_cvars.sys_error_debugbreak, 0, VF_CHEAT, "__debugbreak() if a VALIDATOR_ERROR_DBGBREAK message is hit"); - // [VR] - AZ::VR::HMDCVars::Register(); - 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 @@ -3694,11 +2984,6 @@ void CSystem::AddCVarGroupDirectory(const string& sPath) string sCVarName = sFilePath; PathUtil::RemoveExtension(sCVarName); - - if (m_env.pConsole != 0) - { - ((CXConsole*)m_env.pConsole)->RegisterCVarGroup(PathUtil::GetFile(sCVarName), sFilePath); - } } } while (handle = gEnv->pCryPak->FindNext(handle)); diff --git a/Code/CryEngine/CrySystem/SystemRender.cpp b/Code/CryEngine/CrySystem/SystemRender.cpp index 68045a86ea..b608ef5335 100644 --- a/Code/CryEngine/CrySystem/SystemRender.cpp +++ b/Code/CryEngine/CrySystem/SystemRender.cpp @@ -35,17 +35,10 @@ #include "PhysRenderer.h" #include -#include "CrySizerStats.h" -#include "CrySizerImpl.h" -#include "VisRegTest.h" #include "ITextModeConsole.h" #include #include -#include "MiniGUI/MiniGUI.h" -#include "PerfHUD.h" -#include "ThreadInfo.h" - #include #if defined(AZ_RESTRICTED_PLATFORM) @@ -61,17 +54,6 @@ extern CMTSafeHeap* g_pPakHeap; extern int CryMemoryGetAllocatedSize(); -///////////////////////////////////////////////////////////////////////////////// -static void VerifySizeRenderVar(ICVar* pVar) -{ - const int size = pVar->GetIVal(); - if (size <= 0) - { - AZ_Error("Console Variable", false, "'%s' set to invalid value: %i. Setting to nearest safe value: 1.", pVar->GetName(), size); - pVar->Set(1); - } -} - ///////////////////////////////////////////////////////////////////////////////// bool CSystem::GetPrimaryPhysicalDisplayDimensions([[maybe_unused]] int& o_widthPixels, [[maybe_unused]] int& o_heightPixels) { @@ -97,130 +79,6 @@ bool CSystem::IsTablet() #endif } -///////////////////////////////////////////////////////////////////////////////// -void CSystem::CreateRendererVars(const SSystemInitParams& startupParams) -{ - int iFullScreenDefault = 1; - int iDisplayInfoDefault = 0; - int iWidthDefault = 1280; - int iHeightDefault = 720; -#if defined(AZ_PLATFORM_ANDROID) || defined(AZ_PLATFORM_IOS) - GetPrimaryPhysicalDisplayDimensions(iWidthDefault, iHeightDefault); -#elif defined(WIN32) || defined(WIN64) - iFullScreenDefault = 0; - iWidthDefault = GetSystemMetrics(SM_CXFULLSCREEN) * 2 / 3; - iHeightDefault = GetSystemMetrics(SM_CYFULLSCREEN) * 2 / 3; -#endif - - if (IsDevMode()) - { - iFullScreenDefault = 0; - iDisplayInfoDefault = 1; - } - - // load renderer settings from engine.ini - m_rWidth = REGISTER_INT_CB("r_Width", iWidthDefault, VF_DUMPTODISK, - "Sets the display width, in pixels. Default is 1280.\n" - "Usage: r_Width [800/1024/..]", VerifySizeRenderVar); - m_rHeight = REGISTER_INT_CB("r_Height", iHeightDefault, VF_DUMPTODISK, - "Sets the display height, in pixels. Default is 720.\n" - "Usage: r_Height [600/768/..]", VerifySizeRenderVar); - m_rWidthAndHeightAsFractionOfScreenSize = REGISTER_FLOAT("r_WidthAndHeightAsFractionOfScreenSize", 1.0f, VF_DUMPTODISK, - "(iOS/Android only) Sets the display width and height as a fraction of the physical screen size. Default is 1.0.\n" - "Usage: rWidthAndHeightAsFractionOfScreenSize [0.1 - 1.0]"); - m_rTabletWidthAndHeightAsFractionOfScreenSize = REGISTER_FLOAT("r_TabletWidthAndHeightAsFractionOfScreenSize", 1.0f, VF_DUMPTODISK, - "(iOS only) NOTE: TABLETS ONLY Sets the display width and height as a fraction of the physical screen size. Default is 1.0.\n" - "Usage: rTabletWidthAndHeightAsFractionOfScreenSize [0.1 - 1.0]"); - m_rMaxWidth = REGISTER_INT("r_MaxWidth", 0, VF_DUMPTODISK, - "(iOS/Android only) Sets the maximum display width while maintaining the device aspect ratio.\n" - "Usage: r_MaxWidth [1024/1920/..] (0 for no max), combined with r_WidthAndHeightAsFractionOfScreenSize [0.1 - 1.0]"); - m_rMaxHeight = REGISTER_INT("r_MaxHeight", 0, VF_DUMPTODISK, - "(iOS/Android only) Sets the maximum display height while maintaining the device aspect ratio.\n" - "Usage: r_MaxHeight [768/1080/..] (0 for no max), combined with r_WidthAndHeightAsFractionOfScreenSize [0.1 - 1.0]"); - m_rColorBits = REGISTER_INT("r_ColorBits", 32, VF_DUMPTODISK, - "Sets the color resolution, in bits per pixel. Default is 32.\n" - "Usage: r_ColorBits [32/24/16/8]"); - m_rDepthBits = REGISTER_INT("r_DepthBits", 24, VF_DUMPTODISK | VF_REQUIRE_APP_RESTART, - "Sets the depth precision, in bits per pixel. Default is 24.\n" - "Usage: r_DepthBits [32/24]"); - m_rStencilBits = REGISTER_INT("r_StencilBits", 8, VF_DUMPTODISK, - "Sets the stencil precision, in bits per pixel. Default is 8.\n"); - - // Needs to be initialized as soon as possible due to swap chain creation modifications.. - m_rHDRDolby = REGISTER_INT_CB("r_HDRDolby", 0, VF_DUMPTODISK, - "HDR dolby output mode\n" - "Usage: r_HDRDolby [Value]\n" - "0: Off (default)\n" - "1: Dolby maui output\n" - "2: Dolby vision output\n", - [] (ICVar* cvar) - { - eDolbyVisionMode mode = static_cast(cvar->GetIVal()); - - if (mode == eDVM_Vision && gEnv->IsEditor()) - { - cvar->Set(static_cast(eDVM_Disabled)); - } - }); - // Restrict the limits of this cvar to the eDolbyVisionMode values - m_rHDRDolby->SetLimits(static_cast(eDVM_Disabled), static_cast(eDVM_Vision)); - -#if defined(WIN32) || defined(WIN64) - REGISTER_INT("r_overrideDXGIAdapter", -1, VF_REQUIRE_APP_RESTART, - "Specifies index of the preferred video adapter to be used for rendering (-1=off, loops until first suitable adapter is found).\n" - "Use this to resolve which video card to use if more than one DX11 capable GPU is available in the system."); -#endif - -#if defined(WIN32) || defined(WIN64) - const char* p_r_DriverDef = "Auto"; -#elif defined(APPLE) - const char* p_r_DriverDef = "METAL"; -#elif defined(ANDROID) - const char* p_r_DriverDef = "GL"; -#elif defined(LINUX) - const char* p_r_DriverDef = "GL"; - if (gEnv->IsDedicated()) - { - p_r_DriverDef = "NULL"; - } -#elif defined(AZ_RESTRICTED_PLATFORM) -#define AZ_RESTRICTED_SECTION SYSTEMRENDERER_CPP_SECTION_1 -#include AZ_RESTRICTED_FILE(SystemRender_cpp) -#else - const char* p_r_DriverDef = "DX9"; // required to be deactivated for final release -#endif - if (startupParams.pCvarsDefault) - { // hack to customize the default value of r_Driver - SCvarsDefault* pCvarsDefault = startupParams.pCvarsDefault; - if (pCvarsDefault->sz_r_DriverDef && pCvarsDefault->sz_r_DriverDef[0]) - { - p_r_DriverDef = startupParams.pCvarsDefault->sz_r_DriverDef; - } - } - - m_rDriver = REGISTER_STRING("r_Driver", p_r_DriverDef, VF_DUMPTODISK | VF_INVISIBLE, - "Sets the renderer driver ( DX11/AUTO/NULL ).\n" - "Specify in bootstrap.cfg like this: r_Driver = \"DX11\""); - - m_rFullscreen = REGISTER_INT("r_Fullscreen", iFullScreenDefault, VF_DUMPTODISK, - "Toggles fullscreen mode. Default is 1 in normal game and 0 in DevMode.\n" - "Usage: r_Fullscreen [0=window/1=fullscreen]"); - - m_rFullscreenWindow = REGISTER_INT("r_FullscreenWindow", 0, VF_DUMPTODISK, - "Toggles fullscreen-as-window mode. Fills screen but allows seamless switching. Default is 0.\n" - "Usage: r_FullscreenWindow [0=locked fullscreen/1=fullscreen as window]"); - - m_rFullscreenNativeRes = REGISTER_INT("r_FullscreenNativeRes", 0, VF_DUMPTODISK, ""); - - m_rDisplayInfo = REGISTER_INT("r_DisplayInfo", iDisplayInfoDefault, VF_RESTRICTEDMODE | VF_DUMPTODISK, - "Toggles debugging information display.\n" - "Usage: r_DisplayInfo [0=off/1=show/2=enhanced/3=compact]"); - - m_rOverscanBordersDrawDebugView = REGISTER_INT("r_OverscanBordersDrawDebugView", 0, VF_RESTRICTEDMODE | VF_DUMPTODISK, - "Toggles drawing overscan borders.\n" - "Usage: r_OverscanBordersDrawDebugView [0=off/1=show]"); -} - void CSystem::OnScene3DEnd() { //Render Console @@ -230,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 b47519eb03..72c43bceed 100644 --- a/Code/CryEngine/CrySystem/SystemWin32.cpp +++ b/Code/CryEngine/CrySystem/SystemWin32.cpp @@ -46,15 +46,11 @@ #include #endif -#include "IDebugCallStack.h" - #if defined(APPLE) || defined(LINUX) #include #endif #include "XConsole.h" -#include "CrySizerStats.h" -#include "CrySizerImpl.h" #include "StreamEngine/StreamEngine.h" #include "LocalizedStringManager.h" #include "XML/XmlUtils.h" @@ -69,51 +65,6 @@ __pragma(comment(lib, "Winmm.lib")) #include #endif - - -static AZStd::vector GetModuleNames() -{ - AZStd::vector moduleNames; - if (moduleNames.empty()) - { -# ifdef MODULE_EXTENSION -# error MODULE_EXTENSION already defined! -# endif -# if defined(LINUX) -# define MODULE_EXTENSION ".so" -# elif defined(APPLE) -# define MODULE_EXTENSION ".dylib" -# else -# define MODULE_EXTENSION ".dll" -# endif - - moduleNames.push_back("Cry3DEngine" MODULE_EXTENSION); - moduleNames.push_back("CryFont" MODULE_EXTENSION); - moduleNames.push_back("CrySystem" MODULE_EXTENSION); - -#undef MODULE_EXTENSION - -# if defined(LINUX) - moduleNames.push_back("CryRenderNULL.so"); -# elif defined(APPLE) - moduleNames.push_back("CryRenderNULL.dylib"); -# else - moduleNames.push_back("Editor.exe"); - moduleNames.push_back("CryRenderD3D9.dll"); - moduleNames.push_back("CryRenderD3D10.dll"); - moduleNames.push_back("CryRenderNULL.dll"); - //TODO: launcher? -# endif - } - - return moduleNames; -} - -static bool QueryModuleMemoryInfo([[maybe_unused]] SCryEngineStatsModuleInfo& moduleInfo, [[maybe_unused]] int index) -{ - return false; -} - // this is the list of modules that can be loaded into the game process // Each array element contains 2 strings: the name of the module (case-insensitive) // and the name of the group the module belongs to @@ -158,30 +109,6 @@ void CSystem::SetAffinity() #endif } - - - - -//! dumps the memory usage statistics to the log -////////////////////////////////////////////////////////////////////////// -void CSystem::DumpMemoryUsageStatistics(bool bUseKB) -{ - // CResourceCollector ResourceCollector; - - // TickMemStats(nMSP_ForDump,&ResourceCollector); - TickMemStats(nMSP_ForDump); - - CrySizerStatsRenderer StatsRenderer (this, m_pMemStats, 10, 0); - StatsRenderer.dump(bUseKB); - - // since we've recalculated this mem stats for dumping, we'll want to calculate it anew the next time it's rendered - SAFE_DELETE(m_pMemStats); -} - -// collects the whole memory statistics into the given sizer object -////////////////////////////////////////////////////////////////////////// - - #if defined(WIN32) #pragma pack(push,1) struct PEHeader_DLL @@ -207,162 +134,6 @@ const SmallModuleInfo* FindModuleInfo(std::vector& vec, const c return 0; } -////////////////////////////////////////////////////////////////////////// -void CSystem::CollectMemInfo(SCryEngineStatsGlobalMemInfo& m_stats) -{ - m_stats.totalUsedInModules = 0; - m_stats.totalCodeAndStatic = 0; - m_stats.countedMemoryModules = 0; - m_stats.totalAllocatedInModules = 0; - m_stats.totalNumAllocsInModules = 0; - - AZStd::vector szModules = GetModuleNames(); - const int numModules = szModules.size(); - - ////////////////////////////////////////////////////////////////////////// - // Hardcoded value for the OS memory allocation. - ////////////////////////////////////////////////////////////////////////// - for (int i = 0; i < numModules; i++) - { - const char* szModule = szModules[i].c_str(); - - SCryEngineStatsModuleInfo moduleInfo; - ZeroStruct(moduleInfo.memInfo); - moduleInfo.moduleStaticSize = moduleInfo.SizeOfCode = moduleInfo.SizeOfInitializedData = moduleInfo.SizeOfUninitializedData = moduleInfo.usedInModule = 0; - moduleInfo.name = szModule; - - if (!QueryModuleMemoryInfo(moduleInfo, i)) - { - continue; - } - - m_stats.totalNumAllocsInModules += moduleInfo.memInfo.num_allocations; - m_stats.totalAllocatedInModules += moduleInfo.memInfo.allocated; - m_stats.totalUsedInModules += moduleInfo.usedInModule; - m_stats.countedMemoryModules++; - m_stats.totalCodeAndStatic += moduleInfo.moduleStaticSize; - - m_stats.modules.push_back(moduleInfo); - } -} - - -void CSystem::CollectMemStats (ICrySizer* pSizer, MemStatsPurposeEnum nPurpose, std::vector* pStats) -{ - std::vector stats; - if (pStats) - { - pStats->assign(stats.begin(), stats.end()); - } - - if (nMSP_ForCrashLog == nPurpose || nMSP_ForBudget == nPurpose) - { - return; - } - - { - SIZER_COMPONENT_NAME(pSizer, "CrySystem"); - { - pSizer->AddObject(this, sizeof(*this)); - { - //SIZER_COMPONENT_NAME (pSizer, "$Allocations waste"); - //const SmallModuleInfo* info = FindModuleInfo(stats, "CrySystem.dll"); - //if (info) - //pSizer->AddObject(info, info->memInfo.allocated - info->memInfo.requested ); - } - - { - SIZER_COMPONENT_NAME(pSizer, "VFS"); - if (m_pStreamEngine) - { - SIZER_COMPONENT_NAME(pSizer, "Stream Engine"); - m_pStreamEngine->GetMemoryStatistics(pSizer); - } - } - { - SIZER_COMPONENT_NAME(pSizer, "Localization Data"); - m_pLocalizationManager->GetMemoryUsage(pSizer); - } - { - SIZER_COMPONENT_NAME(pSizer, "XML"); - m_pXMLUtils->GetMemoryUsage(pSizer); - } - if (m_env.pConsole) - { - SIZER_COMPONENT_NAME (pSizer, "Console"); - m_env.pConsole->GetMemoryUsage (pSizer); - } - - if (m_env.pLog) - { - SIZER_COMPONENT_NAME (pSizer, "Log"); - m_env.pLog->GetMemoryUsage(pSizer); - } - } - } - - if (m_env.pRenderer) - { - SIZER_COMPONENT_NAME(pSizer, "CryRenderer"); - { - { - SIZER_COMPONENT_NAME (pSizer, "$Allocations waste D3D9"); - const SmallModuleInfo* info = FindModuleInfo(stats, "CryRenderD3D9.dll"); - if (info) - { - pSizer->AddObject(info, info->memInfo.allocated - info->memInfo.requested); - } - } - { - SIZER_COMPONENT_NAME (pSizer, "$Allocations waste D3D10"); - const SmallModuleInfo* info = FindModuleInfo(stats, "CryRenderD3D10.dll"); - if (info) - { - pSizer->AddObject(info, info->memInfo.allocated - info->memInfo.requested); - } - } - - m_env.pRenderer->GetMemoryUsage(pSizer); - } - } - - if (m_env.pCryFont) - { - SIZER_COMPONENT_NAME(pSizer, "CryFont"); - { - { - SIZER_COMPONENT_NAME (pSizer, "$Allocations waste"); - const SmallModuleInfo* info = FindModuleInfo(stats, "CryFont.dll"); - if (info) - { - pSizer->AddObject(info, info->memInfo.allocated - info->memInfo.requested); - } - } - - m_env.pCryFont->GetMemoryUsage(pSizer); - // m_pIFont and m_pIFontUi are both counted in pCryFont sizing if they exist. - // no need to manually add them here. - } - } - - { - SIZER_COMPONENT_NAME(pSizer, "UserData"); - if (m_pUserCallback) - { - m_pUserCallback->GetMemoryUsage(pSizer); - } - } - -#ifdef WIN32 - { - SIZER_COMPONENT_NAME(pSizer, "Code"); - GetExeSizes (pSizer, nPurpose); - } -#endif - - pSizer->End(); -} - ////////////////////////////////////////////////////////////////////////// const char* CSystem::GetUserName() { @@ -460,52 +231,6 @@ int CSystem::GetApplicationLogInstance([[maybe_unused]] const char* logFilePath) #endif } - -// refreshes the m_pMemStats if necessary; creates it if it's not created -////////////////////////////////////////////////////////////////////////// -void CSystem::TickMemStats(MemStatsPurposeEnum nPurpose, IResourceCollector* pResourceCollector) -{ - // gather the statistics, if required - // if there's no object, or if it's time to recalculate, or if it's for dump, then recalculate it - if (!m_pMemStats || (m_env.pRenderer->GetFrameID(false) % m_cvMemStats->GetIVal()) == 0 || nPurpose == nMSP_ForDump) - { - if (!m_pMemStats) - { - if (m_cvMemStats->GetIVal() < 4 && m_cvMemStats->GetIVal()) - { - GetILog()->LogToConsole("memstats is too small (%d). Performance impact can be significant. Please set to a greater value.", m_cvMemStats->GetIVal()); - } - m_pMemStats = new CrySizerStats(); - } - - if (!m_pSizer) - { - m_pSizer = new CrySizerImpl(); - } - - m_pSizer->SetResourceCollector(pResourceCollector); - - m_pMemStats->startTimer(0, GetITimer()); - CollectMemStats (m_pSizer, nPurpose); - m_pMemStats->stopTimer(0, GetITimer()); - - m_pMemStats->startTimer(1, GetITimer()); - CrySizerStatsBuilder builder (m_pSizer); - builder.build (m_pMemStats); - m_pMemStats->stopTimer(1, GetITimer()); - - m_pMemStats->startTimer(2, GetITimer()); - m_pSizer->clear(); - m_pMemStats->stopTimer(2, GetITimer()); - } - else - { - m_pMemStats->incAgeFrames(); - } -} - -//#define __HASXP - // these 2 functions are duplicated in System.cpp in editor ////////////////////////////////////////////////////////////////////////// #if !defined(LINUX) @@ -839,51 +564,6 @@ const char* GetModuleGroup (const char* szString) return "Other"; } -////////////////////////////////////////////////////////////////////////// -void CSystem::GetExeSizes (ICrySizer* pSizer, MemStatsPurposeEnum nPurpose) -{ - HANDLE hSnapshot; - hSnapshot = CreateToolhelp32Snapshot (TH32CS_SNAPMODULE, 0); - if (hSnapshot == INVALID_HANDLE_VALUE) - { - CryLogAlways ("Cannot get the module snapshot, error code %d", GetLastError()); - return; - } - - DWORD dwProcessID = GetCurrentProcessId(); - - MODULEENTRY32 me; - memset (&me, 0, sizeof(me)); - me.dwSize = sizeof(me); - - if (Module32First (hSnapshot, &me)) - { - // the sizes of each module group - StringToSizeMap mapGroupSize; - do - { - dwProcessID = me.th32ProcessID; - const char* szGroup = GetModuleGroup (me.szModule); - SIZER_COMPONENT_NAME(pSizer, szGroup); - if (nPurpose == nMSP_ForDump) - { - SIZER_COMPONENT_NAME(pSizer, me.szModule); - pSizer->AddObject(me.modBaseAddr, me.modBaseSize); - } - else - { - pSizer->AddObject(me.modBaseAddr, me.modBaseSize); - } - } while (Module32Next(hSnapshot, &me)); - } - else - { - CryLogAlways ("No modules to dump"); - } - - CloseHandle (hSnapshot); -} - #endif ////////////////////////////////////////////////////////////////////////// @@ -1061,29 +741,15 @@ void CSystem::FatalError(const char* format, ...) LogSystemInfo(); - CollectMemStats(0, nMSP_ForCrashLog); - OutputDebugString(szBuffer); #ifdef WIN32 OnFatalError(szBuffer); if (!g_cvars.sys_no_crash_dialog) { - ICVar* pFullscreen = (gEnv && gEnv->pConsole) ? gEnv->pConsole->GetCVar("r_Fullscreen") : 0; - if (pFullscreen && pFullscreen->GetIVal() != 0 && gEnv->pRenderer && gEnv->pRenderer->GetHWND()) - { - ::ShowWindow((HWND)gEnv->pRenderer->GetHWND(), SW_MINIMIZE); - } ::MessageBox(NULL, szBuffer, "Open 3D Engine Error", MB_OK | MB_ICONERROR | MB_SYSTEMMODAL); } // 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(); @@ -1125,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 } @@ -1169,12 +833,6 @@ void CSystem::debug_LogCallStack(int nMaxFuncs, [[maybe_unused]] int nFlags) // Print call stack for each find. const char* funcs[32]; int nCount = nMaxFuncs; - int nCurFrame = 0; - if (m_env.pRenderer) - { - nCurFrame = (int)m_env.pRenderer->GetFrameID(false); - } - CryLogAlways(" ----- CallStack (Frame: %d) -----", nCurFrame); GetISystem()->debug_GetCallStack(funcs, nCount); for (int i = 1; i < nCount; i++) // start from 1 to skip this function. { @@ -1241,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/Tests/Test_CrySizer.cpp b/Code/CryEngine/CrySystem/Tests/Test_CrySizer.cpp deleted file mode 100644 index c9aa248eee..0000000000 --- a/Code/CryEngine/CrySystem/Tests/Test_CrySizer.cpp +++ /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. -* -*/ - -#include "CrySystem_precompiled.h" - -#include -#include -#include - -#include - -#include "CrySizerImpl.h" - -namespace UnitTest -{ - class CrySizerTest - : public AllocatorsFixture - { - public: - void SetUp() override - { - AZ::AllocatorInstance::Create(); - AZ::AllocatorInstance::Create(); - - m_sizer = new CrySizerImpl(); - } - - void TearDown() override - { - delete m_sizer; - - AZ::AllocatorInstance::Destroy(); - AZ::AllocatorInstance::Destroy(); - } - protected: - CrySizerImpl* m_sizer; - }; //class StatisticsTest - - /** - * The key data structures fed to ICrySizer in CTerrain::GetMemoryUsage(class ICrySizer* pSizer): - * 1. structs and classes. - * 2. PodArray< of structs / classes> - * 3. PodArray< of pointers> - */ - TEST_F(CrySizerTest, CrySizerTest_AddSomeObjectsUsedInCTerrain_GetExpectedSize) - { - struct TmpStruct - { - AZ::u32 a; - AZ::u32 b; - }; - TmpStruct tmpStructObj; - //Tracking a simple struct. - m_sizer->AddObjectSize(&tmpStructObj); - - //The AddObject method is only available when using the ICrySizer base class. - ICrySizer* sizer = static_cast(m_sizer); - - const int numItemsPerArray = 1024; - - //PodArray of structs - PodArray podArrayOfTmpStruct; - podArrayOfTmpStruct.resize(numItemsPerArray); - sizer->AddObject(podArrayOfTmpStruct); - - //PodArray of pointers - PodArray podArrayOfTmpStructPointers; - podArrayOfTmpStructPointers.resize(numItemsPerArray); - sizer->AddObject(podArrayOfTmpStructPointers); - - //PodArray of Array2d of pointers. - const int array2dAxisSize = 64; - PodArray> podArrayOfArray2d; - podArrayOfArray2d.resize(numItemsPerArray); - for (int i = 0; i < numItemsPerArray; ++i) - { - //Array2d will allocate array2dAxisSize * array2dAxisSize elements. - podArrayOfArray2d[i].Allocate(array2dAxisSize); - } - sizer->AddObject(podArrayOfArray2d); - - //Calculate the total expected size - const size_t expectedSizeOfArray2d = sizeof(Array2d) - + (array2dAxisSize * array2dAxisSize) * sizeof(TmpStruct*); - const size_t expectedTotalSize = sizeof(TmpStruct) - + numItemsPerArray * sizeof(TmpStruct) - + numItemsPerArray * sizeof(TmpStruct*) - + numItemsPerArray * expectedSizeOfArray2d; - - EXPECT_EQ( m_sizer->GetTotalSize(), expectedTotalSize); - } - -}//namespace UnitTest 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/Timer.cpp b/Code/CryEngine/CrySystem/Timer.cpp index eb53c1b257..7545b42765 100644 --- a/Code/CryEngine/CrySystem/Timer.cpp +++ b/Code/CryEngine/CrySystem/Timer.cpp @@ -26,9 +26,6 @@ #include "Mmsystem.h" #endif -//this should not be included here -#include // needed for m_pSystem->GetIRenderer()->EF_Query(EFQ_RecurseLevel) - //#define PROFILING 1 #ifdef PROFILING static int64 g_lCurrentTime = 0; @@ -432,7 +429,7 @@ void CTimer::UpdateOnFrameStart() if (m_TimeDebug > 1) { - CryLogAlways("[CTimer]: Frame=%d Cur=%lld Now=%lld Off=%lld Async=%f CurrTime=%f UI=%f", gEnv->pRenderer->GetFrameID(false), (long long)currentTime, (long long)now, (long long)m_lOffsetTime, GetAsyncCurTime(), GetCurrTime(ETIMER_GAME), GetCurrTime(ETIMER_UI)); + CryLogAlways("[CTimer]: Cur=%lld Now=%lld Off=%lld Async=%f CurrTime=%f UI=%f", (long long)currentTime, (long long)now, (long long)m_lOffsetTime, GetAsyncCurTime(), GetCurrTime(ETIMER_GAME), GetCurrTime(ETIMER_UI)); } } @@ -558,7 +555,7 @@ void CTimer::Serialize(TSerialize ser) if (m_TimeDebug) { const int64 now = CryGetTicks(); - CryLogAlways("[CTimer]: Serialize: Frame=%d Last=%lld Now=%lld Off=%lld Async=%f CurrTime=%f UI=%f", gEnv->pRenderer->GetFrameID(false), (long long)m_lLastTime, (long long)now, (long long)m_lOffsetTime, GetAsyncCurTime(), GetCurrTime(ETIMER_GAME), GetCurrTime(ETIMER_UI)); + CryLogAlways("[CTimer]: Serialize: Last=%lld Now=%lld Off=%lld Async=%f CurrTime=%f UI=%f", (long long)m_lLastTime, (long long)now, (long long)m_lOffsetTime, GetAsyncCurTime(), GetCurrTime(ETIMER_GAME), GetCurrTime(ETIMER_UI)); } } } @@ -584,7 +581,7 @@ bool CTimer::PauseTimer(ETimer which, bool bPause) m_lGameTimerPausedTime = m_lLastTime + m_lOffsetTime; if (m_TimeDebug) { - CryLogAlways("[CTimer]: Pausing ON: Frame=%d Last=%lld Off=%lld Async=%f CurrTime=%f UI=%f", gEnv->pRenderer->GetFrameID(false), (long long)m_lLastTime, (long long)m_lOffsetTime, GetAsyncCurTime(), GetCurrTime(ETIMER_GAME), GetCurrTime(ETIMER_UI)); + CryLogAlways("[CTimer]: Pausing ON: Last=%lld Off=%lld Async=%f CurrTime=%f UI=%f", (long long)m_lLastTime, (long long)m_lOffsetTime, GetAsyncCurTime(), GetCurrTime(ETIMER_GAME), GetCurrTime(ETIMER_UI)); } } else @@ -593,7 +590,7 @@ bool CTimer::PauseTimer(ETimer which, bool bPause) m_lGameTimerPausedTime = 0; if (m_TimeDebug) { - CryLogAlways("[CTimer]: Pausing OFF: Frame=%d Last=%lld Off=%lld Async=%f CurrTime=%f UI=%f", gEnv->pRenderer->GetFrameID(false), (long long)m_lLastTime, (long long)m_lOffsetTime, GetAsyncCurTime(), GetCurrTime(ETIMER_GAME), GetCurrTime(ETIMER_UI)); + CryLogAlways("[CTimer]: Pausing OFF: Last=%lld Off=%lld Async=%f CurrTime=%f UI=%f", (long long)m_lLastTime, (long long)m_lOffsetTime, GetAsyncCurTime(), GetCurrTime(ETIMER_GAME), GetCurrTime(ETIMER_UI)); } } 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/Validator.h b/Code/CryEngine/CrySystem/Validator.h index 409377ee28..83dc0533f6 100644 --- a/Code/CryEngine/CrySystem/Validator.h +++ b/Code/CryEngine/CrySystem/Validator.h @@ -43,11 +43,6 @@ struct SDefaultValidator } #ifdef WIN32 - ICVar* pFullscreen = (gEnv && gEnv->pConsole) ? gEnv->pConsole->GetCVar("r_Fullscreen") : 0; - if (pFullscreen && pFullscreen->GetIVal() != 0 && gEnv->pRenderer && gEnv->pRenderer->GetHWND()) - { - ::ShowWindow((HWND)gEnv->pRenderer->GetHWND(), SW_MINIMIZE); - } string strMessage = record.text; strMessage += "\n---------------------------------------------\nAbort - terminate application\nRetry - continue running the application\nIgnore - don't show this message box any more"; switch (::MessageBox(NULL, strMessage.c_str(), "CryEngine Warning", MB_ABORTRETRYIGNORE | MB_DEFBUTTON2 | MB_ICONWARNING | MB_SYSTEMMODAL)) diff --git a/Code/CryEngine/CrySystem/ViewSystem/DebugCamera.cpp b/Code/CryEngine/CrySystem/ViewSystem/DebugCamera.cpp index ace30d5df7..f38dda32c7 100644 --- a/Code/CryEngine/CrySystem/ViewSystem/DebugCamera.cpp +++ b/Code/CryEngine/CrySystem/ViewSystem/DebugCamera.cpp @@ -137,15 +137,6 @@ void DebugCamera::PostUpdate() CCamera& camera = gEnv->pSystem->GetViewCamera(); camera.SetMatrix(Matrix34(m_view, m_position)); - - const float FONT_COLOR[4] = { 1.0f, 0.0f, 0.0f, 1.0f }; - gEnv->pRenderer->Draw2dLabel(0.0f, 700.0f, 1.3f, FONT_COLOR, false, - "Debug Camera: pos [ %.3f, %.3f, %.3f ] p/y [ %.1f, %.1f ] dir [ %.3f, %.3f, %.3f ] scl %.2f inv %d", - m_position.x, m_position.y, m_position.z, - m_cameraPitch, m_cameraYaw, - m_view.GetColumn1().x, m_view.GetColumn1().y, m_view.GetColumn1().z, - m_moveScale, - m_isYInverted); } /////////////////////////////////////////////////////////////////////////////// diff --git a/Code/CryEngine/CrySystem/ViewSystem/View.cpp b/Code/CryEngine/CrySystem/ViewSystem/View.cpp index f8b84bea19..0ab2d6169b 100644 --- a/Code/CryEngine/CrySystem/ViewSystem/View.cpp +++ b/Code/CryEngine/CrySystem/ViewSystem/View.cpp @@ -101,25 +101,6 @@ void CView::Update(float frameTime, bool isActive) const float farPlane = (m_viewParams.farplane > 0.f) ? m_viewParams.farplane : DEFAULT_FAR; float fov = (m_viewParams.fov < 0.001f) ? DEFAULT_FOV : m_viewParams.fov; - // [VR] specific - // Modify FOV based on the HMD device configuration - bool isRenderingToHMD = gEnv->pRenderer ? gEnv->pRenderer->GetIStereoRenderer()->IsRenderingToHMD() : false; - if (isRenderingToHMD) - { - const AZ::VR::HMDDeviceInfo* deviceInfo = nullptr; - EBUS_EVENT_RESULT(deviceInfo, AZ::VR::HMDDeviceRequestBus, GetDeviceInfo); - if (deviceInfo) - { - //Add 12 degrees to the FOV here used for culling. - //It won't be used for rendering, just to make sure we don't cull - //anything out incorrectly. - //This value was decided based on experimentation with the HTC Vive - //and works perfectly fine for the Oculus Rift - const float fovCorrection = 12.0f; - fov = deviceInfo->fovV + DEG2RAD(fovCorrection); - } - } - m_camera.SetFrustum(pSysCam->GetViewSurfaceX(), pSysCam->GetViewSurfaceZ(), fov, nearPlane, farPlane, pSysCam->GetPixelAspectRatio()); //apply shake & set the view matrix @@ -140,20 +121,6 @@ void CView::Update(float frameTime, bool isActive) Vec3 pos = m_viewParams.position; Vec3 p = Vec3(ZERO); - if (isRenderingToHMD) - { - //This HMD tracking state is used JUST for use in the visibility system. - //RT_SetStereoCamera in D3DRendPipeline will override this info before rendering with the absolute - //latest tracking info. - const AZ::VR::TrackingState* trackingState = nullptr; - EBUS_EVENT_RESULT(trackingState, AZ::VR::HMDDeviceRequestBus, GetTrackingState); - if (trackingState && trackingState->CheckStatusFlags(AZ::VR::HMDStatus_IsUsable)) - { - p = q * AZVec3ToLYVec3(trackingState->pose.position); - q = q * AZQuaternionToLYQuaternion(trackingState->pose.orientation); - } - } - Matrix34 viewMtx(q); viewMtx.SetTranslation(pos + p); m_camera.SetMatrix(viewMtx); diff --git a/Code/CryEngine/CrySystem/ViewSystem/ViewSystem.cpp b/Code/CryEngine/CrySystem/ViewSystem/ViewSystem.cpp index 13f7f5b82d..c0f681511b 100644 --- a/Code/CryEngine/CrySystem/ViewSystem/ViewSystem.cpp +++ b/Code/CryEngine/CrySystem/ViewSystem/ViewSystem.cpp @@ -640,30 +640,6 @@ void CViewSystem::ClearAllViews() //////////////////////////////////////////////////////////////////// void CViewSystem::DebugDraw() { - IRenderer* pRenderer = gEnv->pRenderer; - if (pRenderer) - { - float xpos = 20; - float ypos = 15; - float fColor[4] = {1.0f, 1.0f, 1.0f, 0.7f}; - float fColorRed[4] = {1.0f, 0.0f, 0.0f, 0.7f}; - float fColorGreen[4] = {0.0f, 1.0f, 0.0f, 0.7f}; - - pRenderer->Draw2dLabel(xpos, 5, 1.35f, fColor, false, "ViewSystem Stats: %" PRISIZE_T " Views ", m_views.size()); - - IView* pActiveView = GetActiveView(); - for (TViewMap::iterator it = m_views.begin(); it != m_views.end(); ++it) - { - IView* pView = it->second; - const CCamera& cam = pView->GetCamera(); - bool isActive = (pView == pActiveView); - Vec3 pos = cam.GetPosition(); - Ang3 ang = cam.GetAngles(); - pRenderer->Draw2dLabel(xpos, ypos, 1.35f, isActive ? fColorGreen : fColorRed, false, "View Camera: %p . View Id: %d, pos (%f, %f, %f), ang (%f, %f, %f)", &cam, it->first, pos.x, pos.y, pos.z, ang.x, ang.y, ang.z); - - ypos += 11; - } - } } ////////////////////////////////////////////////////////////////////////// diff --git a/Code/CryEngine/CrySystem/VisRegTest.cpp b/Code/CryEngine/CrySystem/VisRegTest.cpp deleted file mode 100644 index 206d8f349a..0000000000 --- a/Code/CryEngine/CrySystem/VisRegTest.cpp +++ /dev/null @@ -1,384 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -// Description : Visual Regression Test - - -#include "CrySystem_precompiled.h" -#include "VisRegTest.h" - -#include "ISystem.h" -#include "IRenderer.h" -#include "IConsole.h" -#include "ITimer.h" -#include "IStreamEngine.h" -#include - -#include - -const float CVisRegTest::MaxStreamingWait = 30.0f; - -CVisRegTest::CVisRegTest() - : m_nextCmd(0) - , m_waitFrames(0) -{ - CryLog("Enabled visual regression tests"); -} - - -void CVisRegTest::Init(IConsoleCmdArgs* pParams) -{ - assert(pParams); - - stack_string configFile("visregtest.xml"); - - // Reset - m_cmdBuf.clear(); - m_dataSamples.clear(); - m_nextCmd = 0; - m_cmdFreq = 0; - m_waitFrames = 0; - m_streamingTimeout = 0.0f; - m_testName = "test"; - m_quitAfterTests = false; - - // Parse arguments - if (pParams->GetArgCount() >= 2) - { - m_testName = pParams->GetArg(1); - } - if (pParams->GetArgCount() >= 3) - { - configFile = pParams->GetArg(2); - } - if (pParams->GetArgCount() >= 4) - { - if (_stricmp(pParams->GetArg(3), "quit") == 0) - { - m_quitAfterTests = true; - } - } - - // Fill cmd buffer - if (!LoadConfig(configFile.c_str())) - { - CryWarning(VALIDATOR_MODULE_SYSTEM, VALIDATOR_ERROR, "VisRegTest: Failed to load config file '%s' from game folder", configFile.c_str()); - return; - } - - gEnv->pTimer->SetTimeScale(0); - GetISystem()->GetISystemEventDispatcher()->OnSystemEvent(ESYSTEM_EVENT_RANDOM_SEED, 0, 0); - srand(0); - - gEnv->pRenderer->EnableGPUTimers2(true); -} - - -void CVisRegTest::AfterRender() -{ - ExecCommands(); -} - - -bool CVisRegTest::LoadConfig(const char* configFile) -{ - XmlNodeRef rootNode = GetISystem()->LoadXmlFromFile(configFile); - if (!rootNode || !rootNode->isTag("VisRegTest")) - { - return false; - } - - m_cmdBuf.push_back(SCmd(eCMDStart, "")); - - for (int i = 0; i < rootNode->getChildCount(); ++i) - { - XmlNodeRef node = rootNode->getChild(i); - - if (node->isTag("Config")) - { - SCmd cmd; - for (int j = 0; j < node->getChildCount(); ++j) - { - XmlNodeRef node2 = node->getChild(j); - - if (node2->isTag("ConsoleCmd")) - { - m_cmdBuf.push_back(SCmd(eCMDConsoleCmd, node2->getAttr("cmd"))); - } - } - } - else if (node->isTag("Map")) - { - const char* mapName = node->getAttr("name"); - int imageIndex = 0; - - m_cmdBuf.push_back(SCmd(eCMDLoadMap, mapName)); - m_cmdBuf.push_back(SCmd(eCMDOnMapLoaded, "")); - - for (int j = 0; j < node->getChildCount(); ++j) - { - XmlNodeRef node2 = node->getChild(j); - - if (node2->isTag("ConsoleCmd")) - { - m_cmdBuf.push_back(SCmd(eCMDConsoleCmd, node2->getAttr("cmd"))); - } - else if (node2->isTag("Sample")) - { - m_cmdBuf.push_back(SCmd(eCMDGoto, node2->getAttr("location"))); - m_cmdBuf.push_back(SCmd(eCMDWaitStreaming, "")); - - char strbuf[256]; -#ifdef WIN32 - sprintf_s(strbuf, "%s_%i.bmp", mapName, imageIndex++); -#else - sprintf_s(strbuf, "%s_%i.tga", mapName, imageIndex++); -#endif - m_cmdBuf.push_back(SCmd(eCMDCaptureSample, strbuf, SampleCount)); - } - } - } - } - - m_cmdBuf.push_back(SCmd(eCMDFinish, "")); - - return true; -} - - -void CVisRegTest::ExecCommands() -{ - if (m_nextCmd >= m_cmdBuf.size()) - { - return; - } - - float col[] = {0, 1, 0, 1}; - gEnv->pRenderer->Draw2dLabel(10, 10, 2, col, false, "Visual Regression Test"); - - if (m_waitFrames > 0) - { - --m_waitFrames; - return; - } - else if (m_waitFrames < 0) // Wait for streaming - { - SStreamEngineOpenStats stats; - gEnv->pSystem->GetStreamEngine()->GetStreamingOpenStatistics(stats); - if (stats.nOpenRequestCount > 0 && m_streamingTimeout > 0) - { - gEnv->pConsole->ExecuteString("t_FixedStep 0"); - m_streamingTimeout -= gEnv->pTimer->GetRealFrameTime(); - m_waitFrames = -16; - } - else if (++m_waitFrames == 0) - { - gEnv->pConsole->ExecuteString("t_FixedStep 0.033333"); - m_waitFrames = 64; // Wait some more frames for tone-mapper to adapt - } - - return; - } - - stack_string tmp; - - while (m_nextCmd < m_cmdBuf.size()) - { - SCmd& cmd = m_cmdBuf[m_nextCmd]; - - if (m_cmdFreq == 0) - { - m_cmdFreq = cmd.freq; - } - - switch (cmd.cmd) - { - case eCMDStart: - break; - case eCMDFinish: - Finish(); - break; - case eCMDOnMapLoaded: - gEnv->pTimer->SetTimer(ITimer::ETIMER_GAME, 0); - gEnv->pTimer->SetTimer(ITimer::ETIMER_UI, 0); - gEnv->pConsole->ExecuteString("t_FixedStep 0.033333"); - GetISystem()->GetISystemEventDispatcher()->OnSystemEvent(ESYSTEM_EVENT_RANDOM_SEED, 0, 0); - srand(0); - break; - case eCMDConsoleCmd: - gEnv->pConsole->ExecuteString(cmd.args.c_str()); - break; - case eCMDLoadMap: - LoadMap(cmd.args.c_str()); - break; - case eCMDWaitStreaming: - m_waitFrames = -1; - m_streamingTimeout = MaxStreamingWait; - break; - case eCMDWaitFrames: - m_waitFrames = (uint32)atoi(cmd.args.c_str()); - break; - case eCMDGoto: - tmp = "playerGoto "; - tmp.append(cmd.args.c_str()); - gEnv->pConsole->ExecuteString(tmp.c_str()); - m_waitFrames = 1; - break; - case eCMDCaptureSample: - CaptureSample(cmd); - break; - } - - if (m_cmdFreq-- == 1) - { - ++m_nextCmd; - } - - if (m_waitFrames != 0) - { - break; - } - } -} - - -void CVisRegTest::LoadMap(const char* mapName) -{ - string mapCmd("map "); - mapCmd.append(mapName); - gEnv->pConsole->ExecuteString(mapCmd.c_str()); - - gEnv->pTimer->SetTimer(ITimer::ETIMER_GAME, 0); - gEnv->pTimer->SetTimer(ITimer::ETIMER_UI, 0); - gEnv->pConsole->ExecuteString("t_FixedStep 0"); - GetISystem()->GetISystemEventDispatcher()->OnSystemEvent(ESYSTEM_EVENT_RANDOM_SEED, 0, 0); - srand(0); -} - - -void CVisRegTest::CaptureSample(const SCmd& cmd) -{ - if (m_cmdFreq == SampleCount) // First sample - { - m_dataSamples.push_back(SSample()); - gEnv->pConsole->ExecuteString("t_FixedStep 0"); - } - - SSample& sample = m_dataSamples.back(); - - // Collect stats - sample.imageName = cmd.args.c_str(); - sample.frameTime += gEnv->pTimer->GetRealFrameTime() * 1000.f; - sample.drawCalls += gEnv->pRenderer->GetCurrentNumberOfDrawCalls(); - - const RPProfilerStats* pRPPStats = gEnv->pRenderer->GetRPPStatsArray(); - - if (pRPPStats) - { - sample.gpuTimes[0] += pRPPStats[eRPPSTATS_OverallFrame].gpuTime; - - sample.gpuTimes[1] += pRPPStats[eRPPSTATS_SceneOverall].gpuTime; - sample.gpuTimes[2] += pRPPStats[eRPPSTATS_ShadowsOverall].gpuTime; - sample.gpuTimes[3] += pRPPStats[eRPPSTATS_LightingOverall].gpuTime; - sample.gpuTimes[4] += pRPPStats[eRPPSTATS_VfxOverall].gpuTime; - } - - if (m_cmdFreq == 1) // Final sample - { - // Screenshot - stack_string filename("@usercache@/TestResults/VisReg/"); // the default unaliased assets folder is read-only! - filename += m_testName + "/" + cmd.args.c_str(); - gEnv->pRenderer->ScreenShot(filename); - - // Average results - sample.frameTime /= (float)SampleCount; - sample.drawCalls /= SampleCount; - for (uint32 i = 0; i < MaxNumGPUTimes; ++i) - { - sample.gpuTimes[i] /= (float)SampleCount; - } - - gEnv->pConsole->ExecuteString("t_FixedStep 0.033333"); - } -} - - -void CVisRegTest::Finish() -{ - WriteResults(); - - gEnv->pConsole->ExecuteString("t_FixedStep 0"); - gEnv->pTimer->SetTimeScale(1); - - gEnv->pRenderer->EnableGPUTimers2(false); - - CryLog("VisRegTest: Finished tests"); - - if (m_quitAfterTests) - { - gEnv->pConsole->ExecuteString("quit"); - return; - } -} - - -bool CVisRegTest::WriteResults() -{ - stack_string filename("@usercache@/TestResults/VisReg/"); - filename += m_testName + "/visreg_results.xml"; - - AZ::IO::HandleType fileHandle = fxopen(filename.c_str(), "wb"); - if (fileHandle == AZ::IO::InvalidHandle) - { - return false; - } - - AZ::IO::Print(fileHandle, "\n"); - AZ::IO::Print(fileHandle, "\t\n"); - - for (int i = 0; i < (int)m_dataSamples.size(); ++i) - { - SSample sample = m_dataSamples[i]; - - AZ::IO::Print(fileHandle, "\t\t\n", i, sample.imageName); - - AZ::IO::Print(fileHandle, "\t\t\t\n"); - AZ::IO::Print(fileHandle, "\t\t\t\t\n", sample.frameTime); - AZ::IO::Print(fileHandle, "\t\t\t\t\n", sample.drawCalls); - AZ::IO::Print(fileHandle, "\t\t\t\n"); - - AZ::IO::Print(fileHandle, "\t\t\t\n"); - AZ::IO::Print(fileHandle, "\t\t\t\t\n", sample.gpuTimes[0]); - AZ::IO::Print(fileHandle, "\t\t\t\t\n", sample.gpuTimes[1]); - AZ::IO::Print(fileHandle, "\t\t\t\t\n", sample.gpuTimes[2]); - AZ::IO::Print(fileHandle, "\t\t\t\t\n", sample.gpuTimes[3]); - AZ::IO::Print(fileHandle, "\t\t\t\t\n", sample.gpuTimes[4]); - AZ::IO::Print(fileHandle, "\t\t\t\t\n", sample.gpuTimes[5]); - AZ::IO::Print(fileHandle, "\t\t\t\t\n", sample.gpuTimes[6]); - AZ::IO::Print(fileHandle, "\t\t\t\t\n", sample.gpuTimes[7]); - AZ::IO::Print(fileHandle, "\t\t\t\t\n", sample.gpuTimes[8]); - AZ::IO::Print(fileHandle, "\t\t\t\t\n", sample.gpuTimes[9]); - AZ::IO::Print(fileHandle, "\t\t\t\t\n", sample.gpuTimes[10]); - AZ::IO::Print(fileHandle, "\t\t\t\t\n", sample.gpuTimes[11]); - AZ::IO::Print(fileHandle, "\t\t\t\t\n", sample.gpuTimes[12]); - AZ::IO::Print(fileHandle, "\t\t\t\n"); - - AZ::IO::Print(fileHandle, "\t\t\n"); - } - - AZ::IO::Print(fileHandle, "\t\n"); - AZ::IO::Print(fileHandle, ""); - gEnv->pFileIO->Close(fileHandle); - - return true; -} diff --git a/Code/CryEngine/CrySystem/VisRegTest.h b/Code/CryEngine/CrySystem/VisRegTest.h deleted file mode 100644 index 19653940a4..0000000000 --- a/Code/CryEngine/CrySystem/VisRegTest.h +++ /dev/null @@ -1,104 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -// Description : Visual Regression Test - - -#ifndef CRYINCLUDE_CRYSYSTEM_VISREGTEST_H -#define CRYINCLUDE_CRYSYSTEM_VISREGTEST_H -#pragma once - - -struct IConsoleCmdArgs; - -class CVisRegTest -{ -public: - static const uint32 SampleCount = 16; - static const uint32 MaxNumGPUTimes = 13; - static const float MaxStreamingWait; - -protected: - - enum ECmd - { - eCMDStart, - eCMDFinish, - eCMDOnMapLoaded, - eCMDConsoleCmd, - eCMDLoadMap, - eCMDWaitStreaming, - eCMDWaitFrames, - eCMDGoto, - eCMDCaptureSample - }; - - struct SCmd - { - ECmd cmd; - uint32 freq; - string args; - - SCmd() {} - SCmd(ECmd _cmd, const string& _args, uint32 _freq = 1) - { this->cmd = _cmd; this->args = _args; this->freq = _freq; } - }; - - struct SSample - { - const char* imageName; - float frameTime; - uint32 drawCalls; - float gpuTimes[MaxNumGPUTimes]; - - SSample() - : imageName(NULL) - , frameTime(0.f) - , drawCalls(0) - { - for (uint32 i = 0; i < MaxNumGPUTimes; ++i) - { - gpuTimes[i] = 0; - } - } - }; - -protected: - string m_testName; - std::vector< SCmd > m_cmdBuf; - std::vector< SSample > m_dataSamples; - uint32 m_nextCmd; - uint32 m_cmdFreq; - int m_waitFrames; - float m_streamingTimeout; - int m_curSample; - bool m_quitAfterTests; - -public: - - CVisRegTest(); - - void Init(IConsoleCmdArgs* pParams); - void AfterRender(); - -protected: - - bool LoadConfig(const char* configFile); - void ExecCommands(); - void LoadMap(const char* mapName); - void CaptureSample(const SCmd& cmd); - void Finish(); - bool WriteResults(); -}; - -#endif // CRYINCLUDE_CRYSYSTEM_VISREGTEST_H diff --git a/Code/CryEngine/CrySystem/XConsole.cpp b/Code/CryEngine/CrySystem/XConsole.cpp index f4271d6dc4..32fe67dcc0 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 @@ -141,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); @@ -328,7 +186,6 @@ CXConsole::CXConsole() m_fRepeatTimer = 0; m_pSysDeactivateConsole = 0; m_pFont = NULL; - m_pRenderer = NULL; m_pImage = NULL; m_nCursorPos = 0; m_nScrollPos = 0; @@ -361,8 +218,6 @@ CXConsole::CXConsole() m_waitSeconds = 0.0f; m_blockCounter = 0; - CNotificationNetworkConsole::Initialize(); - AzFramework::ConsoleRequestBus::Handler::BusConnect(); AzFramework::CommandRegistrationBus::Handler::BusConnect(); @@ -381,8 +236,6 @@ CXConsole::~CXConsole() gEnv->pSystem->GetIRemoteConsole()->UnregisterListener(this); } - CNotificationNetworkConsole::Shutdown(); - if (!m_mapVariables.empty()) { while (!m_mapVariables.empty()) @@ -397,18 +250,6 @@ CXConsole::~CXConsole() ////////////////////////////////////////////////////////////////////////// void CXConsole::FreeRenderResources() { - if (m_pRenderer) - { - if (m_nLoadingBackTexID) - { - m_pRenderer->RemoveTexture(m_nLoadingBackTexID); - m_nLoadingBackTexID = -1; - } - if (m_pImage) - { - m_pImage->Release(); - } - } } ////////////////////////////////////////////////////////////////////////// @@ -485,7 +326,6 @@ void CXConsole::Init(ISystem* pSystem) { m_pFont = pSystem->GetICryFont()->GetFont("default"); } - m_pRenderer = pSystem->GetIRenderer(); m_pTimer = pSystem->GetITimer(); AzFramework::InputChannelEventListener::Connect(); @@ -534,10 +374,7 @@ void CXConsole::Init(ISystem* pSystem) // ---------------------------------------------------------- - if (!m_pRenderer || gEnv->IsInToolMode()) - { - m_nLoadingBackTexID = -1; - } + m_nLoadingBackTexID = -1; if (gEnv->IsDedicated()) { @@ -1176,7 +1013,6 @@ void CXConsole::Clear() ////////////////////////////////////////////////////////////////////////// void CXConsole::Update() { - // Repeat GetIRenderer (For Editor). if (!m_pSystem) { return; @@ -1192,8 +1028,6 @@ void CXConsole::Update() // Execute the deferred commands ExecuteDeferredCommands(); - m_pRenderer = m_pSystem->GetIRenderer(); - if (!m_bConsoleActive) { m_nRepeatEventId = s_nullRepeatEventId; @@ -1226,8 +1060,6 @@ void CXConsole::Update() } } } - - CNotificationNetworkConsole::Update(); } //enable this for now, we need it for profiling etc @@ -1588,206 +1420,10 @@ const char* CXConsole::GetHistoryElement(const bool bUpOrDown) ////////////////////////////////////////////////////////////////////////// void CXConsole::Draw() { - //ShowConsole(true); - if (!m_pSystem || !m_nTempScrollMax) - { - return; - } - - if (!m_pRenderer) - { - // For Editor. - m_pRenderer = m_pSystem->GetIRenderer(); - } - - if (!m_pRenderer) - { - return; - } - - if (!m_pFont) - { - // For Editor. - ICryFont* pICryFont = m_pSystem->GetICryFont(); - - if (pICryFont) - { - m_pFont = m_pSystem->GetICryFont()->GetFont("default"); - } - } - - ScrollConsole(); - - if (!m_bConsoleActive && con_display_last_messages == 0) - { - return; - } - - if (m_pRenderer->GetIRenderAuxGeom()) - { - m_pRenderer->GetIRenderAuxGeom()->Flush(); - } - - m_pRenderer->EF_RenderTextMessages(); - - m_pRenderer->PushProfileMarker("DISPLAY_CONSOLE"); - - if (m_nScrollPos <= 0) - { - DrawBuffer(70, "console"); - } - else - { - // cursor blinking - { - m_fCursorBlinkTimer += gEnv->pTimer->GetRealFrameTime(); // works even when time is manipulated - // m_fCursorBlinkTimer += gEnv->pTimer->GetFrameTime(ITimer::ETIMER_UI); // can be used once ETIMER_UI works even with t_FixedTime - - const float fCursorBlinkDelay = 0.5f; // in sec (similar to Windows default but might differ from actual setting) - - if (m_fCursorBlinkTimer > fCursorBlinkDelay) - { - m_bDrawCursor = !m_bDrawCursor; - m_fCursorBlinkTimer = 0.0f; - } - } - - CScopedWireFrameMode scopedWireFrame(m_pRenderer, R_SOLID_MODE); - - if (!m_nProgressRange) - { - int whiteTexId = gEnv->pRenderer ? gEnv->pRenderer->GetWhiteTextureId() : -1; - - if (m_bStaticBackground) - { - m_pRenderer->SetState(GS_NODEPTHTEST); - m_pRenderer->Draw2dImage(0, 0, 800, 600, m_pImage ? m_pImage->GetTextureID() : whiteTexId, 0.0f, 1.0f, 1.0f, 0.0f); - } - else - { - TransformationMatrices backupSceneMatrices; - m_pRenderer->Set2DMode(m_pRenderer->GetWidth(), m_pRenderer->GetHeight(), backupSceneMatrices); - - float fReferenceSize = 600.0f; - - float fSizeX = (float)m_pRenderer->GetWidth(); - float fSizeY = m_nTempScrollMax * m_pRenderer->GetHeight() / fReferenceSize; - - m_pRenderer->SetState(GS_NODEPTHTEST | GS_BLSRC_SRCALPHA | GS_BLDST_ONEMINUSSRCALPHA); - m_pRenderer->DrawImage(0, 0, fSizeX, fSizeY, whiteTexId, 0.0f, 0.0f, 1.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.7f); - m_pRenderer->DrawImage(0, fSizeY, fSizeX, 2.0f * m_pRenderer->GetHeight() / fReferenceSize, whiteTexId, 0, 0, 0, 0, 0.0f, 0.0f, 0.0f, 1.0f); - - m_pRenderer->Unset2DMode(backupSceneMatrices); - } - } - - // draw progress bar - if (m_nProgressRange) - { - m_pRenderer->SetState(GS_BLSRC_SRCALPHA | GS_BLDST_ONEMINUSSRCALPHA | GS_NODEPTHTEST); - m_pRenderer->Draw2dImage(0.0, 0.0, 800.0f, 600.0f, m_nLoadingBackTexID, 0.0f, 1.0f, 1.0f, 0.0f); - } - - DrawBuffer(m_nScrollPos, "console"); - } - - m_pRenderer->PopProfileMarker("DISPLAY_CONSOLE"); } -void CXConsole::DrawBuffer(int nScrollPos, const char* szEffect) +void CXConsole::DrawBuffer(int, const char*) { - if (m_pFont && m_pRenderer) - { - // The scroll position is in pixels for a 800x600 screen so we scale it to the current resolution. - Vec2 referenceSize(800.0f, 600.0f); - const float fontSizeIn800x600 = 14; - const float maxYPos = nScrollPos * (m_pRenderer->GetHeight() / referenceSize.y); - // We also scale the font from the original 800x600 size - float fontSize = fontSizeIn800x600 * (m_pRenderer->GetWidth() / referenceSize.x); - const float fontAspectRatio = 0.75f; - float minFontSize = 10.f; - float maxFontSize = 50.f; - ICVar* minFontCVar = GetCVar("r_minConsoleFontSize"); - if (minFontCVar) - { - minFontSize = minFontCVar->GetFVal(); - } - - ICVar* maxFontCVar = GetCVar("r_maxConsoleFontSize"); - if (maxFontCVar) - { - maxFontSize = maxFontCVar->GetFVal(); - } - - // Limit max font size in case minFontSize > maxFontSize - maxFontSize = AZStd::max(minFontSize, maxFontSize); - fontSize = AZStd::min(AZStd::max(fontSize, minFontSize), maxFontSize); - - STextDrawContext ctx; - //ctx.Reset(); - ctx.SetEffect(m_pFont->GetEffectId(szEffect)); - ctx.SetProportional(false); - ctx.SetCharWidthScale(0.5f); - ctx.SetSize(Vec2(fontSize, fontAspectRatio * fontSize)); - ctx.SetColor(ColorF(1, 1, 1, 1)); - ctx.SetFlags(eDrawText_CenterV | eDrawText_2D); - - float csize = 0.8f * ctx.GetCharHeight(); - ctx.SetSizeIn800x600(false); - - float yPos = maxYPos - csize - 3.0f; - float xPos = LINE_BORDER; - - float fCharWidth = (ctx.GetCharWidth() * ctx.GetCharWidthScale()); - - //int ypos=nScrollPos-csize-3; - - //Draw the input line - if (m_bConsoleActive && !m_nProgressRange) - { - /*m_pRenderer->DrawString(xPos-nCharWidth, yPos, false, ">"); - m_pRenderer->DrawString(xPos, yPos, false, m_sInputBuffer.c_str()); - if(m_bDrawCursor) - m_pRenderer->DrawString(xPos+nCharWidth*m_nCursorPos, yPos, false, "_");*/ - - m_pFont->DrawString((float)(xPos - fCharWidth), (float)yPos, ">", false, ctx); - m_pFont->DrawString((float)xPos, (float)yPos, m_sInputBuffer.c_str(), false, ctx); - - if (m_bDrawCursor) - { - string szCursorLeft(m_sInputBuffer.c_str(), m_sInputBuffer.c_str() + m_nCursorPos); - int n = m_pFont->GetTextLength(szCursorLeft.c_str(), false); - - m_pFont->DrawString((float)(xPos + (fCharWidth * n)), (float)yPos, "_", false, ctx); - } - } - - yPos -= csize; - - ConsoleBufferRItor ritor; - ritor = m_dqConsoleBuffer.rbegin(); - int nScroll = 0; - while (ritor != m_dqConsoleBuffer.rend() && yPos >= 0) - { - if (nScroll >= m_nScrollLine) - { - const char* buf = ritor->c_str();// GetBuf(k); - - if (*buf > 0 && *buf < 32) - { - buf++; // to jump over verbosity level character - } - if (yPos + csize > 0) - { - m_pFont->DrawString((float)xPos, (float)yPos, buf, false, ctx); - } - yPos -= csize; - } - nScroll++; - - ++ritor; - } //k - } } @@ -1828,44 +1464,6 @@ int CXConsole::GetLineCount() const ////////////////////////////////////////////////////////////////////////// void CXConsole::ScrollConsole() { - if (!m_pRenderer) - { - return; - } - - int nCurrHeight = m_pRenderer->GetHeight(); - - switch (m_sdScrollDir) - { - ///////////////////////////////// - case sdDOWN: // The console is scrolling down - - // Vlads note: console should go down immediately, otherwise it can look very bad on startup - //m_nScrollPos+=nCurrHeight/2; - m_nScrollPos = m_nTempScrollMax; - - if (m_nScrollPos > m_nTempScrollMax) - { - m_nScrollPos = m_nTempScrollMax; - m_sdScrollDir = sdNONE; - } - break; - ///////////////////////////////// - case sdUP: // The console is scrolling up - - m_nScrollPos -= nCurrHeight;//2; - - if (m_nScrollPos < 0) - { - m_nScrollPos = 0; - m_sdScrollDir = sdNONE; - } - break; - ///////////////////////////////// - case sdNONE: - break; - ///////////////////////////////// - } } @@ -2004,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) { @@ -2041,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; } } @@ -2065,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", @@ -2077,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; } @@ -2098,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", @@ -2112,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; } @@ -2467,13 +2035,6 @@ void CXConsole::ExecuteStringInternal(const char* command, const bool bFromConso if (!sTemp.empty() || (pCVar->GetType() == CVAR_STRING)) { - // renderer cvars will be updated in the render thread - if ((pCVar->GetFlags() & VF_RENDERER_CVAR) && m_pRenderer) - { - m_pRenderer->SetRendererCVar(pCVar, sTemp.c_str(), bSilentMode); - continue; - } - pCVar->Set(sTemp.c_str()); } } @@ -2500,36 +2061,8 @@ void CXConsole::ExecuteDeferredCommands() { TDeferredCommandList::iterator it; - // const float fontHeight = 10; - // ColorF col = Col_Yellow; - // - // float curX = 10; - // float curY = 10; - - //IRenderer* pRenderer = gEnv->pRenderer; - - // Print the deferred messages - // it = m_deferredCommands.begin(); - // if (it != m_deferredCommands.end()) - // { - // pRenderer->Draw2dLabel( curX, curY += fontHeight, 1.2f, &col.r, false - // , "Pending deferred commands = %d", m_deferredCommands.size() ); - // } - // - // for ( - // ; it != m_deferredCommands.end() - // ; ++it - // ) - // { - // pRenderer->Draw2dLabel( curX + fontHeight * 2.0f, curY += fontHeight, 1.2f, &col.r, false - // , "Cmd: %s", it->command.c_str() ); - // } - if (m_waitFrames) { - // pRenderer->Draw2dLabel( curX, curY += fontHeight, 1.2f, &col.r, false - // , "Waiting frames = %d", m_waitFrames ); - --m_waitFrames; return; } @@ -2538,10 +2071,6 @@ void CXConsole::ExecuteDeferredCommands() { if (m_waitSeconds > gEnv->pTimer->GetFrameStartTime()) { - // pRenderer->Draw2dLabel( curX, curY += fontHeight, 1.2f, &col.r, false - // , "Waiting seconds = %f" - // , m_waitSeconds.GetSeconds() - gEnv->pTimer->GetFrameStartTime().GetSeconds() ); - return; } @@ -2566,8 +2095,6 @@ void CXConsole::ExecuteDeferredCommands() break; } } - - //m_deferredExecution = false; } ////////////////////////////////////////////////////////////////////////// @@ -2816,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; @@ -2861,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); @@ -2886,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()); } @@ -2909,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); } @@ -3143,71 +2653,18 @@ void CXConsole::PostLine(const char* lineOfText, size_t len) } ////////////////////////////////////////////////////////////////////////// -void CXConsole::ResetProgressBar(int nProgressBarRange) +void CXConsole::ResetProgressBar(int) { - m_nProgressRange = nProgressBarRange; - m_nProgress = 0; - - if (nProgressBarRange < 0) - { - nProgressBarRange = 0; - } - - if (!m_nProgressRange) - { - if (m_nLoadingBackTexID) - { - if (m_pRenderer) - { - m_pRenderer->RemoveTexture(m_nLoadingBackTexID); - } - m_nLoadingBackTexID = -1; - } - } - - static ICVar* log_Verbosity = GetCVar("log_Verbosity"); - - if (log_Verbosity && (!log_Verbosity->GetIVal())) - { - Clear(); - } } ////////////////////////////////////////////////////////////////////////// void CXConsole::TickProgressBar() { - if (m_nProgressRange != 0 && m_nProgressRange > m_nProgress) - { - m_nProgress++; - m_pSystem->UpdateLoadingScreen(); - } - if (m_pSystem->GetIRenderer()) - { - m_pSystem->GetIRenderer()->FlushRTCommands(false, false, false); // Try to switch render thread contexts to make RT always busy during loading - } } ////////////////////////////////////////////////////////////////////////// -void CXConsole::SetLoadingImage(const char* szFilename) +void CXConsole::SetLoadingImage(const char*) { - ITexture* pTex = 0; - - pTex = m_pSystem->GetIRenderer()->EF_LoadTexture(szFilename, FT_DONT_STREAM | FT_NOMIPS); - - if (!pTex || (pTex->GetFlags() & FT_FAILED)) - { - SAFE_RELEASE(pTex); - pTex = m_pSystem->GetIRenderer()->EF_LoadTexture("Textures/Console/loadscreen_default.dds", FT_DONT_STREAM | FT_NOMIPS); - } - - if (pTex) - { - m_nLoadingBackTexID = pTex->GetTextureID(); - } - else - { - m_nLoadingBackTexID = -1; - } } ////////////////////////////////////////////////////////////////////////// @@ -3339,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/XConsole.h b/Code/CryEngine/CrySystem/XConsole.h index ed3a3e9b82..01649872ba 100644 --- a/Code/CryEngine/CrySystem/XConsole.h +++ b/Code/CryEngine/CrySystem/XConsole.h @@ -418,7 +418,6 @@ private: // ---------------------------------------------------------- CSystem* m_pSystem; IFFont* m_pFont; - IRenderer* m_pRenderer; ITimer* m_pTimer; ICVar* m_pSysDeactivateConsole; 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 bfc7b092fd..50cbdc24e4 100644 --- a/Code/CryEngine/CrySystem/crysystem_files.cmake +++ b/Code/CryEngine/CrySystem/crysystem_files.cmake @@ -19,15 +19,11 @@ set(FILES ConsoleBatchFile.cpp ConsoleHelpGen.cpp CryAsyncMemcpy.cpp - CrySizerStats.cpp - DebugCallStack.cpp GeneralMemoryHeap.cpp HandlerBase.cpp - IDebugCallStack.cpp AsyncPakManager.cpp Log.cpp SystemRender.cpp - NotificationNetwork.cpp PhysRenderer.cpp ResourceManager.cpp ServerHandler.cpp @@ -37,7 +33,6 @@ set(FILES SystemCFG.cpp SystemEventDispatcher.cpp SystemInit.cpp - SystemScheduler.cpp SystemWin32.cpp Timer.cpp UnixConsole.cpp @@ -53,31 +48,18 @@ set(FILES ServerHandler.h ServerThrottle.h SyncLock.h - SystemScheduler.h UnixConsole.h SystemInit.h - Serialization/MemoryReader.h - MemoryFragmentationProfiler.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 CmdLineArg.h ConsoleBatchFile.h ConsoleHelpGen.h - CrySizerStats.h CryWaterMark.h - DebugCallStack.h GeneralMemoryHeap.h - IDebugCallStack.h - IThreadConfigManager.h Log.h - NotificationNetwork.h resource.h SimpleStringPool.h CrySystem_precompiled.h @@ -92,13 +74,11 @@ set(FILES crash_face.bmp ImageHandler.h ImageHandler.cpp - DefragAllocator.cpp MemoryAddressRange.cpp PageMappingHeap.cpp CustomMemoryHeap.cpp MemoryManager.cpp MTSafeAllocator.cpp - DefragAllocator.h MemoryAddressRange.h PageMappingHeap.h MemoryManager.h @@ -118,58 +98,18 @@ set(FILES XML/WriteXMLSource.cpp ZipFile.h ZipFileFormat_info.h - PerfHUD.cpp - ProfileLogSystem.cpp Sampler.cpp - PerfHUD.h - 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 - ExtensionSystem/CryFactoryRegistryImpl.cpp - ExtensionSystem/CryFactoryRegistryImpl.h - ExtensionSystem/TestCases/TestExtensions.cpp - ExtensionSystem/TestCases/TestExtensions.h - MiniGUI/DrawContext.cpp - MiniGUI/MiniButton.cpp - MiniGUI/MiniGUI.cpp - MiniGUI/MiniInfoBox.cpp - MiniGUI/MiniMenu.cpp - MiniGUI/MiniTable.cpp - MiniGUI/DrawContext.h - MiniGUI/MiniButton.h - MiniGUI/MiniGUI.h - MiniGUI/MiniInfoBox.h - MiniGUI/MiniMenu.h - MiniGUI/MiniTable.h ZLibCompressor.cpp ZLibCompressor.h - SoftCode/SoftCodeMgr.cpp - SoftCode/SoftCodeMgr.h - OverloadSceneManager/OverloadSceneManager.cpp - OverloadSceneManager/OverloadSceneManager.h Huffman.cpp Huffman.h RemoteConsole/RemoteConsole.cpp 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 @@ -186,19 +126,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 - HMDCVars.h - HMDCVars.cpp StreamEngine/StreamAsyncFileRequest.cpp StreamEngine/StreamAsyncFileRequest_Jobs.cpp StreamEngine/StreamEngine.cpp @@ -210,13 +137,9 @@ set(FILES StreamEngine/StreamIOThread.h StreamEngine/StreamReadStream.h StreamEngine/AZRequestReadStream.h - VisRegTest.cpp - VisRegTest.h CrashHandler.rc CrySystem_precompiled.cpp CPUDetect.cpp CPUDetect.h - CrySizerImpl.cpp - CrySizerImpl.h WindowsErrorReporting.cpp ) diff --git a/Code/CryEngine/CrySystem/crysystem_test_files.cmake b/Code/CryEngine/CrySystem/crysystem_test_files.cmake index 650e9b0063..d8f6887da6 100644 --- a/Code/CryEngine/CrySystem/crysystem_test_files.cmake +++ b/Code/CryEngine/CrySystem/crysystem_test_files.cmake @@ -11,16 +11,12 @@ set(FILES Components/MathConversionTests.cpp - Serialization/Test_ArchiveHost.cpp Tests/Test_CLog.cpp Tests/Test_CommandRegistration.cpp Tests/Test_CryPrimitives.cpp - Tests/Test_CrySizer.cpp Tests/test_CrySystem.cpp 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/AtomCore/AtomCore/Serialization/Json/JsonUtils.cpp b/Code/Framework/AtomCore/AtomCore/Serialization/Json/JsonUtils.cpp index dbc0be55f9..dc7d26577b 100644 --- a/Code/Framework/AtomCore/AtomCore/Serialization/Json/JsonUtils.cpp +++ b/Code/Framework/AtomCore/AtomCore/Serialization/Json/JsonUtils.cpp @@ -189,7 +189,7 @@ namespace AZ if (!WasLoadSuccess(result.GetOutcome())) { // This if is a hack around fault in the JSON serialization system - // Jira: https://jira.agscollab.com/browse/LY-106587 + // Jira: LY-106587 if (message != "No part of the string could be interpreted as a uuid.") { deserializeError.append(message); 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..555eedf034 100644 --- a/Code/Framework/AzCore/AzCore/Asset/AssetJsonSerializer.cpp +++ b/Code/Framework/AzCore/AzCore/Asset/AssetJsonSerializer.cpp @@ -70,6 +70,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,14 +111,28 @@ namespace AZ AssetId id; JSR::ResultCode result(JSR::Tasks::ReadField); + SerializedAssetTracker* assetTracker = + context.GetMetadata().Find(); + + { + Data::AssetLoadBehavior loadBehavior = instance->GetAutoLoadBehavior(); + + result = + ContinueLoadingFromJsonObjectField(&loadBehavior, + azrtti_typeid(), + inputValue, "loadBehavior", context); + + instance->SetAutoLoadBehavior(loadBehavior); + } + auto it = inputValue.FindMember("assetId"); 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(), AssetLoadBehavior::NoLoad); + *instance = AssetManager::Instance().FindOrCreateAsset(id, instance->GetType(), instance->GetAutoLoadBehavior()); result.Combine(context.Report(result, "Successfully created Asset with id.")); @@ -142,6 +167,11 @@ namespace AZ "The asset hint is missing for Asset, so it will be left empty.")); } + if (assetTracker) + { + assetTracker->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 = @@ -150,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..780066cd42 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 final + { + 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/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/Component/Component.cpp b/Code/Framework/AzCore/AzCore/Component/Component.cpp index f1e8aa1fb0..498e4d03d3 100644 --- a/Code/Framework/AzCore/AzCore/Component/Component.cpp +++ b/Code/Framework/AzCore/AzCore/Component/Component.cpp @@ -14,6 +14,7 @@ #include #include #include +#include #include #include @@ -173,7 +174,11 @@ namespace AZ //========================================================================= void ComponentDescriptor::ReleaseDescriptor() { - EBUS_EVENT(ComponentApplicationBus, UnregisterComponentDescriptor, this); + AZ::ComponentApplicationRequests* componentApplication = AZ::Interface::Get(); + if (componentApplication != nullptr) + { + componentApplication->UnregisterComponentDescriptor(this); + } delete this; } } // namespace AZ diff --git a/Code/Framework/AzCore/AzCore/Component/ComponentApplication.cpp b/Code/Framework/AzCore/AzCore/Component/ComponentApplication.cpp index d0f277a6b8..daf5b5efd2 100644 --- a/Code/Framework/AzCore/AzCore/Component/ComponentApplication.cpp +++ b/Code/Framework/AzCore/AzCore/Component/ComponentApplication.cpp @@ -526,6 +526,11 @@ namespace AZ // are destroyed m_commandLine = {}; + m_entityAddedEvent.DisconnectAllHandlers(); + m_entityRemovedEvent.DisconnectAllHandlers(); + m_entityActivatedEvent.DisconnectAllHandlers(); + m_entityDeactivatedEvent.DisconnectAllHandlers(); + DestroyAllocator(); } @@ -980,6 +985,26 @@ namespace AZ handler.Connect(m_entityRemovedEvent); } + void ComponentApplication::RegisterEntityActivatedEventHandler(EntityActivatedEvent::Handler& handler) + { + handler.Connect(m_entityActivatedEvent); + } + + void ComponentApplication::RegisterEntityDeactivatedEventHandler(EntityDeactivatedEvent::Handler& handler) + { + handler.Connect(m_entityDeactivatedEvent); + } + + void ComponentApplication::SignalEntityActivated(AZ::Entity* entity) + { + m_entityActivatedEvent.Signal(entity); + } + + void ComponentApplication::SignalEntityDeactivated(AZ::Entity* entity) + { + m_entityDeactivatedEvent.Signal(entity); + } + //========================================================================= // AddEntity // [5/30/2012] diff --git a/Code/Framework/AzCore/AzCore/Component/ComponentApplication.h b/Code/Framework/AzCore/AzCore/Component/ComponentApplication.h index 8617aa5f2e..fac2867074 100644 --- a/Code/Framework/AzCore/AzCore/Component/ComponentApplication.h +++ b/Code/Framework/AzCore/AzCore/Component/ComponentApplication.h @@ -204,6 +204,10 @@ namespace AZ void UnregisterComponentDescriptor(const ComponentDescriptor* descriptor) override final; void RegisterEntityAddedEventHandler(EntityAddedEvent::Handler& handler) override final; void RegisterEntityRemovedEventHandler(EntityRemovedEvent::Handler& handler) override final; + void RegisterEntityActivatedEventHandler(EntityActivatedEvent::Handler& handler) override final; + void RegisterEntityDeactivatedEventHandler(EntityDeactivatedEvent::Handler& handler) override final; + void SignalEntityActivated(Entity* entity) override final; + void SignalEntityDeactivated(Entity* entity) override final; bool AddEntity(Entity* entity) override; bool RemoveEntity(Entity* entity) override; bool DeleteEntity(const EntityId& id) override; @@ -382,6 +386,8 @@ namespace AZ AZStd::unique_ptr m_settingsRegistry; EntityAddedEvent m_entityAddedEvent; EntityRemovedEvent m_entityRemovedEvent; + EntityAddedEvent m_entityActivatedEvent; + EntityRemovedEvent m_entityDeactivatedEvent; AZ::IConsole* m_console{}; Descriptor m_descriptor; bool m_isStarted{ false }; diff --git a/Code/Framework/AzCore/AzCore/Component/ComponentApplicationBus.h b/Code/Framework/AzCore/AzCore/Component/ComponentApplicationBus.h index 3582e6ebb8..c93f07f347 100644 --- a/Code/Framework/AzCore/AzCore/Component/ComponentApplicationBus.h +++ b/Code/Framework/AzCore/AzCore/Component/ComponentApplicationBus.h @@ -72,6 +72,8 @@ namespace AZ using EntityAddedEvent = AZ::Event; using EntityRemovedEvent = AZ::Event; + using EntityActivatedEvent = AZ::Event; + using EntityDeactivatedEvent = AZ::Event; //! Interface that components can use to make requests of the main application. class ComponentApplicationRequests @@ -102,6 +104,22 @@ namespace AZ //! @param handler the event handler to signal. virtual void RegisterEntityRemovedEventHandler(EntityRemovedEvent::Handler& handler) = 0; + //! Registers an event handler that will be signalled whenever an entity is added. + //! @param handler the event handler to signal. + virtual void RegisterEntityActivatedEventHandler(EntityActivatedEvent::Handler& handler) = 0; + + //! Registers an event handler that will be signalled whenever an entity is removed. + //! @param handler the event handler to signal. + virtual void RegisterEntityDeactivatedEventHandler(EntityDeactivatedEvent::Handler& handler) = 0; + + //! Signals that the provided entity has been activated. + //! @param entity the entity being activated. + virtual void SignalEntityActivated(AZ::Entity* entity) = 0; + + //! Signals that the provided entity has been deactivated. + //! @param entity the entity being deactivated. + virtual void SignalEntityDeactivated(AZ::Entity* entity) = 0; + //! Adds an entity to the application's registry. //! Calling Init() on an entity automatically performs this operation. //! @param entity A pointer to the entity to add to the application's registry. diff --git a/Code/Framework/AzCore/AzCore/Component/Entity.cpp b/Code/Framework/AzCore/AzCore/Component/Entity.cpp index b18474e428..b7c161b53c 100644 --- a/Code/Framework/AzCore/AzCore/Component/Entity.cpp +++ b/Code/Framework/AzCore/AzCore/Component/Entity.cpp @@ -112,7 +112,11 @@ namespace AZ { EBUS_EVENT(EntitySystemBus, OnEntityDestruction, m_id); EBUS_EVENT_ID(m_id, EntityBus, OnEntityDestruction, m_id); - EBUS_EVENT(ComponentApplicationBus, RemoveEntity, this); + AZ::ComponentApplicationRequests* componentApplication = AZ::Interface::Get(); + if (componentApplication != nullptr) + { + componentApplication->RemoveEntity(this); + } m_stateEvent.Signal(State::Init, State::Destroying); } @@ -216,12 +220,22 @@ namespace AZ EBUS_EVENT_ID(m_id, EntityBus, OnEntityActivated, m_id); EBUS_EVENT(EntitySystemBus, OnEntityActivated, m_id); + AZ::ComponentApplicationRequests* componentApplication = AZ::Interface::Get(); + if (componentApplication != nullptr) + { + componentApplication->SignalEntityActivated(this); + } } void Entity::Deactivate() { AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzCore); + AZ::ComponentApplicationRequests* componentApplication = AZ::Interface::Get(); + if (componentApplication != nullptr) + { + componentApplication->SignalEntityDeactivated(this); + } EBUS_EVENT_ID(m_id, EntityBus, OnEntityDeactivated, m_id); EBUS_EVENT(EntitySystemBus, OnEntityDeactivated, m_id); diff --git a/Code/Framework/AzCore/AzCore/Console/LoggerSystemComponent.cpp b/Code/Framework/AzCore/AzCore/Console/LoggerSystemComponent.cpp index 6c142975e0..c004e2c406 100644 --- a/Code/Framework/AzCore/AzCore/Console/LoggerSystemComponent.cpp +++ b/Code/Framework/AzCore/AzCore/Console/LoggerSystemComponent.cpp @@ -126,9 +126,11 @@ namespace AZ char buffer[MaxLogBufferSize]; const AZStd::size_t length = azvsnprintf(buffer, MaxLogBufferSize, format, args); - buffer[AZStd::min(length, MaxLogBufferSize - 2)] = '\n'; buffer[AZStd::min(length + 1, MaxLogBufferSize - 1)] = '\0'; + m_logEvent.Signal(level, buffer, file, function, line); + // Force a new-line before calling the AZ::Debug::Trace functions, as they assume a newline is present + buffer[AZStd::min(length + 1, MaxLogBufferSize - 2)] = '\n'; switch (level) { case LogLevel::Warn: @@ -142,8 +144,6 @@ namespace AZ AZ::Debug::Trace::Output("Logger", buffer); break; } - - m_logEvent.Signal(level, buffer, file, function, line); } void LoggerSystemComponent::SetLevel(const AZ::ConsoleCommandContainer& arguments) diff --git a/Code/Framework/AzCore/AzCore/EBus/Event.inl b/Code/Framework/AzCore/AzCore/EBus/Event.inl index 82f5645ccd..3786f1c26b 100644 --- a/Code/Framework/AzCore/AzCore/EBus/Event.inl +++ b/Code/Framework/AzCore/AzCore/EBus/Event.inl @@ -233,6 +233,14 @@ namespace AZ AZ_Assert(handler->m_event == this, "Entry event does not match"); handler->Disconnect(); } + + // Free up any owned memory + AZStd::vector freeHandlers; + m_handlers.swap(freeHandlers); + AZStd::vector freeAdds; + m_addList.swap(freeAdds); + AZStd::stack freeFree; + m_freeList.swap(freeFree); } diff --git a/Code/Framework/AzCore/AzCore/Math/MathUtils.h b/Code/Framework/AzCore/AzCore/Math/MathUtils.h index 4a331e4a83..a7fedf5ffa 100644 --- a/Code/Framework/AzCore/AzCore/Math/MathUtils.h +++ b/Code/Framework/AzCore/AzCore/Math/MathUtils.h @@ -13,16 +13,17 @@ #pragma once #include +#include +#include +#include #include #include #include -#include + #include #include -#include +#include #include -#include -#include // We have a separate inline define for math functions. // The performance of these functions is very sensitive to inlining, and some compilers don't deal well with this. @@ -308,12 +309,12 @@ namespace AZ AZ_MATH_INLINE bool IsClose(float a, float b, float tolerance = Constants::Tolerance) { - return (fabsf(a - b) <= tolerance); + return (AZStd::abs(a - b) <= tolerance); } AZ_MATH_INLINE bool IsClose(double a, double b, double tolerance = Constants::Tolerance) { - return (fabs(a - b) <= tolerance); + return (AZStd::abs(a - b) <= tolerance); } //! Returns x >= 0.0f ? 1.0f : -1.0f. @@ -402,12 +403,12 @@ namespace AZ AZ_MATH_INLINE float GetAbs(float a) { - return fabsf(a); + return AZStd::abs(a); } AZ_MATH_INLINE double GetAbs(double a) { - return std::abs(a); + return AZStd::abs(a); } AZ_MATH_INLINE float GetMod(float a, float b) @@ -441,7 +442,7 @@ namespace AZ template AZ_MATH_INLINE bool IsCloseMag(T x, T y, T epsilonValue = std::numeric_limits::epsilon()) { - return (std::fabs(x - y) <= epsilonValue * GetMax(GetMax(T(1.0), std::fabs(x)), std::fabs(y))); + return (AZStd::abs(x - y) <= epsilonValue * GetMax(GetMax(T(1.0), AZStd::abs(x)), AZStd::abs(y))); } //! ClampIfCloseMag(x, y, epsilon) returns y when x and y are within epsilon of each other (taking magnitude into account). Otherwise returns x. 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/UnitTest/MockComponentApplication.h b/Code/Framework/AzCore/AzCore/UnitTest/MockComponentApplication.h index e15071f56c..873bb5ad22 100644 --- a/Code/Framework/AzCore/AzCore/UnitTest/MockComponentApplication.h +++ b/Code/Framework/AzCore/AzCore/UnitTest/MockComponentApplication.h @@ -33,6 +33,10 @@ namespace UnitTest 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&)); diff --git a/Code/Framework/AzCore/AzCore/Utils/Utils.cpp b/Code/Framework/AzCore/AzCore/Utils/Utils.cpp index 71f01cb349..7025b3977e 100644 --- a/Code/Framework/AzCore/AzCore/Utils/Utils.cpp +++ b/Code/Framework/AzCore/AzCore/Utils/Utils.cpp @@ -169,5 +169,10 @@ namespace AZ::Utils template AZ::Outcome, AZStd::string> ReadFile(AZStd::string_view filePath, size_t maxFileSize); template AZ::Outcome, AZStd::string> ReadFile(AZStd::string_view filePath, size_t maxFileSize); - + AZ::IO::FixedMaxPathString GetO3deManifestDirectory() + { + AZ::IO::FixedMaxPath path = GetHomeDirectory(); + path /= ".o3de"; + return path.Native(); + } } diff --git a/Code/Framework/AzCore/AzCore/Utils/Utils.h b/Code/Framework/AzCore/AzCore/Utils/Utils.h index f6152d0e9b..4e64ce5a39 100644 --- a/Code/Framework/AzCore/AzCore/Utils/Utils.h +++ b/Code/Framework/AzCore/AzCore/Utils/Utils.h @@ -88,6 +88,9 @@ namespace AZ //! Retrieves the project name from the settings registry AZ::SettingsRegistryInterface::FixedValueString GetProjectName(); + //! Retrieves the full directory to the Home directory, i.e. " or overrideHomeDirectory" + AZ::IO::FixedMaxPathString GetHomeDirectory(); + //! Retrieves the full directory to the O3DE manifest directory, i.e. "/.o3de" AZ::IO::FixedMaxPathString GetO3deManifestDirectory(); diff --git a/Code/Framework/AzCore/AzCore/std/azstd_files.cmake b/Code/Framework/AzCore/AzCore/std/azstd_files.cmake index 8de54138ee..ebf26cad68 100644 --- a/Code/Framework/AzCore/AzCore/std/azstd_files.cmake +++ b/Code/Framework/AzCore/AzCore/std/azstd_files.cmake @@ -31,6 +31,7 @@ set(FILES iterator.h limits.h numeric.h + math.h optional.h ratio.h reference_wrapper.h diff --git a/Code/Framework/AzCore/AzCore/std/math.h b/Code/Framework/AzCore/AzCore/std/math.h new file mode 100644 index 0000000000..9e9be7944a --- /dev/null +++ b/Code/Framework/AzCore/AzCore/std/math.h @@ -0,0 +1,31 @@ +/* + * All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or + * its licensors. + * + * For complete copyright and license terms please see the LICENSE at the root of this + * distribution (the "License"). All use of this software is governed by the License, + * or, if provided, by the license below or the license accompanying this file. Do not + * remove or 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 AZStd +{ + using std::abs; + using std::acos; + using std::asin; + using std::atan; + using std::atan2; + using std::cos; + using std::exp2; + using std::fmod; + using std::round; + using std::sin; + using std::sqrt; + using std::tan; +} // namespace AZStd diff --git a/Code/Framework/AzCore/Platform/Common/Unimplemented/AzCore/Utils/Utils_Unimplemented.cpp b/Code/Framework/AzCore/Platform/Common/Unimplemented/AzCore/Utils/Utils_Unimplemented.cpp index 20a9edbe2c..0ea17e938a 100644 --- a/Code/Framework/AzCore/Platform/Common/Unimplemented/AzCore/Utils/Utils_Unimplemented.cpp +++ b/Code/Framework/AzCore/Platform/Common/Unimplemented/AzCore/Utils/Utils_Unimplemented.cpp @@ -14,7 +14,7 @@ namespace AZ::Utils { - AZ::IO::FixedMaxPathString GetO3deManifestDirectory() + AZ::IO::FixedMaxPathString GetHomeDirectory() { return {}; } diff --git a/Code/Framework/AzCore/Platform/Common/UnixLike/AzCore/Utils/Utils_UnixLike.cpp b/Code/Framework/AzCore/Platform/Common/UnixLike/AzCore/Utils/Utils_UnixLike.cpp index 2763baac1d..9dbe8f7264 100644 --- a/Code/Framework/AzCore/Platform/Common/UnixLike/AzCore/Utils/Utils_UnixLike.cpp +++ b/Code/Framework/AzCore/Platform/Common/UnixLike/AzCore/Utils/Utils_UnixLike.cpp @@ -25,8 +25,19 @@ namespace AZ void NativeErrorMessageBox(const char*, const char*) {} - AZ::IO::FixedMaxPathString GetO3deManifestDirectory() + AZ::IO::FixedMaxPathString GetHomeDirectory() { + constexpr AZStd::string_view overrideHomeDirKey = "/Amazon/Settings/override_home_dir"; + AZ::IO::FixedMaxPathString overrideHomeDir; + if (auto settingsRegistry = AZ::SettingsRegistry::Get(); settingsRegistry != nullptr) + { + if (settingsRegistry->Get(overrideHomeDir, overrideHomeDirKey)) + { + AZ::IO::FixedMaxPath path{overrideHomeDir}; + return path.Native(); + } + } + if (const char* homePath = std::getenv("HOME"); homePath != nullptr) { AZ::IO::FixedMaxPath path{homePath}; diff --git a/Code/Framework/AzCore/Platform/Windows/AzCore/Utils/Utils_Windows.cpp b/Code/Framework/AzCore/Platform/Windows/AzCore/Utils/Utils_Windows.cpp index 2ade67955b..18cef227db 100644 --- a/Code/Framework/AzCore/Platform/Windows/AzCore/Utils/Utils_Windows.cpp +++ b/Code/Framework/AzCore/Platform/Windows/AzCore/Utils/Utils_Windows.cpp @@ -22,15 +22,25 @@ namespace AZ::Utils ::MessageBox(0, message, title, MB_OK | MB_ICONERROR); } - AZ::IO::FixedMaxPathString GetO3deManifestDirectory() + AZ::IO::FixedMaxPathString GetHomeDirectory() { + constexpr AZStd::string_view overrideHomeDirKey = "/Amazon/Settings/override_home_dir"; + AZ::IO::FixedMaxPathString overrideHomeDir; + if (auto settingsRegistry = AZ::SettingsRegistry::Get(); settingsRegistry != nullptr) + { + if (settingsRegistry->Get(overrideHomeDir, overrideHomeDirKey)) + { + AZ::IO::FixedMaxPath path{overrideHomeDir}; + return path.Native(); + } + } + char userProfileBuffer[AZ::IO::MaxPathLength]{}; size_t variableSize = 0; auto err = getenv_s(&variableSize, userProfileBuffer, AZ::IO::MaxPathLength, "USERPROFILE"); if (!err) { AZ::IO::FixedMaxPath path{ userProfileBuffer }; - path /= ".o3de"; return path.Native(); } 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 diff --git a/Code/Framework/AzCore/Tests/AssetJsonSerializerTests.cpp b/Code/Framework/AzCore/Tests/AssetJsonSerializerTests.cpp index e44f77b119..3e4ddac3af 100644 --- a/Code/Framework/AzCore/Tests/AssetJsonSerializerTests.cpp +++ b/Code/Framework/AzCore/Tests/AssetJsonSerializerTests.cpp @@ -135,6 +135,7 @@ namespace JsonSerializationTests auto instance = AZStd::make_shared(); instance->Create(id, false); instance->SetHint("TestFile"); + instance->SetAutoLoadBehavior(AZ::Data::AssetLoadBehavior::PreLoad); return instance; } @@ -158,6 +159,7 @@ namespace JsonSerializationTests "guid": "{BBEAC89F-8BAD-4A9D-BF6E-D0DF84A8DFD6}", "subId": 1 }, + "loadBehavior": "PreLoad", "assetHint": "TestFile" })"; } diff --git a/Code/Framework/AzCore/Tests/BehaviorContextFixture.h b/Code/Framework/AzCore/Tests/BehaviorContextFixture.h index 687aee8aa4..6ae97e1304 100644 --- a/Code/Framework/AzCore/Tests/BehaviorContextFixture.h +++ b/Code/Framework/AzCore/Tests/BehaviorContextFixture.h @@ -49,9 +49,13 @@ namespace UnitTest // ComponentApplicationBus AZ::ComponentApplication* GetApplication() override { return nullptr; } void RegisterComponentDescriptor(const AZ::ComponentDescriptor*) override {} + void UnregisterComponentDescriptor(const AZ::ComponentDescriptor*) override {} void RegisterEntityAddedEventHandler(AZ::EntityAddedEvent::Handler&) override {} void RegisterEntityRemovedEventHandler(AZ::EntityRemovedEvent::Handler&) override {} - void UnregisterComponentDescriptor(const AZ::ComponentDescriptor*) override {} + void RegisterEntityActivatedEventHandler(AZ::EntityActivatedEvent::Handler&) override {} + void RegisterEntityDeactivatedEventHandler(AZ::EntityDeactivatedEvent::Handler&) override {} + void SignalEntityActivated(AZ::Entity*) override {} + void SignalEntityDeactivated(AZ::Entity*) override {} bool AddEntity(AZ::Entity*) override { return true; } bool RemoveEntity(AZ::Entity*) override { return true; } bool DeleteEntity(const AZ::EntityId&) override { return true; } diff --git a/Code/Framework/AzCore/Tests/Serialization.cpp b/Code/Framework/AzCore/Tests/Serialization.cpp index 35cf17c2e0..036942f9dd 100644 --- a/Code/Framework/AzCore/Tests/Serialization.cpp +++ b/Code/Framework/AzCore/Tests/Serialization.cpp @@ -1232,6 +1232,10 @@ namespace UnitTest void UnregisterComponentDescriptor(const ComponentDescriptor*) override { } void RegisterEntityAddedEventHandler(EntityAddedEvent::Handler&) override { } void RegisterEntityRemovedEventHandler(EntityRemovedEvent::Handler&) override { } + void RegisterEntityActivatedEventHandler(EntityActivatedEvent::Handler&) override { } + void RegisterEntityDeactivatedEventHandler(EntityDeactivatedEvent::Handler&) override { } + void SignalEntityActivated(Entity*) override { } + void SignalEntityDeactivated(Entity*) override { } bool AddEntity(Entity*) override { return false; } bool RemoveEntity(Entity*) override { return false; } bool DeleteEntity(const EntityId&) override { return false; } @@ -1252,6 +1256,7 @@ namespace UnitTest m_serializeContext.reset(aznew AZ::SerializeContext()); ComponentApplicationBus::Handler::BusConnect(); + AZ::Interface::Register(this); AZ::AllocatorInstance::Create(); AZ::AllocatorInstance::Create(); @@ -1270,6 +1275,7 @@ namespace UnitTest AZ::AllocatorInstance::Destroy(); AZ::AllocatorInstance::Destroy(); + AZ::Interface::Unregister(this); ComponentApplicationBus::Handler::BusDisconnect(); } 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/Archive/ArchiveVars.h b/Code/Framework/AzFramework/AzFramework/Archive/ArchiveVars.h index fd72c37b60..4e89e0a45c 100644 --- a/Code/Framework/AzFramework/AzFramework/Archive/ArchiveVars.h +++ b/Code/Framework/AzFramework/AzFramework/Archive/ArchiveVars.h @@ -51,7 +51,6 @@ namespace AZ::IO : ArchiveLocationPriority::ePakPriorityFileFirst }; // Which file location to favor (loose vs. pak files) int nMessageInvalidFileAccess{}; int nLogInvalidFileAccess{ IsReleaseConfig ? 0 : 1 }; - int nLoadFrontendShaderCache{ FRONTEND_SHADER_CACHE_DEFAULT }; int nDisableNonLevelRelatedPaks{ 1 }; int nWarnOnPakAccessFails{ 1 }; // Whether to treat failed pak access as a warning or log message int nSetLogLevel{ 3 }; 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 910d6749af..3c05887a89 100644 --- a/Code/Framework/AzFramework/AzFramework/Components/TransformComponent.cpp +++ b/Code/Framework/AzFramework/AzFramework/Components/TransformComponent.cpp @@ -11,10 +11,12 @@ */ #include +#include #include #include #include #include +#include #include #include @@ -693,9 +695,8 @@ namespace AzFramework parentId = handler->GetParentId(); } #endif - - AZ::Entity* parentEntity = nullptr; - EBUS_EVENT_RESULT(parentEntity, AZ::ComponentApplicationBus, FindEntity, parentEntityId); + AZ::ComponentApplicationRequests* componentApplication = AZ::Interface::Get(); + AZ::Entity* parentEntity = (componentApplication != nullptr) ? componentApplication->FindEntity(parentEntityId) : nullptr; AZ_Assert(parentEntity, "We expect to have a parent entity associated with the provided parent's entity Id."); if (parentEntity) { @@ -744,8 +745,8 @@ namespace AzFramework m_parentId = parentId; if (m_parentId.IsValid()) { - AZ::Entity* parentEntity = nullptr; - AZ::ComponentApplicationBus::BroadcastResult(parentEntity, &AZ::ComponentApplicationBus::Events::FindEntity, m_parentId); + AZ::ComponentApplicationRequests* componentApplication = AZ::Interface::Get(); + AZ::Entity* parentEntity = (componentApplication != nullptr) ? componentApplication->FindEntity(m_parentId) : nullptr; m_parentActive = parentEntity && (parentEntity->GetState() == AZ::Entity::State::Active); m_onNewParentKeepWorldTM = isKeepWorldTM; @@ -832,6 +833,12 @@ namespace AzFramework EBUS_EVENT_PTR(m_notificationBus, AZ::TransformNotificationBus, OnTransformChanged, m_localTM, m_worldTM); m_transformChangedEvent.Signal(m_localTM, m_worldTM); + + AzFramework::IEntityBoundsUnion* boundsUnion = AZ::Interface::Get(); + if (boundsUnion != nullptr) + { + boundsUnion->OnTransformUpdated(GetEntity()); + } } void TransformComponent::ComputeWorldTM() @@ -871,15 +878,15 @@ namespace AzFramework AZ::SerializeContext* serializeContext = azrtti_cast(reflection); if (serializeContext) { - serializeContext->Class() + serializeContext->ClassDeprecate("NetBindable", "{80206665-D429-4703-B42E-94434F82F381}"); + + 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/Entity/GameEntityContextComponent.cpp b/Code/Framework/AzFramework/AzFramework/Entity/GameEntityContextComponent.cpp index 999013fdf8..461d578e28 100644 --- a/Code/Framework/AzFramework/AzFramework/Entity/GameEntityContextComponent.cpp +++ b/Code/Framework/AzFramework/AzFramework/Entity/GameEntityContextComponent.cpp @@ -93,6 +93,8 @@ namespace AzFramework InitContext(); GameEntityContextRequestBus::Handler::BusConnect(); + + m_entityVisibilityBoundsUnionSystem.Connect(); } //========================================================================= @@ -100,6 +102,8 @@ namespace AzFramework //========================================================================= void GameEntityContextComponent::Deactivate() { + m_entityVisibilityBoundsUnionSystem.Disconnect(); + GameEntityContextRequestBus::Handler::BusDisconnect(); DestroyContext(); diff --git a/Code/Framework/AzFramework/AzFramework/Entity/GameEntityContextComponent.h b/Code/Framework/AzFramework/AzFramework/Entity/GameEntityContextComponent.h index 482b2133ca..35424fd09c 100644 --- a/Code/Framework/AzFramework/AzFramework/Entity/GameEntityContextComponent.h +++ b/Code/Framework/AzFramework/AzFramework/Entity/GameEntityContextComponent.h @@ -18,6 +18,7 @@ #include #include #include +#include #include "EntityContext.h" @@ -91,6 +92,9 @@ namespace AzFramework { required.push_back(AZ_CRC("SliceSystemService", 0x1a5b7aad)); } + + private: + AzFramework::EntityVisibilityBoundsUnionSystem m_entityVisibilityBoundsUnionSystem; }; } // namespace AzFramework 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/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/Render/Intersector.cpp b/Code/Framework/AzFramework/AzFramework/Render/Intersector.cpp index 23d74f7578..143c1f7916 100644 --- a/Code/Framework/AzFramework/AzFramework/Render/Intersector.cpp +++ b/Code/Framework/AzFramework/AzFramework/Render/Intersector.cpp @@ -139,7 +139,8 @@ namespace AzFramework "Implementers of IntersectionRequestBus must also implement BoundsRequestBus to ensure valid " "bounds are returned"); - m_registeredEntities.Update({ entityId, CalculateEntityWorldBoundsUnion(entityId) }); + AZ::Entity* entity = AZ::Interface::Get()->FindEntity(entityId); + m_registeredEntities.Update({ entityId, CalculateEntityWorldBoundsUnion(entity) }); } m_dirtyEntities.clear(); 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))); + 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); - bool readValue = false; - - if (netBindingTable != nullptr) + 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); - } - } - - 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_pushvalue(lua, lookupKey); 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); - } } - - // 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); - - // Cache the value so that subsequent accesses to this property don't result in warnings - lua_rawset(lua, lookupTable); } + + 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)) + { + // 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); + + // 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); + 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/Viewport/CameraInput.cpp b/Code/Framework/AzFramework/AzFramework/Viewport/CameraInput.cpp index e9dace3433..8669b58911 100644 --- a/Code/Framework/AzFramework/AzFramework/Viewport/CameraInput.cpp +++ b/Code/Framework/AzFramework/AzFramework/Viewport/CameraInput.cpp @@ -29,14 +29,14 @@ namespace AzFramework AZ_CVAR(float, ed_cameraSystemOrbitDollyScrollSpeed, 0.02f, nullptr, AZ::ConsoleFunctorFlags::Null, ""); AZ_CVAR(float, ed_cameraSystemOrbitDollyCursorSpeed, 0.01f, nullptr, AZ::ConsoleFunctorFlags::Null, ""); AZ_CVAR(float, ed_cameraSystemScrollTranslateSpeed, 0.02f, nullptr, AZ::ConsoleFunctorFlags::Null, ""); - AZ_CVAR(float, ed_cameraSystemDefaultOrbitDistance, 60.0f, nullptr, AZ::ConsoleFunctorFlags::Null, ""); - AZ_CVAR(float, ed_cameraSystemMaxOrbitDistance, 100.0f, nullptr, AZ::ConsoleFunctorFlags::Null, ""); + AZ_CVAR(float, ed_cameraSystemMaxOrbitDistance, 60.0f, nullptr, AZ::ConsoleFunctorFlags::Null, ""); AZ_CVAR(float, ed_cameraSystemLookSmoothness, 5.0f, nullptr, AZ::ConsoleFunctorFlags::Null, ""); AZ_CVAR(float, ed_cameraSystemTranslateSmoothness, 5.0f, nullptr, AZ::ConsoleFunctorFlags::Null, ""); AZ_CVAR(float, ed_cameraSystemRotateSpeed, 0.005f, nullptr, AZ::ConsoleFunctorFlags::Null, ""); AZ_CVAR(float, ed_cameraSystemPanSpeed, 0.01f, nullptr, AZ::ConsoleFunctorFlags::Null, ""); AZ_CVAR(bool, ed_cameraSystemPanInvertX, true, nullptr, AZ::ConsoleFunctorFlags::Null, ""); AZ_CVAR(bool, ed_cameraSystemPanInvertY, true, nullptr, AZ::ConsoleFunctorFlags::Null, ""); + AZ_CVAR(float, ed_cameraSystemLookDeadzone, 2.0f, nullptr, AZ::ConsoleFunctorFlags::Null, ""); AZ_CVAR( AZ::CVarFixedString, ed_cameraSystemTranslateForwardKey, "keyboard_key_alphanumeric_W", nullptr, AZ::ConsoleFunctorFlags::Null, ""); @@ -125,22 +125,22 @@ namespace AzFramework { if (orientation.GetElement(2, 0) > -1.0f) { - x = std::atan2(orientation.GetElement(2, 1), orientation.GetElement(2, 2)); - y = std::asin(-orientation.GetElement(2, 0)); - z = std::atan2(orientation.GetElement(1, 0), orientation.GetElement(0, 0)); + x = AZStd::atan2(orientation.GetElement(2, 1), orientation.GetElement(2, 2)); + y = AZStd::asin(-orientation.GetElement(2, 0)); + z = AZStd::atan2(orientation.GetElement(1, 0), orientation.GetElement(0, 0)); } else { x = 0.0f; y = AZ::Constants::Pi * 0.5f; - z = -std::atan2(-orientation.GetElement(2, 1), orientation.GetElement(1, 1)); + z = -AZStd::atan2(-orientation.GetElement(2, 1), orientation.GetElement(1, 1)); } } else { x = 0.0f; y = -AZ::Constants::Pi * 0.5f; - z = std::atan2(-orientation.GetElement(1, 2), orientation.GetElement(1, 1)); + z = AZStd::atan2(-orientation.GetElement(1, 2), orientation.GetElement(1, 1)); } return {x, y, z}; @@ -150,31 +150,35 @@ namespace AzFramework { const auto eulerAngles = AzFramework::EulerAngles(AZ::Matrix3x3::CreateFromTransform(transform)); - camera.m_lookAt = transform.GetTranslation(); camera.m_pitch = eulerAngles.GetX(); camera.m_yaw = eulerAngles.GetZ(); + // note: m_lookDist is negative so we must invert it here + 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_motion = AZStd::get_if(&event)) + if (const auto& cursor = AZStd::get_if(&event)) { - m_currentCursorPosition = cursor_motion->m_position; + m_currentCursorPosition = cursor->m_position; } else if (const auto& scroll = AZStd::get_if(&event)) { m_scrollDelta = scroll->m_delta; } - return m_cameras.HandleEvents(event); + return m_cameras.HandleEvents(event, CursorDelta(m_currentCursorPosition, m_lastCursorPosition), m_scrollDelta); } Camera CameraSystem::StepCamera(const Camera& targetCamera, const float deltaTime) { - const auto cursorDelta = m_currentCursorPosition.has_value() && m_lastCursorPosition.has_value() - ? m_currentCursorPosition.value() - m_lastCursorPosition.value() - : ScreenVector(0, 0); - + const auto cursorDelta = CursorDelta(m_currentCursorPosition, m_lastCursorPosition); if (m_currentCursorPosition.has_value()) { m_lastCursorPosition = m_currentCursorPosition; @@ -192,18 +196,18 @@ namespace AzFramework m_idleCameraInputs.push_back(AZStd::move(cameraInput)); } - bool Cameras::HandleEvents(const InputEvent& event) + bool Cameras::HandleEvents(const InputEvent& event, const ScreenVector& cursorDelta, float scrollDelta) { bool handling = false; for (auto& cameraInput : m_activeCameraInputs) { - cameraInput->HandleEvents(event); + cameraInput->HandleEvents(event, cursorDelta, scrollDelta); handling = !cameraInput->Idle() || handling; } for (auto& cameraInput : m_idleCameraInputs) { - cameraInput->HandleEvents(event); + cameraInput->HandleEvents(event, cursorDelta, scrollDelta); } return handling; @@ -215,8 +219,8 @@ namespace AzFramework { auto& cameraInput = m_idleCameraInputs[i]; const bool canBegin = cameraInput->Beginning() && - std::all_of(m_activeCameraInputs.cbegin(), m_activeCameraInputs.cend(), - [](const auto& input) { return !input->Exclusive(); }) && + AZStd::all_of(m_activeCameraInputs.cbegin(), m_activeCameraInputs.cend(), + [](const auto& input) { return !input->Exclusive(); }) && (!cameraInput->Exclusive() || (cameraInput->Exclusive() && m_activeCameraInputs.empty())); if (canBegin) @@ -271,7 +275,7 @@ namespace AzFramework } } - void RotateCameraInput::HandleEvents(const InputEvent& event) + void RotateCameraInput::HandleEvents(const InputEvent& event, const ScreenVector& cursorDelta, [[maybe_unused]] float scrollDelta) { if (const auto& input = AZStd::get_if(&event)) { @@ -279,14 +283,27 @@ namespace AzFramework { if (input->m_state == InputChannel::State::Began) { - BeginActivation(); + m_tryingToBegin = true; + m_moveAccumulator = 0.0f; } else if (input->m_state == InputChannel::State::Ended) { + m_tryingToBegin = false; EndActivation(); } } } + + if (m_tryingToBegin) + { + // 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; + } + } } Camera RotateCameraInput::StepCamera( @@ -298,7 +315,7 @@ namespace AzFramework nextCamera.m_pitch -= float(cursorDelta.m_y) * ed_cameraSystemRotateSpeed; nextCamera.m_yaw -= float(cursorDelta.m_x) * ed_cameraSystemRotateSpeed; - const auto clampRotation = [](const float angle) { return std::fmod(angle + AZ::Constants::TwoPi, AZ::Constants::TwoPi); }; + const auto clampRotation = [](const float angle) { return AZStd::fmod(angle + AZ::Constants::TwoPi, AZ::Constants::TwoPi); }; nextCamera.m_yaw = clampRotation(nextCamera.m_yaw); // clamp pitch to be +-90 degrees @@ -307,7 +324,8 @@ namespace AzFramework return nextCamera; } - void PanCameraInput::HandleEvents(const InputEvent& event) + void PanCameraInput::HandleEvents( + const InputEvent& event, [[maybe_unused]] const ScreenVector& cursorDelta, [[maybe_unused]] float scrollDelta) { if (const auto& input = AZStd::get_if(&event)) { @@ -382,17 +400,13 @@ namespace AzFramework return TranslationType::Nil; } - void TranslateCameraInput::HandleEvents(const InputEvent& event) + void TranslateCameraInput::HandleEvents( + const InputEvent& event, [[maybe_unused]] const ScreenVector& cursorDelta, [[maybe_unused]] float scrollDelta) { if (const auto& input = AZStd::get_if(&event)) { 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) { @@ -478,7 +492,7 @@ namespace AzFramework m_boost = false; } - void OrbitCameraInput::HandleEvents(const InputEvent& event) + void OrbitCameraInput::HandleEvents(const InputEvent& event, const ScreenVector& cursorDelta, float scrollDelta) { if (const auto* input = AZStd::get_if(&event)) { @@ -497,7 +511,7 @@ namespace AzFramework if (Active()) { - m_orbitCameras.HandleEvents(event); + m_orbitCameras.HandleEvents(event, cursorDelta, scrollDelta); } } @@ -509,8 +523,10 @@ namespace AzFramework if (Beginning()) { float hit_distance = 0.0f; - if (AZ::Plane::CreateFromNormalAndPoint(AZ::Vector3::CreateAxisZ(), AZ::Vector3::CreateAxisZ(ed_cameraSystemDefaultPlaneHeight)) - .CastRay(targetCamera.Translation(), targetCamera.Rotation().GetBasisY(), hit_distance)) + AZ::Plane::CreateFromNormalAndPoint(AZ::Vector3::CreateAxisZ(), AZ::Vector3::CreateAxisZ(ed_cameraSystemDefaultPlaneHeight)) + .CastRay(targetCamera.Translation(), targetCamera.Rotation().GetBasisY(), hit_distance); + + if (hit_distance > 0.0f) { hit_distance = AZStd::min(hit_distance, ed_cameraSystemMaxOrbitDistance); nextCamera.m_lookDist = -hit_distance; @@ -539,7 +555,8 @@ namespace AzFramework return nextCamera; } - void OrbitDollyScrollCameraInput::HandleEvents(const InputEvent& event) + void OrbitDollyScrollCameraInput::HandleEvents( + const InputEvent& event, [[maybe_unused]] const ScreenVector& cursorDelta, [[maybe_unused]] float scrollDelta) { if (const auto* scroll = AZStd::get_if(&event)) { @@ -557,7 +574,8 @@ namespace AzFramework return nextCamera; } - void OrbitDollyCursorMoveCameraInput::HandleEvents(const InputEvent& event) + void OrbitDollyCursorMoveCameraInput::HandleEvents( + const InputEvent& event, [[maybe_unused]] const ScreenVector& cursorDelta, [[maybe_unused]] float scrollDelta) { if (const auto& input = AZStd::get_if(&event)) { @@ -584,7 +602,8 @@ namespace AzFramework return nextCamera; } - void ScrollTranslationCameraInput::HandleEvents(const InputEvent& event) + void ScrollTranslationCameraInput::HandleEvents( + const InputEvent& event, [[maybe_unused]] const ScreenVector& cursorDelta, [[maybe_unused]] float scrollDelta) { if (const auto* scroll = AZStd::get_if(&event)) { @@ -610,7 +629,7 @@ namespace AzFramework Camera SmoothCamera(const Camera& currentCamera, const Camera& targetCamera, const float deltaTime) { - const auto clamp_rotation = [](const float angle) { return std::fmod(angle + AZ::Constants::TwoPi, AZ::Constants::TwoPi); }; + const auto clamp_rotation = [](const float angle) { return AZStd::fmod(angle + AZ::Constants::TwoPi, AZ::Constants::TwoPi); }; // keep yaw in 0 - 360 range float targetYaw = clamp_rotation(targetCamera.m_yaw); @@ -621,7 +640,7 @@ namespace AzFramework // ensure smooth transition when moving across 0 - 360 boundary const float yawDelta = targetYaw - currentYaw; - if (std::abs(yawDelta) >= AZ::Constants::Pi) + if (AZStd::abs(yawDelta) >= AZ::Constants::Pi) { targetYaw -= AZ::Constants::TwoPi * sign(yawDelta); } @@ -629,12 +648,12 @@ namespace AzFramework Camera camera; // note: the math for the lerp smoothing implementation for camera rotation and translation was inspired by this excellent // article by Scott Lembcke: https://www.gamasutra.com/blogs/ScottLembcke/20180404/316046/Improved_Lerp_Smoothing.php - const float lookRate = std::exp2(ed_cameraSystemLookSmoothness); - const float lookT = std::exp2(-lookRate * deltaTime); + const float lookRate = AZStd::exp2(ed_cameraSystemLookSmoothness); + const float lookT = AZStd::exp2(-lookRate * deltaTime); camera.m_pitch = AZ::Lerp(targetCamera.m_pitch, currentCamera.m_pitch, lookT); camera.m_yaw = AZ::Lerp(targetYaw, currentYaw, lookT); - const float moveRate = std::exp2(ed_cameraSystemTranslateSmoothness); - const float moveT = std::exp2(-moveRate * deltaTime); + const float moveRate = AZStd::exp2(ed_cameraSystemTranslateSmoothness); + const float moveT = AZStd::exp2(-moveRate * deltaTime); camera.m_lookDist = AZ::Lerp(targetCamera.m_lookDist, currentCamera.m_lookDist, moveT); camera.m_lookAt = targetCamera.m_lookAt.Lerp(currentCamera.m_lookAt, moveT); return camera; @@ -655,7 +674,7 @@ namespace AzFramework const auto* position = inputChannel.GetCustomData(); AZ_Assert(position, "Expected PositionData2D but found nullptr"); - return CursorMotionEvent{ScreenPoint( + return CursorEvent{ScreenPoint( position->m_normalizedPosition.GetX() * windowSize.m_width, position->m_normalizedPosition.GetY() * windowSize.m_height)}; } else if (inputChannelId == InputDeviceMouse::Movement::Z) diff --git a/Code/Framework/AzFramework/AzFramework/Viewport/CameraInput.h b/Code/Framework/AzFramework/AzFramework/Viewport/CameraInput.h index 6ccd7c43eb..6475753017 100644 --- a/Code/Framework/AzFramework/AzFramework/Viewport/CameraInput.h +++ b/Code/Framework/AzFramework/AzFramework/Viewport/CameraInput.h @@ -70,7 +70,7 @@ namespace AzFramework void UpdateCameraFromTransform(Camera& camera, const AZ::Transform& transform); - struct CursorMotionEvent + struct CursorEvent { ScreenPoint m_position; }; @@ -86,7 +86,7 @@ namespace AzFramework InputChannel::State m_state; //!< Channel state. (e.g. Begin/update/end event). }; - using InputEvent = AZStd::variant; + using InputEvent = AZStd::variant; class CameraInput { @@ -147,7 +147,7 @@ namespace AzFramework ResetImpl(); } - virtual void HandleEvents(const InputEvent& event) = 0; + virtual void HandleEvents(const InputEvent& event, const ScreenVector& cursorDelta, float scrollDelta) = 0; virtual Camera StepCamera(const Camera& targetCamera, const ScreenVector& cursorDelta, float scrollDelta, float deltaTime) = 0; virtual bool Exclusive() const @@ -170,7 +170,7 @@ namespace AzFramework { public: void AddCamera(AZStd::shared_ptr cameraInput); - bool HandleEvents(const InputEvent& event); + bool HandleEvents(const InputEvent& event, const ScreenVector& cursorDelta, float scrollDelta); Camera StepCamera(const Camera& targetCamera, const ScreenVector& cursorDelta, float scrollDelta, float deltaTime); void Reset(); @@ -201,11 +201,13 @@ namespace AzFramework { } - void HandleEvents(const InputEvent& event) override; + 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; }; struct PanAxes @@ -243,7 +245,7 @@ namespace AzFramework , m_panChannelId(panChannelId) { } - void HandleEvents(const InputEvent& event) override; + 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: @@ -285,7 +287,7 @@ namespace AzFramework : m_translationAxesFn(AZStd::move(translationAxesFn)) { } - void HandleEvents(const InputEvent& event) override; + 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; @@ -354,7 +356,7 @@ namespace AzFramework class OrbitDollyScrollCameraInput : public CameraInput { public: - void HandleEvents(const InputEvent& event) override; + void HandleEvents(const InputEvent& event, const ScreenVector& cursorDelta, float scrollDelta) override; Camera StepCamera(const Camera& targetCamera, const ScreenVector& cursorDelta, float scrollDelta, float deltaTime) override; }; @@ -364,7 +366,7 @@ namespace AzFramework explicit OrbitDollyCursorMoveCameraInput(const InputChannelId dollyChannelId) : m_dollyChannelId(dollyChannelId) {} - void HandleEvents(const InputEvent& event) override; + 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: @@ -374,14 +376,14 @@ namespace AzFramework class ScrollTranslationCameraInput : public CameraInput { public: - void HandleEvents(const InputEvent& event) override; + void HandleEvents(const InputEvent& event, const ScreenVector& cursorDelta, float scrollDelta) override; Camera StepCamera(const Camera& targetCamera, const ScreenVector& cursorDelta, float scrollDelta, float deltaTime) override; }; class OrbitCameraInput : public CameraInput { public: - void HandleEvents(const InputEvent& event) override; + void HandleEvents(const InputEvent& event, const ScreenVector& cursorDelta, float scrollDelta) override; Camera StepCamera(const Camera& targetCamera, const ScreenVector& cursorDelta, float scrollDelta, float deltaTime) override; bool Exclusive() const override { diff --git a/Code/Framework/AzFramework/AzFramework/Viewport/ScreenGeometry.h b/Code/Framework/AzFramework/AzFramework/Viewport/ScreenGeometry.h index d3ae4e16f3..c48b1a5878 100644 --- a/Code/Framework/AzFramework/AzFramework/Viewport/ScreenGeometry.h +++ b/Code/Framework/AzFramework/AzFramework/Viewport/ScreenGeometry.h @@ -134,11 +134,16 @@ namespace AzFramework return !operator==(lhs, rhs); } + inline float ScreenVectorLength(const ScreenVector& screenVector) + { + return aznumeric_cast(AZStd::sqrt(screenVector.m_x * screenVector.m_x + screenVector.m_y * screenVector.m_y)); + } + inline ScreenPoint ScreenPointFromNDC(const AZ::Vector3& screenNDC, const AZ::Vector2& viewportSize) { return ScreenPoint( - aznumeric_caster(std::round(screenNDC.GetX() * viewportSize.GetX())), - aznumeric_caster(std::round((1.0f - screenNDC.GetY()) * viewportSize.GetY()))); + aznumeric_caster(AZStd::round(screenNDC.GetX() * viewportSize.GetX())), + aznumeric_caster(AZStd::round((1.0f - screenNDC.GetY()) * viewportSize.GetY()))); } inline AZ::Vector2 NDCFromScreenPoint(const ScreenPoint& screenPoint, const AZ::Vector2& viewportSize) diff --git a/Code/Framework/AzFramework/AzFramework/Visibility/BoundsBus.h b/Code/Framework/AzFramework/AzFramework/Visibility/BoundsBus.h index 65c62c7e64..3ffe9990df 100644 --- a/Code/Framework/AzFramework/AzFramework/Visibility/BoundsBus.h +++ b/Code/Framework/AzFramework/AzFramework/Visibility/BoundsBus.h @@ -12,6 +12,7 @@ #pragma once +#include #include #include #include @@ -27,7 +28,8 @@ namespace AZ namespace AzFramework { //! Implemented by components that provide bounds for use with various systems. - class BoundsRequests : public AZ::ComponentBus + class BoundsRequests + : public AZ::ComponentBus { public: static void Reflect(AZ::ReflectContext* context); @@ -37,6 +39,7 @@ namespace AzFramework //! more than one component may be providing a bound. It isn't guaranteed which bound //! will be returned by a single call to GetWorldBounds. virtual AZ::Aabb GetWorldBounds() = 0; + //! Returns an axis aligned bounding box in local space. //! @note It is preferred to use CalculateEntityLocalBoundsUnion in the general case as //! more than one component may be providing a bound. It isn't guaranteed which bound @@ -46,17 +49,15 @@ namespace AzFramework protected: ~BoundsRequests() = default; }; - using BoundsRequestBus = AZ::EBus; //! Returns a union of all local Aabbs provided by components implementing the BoundsRequestBus. //! @note It is preferred to call this function as opposed to GetLocalBounds directly as more than one //! component may be implementing this bus on an Entity and so only the first result (Aabb) will be returned. - inline AZ::Aabb CalculateEntityLocalBoundsUnion(const AZ::EntityId entityId) + inline AZ::Aabb CalculateEntityLocalBoundsUnion(const AZ::Entity* entity) { AZ::EBusReduceResult aabbResult(AZ::Aabb::CreateNull()); - BoundsRequestBus::EventResult( - aabbResult, entityId, &BoundsRequestBus::Events::GetLocalBounds); + BoundsRequestBus::EventResult(aabbResult, entity->GetId(), &BoundsRequestBus::Events::GetLocalBounds); if (aabbResult.value.IsValid()) { @@ -69,18 +70,18 @@ namespace AzFramework //! Returns a union of all world Aabbs provided by components implementing the BoundsRequestBus. //! @note It is preferred to call this function as opposed to GetWorldBounds directly as more than one //! component may be implementing this bus on an Entity and so only the first result (Aabb) will be returned. - inline AZ::Aabb CalculateEntityWorldBoundsUnion(const AZ::EntityId entityId) + inline AZ::Aabb CalculateEntityWorldBoundsUnion(const AZ::Entity* entity) { AZ::EBusReduceResult aabbResult(AZ::Aabb::CreateNull()); - BoundsRequestBus::EventResult(aabbResult, entityId, &BoundsRequestBus::Events::GetWorldBounds); + BoundsRequestBus::EventResult(aabbResult, entity->GetId(), &BoundsRequestBus::Events::GetWorldBounds); if (aabbResult.value.IsValid()) { return aabbResult.value; } - AZ::Vector3 worldTranslation = AZ::Vector3::CreateZero(); - AZ::TransformBus::EventResult(worldTranslation, entityId, &AZ::TransformBus::Events::GetWorldTranslation); + AZ::TransformInterface* transformInterface = entity->GetTransform(); + const AZ::Vector3 worldTranslation = transformInterface->GetWorldTranslation(); return AZ::Aabb::CreateCenterHalfExtents(worldTranslation, AZ::Vector3(0.5f)); } } // namespace AzFramework diff --git a/Code/Framework/AzFramework/AzFramework/Visibility/EntityBoundsUnionBus.h b/Code/Framework/AzFramework/AzFramework/Visibility/EntityBoundsUnionBus.h index 4424cbcf60..e95e25871a 100644 --- a/Code/Framework/AzFramework/AzFramework/Visibility/EntityBoundsUnionBus.h +++ b/Code/Framework/AzFramework/AzFramework/Visibility/EntityBoundsUnionBus.h @@ -23,9 +23,11 @@ namespace AzFramework { //! Provides an interface to retrieve and update the union of all Aabbs on a single Entity. //! @note This will be the combination/union of all individual Component Aabbs. - class EntityBoundsUnionRequests : public AZ::EBusTraits + class IEntityBoundsUnion { public: + AZ_RTTI(IEntityBoundsUnion, "{106968DD-43C0-478E-8045-523E0BF5D0F5}"); + //! Requests the cached union of component Aabbs to be recalculated as one may have changed. //! @note This is used to drive event driven updates to the visibility system. virtual void RefreshEntityLocalBoundsUnion(AZ::EntityId entityId) = 0; @@ -38,9 +40,21 @@ namespace AzFramework //! also be called explicitly (e.g. For testing purposes). virtual void ProcessEntityBoundsUnionRequests() = 0; + //! Notifies the EntityBoundsUnion system that an entities transform has been modified. + //! @param entity the entity whose transform has been modified. + virtual void OnTransformUpdated(AZ::Entity* entity) = 0; + protected: - ~EntityBoundsUnionRequests() = default; + ~IEntityBoundsUnion() = default; }; - using EntityBoundsUnionRequestBus = AZ::EBus; + // EBus wrapper for ScriptCanvas + class IEntityBoundsUnionTraits + : public AZ::EBusTraits + { + public: + static const AZ::EBusHandlerPolicy HandlerPolicy = AZ::EBusHandlerPolicy::Single; + static const AZ::EBusAddressPolicy AddressPolicy = AZ::EBusAddressPolicy::Single; + }; + using IEntityBoundsUnionRequestBus = AZ::EBus; } // namespace AzFramework diff --git a/Code/Framework/AzFramework/AzFramework/Visibility/EntityVisibilityBoundsUnionSystem.cpp b/Code/Framework/AzFramework/AzFramework/Visibility/EntityVisibilityBoundsUnionSystem.cpp index e9b0d4609e..c71adc5c3f 100644 --- a/Code/Framework/AzFramework/AzFramework/Visibility/EntityVisibilityBoundsUnionSystem.cpp +++ b/Code/Framework/AzFramework/AzFramework/Visibility/EntityVisibilityBoundsUnionSystem.cpp @@ -17,69 +17,70 @@ namespace AzFramework { + EntityVisibilityBoundsUnionSystem::EntityVisibilityBoundsUnionSystem() + : m_entityActivatedEventHandler([this](AZ::Entity* entity) { OnEntityActivated(entity); }) + , m_entityDeactivatedEventHandler([this](AZ::Entity* entity) { OnEntityDeactivated(entity); }) + { + ; + } + void EntityVisibilityBoundsUnionSystem::Connect() { - EntityBoundsUnionRequestBus::Handler::BusConnect(); - AZ::TransformNotificationBus::Router::BusRouterConnect(); - AZ::EntitySystemBus::Handler::BusConnect(); + AZ::Interface::Register(this); + IEntityBoundsUnionRequestBus::Handler::BusConnect(); AZ::TickBus::Handler::BusConnect(); + + AZ::Interface::Get()->RegisterEntityActivatedEventHandler(m_entityActivatedEventHandler); + AZ::Interface::Get()->RegisterEntityDeactivatedEventHandler(m_entityDeactivatedEventHandler); } void EntityVisibilityBoundsUnionSystem::Disconnect() { + m_entityActivatedEventHandler.Disconnect(); + m_entityDeactivatedEventHandler.Disconnect(); + AZ::TickBus::Handler::BusDisconnect(); - AZ::EntitySystemBus::Handler::BusDisconnect(); - AZ::TransformNotificationBus::Router::BusRouterDisconnect(); - EntityBoundsUnionRequestBus::Handler::BusDisconnect(); + IEntityBoundsUnionRequestBus::Handler::BusDisconnect(); + AZ::Interface::Unregister(this); } - static void SetUserDataEntityId(VisibilityEntry& visibilityEntry, const AZ::EntityId entityId) - { - static_assert( - sizeof(AZ::EntityId) <= sizeof(visibilityEntry.m_userData), "Ensure EntityId fits into m_userData"); - - visibilityEntry.m_typeFlags = VisibilityEntry::TYPE_Entity; - - std::memcpy(&visibilityEntry.m_userData, &entityId, sizeof(AZ::EntityId)); - } - - void EntityVisibilityBoundsUnionSystem::OnEntityActivated(const AZ::EntityId& entityId) + void EntityVisibilityBoundsUnionSystem::OnEntityActivated(AZ::Entity* entity) { AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzFramework); // ignore any entity that might activate which does not have a TransformComponent - if (!AZ::TransformBus::HasHandlers(entityId)) + if (entity->GetTransform() == nullptr) { return; } - if (auto instance_it = m_entityVisibilityBoundsUnionInstanceMapping.find(entityId); + if (auto instance_it = m_entityVisibilityBoundsUnionInstanceMapping.find(entity); instance_it == m_entityVisibilityBoundsUnionInstanceMapping.end()) { - AZ::Transform worldFromLocal = AZ::Transform::CreateIdentity(); - AZ::TransformBus::EventResult(worldFromLocal, entityId, &AZ::TransformBus::Events::GetWorldTM); + AZ::TransformInterface* transformInterface = entity->GetTransform(); + const AZ::Vector3 entityPosition = transformInterface->GetWorldTranslation(); EntityVisibilityBoundsUnionInstance instance; - instance.m_worldTransform = worldFromLocal; - instance.m_localEntityBoundsUnion = CalculateEntityLocalBoundsUnion(entityId); - SetUserDataEntityId(instance.m_visibilityEntry, entityId); + instance.m_localEntityBoundsUnion = CalculateEntityLocalBoundsUnion(entity); + instance.m_visibilityEntry.m_typeFlags = VisibilityEntry::TYPE_Entity; + instance.m_visibilityEntry.m_userData = static_cast(entity); - auto next_it = m_entityVisibilityBoundsUnionInstanceMapping.insert({entityId, instance}); - UpdateVisibilitySystem(next_it.first->second); + auto next_it = m_entityVisibilityBoundsUnionInstanceMapping.insert({ entity, instance }); + UpdateVisibilitySystem(entity, next_it.first->second); } } - void EntityVisibilityBoundsUnionSystem::OnEntityDeactivated(const AZ::EntityId& entityId) + void EntityVisibilityBoundsUnionSystem::OnEntityDeactivated(AZ::Entity* entity) { AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzFramework); // ignore any entity that might deactivate which does not have a TransformComponent - if (!AZ::TransformBus::HasHandlers(entityId)) + if (entity->GetTransform() == nullptr) { return; } - if (auto instance_it = m_entityVisibilityBoundsUnionInstanceMapping.find(entityId); + if (auto instance_it = m_entityVisibilityBoundsUnionInstanceMapping.find(entity); instance_it != m_entityVisibilityBoundsUnionInstanceMapping.end()) { if (IVisibilitySystem* visibilitySystem = AZ::Interface::Get()) @@ -90,7 +91,7 @@ namespace AzFramework } } - void EntityVisibilityBoundsUnionSystem::UpdateVisibilitySystem(EntityVisibilityBoundsUnionInstance& instance) + void EntityVisibilityBoundsUnionSystem::UpdateVisibilitySystem(AZ::Entity* entity, EntityVisibilityBoundsUnionInstance& instance) { AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzFramework); @@ -98,8 +99,8 @@ namespace AzFramework { // note: worldEntityBounds will not be a 'tight-fit' Aabb but that of a transformed local aabb // there will be some wasted space but it should be sufficient for the visibility system - const AZ::Aabb worldEntityBoundsUnion = - localEntityBoundsUnions.GetTransformedAabb(instance.m_worldTransform); + AZ::TransformInterface* transformInterface = entity->GetTransform(); + const AZ::Aabb worldEntityBoundsUnion = localEntityBoundsUnions.GetTransformedAabb(transformInterface->GetWorldTM()); IVisibilitySystem* visibilitySystem = AZ::Interface::Get(); if (visibilitySystem && !worldEntityBoundsUnion.IsClose(instance.m_visibilityEntry.m_boundingVolume)) { @@ -111,19 +112,27 @@ namespace AzFramework void EntityVisibilityBoundsUnionSystem::RefreshEntityLocalBoundsUnion(const AZ::EntityId entityId) { - // track entities that need their bounds union to be recalculated - m_entityIdsBoundsDirty.insert(entityId); + AZ::Entity* entity = AZ::Interface::Get()->FindEntity(entityId); + if (entity != nullptr) + { + // track entities that need their bounds union to be recalculated + m_entityBoundsDirty.insert(entity); + } } AZ::Aabb EntityVisibilityBoundsUnionSystem::GetEntityLocalBoundsUnion(const AZ::EntityId entityId) const { - // if the EntityId is not found in the mapping then return a null Aabb, this is to mimic - // as closely as possible the behavior of an individual GetLocalBounds call to an Entity that - // had been deleted (there would be no response, leaving the default value assigned) - if (auto instance_it = m_entityVisibilityBoundsUnionInstanceMapping.find(entityId); - instance_it != m_entityVisibilityBoundsUnionInstanceMapping.end()) + AZ::Entity* entity = AZ::Interface::Get()->FindEntity(entityId); + if (entity != nullptr) { - return instance_it->second.m_localEntityBoundsUnion; + // if the entity is not found in the mapping then return a null Aabb, this is to mimic + // as closely as possible the behavior of an individual GetLocalBounds call to an Entity that + // had been deleted (there would be no response, leaving the default value assigned) + if (auto instance_it = m_entityVisibilityBoundsUnionInstanceMapping.find(entity); + instance_it != m_entityVisibilityBoundsUnionInstanceMapping.end()) + { + return instance_it->second.m_localEntityBoundsUnion; + } } return AZ::Aabb::CreateNull(); @@ -134,45 +143,29 @@ namespace AzFramework AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzFramework); // iterate over all entities whose bounds changed and recalculate them - for (const auto& entityId : m_entityIdsBoundsDirty) + for (const auto& entity : m_entityBoundsDirty) { - if (auto instance_it = m_entityVisibilityBoundsUnionInstanceMapping.find(entityId); + if (auto instance_it = m_entityVisibilityBoundsUnionInstanceMapping.find(entity); instance_it != m_entityVisibilityBoundsUnionInstanceMapping.end()) { - instance_it->second.m_localEntityBoundsUnion = CalculateEntityLocalBoundsUnion(entityId); - } - } - - auto allDirtyEntityIds = m_entityIdsTransformDirty; - allDirtyEntityIds.insert(m_entityIdsBoundsDirty.begin(), m_entityIdsBoundsDirty.end()); - - for (const auto& dirtyEntityId : allDirtyEntityIds) - { - if (auto instance_it = m_entityVisibilityBoundsUnionInstanceMapping.find(dirtyEntityId); - instance_it != m_entityVisibilityBoundsUnionInstanceMapping.end()) - { - UpdateVisibilitySystem(instance_it->second); + instance_it->second.m_localEntityBoundsUnion = CalculateEntityLocalBoundsUnion(entity); + UpdateVisibilitySystem(entity, instance_it->second); } } // clear dirty entities once the visibility system has been updated - m_entityIdsBoundsDirty.clear(); - m_entityIdsTransformDirty.clear(); + m_entityBoundsDirty.clear(); } - void EntityVisibilityBoundsUnionSystem::OnTransformChanged( - [[maybe_unused]] const AZ::Transform& local, const AZ::Transform& world) + void EntityVisibilityBoundsUnionSystem::OnTransformUpdated(AZ::Entity* entity) { AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzFramework); - const AZ::EntityId entityId = *AZ::TransformNotificationBus::GetCurrentBusId(); - m_entityIdsTransformDirty.insert(entityId); - // update the world transform of the visibility bounds union - if (auto instance_it = m_entityVisibilityBoundsUnionInstanceMapping.find(entityId); + if (auto instance_it = m_entityVisibilityBoundsUnionInstanceMapping.find(entity); instance_it != m_entityVisibilityBoundsUnionInstanceMapping.end()) { - instance_it->second.m_worldTransform = world; + UpdateVisibilitySystem(entity, instance_it->second); } } diff --git a/Code/Framework/AzFramework/AzFramework/Visibility/EntityVisibilityBoundsUnionSystem.h b/Code/Framework/AzFramework/AzFramework/Visibility/EntityVisibilityBoundsUnionSystem.h index 56d6ba9670..808f834ebc 100644 --- a/Code/Framework/AzFramework/AzFramework/Visibility/EntityVisibilityBoundsUnionSystem.h +++ b/Code/Framework/AzFramework/AzFramework/Visibility/EntityVisibilityBoundsUnionSystem.h @@ -23,12 +23,12 @@ namespace AzFramework { //! Provide a unified hook between entities and the visibility system. class EntityVisibilityBoundsUnionSystem - : public EntityBoundsUnionRequestBus::Handler - , private AZ::EntitySystemBus::Handler - , private AZ::TransformNotificationBus::Router + : public IEntityBoundsUnionRequestBus::Handler , private AZ::TickBus::Handler { public: + EntityVisibilityBoundsUnionSystem(); + void Connect(); void Disconnect(); @@ -36,34 +36,31 @@ namespace AzFramework void RefreshEntityLocalBoundsUnion(AZ::EntityId entityId) override; AZ::Aabb GetEntityLocalBoundsUnion(AZ::EntityId entityId) const override; void ProcessEntityBoundsUnionRequests() override; + void OnTransformUpdated(AZ::Entity* entity) override; private: struct EntityVisibilityBoundsUnionInstance { - AZ::Transform m_worldTransform = AZ::Transform::CreateIdentity(); //!< The world transform of the Entity. - AZ::Aabb m_localEntityBoundsUnion = - AZ::Aabb::CreateNull(); //!< Entity union bounding volume in local space. + AZ::Aabb m_localEntityBoundsUnion = AZ::Aabb::CreateNull(); //!< Entity union bounding volume in local space. VisibilityEntry m_visibilityEntry; //!< Hook into the IVisibilitySystem interface. }; - using UniqueEntityIds = AZStd::unordered_set; + using UniqueEntities = AZStd::set; using EntityVisibilityBoundsUnionInstanceMapping = - AZStd::unordered_map; + AZStd::unordered_map; + + void OnEntityActivated(AZ::Entity* entity); + void OnEntityDeactivated(AZ::Entity* entity); // TickBus overrides ... void OnTick(float deltaTime, AZ::ScriptTimePoint time) override; - // EntitySystemBus overrides ... - void OnEntityActivated(const AZ::EntityId& entityId) override; - void OnEntityDeactivated(const AZ::EntityId& entityId) override; - - // TransformNotificationBus overrides ... - void OnTransformChanged(const AZ::Transform& local, const AZ::Transform& world) override; - - void UpdateVisibilitySystem(EntityVisibilityBoundsUnionInstance& instance); + void UpdateVisibilitySystem(AZ::Entity* entity, EntityVisibilityBoundsUnionInstance& instance); EntityVisibilityBoundsUnionInstanceMapping m_entityVisibilityBoundsUnionInstanceMapping; - UniqueEntityIds m_entityIdsBoundsDirty; - UniqueEntityIds m_entityIdsTransformDirty; + UniqueEntities m_entityBoundsDirty; + + AZ::EntityActivatedEvent::Handler m_entityActivatedEventHandler; + AZ::EntityDeactivatedEvent::Handler m_entityDeactivatedEventHandler; }; } // namespace AzFramework diff --git a/Code/Framework/AzFramework/AzFramework/Visibility/EntityVisibilityQuery.cpp b/Code/Framework/AzFramework/AzFramework/Visibility/EntityVisibilityQuery.cpp index fd119c8199..3d3d4bc65b 100644 --- a/Code/Framework/AzFramework/AzFramework/Visibility/EntityVisibilityQuery.cpp +++ b/Code/Framework/AzFramework/AzFramework/Visibility/EntityVisibilityQuery.cpp @@ -14,6 +14,7 @@ #include #include +#include #include #include #include @@ -66,6 +67,7 @@ namespace AzFramework octreeDebug.m_nodeBounds.push_back(nodeData.m_bounds); } + visibleEntityIdsOut.reserve(visibleEntityIdsOut.size() + nodeData.m_entries.size()); for (const auto* visibilityEntry : nodeData.m_entries) { if (ed_visibility_showDebug) @@ -88,8 +90,7 @@ namespace AzFramework octreeDebug.m_entryAabbsInFrustum.push_back(visibilityEntry->m_boundingVolume); } - AZ::EntityId entityId; - std::memcpy(&entityId, &visibilityEntry->m_userData, sizeof(AZ::EntityId)); + AZ::EntityId entityId = static_cast(visibilityEntry->m_userData)->GetId(); visibleEntityIdsOut.push_back(entityId); } }); diff --git a/Code/Framework/AzFramework/AzFramework/azframework_files.cmake b/Code/Framework/AzFramework/AzFramework/azframework_files.cmake index 1b1cd49aa7..48b0202a5b 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 @@ -279,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/Code/Framework/AzFramework/Platform/Android/AzFramework/Archive/ArchiveVars_Android.h b/Code/Framework/AzFramework/Platform/Android/AzFramework/Archive/ArchiveVars_Android.h index f8ca242409..40fbe0bf30 100644 --- a/Code/Framework/AzFramework/Platform/Android/AzFramework/Archive/ArchiveVars_Android.h +++ b/Code/Framework/AzFramework/Platform/Android/AzFramework/Archive/ArchiveVars_Android.h @@ -13,4 +13,3 @@ #pragma once #define STREAM_CACHE_DEFAULT 0 -#define FRONTEND_SHADER_CACHE_DEFAULT 0 diff --git a/Code/Framework/AzFramework/Platform/Linux/AzFramework/Archive/ArchiveVars_Linux.h b/Code/Framework/AzFramework/Platform/Linux/AzFramework/Archive/ArchiveVars_Linux.h index f8ca242409..40fbe0bf30 100644 --- a/Code/Framework/AzFramework/Platform/Linux/AzFramework/Archive/ArchiveVars_Linux.h +++ b/Code/Framework/AzFramework/Platform/Linux/AzFramework/Archive/ArchiveVars_Linux.h @@ -13,4 +13,3 @@ #pragma once #define STREAM_CACHE_DEFAULT 0 -#define FRONTEND_SHADER_CACHE_DEFAULT 0 diff --git a/Code/Framework/AzFramework/Platform/Mac/AzFramework/Archive/ArchiveVars_Mac.h b/Code/Framework/AzFramework/Platform/Mac/AzFramework/Archive/ArchiveVars_Mac.h index f8ca242409..40fbe0bf30 100644 --- a/Code/Framework/AzFramework/Platform/Mac/AzFramework/Archive/ArchiveVars_Mac.h +++ b/Code/Framework/AzFramework/Platform/Mac/AzFramework/Archive/ArchiveVars_Mac.h @@ -13,4 +13,3 @@ #pragma once #define STREAM_CACHE_DEFAULT 0 -#define FRONTEND_SHADER_CACHE_DEFAULT 0 diff --git a/Code/Framework/AzFramework/Platform/Windows/AzFramework/Archive/ArchiveVars_Windows.h b/Code/Framework/AzFramework/Platform/Windows/AzFramework/Archive/ArchiveVars_Windows.h index f8ca242409..40fbe0bf30 100644 --- a/Code/Framework/AzFramework/Platform/Windows/AzFramework/Archive/ArchiveVars_Windows.h +++ b/Code/Framework/AzFramework/Platform/Windows/AzFramework/Archive/ArchiveVars_Windows.h @@ -13,4 +13,3 @@ #pragma once #define STREAM_CACHE_DEFAULT 0 -#define FRONTEND_SHADER_CACHE_DEFAULT 0 diff --git a/Code/Framework/AzFramework/Platform/iOS/AzFramework/Archive/ArchiveVars_iOS.h b/Code/Framework/AzFramework/Platform/iOS/AzFramework/Archive/ArchiveVars_iOS.h index f8ca242409..40fbe0bf30 100644 --- a/Code/Framework/AzFramework/Platform/iOS/AzFramework/Archive/ArchiveVars_iOS.h +++ b/Code/Framework/AzFramework/Platform/iOS/AzFramework/Archive/ArchiveVars_iOS.h @@ -13,4 +13,3 @@ #pragma once #define STREAM_CACHE_DEFAULT 0 -#define FRONTEND_SHADER_CACHE_DEFAULT 0 diff --git a/Code/Framework/AzNetworking/AzNetworking/Serialization/HashSerializer.cpp b/Code/Framework/AzNetworking/AzNetworking/Serialization/HashSerializer.cpp index 80096365a4..c7f47cbc04 100644 --- a/Code/Framework/AzNetworking/AzNetworking/Serialization/HashSerializer.cpp +++ b/Code/Framework/AzNetworking/AzNetworking/Serialization/HashSerializer.cpp @@ -19,9 +19,10 @@ namespace AzNetworking static const int32_t FloatHashMinValue = (INT_MIN >> 7); static const int32_t FloatHashMaxValue = (INT_MAX >> 7); - AZ::HashValue64 HashSerializer::GetHash() const + AZ::HashValue32 HashSerializer::GetHash() const { - return m_hash; + // Just truncate the upper bits + return static_cast(m_hash); } SerializerMode HashSerializer::GetSerializerMode() const diff --git a/Code/Framework/AzNetworking/AzNetworking/Serialization/HashSerializer.h b/Code/Framework/AzNetworking/AzNetworking/Serialization/HashSerializer.h index b4bc991746..2f86d1aafe 100644 --- a/Code/Framework/AzNetworking/AzNetworking/Serialization/HashSerializer.h +++ b/Code/Framework/AzNetworking/AzNetworking/Serialization/HashSerializer.h @@ -27,7 +27,7 @@ namespace AzNetworking HashSerializer() = default; - AZ::HashValue64 GetHash() const; + AZ::HashValue32 GetHash() const; // ISerializer interfaces SerializerMode GetSerializerMode() const override; diff --git a/Code/Framework/AzNetworking/AzNetworking/Serialization/StringifySerializer.cpp b/Code/Framework/AzNetworking/AzNetworking/Serialization/StringifySerializer.cpp new file mode 100644 index 0000000000..bcd09f274c --- /dev/null +++ b/Code/Framework/AzNetworking/AzNetworking/Serialization/StringifySerializer.cpp @@ -0,0 +1,162 @@ +/* +* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or +* its licensors. +* +* For complete copyright and license terms please see the LICENSE at the root of this +* distribution (the "License"). All use of this software is governed by the License, +* or, if provided, by the license below or the license accompanying this file. Do not +* remove or 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 AzNetworking +{ + StringifySerializer::StringifySerializer(char delimeter, bool outputFieldNames, const AZStd::string& seperator) + : m_delimeter(delimeter) + , m_outputFieldNames(outputFieldNames) + , m_separator(seperator) + { + ; + } + + const AZStd::string& StringifySerializer::GetString() const + { + return m_string; + } + + const StringifySerializer::StringMap& StringifySerializer::GetValueMap() const + { + return m_map; + } + + SerializerMode StringifySerializer::GetSerializerMode() const + { + return SerializerMode::ReadFromObject; + } + + bool StringifySerializer::Serialize(bool& value, const char* name) + { + return ProcessData(name, value); + } + + bool StringifySerializer::Serialize(char& value, const char* name, char, char) + { + const int val = value; // Print chars as integers + return ProcessData(name, val); + } + + bool StringifySerializer::Serialize(int8_t& value, const char* name, int8_t, int8_t) + { + return ProcessData(name, value); + } + + bool StringifySerializer::Serialize(int16_t& value, const char* name, int16_t, int16_t) + { + return ProcessData(name, value); + } + + bool StringifySerializer::Serialize(int32_t& value, const char* name, int32_t, int32_t) + { + return ProcessData(name, value); + } + + bool StringifySerializer::Serialize(int64_t& value, const char* name, int64_t, int64_t) + { + return ProcessData(name, value); + } + + bool StringifySerializer::Serialize(uint8_t& value, const char* name, uint8_t, uint8_t) + { + return ProcessData(name, value); + } + + bool StringifySerializer::Serialize(uint16_t& value, const char* name, uint16_t, uint16_t) + { + return ProcessData(name, value); + } + + bool StringifySerializer::Serialize(uint32_t& value, const char* name, uint32_t, uint32_t) + { + return ProcessData(name, value); + } + + bool StringifySerializer::Serialize(uint64_t& value, const char* name, uint64_t, uint64_t) + { + return ProcessData(name, value); + } + + bool StringifySerializer::Serialize(float& value, const char* name, float, float) + { + return ProcessData(name, value); + } + + bool StringifySerializer::Serialize(double& value, const char* name, double, double) + { + return ProcessData(name, value); + } + + bool StringifySerializer::SerializeBytes(uint8_t* buffer, uint32_t, bool isString, uint32_t&, const char* name) + { + if (isString) + { + AZ::CVarFixedString value = reinterpret_cast(buffer); + return ProcessData(name, value); + } + return false; + } + + bool StringifySerializer::BeginObject(const char* name, const char*) + { + m_prefixSizeStack.push_back(m_prefix.size()); + m_prefix += name; + m_prefix += "."; + return true; + } + + bool StringifySerializer::EndObject(const char*, const char*) + { + m_prefix.resize(m_prefixSizeStack.back()); + m_prefixSizeStack.pop_back(); + return true; + } + + const uint8_t* StringifySerializer::GetBuffer() const + { + return nullptr; + } + + uint32_t StringifySerializer::GetCapacity() const + { + return 0; + } + + uint32_t StringifySerializer::GetSize() const + { + return 0; + } + + template + bool StringifySerializer::ProcessData(const char* name, const T& value) + { + // Only add delimeters after we have processed at least one element + if (!m_string.empty()) + { + m_string += m_delimeter; + } + + if (m_outputFieldNames) + { + m_string += m_prefix; + m_string += name; + m_string += m_separator; + } + + AZ::CVarFixedString string = AZ::ConsoleTypeHelpers::ValueToString(value); + m_string += string.c_str(); + m_map[m_prefix + name] = string.c_str(); + return true; + } +} diff --git a/Code/Framework/AzNetworking/AzNetworking/Serialization/StringifySerializer.h b/Code/Framework/AzNetworking/AzNetworking/Serialization/StringifySerializer.h new file mode 100644 index 0000000000..aa8c58ae60 --- /dev/null +++ b/Code/Framework/AzNetworking/AzNetworking/Serialization/StringifySerializer.h @@ -0,0 +1,80 @@ +/* +* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or +* its licensors. +* +* For complete copyright and license terms please see the LICENSE at the root of this +* distribution (the "License"). All use of this software is governed by the License, +* or, if provided, by the license below or the license accompanying this file. Do not +* remove or 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 AzNetworking +{ + // StringifySerializer + // Generate a debug string of a serializable object + class StringifySerializer + : public ISerializer + { + public: + + using StringMap = AZStd::map; + + StringifySerializer(char delimeter = ' ', bool outputFieldNames = true, const AZStd::string& seperator = "="); + + // GetString + // After serializing objects, get the serialized values as a single string + const AZStd::string& GetString() const; + + // GetValueMap + // After serializing objects, get the serialized values as key value pairs + const StringMap& GetValueMap() const; + + // ISerializer interfaces + SerializerMode GetSerializerMode() const override; + bool Serialize(bool& value, const char* name) override; + bool Serialize(char& value, const char* name, char minValue, char maxValue) override; + bool Serialize(int8_t& value, const char* name, int8_t minValue, int8_t maxValue) override; + bool Serialize(int16_t& value, const char* name, int16_t minValue, int16_t maxValue) override; + bool Serialize(int32_t& value, const char* name, int32_t minValue, int32_t maxValue) override; + bool Serialize(int64_t& value, const char* name, int64_t minValue, int64_t maxValue) override; + bool Serialize(uint8_t& value, const char* name, uint8_t minValue, uint8_t maxValue) override; + bool Serialize(uint16_t& value, const char* name, uint16_t minValue, uint16_t maxValue) override; + bool Serialize(uint32_t& value, const char* name, uint32_t minValue, uint32_t maxValue) override; + bool Serialize(uint64_t& value, const char* name, uint64_t minValue, uint64_t maxValue) override; + bool Serialize(float& value, const char* name, float minValue, float maxValue) override; + bool Serialize(double& value, const char* name, double minValue, double maxValue) override; + bool SerializeBytes(uint8_t* buffer, uint32_t bufferCapacity, bool isString, uint32_t& outSize, const char* name) override; + bool BeginObject(const char* name, const char* typeName) override; + bool EndObject(const char* name, const char* typeName) override; + + const uint8_t* GetBuffer() const override; + uint32_t GetCapacity() const override; + uint32_t GetSize() const override; + void ClearTrackedChangesFlag() override {} + bool GetTrackedChangesFlag() const override { return false; } + // ISerializer interfaces + + private: + + template + bool ProcessData(const char* name, const T& value); + + private: + + char m_delimeter; + bool m_outputFieldNames = true; + + StringMap m_map; + AZStd::string m_string; + AZStd::string m_prefix; + AZStd::string m_separator; + AZStd::deque m_prefixSizeStack; + }; +} diff --git a/Code/Framework/AzNetworking/AzNetworking/aznetworking_files.cmake b/Code/Framework/AzNetworking/AzNetworking/aznetworking_files.cmake index ea84f3fdc9..b8d488a1e4 100644 --- a/Code/Framework/AzNetworking/AzNetworking/aznetworking_files.cmake +++ b/Code/Framework/AzNetworking/AzNetworking/aznetworking_files.cmake @@ -65,6 +65,8 @@ set(FILES Serialization/NetworkOutputSerializer.cpp Serialization/NetworkOutputSerializer.h Serialization/NetworkOutputSerializer.inl + Serialization/StringifySerializer.cpp + Serialization/StringifySerializer.h Serialization/TrackChangedSerializer.h Serialization/TrackChangedSerializer.inl TcpTransport/TcpConnection.cpp diff --git a/Code/Framework/AzQtComponents/AzQtComponents/Components/FilteredSearchWidget.cpp b/Code/Framework/AzQtComponents/AzQtComponents/Components/FilteredSearchWidget.cpp index 2cfe2a7abf..5ba223dec4 100644 --- a/Code/Framework/AzQtComponents/AzQtComponents/Components/FilteredSearchWidget.cpp +++ b/Code/Framework/AzQtComponents/AzQtComponents/Components/FilteredSearchWidget.cpp @@ -180,6 +180,8 @@ namespace AzQtComponents textSearch->setFrame(false); textSearch->setText(QString()); textSearch->setPlaceholderText(QObject::tr("Search...")); + textSearch->setClearButtonEnabled(true); + LineEdit::applySearchStyle(textSearch); connect(textSearch, &QLineEdit::textChanged, this, &SearchTypeSelector::FilterTextChanged); m_searchLayout->addWidget(textSearch); diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/API/ToolsApplicationAPI.h b/Code/Framework/AzToolsFramework/AzToolsFramework/API/ToolsApplicationAPI.h index 83e40474d6..82fa3f94f5 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/API/ToolsApplicationAPI.h +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/API/ToolsApplicationAPI.h @@ -761,16 +761,6 @@ namespace AzToolsFramework /// If the view pane was not registered with the ViewPaneOptions.isDeletable set to true, the view pane will be hidden instead. virtual void CloseViewPane(const char* /*paneName*/) {} - /// Request generation of all level cubemaps. - virtual void GenerateAllCubemaps() {} - - /// Regenerate cubemap for a particular entity. - /// \param entityId ID of the entity that the cubemap is for - /// \param cubemapOutputPath path to a image file to generate - /// \param hideEntity Indicates whether the entity should be hidden during cubemap generation. Controls whether the entity's current cubemap output is baked into the new cubemap. - virtual void GenerateCubemapForEntity(AZ::EntityId /*entityId*/, AZStd::string* /*cubemapOutputPath*/, bool /*hideEntity*/) {} - virtual void GenerateCubemapWithIDForEntity(AZ::EntityId /*entityId*/, AZ::Uuid /*cubemapId*/, AZStd::string* /*cubemapOutputPath*/, bool /*hideEntity*/, bool /*hasCubemapId*/) {} - //! Spawn asset browser for the appropriate asset types. virtual void BrowseForAssets(AssetBrowser::AssetSelectionModel& /*selection*/) = 0; 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/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/Framework/AzToolsFramework/AzToolsFramework/Entity/EditorEntityContextComponent.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/Entity/EditorEntityContextComponent.cpp index 44c8487272..041a0f4195 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Entity/EditorEntityContextComponent.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Entity/EditorEntityContextComponent.cpp @@ -189,9 +189,6 @@ namespace AzToolsFramework SliceEditorEntityOwnershipServiceNotificationBus::Handler::BusConnect(); EditorLegacyGameModeNotificationBus::Handler::BusConnect(); - - m_entityVisibilityBoundsUnionSystem.Connect(); - } //========================================================================= @@ -199,8 +196,6 @@ namespace AzToolsFramework //========================================================================= void EditorEntityContextComponent::Deactivate() { - m_entityVisibilityBoundsUnionSystem.Disconnect(); - EditorLegacyGameModeNotificationBus::Handler::BusDisconnect(); SliceEditorEntityOwnershipServiceNotificationBus::Handler::BusDisconnect(); diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Entity/EditorEntityContextComponent.h b/Code/Framework/AzToolsFramework/AzToolsFramework/Entity/EditorEntityContextComponent.h index 2313f27437..92c7f84703 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Entity/EditorEntityContextComponent.h +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Entity/EditorEntityContextComponent.h @@ -189,8 +189,6 @@ namespace AzToolsFramework //! EditorEntityContextRequestBus::Events::AddRequiredComponents() AZ::ComponentTypeList m_requiredEditorComponentTypes; - //! Edit time visibility management integrating entities with the IVisibilitySystem. - AzFramework::EntityVisibilityBoundsUnionSystem m_entityVisibilityBoundsUnionSystem; bool m_isLegacySliceService; UndoSystem::UndoCacheInterface* m_undoCacheInterface = nullptr; diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Entity/PrefabEditorEntityOwnershipService.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/Entity/PrefabEditorEntityOwnershipService.cpp index 81233069a9..6b6f1475bb 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,65 @@ namespace AzToolsFramework m_validateEntitiesCallback = AZStd::move(validateEntitiesCallback); } + 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()) + { + AZ_Error("Prefab", false, "Invalid asset found referenced in scene while entering game mode"); + 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(); + + asset = AZ::Data::AssetManager::Instance().GetAsset(assetId, assetType, loadBehavior); + + if (!asset.GetId().IsValid()) + { + AZ_Error("Prefab", false, "Invalid asset found referenced in scene while entering game mode"); + continue; + } + } + + // 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()) + { + AZ_Error("Prefab", false, "Invalid asset found referenced in scene while entering game mode"); + continue; + } + + const AZ::Data::AssetLoadBehavior loadBehavior = asset.GetAutoLoadBehavior(); + + 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; + } + } + } + void PrefabEditorEntityOwnershipService::StartPlayInEditor() { // This is a workaround until the replacement for GameEntityContext is done @@ -381,16 +441,21 @@ 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); } + // 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) { 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; diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Manipulators/AngularManipulator.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/Manipulators/AngularManipulator.cpp index 6fbd467f04..9a4a952d8f 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Manipulators/AngularManipulator.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Manipulators/AngularManipulator.cpp @@ -85,14 +85,14 @@ namespace AzToolsFramework // if we're snapping, only increment current radians when we know // preSnapRadians is greater than the angleStep - if (snapping) + if (snapping && AZStd::abs(angleStepDegrees) > 0.0f) { actionInternal.m_current.m_preSnapRadians += rotationAngleRad * rotateSign; const float angleStepRad = AZ::DegToRad(angleStepDegrees); const float preSnapRotateSign = Sign(actionInternal.m_current.m_preSnapRadians); // if we move more than angleStep in a frame, make sure we catch up - while (fabsf(actionInternal.m_current.m_preSnapRadians) >= angleStepRad) + while (AZStd::abs(actionInternal.m_current.m_preSnapRadians) >= angleStepRad) { actionInternal.m_current.m_radians += angleStepRad * preSnapRotateSign; actionInternal.m_current.m_preSnapRadians -= angleStepRad * preSnapRotateSign; diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabDomUtils.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabDomUtils.cpp index d53aeaa241..0bffd26be0 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,48 @@ namespace AzToolsFramework return true; } + bool LoadInstanceFromPrefabDom( + 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 + // is avoided. + AZ::Data::AssetManager::Instance().SuspendAssetRelease(); + + InstanceEntityIdMapper entityIdMapper; + entityIdMapper.SetLoadingInstance(instance); + if ((flags & LoadInstanceFlags::AssignRandomEntityId) == LoadInstanceFlags::AssignRandomEntityId) + { + entityIdMapper.SetEntityIdGenerationApproach(InstanceEntityIdMapper::EntityIdGenerationApproach::Random); + } + + 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.Create(); + + 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; + } + AZ::Data::SerializedAssetTracker* assetTracker = settings.m_metadata.Find(); + + referencedAssets = AZStd::move(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..c7c2827770 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 @@ -42,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); @@ -60,20 +61,32 @@ 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( 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 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. + */ + bool LoadInstanceFromPrefabDom( + 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. * @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( diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicHandler.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicHandler.cpp index 475510c52f..14537683ef 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicHandler.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicHandler.cpp @@ -89,7 +89,7 @@ namespace AzToolsFramework if (!RetrieveAndSortPrefabEntitiesAndInstances(inputEntityList, commonRootEntityOwningInstance->get(), entities, instances)) { return AZ::Failure( - AZStd::string("Could not create a new prefab out of the entities provided - entities do not share a common root.")); + AZStd::string("Could not create a new prefab out of the entities provided - invalid selection.")); } // When we create a prefab with other prefab instances, we have to remove the existing links between the source and @@ -140,9 +140,13 @@ namespace AzToolsFramework // 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); + AZ::EntityId topLevelEntityId = topLevelEntity->GetId(); + if (topLevelEntityId.IsValid()) + { + m_prefabUndoCache.UpdateCache(topLevelEntityId); + undoBatch.MarkEntityDirty(topLevelEntityId); + AZ::TransformBus::Event(topLevelEntityId, &AZ::TransformBus::Events::SetParent, containerEntityId); + } } // Select Container Entity @@ -182,6 +186,22 @@ namespace AzToolsFramework instanceToParentUnder = prefabEditorEntityOwnershipInterface->GetRootPrefabInstance(); parent = instanceToParentUnder->get().GetContainerEntityId(); } + + //Detect whether this instantiation would produce a cyclical dependency + auto relativePath = m_prefabLoaderInterface->GetRelativePathToProject(filePath); + Prefab::TemplateId templateId = m_prefabSystemComponentInterface->GetTemplateIdFromFilePath(relativePath); + + // If the template isn't currently loaded, there's no way for it to be in the hierarchy so we just skip the check. + if (templateId != Prefab::InvalidTemplateId && IsPrefabInInstanceAncestorHierarchy(templateId, instanceToParentUnder->get())) + { + return AZ::Failure( + AZStd::string::format( + "Instantiate Prefab operation aborted - Cyclical dependency detected\n(%s depends on %s).", + relativePath.Native().c_str(), + instanceToParentUnder->get().GetTemplateSourcePath().Native().c_str() + ) + ); + } { // Initialize Undo Batch object @@ -192,7 +212,7 @@ namespace AzToolsFramework instanceToParentUnderDomBeforeCreate, instanceToParentUnder->get()); // Instantiate the Prefab - auto instanceToCreate = prefabEditorEntityOwnershipInterface->InstantiatePrefab(filePath, instanceToParentUnder); + auto instanceToCreate = prefabEditorEntityOwnershipInterface->InstantiatePrefab(relativePath, instanceToParentUnder); if (!instanceToCreate) { @@ -221,6 +241,21 @@ namespace AzToolsFramework // Retrieve entityList from entityIds inputEntityList = EntityIdListToEntityList(entityIds); + // Remove Level Container Entity if it's part of the list + AZ::EntityId levelEntityId = GetLevelInstanceContainerEntityId(); + if (levelEntityId.IsValid()) + { + AZ::Entity* levelEntity = GetEntityById(levelEntityId); + if (levelEntity) + { + auto levelEntityIter = AZStd::find(inputEntityList.begin(), inputEntityList.end(), levelEntity); + if (levelEntityIter != inputEntityList.end()) + { + inputEntityList.erase(levelEntityIter); + } + } + } + // Find common root and top level entities bool entitiesHaveCommonRoot = false; @@ -242,6 +277,23 @@ namespace AzToolsFramework return AZ::Success(); } + bool PrefabPublicHandler::IsPrefabInInstanceAncestorHierarchy(TemplateId prefabTemplateId, InstanceOptionalConstReference instance) + { + InstanceOptionalConstReference currentInstance = instance; + + while (currentInstance.has_value()) + { + if (currentInstance->get().GetTemplateId() == prefabTemplateId) + { + return true; + } + + currentInstance = currentInstance->get().GetParentInstance(); + } + + return false; + } + void PrefabPublicHandler::CreateLink( const EntityList& topLevelEntities, Instance& sourceInstance, TemplateId targetTemplateId, UndoSystem::URSequencePoint* undoBatch, AZ::EntityId commonRootEntityId) @@ -774,6 +826,11 @@ namespace AzToolsFramework const EntityList& inputEntities, Instance& commonRootEntityOwningInstance, EntityList& outEntities, AZStd::vector>& outInstances) const { + if (inputEntities.size() == 0) + { + return false; + } + AZStd::queue entityQueue; for (auto inputEntity : inputEntities) @@ -861,7 +918,7 @@ namespace AzToolsFramework outInstances.push_back(AZStd::move(commonRootEntityOwningInstance.DetachNestedInstance(instancePtr->GetInstanceAlias()))); } - return true; + return (outEntities.size() + outInstances.size()) > 0; } bool PrefabPublicHandler::EntitiesBelongToSameInstance(const EntityIdList& entityIds) const diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicHandler.h b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicHandler.h index 5ade666a40..03b3827328 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicHandler.h +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicHandler.h @@ -106,6 +106,14 @@ namespace AzToolsFramework const AZStd::vector& entityIds, EntityList& inputEntityList, EntityList& topLevelEntities, AZ::EntityId& commonRootEntityId, InstanceOptionalReference& commonRootEntityOwningInstance); + /* Detects whether an instance of prefabTemplateId is present in the hierarchy of ancestors of instance. + * + * \param prefabTemplateId The template id to test for + * \param instance The instance whose ancestor hierarchy prefabTemplateId will be tested against. + * \return true if an instance of the template of id prefabTemplateId could be found in the ancestor hierarchy of instance, false otherwise. + */ + bool IsPrefabInInstanceAncestorHierarchy(TemplateId prefabTemplateId, InstanceOptionalConstReference instance); + static Instance* GetParentInstance(Instance* instance); static Instance* GetAncestorOfInstanceThatIsChildOfRoot(const Instance* ancestor, Instance* descendant); static void GenerateContainerEntityTransform(const EntityList& topLevelEntities, AZ::Vector3& translation, AZ::Quaternion& rotation); diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabSystemComponent.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabSystemComponent.cpp index 4413586e77..3910e80f75 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabSystemComponent.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabSystemComponent.cpp @@ -721,6 +721,8 @@ namespace AzToolsFramework TemplateId PrefabSystemComponent::GetTemplateIdFromFilePath(AZ::IO::PathView filePath) const { + AZ_Assert(!filePath.IsAbsolute(), "Prefab - GetTemplateIdFromFilePath was passed an absolute path. Prefabs use paths relative to the project folder."); + auto found = m_templateFilePathToIdMap.find(filePath); if (found != m_templateFilePathToIdMap.end()) { diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/Spawnable/PrefabCatchmentProcessor.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/Spawnable/PrefabCatchmentProcessor.cpp index 5d8f1f35e3..fa8eb3fd65 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/Spawnable/PrefabCatchmentProcessor.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/Spawnable/PrefabCatchmentProcessor.cpp @@ -63,7 +63,7 @@ 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); + bool result = SpawnableUtils::CreateSpawnable(*spawnable, prefab, object.GetReferencedAssets()); if (result) { AzFramework::Spawnable::EntityList& entities = spawnable->GetEntities(); @@ -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..38f58503ed 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,44 @@ namespace AzToolsFramework::Prefab::PrefabConversionUtils return !m_prefabs.empty(); } + bool PrefabProcessorContext::RegisterSpawnableProductAssetDependency(AZStd::string prefabName, AZStd::string dependentPrefabName) + { + using ConversionUtils = PrefabConversionUtils::ProcessedObjectStore; + + prefabName += AzFramework::Spawnable::DotFileExtension; + uint32_t spawnableSubId = ConversionUtils::BuildSubId(AZStd::move(prefabName)); + + dependentPrefabName += AzFramework::Spawnable::DotFileExtension; + uint32_t spawnablePrefabSubId = ConversionUtils::BuildSubId(AZStd::move(dependentPrefabName)); + + return RegisterSpawnableProductAssetDependency(spawnableSubId, spawnablePrefabSubId); + } + + bool PrefabProcessorContext::RegisterSpawnableProductAssetDependency(AZStd::string prefabName, const AZ::Data::AssetId& dependentAssetId) + { + using ConversionUtils = PrefabConversionUtils::ProcessedObjectStore; + + prefabName += AzFramework::Spawnable::DotFileExtension; + uint32_t spawnableSubId = ConversionUtils::BuildSubId(AZStd::move(prefabName)); + + AZ::Data::AssetId spawnableAssetId(GetSourceUuid(), spawnableSubId); + + return RegisterProductAssetDependency(spawnableAssetId, dependentAssetId); + } + + bool PrefabProcessorContext::RegisterSpawnableProductAssetDependency(uint32_t spawnableAssetSubId, uint32_t dependentSpawnableAssetSubId) + { + AZ::Data::AssetId spawnableAssetId(GetSourceUuid(), spawnableAssetSubId); + AZ::Data::AssetId dependentSpawnableAssetId(GetSourceUuid(), dependentSpawnableAssetSubId); + + return RegisterProductAssetDependency(spawnableAssetId, dependentSpawnableAssetId); + } + + bool PrefabProcessorContext::RegisterProductAssetDependency(const AZ::Data::AssetId& assetId, const AZ::Data::AssetId& dependentAssetId) + { + return m_registeredProductAssetDependencies[assetId].emplace(dependentAssetId).second; + } + PrefabProcessorContext::ProcessedObjectStoreContainer& PrefabProcessorContext::GetProcessedObjects() { return m_products; @@ -80,6 +97,16 @@ namespace AzToolsFramework::Prefab::PrefabConversionUtils return m_products; } + PrefabProcessorContext::ProductAssetDependencyContainer& PrefabProcessorContext::GetRegisteredProductAssetDependencies() + { + return m_registeredProductAssetDependencies; + } + + const PrefabProcessorContext::ProductAssetDependencyContainer& PrefabProcessorContext::GetRegisteredProductAssetDependencies() const + { + return m_registeredProductAssetDependencies; + } + 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 66368f335b..3dc8c99bf3 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 ProductAssetDependencyContainer = + AZStd::unordered_map>; AZ_CLASS_ALLOCATOR(PrefabProcessorContext, AZ::SystemAllocator, 0); AZ_RTTI(PrefabProcessorContext, "{C7D77E3A-C544-486B-B774-7C82C38FE22F}"); @@ -37,14 +39,21 @@ 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 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 ProductAssetDependencyContainer& GetRegisteredProductAssetDependencies(); + virtual const ProductAssetDependencyContainer& GetRegisteredProductAssetDependencies() const; + virtual void SetPlatformTags(AZ::PlatformTagSet tags); virtual const AZ::PlatformTagSet& GetPlatformTags() const; virtual const AZ::Uuid& GetSourceUuid() const; @@ -57,7 +66,8 @@ namespace AzToolsFramework::Prefab::PrefabConversionUtils NamedPrefabContainer m_prefabs; ProcessedObjectStoreContainer m_products; - AZStd::vector m_delayedDelete; + ProductAssetDependencyContainer m_registeredProductAssetDependencies; + AZ::PlatformTagSet m_platformTags; AZ::Uuid m_sourceUuid; bool m_isIterating{ false }; 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..716c3098d9 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/Spawnable/SpawnableUtils.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/Spawnable/SpawnableUtils.cpp @@ -28,16 +28,23 @@ 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) + { + AZStd::vector> referencedAssets; + return CreateSpawnable(spawnable, prefabDom, referencedAssets); + } + + 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..3b5ea488cb 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/Spawnable/SpawnableUtils.h +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/Spawnable/SpawnableUtils.h @@ -19,6 +19,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 diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Slice/SliceUtilities.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/Slice/SliceUtilities.cpp index 75070d9b41..4b73166b3d 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Slice/SliceUtilities.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Slice/SliceUtilities.cpp @@ -1353,7 +1353,7 @@ namespace AzToolsFramework // Iterate over the entities left in the instance and if none of them have this // asset entity as its ancestor, then we want to remove it. // \todo - Investigate ways to make this non-linear time. Tricky since removed entities - // obviously aren't maintained in any maps. (https://jira.agscollab.com/browse/LY-88218) + // obviously aren't maintained in any maps. (LY-88218) bool foundAsAncestor = false; for (const AZ::Entity* instanceEntity : instanceEntities) { 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/ToolsComponents/TransformComponent.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/ToolsComponents/TransformComponent.cpp index 6ce797c3ee..8192e86956 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/ToolsComponents/TransformComponent.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/ToolsComponents/TransformComponent.cpp @@ -25,6 +25,7 @@ #include #include #include +#include #include #include #include @@ -265,7 +266,13 @@ namespace AzToolsFramework AZ::TransformNotificationBus::Event( GetEntityId(), &TransformNotification::OnTransformChanged, localTM, worldTM); + m_transformChangedEvent.Signal(localTM, worldTM); + AzFramework::IEntityBoundsUnion* boundsUnion = AZ::Interface::Get(); + if (boundsUnion != nullptr) + { + boundsUnion->OnTransformUpdated(GetEntity()); + } // Fire a property changed notification for this component if (const AZ::Component* component = entity->FindComponent()) { @@ -950,15 +957,14 @@ namespace AzToolsFramework { return nullptr; } - - AZ::Entity* pEntity = nullptr; - EBUS_EVENT_RESULT(pEntity, AZ::ComponentApplicationBus, FindEntity, otherEntityId); - if (!pEntity) + + AZ::Entity* entity = AZ::Interface::Get()->FindEntity(otherEntityId); + if (!entity) { return nullptr; } - return pEntity->FindComponent(); + return entity->FindComponent(); } AZ::TransformInterface* TransformComponent::GetParent() @@ -1297,7 +1303,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); @@ -1332,21 +1337,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/AzToolsFramework/AzToolsFramework/UI/Prefab/PrefabIntegrationManager.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/UI/Prefab/PrefabIntegrationManager.cpp index 6ce3fdc755..7f28080e9e 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/UI/Prefab/PrefabIntegrationManager.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/UI/Prefab/PrefabIntegrationManager.cpp @@ -151,32 +151,36 @@ namespace AzToolsFramework { if (!selectedEntities.empty()) { - bool layerInSelection = false; - - for (AZ::EntityId entityId : selectedEntities) + // Hide if the only selected entity is the Level Container + if (selectedEntities.size() > 1 || !s_prefabPublicInterface->IsLevelInstanceContainerEntity(selectedEntities[0])) { - if (!layerInSelection) - { - AzToolsFramework::Layers::EditorLayerComponentRequestBus::EventResult( - layerInSelection, entityId, - &AzToolsFramework::Layers::EditorLayerComponentRequestBus::Events::HasLayer); + bool layerInSelection = false; - if (layerInSelection) + for (AZ::EntityId entityId : selectedEntities) + { + if (!layerInSelection) { - break; + AzToolsFramework::Layers::EditorLayerComponentRequestBus::EventResult( + layerInSelection, entityId, + &AzToolsFramework::Layers::EditorLayerComponentRequestBus::Events::HasLayer); + + if (layerInSelection) + { + break; + } } } - } - // Layers can't be in prefabs. - if (!layerInSelection) - { - QAction* createAction = menu->addAction(QObject::tr("Create Prefab...")); - createAction->setToolTip(QObject::tr("Creates a prefab out of the currently selected entities.")); + // Layers can't be in prefabs. + if (!layerInSelection) + { + QAction* createAction = menu->addAction(QObject::tr("Create Prefab...")); + createAction->setToolTip(QObject::tr("Creates a prefab out of the currently selected entities.")); - QObject::connect(createAction, &QAction::triggered, createAction, [this, selectedEntities] { - ContextMenu_CreatePrefab(selectedEntities); - }); + QObject::connect(createAction, &QAction::triggered, createAction, [this, selectedEntities] { + ContextMenu_CreatePrefab(selectedEntities); + }); + } } } } @@ -272,6 +276,15 @@ namespace AzToolsFramework QWidget* activeWindow = QApplication::activeWindow(); const AZStd::string prefabFilesPath = "@devassets@/Prefabs"; + // Remove Level entity if it's part of the list + + auto levelContainerIter = + AZStd::find(selectedEntities.begin(), selectedEntities.end(), s_prefabPublicInterface->GetLevelInstanceContainerEntityId()); + if (levelContainerIter != selectedEntities.end()) + { + selectedEntities.erase(levelContainerIter); + } + // Set default folder for prefabs AZ::IO::FileIOBase* fileIoBaseInstance = AZ::IO::FileIOBase::GetInstance(); diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/UI/PropertyEditor/EntityPropertyEditor.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/UI/PropertyEditor/EntityPropertyEditor.cpp index bfb2ff4256..d0f3fa452a 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/UI/PropertyEditor/EntityPropertyEditor.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/UI/PropertyEditor/EntityPropertyEditor.cpp @@ -335,6 +335,7 @@ namespace AzToolsFramework m_gui->m_entityDetailsLabel->setObjectName("LabelEntityDetails"); m_gui->m_entitySearchBox->setReadOnly(false); m_gui->m_entitySearchBox->setContextMenuPolicy(Qt::CustomContextMenu); + m_gui->m_entitySearchBox->setClearButtonEnabled(true); AzQtComponents::LineEdit::applySearchStyle(m_gui->m_entitySearchBox); AzFramework::ApplicationRequests::Bus::BroadcastResult( 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/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportSelection/EditorHelpers.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportSelection/EditorHelpers.cpp index 68a5b43d73..d649e036ee 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportSelection/EditorHelpers.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportSelection/EditorHelpers.cpp @@ -68,6 +68,7 @@ namespace AzToolsFramework { AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + const AZ::Entity* entity = AZ::Interface::Get()->FindEntity(entityId); AzFramework::EntityDebugDisplayEventBus::Event( entityId, &AzFramework::EntityDebugDisplayEvents::DisplayEntityViewport, viewportInfo, debugDisplay); @@ -84,10 +85,9 @@ namespace AzToolsFramework if (ed_visibility_showAggregateEntityTransformedLocalBounds) { - AZ::Transform worldFromLocal = AZ::Transform::CreateIdentity(); - AZ::TransformBus::EventResult(worldFromLocal, entityId, &AZ::TransformBus::Events::GetWorldTM); + AZ::Transform worldFromLocal = entity->GetTransform()->GetWorldTM(); - if (const AZ::Aabb localAabb = AzFramework::CalculateEntityLocalBoundsUnion(entityId); localAabb.IsValid()) + if (const AZ::Aabb localAabb = AzFramework::CalculateEntityLocalBoundsUnion(entity); localAabb.IsValid()) { const AZ::Aabb worldAabb = localAabb.GetTransformedAabb(worldFromLocal); debugDisplay.SetColor(AZ::Colors::Turquoise); @@ -97,7 +97,7 @@ namespace AzToolsFramework if (ed_visibility_showAggregateEntityWorldBounds) { - if (const AZ::Aabb worldAabb = AzFramework::CalculateEntityWorldBoundsUnion(entityId); worldAabb.IsValid()) + if (const AZ::Aabb worldAabb = AzFramework::CalculateEntityWorldBoundsUnion(entity); worldAabb.IsValid()) { debugDisplay.SetColor(AZ::Colors::Magenta); debugDisplay.DrawWireBox(worldAabb.GetMin(), worldAabb.GetMax()); diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportSelection/EditorSelectionUtil.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportSelection/EditorSelectionUtil.cpp index 3be4bc9db2..88b92e8c41 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportSelection/EditorSelectionUtil.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportSelection/EditorSelectionUtil.cpp @@ -13,7 +13,9 @@ #include "EditorSelectionUtil.h" #include +#include #include +#include #include #include #include @@ -28,7 +30,8 @@ namespace AzToolsFramework { if (Centered(pivot)) { - if (const AZ::Aabb localBound = AzFramework::CalculateEntityLocalBoundsUnion(entityId); + const AZ::Entity* entity = AZ::Interface::Get()->FindEntity(entityId); + if (const AZ::Aabb localBound = AzFramework::CalculateEntityLocalBoundsUnion(entity); localBound.IsValid()) { return localBound.GetCenter(); 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 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/Framework/AzToolsFramework/Tests/Viewport/ViewportScreenTests.cpp b/Code/Framework/AzToolsFramework/Tests/Viewport/ViewportScreenTests.cpp index 8b3a564c4d..8f4133de63 100644 --- a/Code/Framework/AzToolsFramework/Tests/Viewport/ViewportScreenTests.cpp +++ b/Code/Framework/AzToolsFramework/Tests/Viewport/ViewportScreenTests.cpp @@ -211,6 +211,15 @@ namespace UnitTest EXPECT_EQ(screenPoint, ScreenPoint(45, 170)); } + TEST(ViewportScreen, ScreenVectorLengthReturned) + { + using AzFramework::ScreenVector; + + EXPECT_NEAR(AzFramework::ScreenVectorLength(ScreenVector(1, 1)), 1.41421f, 0.001f); + EXPECT_NEAR(AzFramework::ScreenVectorLength(ScreenVector(3, 4)), 5.0f, 0.001f); + EXPECT_NEAR(AzFramework::ScreenVectorLength(ScreenVector(12, 15)), 19.20937f, 0.001f); + } + TEST(ViewportScreen, CanGetCameraTransformFromCameraViewAndBack) { const auto screenDimensions = AZ::Vector2(1024.0f, 768.0f); diff --git a/Code/Framework/AzToolsFramework/Tests/Visibility/EditorVisibilityTests.cpp b/Code/Framework/AzToolsFramework/Tests/Visibility/EditorVisibilityTests.cpp index 0b059594be..a7aeee5660 100644 --- a/Code/Framework/AzToolsFramework/Tests/Visibility/EditorVisibilityTests.cpp +++ b/Code/Framework/AzToolsFramework/Tests/Visibility/EditorVisibilityTests.cpp @@ -62,8 +62,8 @@ namespace UnitTest SetupRowOfEntities(AZ::Vector3::CreateAxisX(-20.0f), AZ::Vector3::CreateAxisX(2.0f)); // request the entity union bounds system to update - AzFramework::EntityBoundsUnionRequestBus::Broadcast( - &AzFramework::EntityBoundsUnionRequestBus::Events::ProcessEntityBoundsUnionRequests); + AzFramework::IEntityBoundsUnionRequestBus::Broadcast( + &AzFramework::IEntityBoundsUnionRequestBus::Events::ProcessEntityBoundsUnionRequests); // create default camera looking down the negative y-axis moved just back from the origin AzFramework::CameraState cameraState = AzFramework::CreateDefaultCamera( @@ -101,8 +101,8 @@ namespace UnitTest SetupRowOfEntities(AZ::Vector3::CreateAxisX(-20.0f), AZ::Vector3::CreateAxisX(2.0f)); // request the entity union bounds system to update - AzFramework::EntityBoundsUnionRequestBus::Broadcast( - &AzFramework::EntityBoundsUnionRequestBus::Events::ProcessEntityBoundsUnionRequests); + AzFramework::IEntityBoundsUnionRequestBus::Broadcast( + &AzFramework::IEntityBoundsUnionRequestBus::Events::ProcessEntityBoundsUnionRequests); // create default camera looking down the negative x-axis moved along the x-axis and tilted slightly down AzFramework::CameraState cameraState = AzFramework::CreateDefaultCamera( @@ -143,15 +143,15 @@ namespace UnitTest SetupRowOfEntities(AZ::Vector3::CreateAxisX(-20.0f), AZ::Vector3::CreateAxisX(2.0f)); // request the entity union bounds system to update - AzFramework::EntityBoundsUnionRequestBus::Broadcast( - &AzFramework::EntityBoundsUnionRequestBus::Events::ProcessEntityBoundsUnionRequests); + AzFramework::IEntityBoundsUnionRequestBus::Broadcast( + &AzFramework::IEntityBoundsUnionRequestBus::Events::ProcessEntityBoundsUnionRequests); const AZ::EntityId entityIdToMove = m_editorEntityIds[10]; AZ::TransformBus::Event( entityIdToMove, &AZ::TransformBus::Events::SetWorldTranslation, AZ::Vector3::CreateAxisZ(100.0f)); - AzFramework::EntityBoundsUnionRequestBus::Broadcast( - &AzFramework::EntityBoundsUnionRequestBus::Events::ProcessEntityBoundsUnionRequests); + AzFramework::IEntityBoundsUnionRequestBus::Broadcast( + &AzFramework::IEntityBoundsUnionRequestBus::Events::ProcessEntityBoundsUnionRequests); // create default camera looking down the negative y-axis moved just back from the origin AzFramework::CameraState cameraState = AzFramework::CreateDefaultCamera( @@ -241,8 +241,8 @@ namespace UnitTest { m_localAabb = localAabb; - AzFramework::EntityBoundsUnionRequestBus::Broadcast( - &AzFramework::EntityBoundsUnionRequestBus::Events::RefreshEntityLocalBoundsUnion, GetEntityId()); + AzFramework::IEntityBoundsUnionRequestBus::Broadcast( + &AzFramework::IEntityBoundsUnionRequestBus::Events::RefreshEntityLocalBoundsUnion, GetEntityId()); } TEST_F(EditorVisibilityFixture, UpdatedBoundsIntersectingFrustumAddsVisibleEntity) @@ -264,8 +264,8 @@ namespace UnitTest entityId, &AZ::TransformBus::Events::SetWorldTranslation, AZ::Vector3(40.0f, -3.0f, 20.0f)); // request the entity union bounds system to update - AzFramework::EntityBoundsUnionRequestBus::Broadcast( - &AzFramework::EntityBoundsUnionRequestBus::Events::ProcessEntityBoundsUnionRequests); + AzFramework::IEntityBoundsUnionRequestBus::Broadcast( + &AzFramework::IEntityBoundsUnionRequestBus::Events::ProcessEntityBoundsUnionRequests); // create default camera looking down the positive x-axis moved to position offset from world origin AzFramework::CameraState cameraState = AzFramework::CreateDefaultCamera( @@ -288,8 +288,8 @@ namespace UnitTest testBoundComponent->ChangeBounds(AZ::Aabb::CreateFromMinMax(AZ::Vector3(-2.5f), AZ::Vector3(2.5f))); // perform an 'update' of the visibility system - AzFramework::EntityBoundsUnionRequestBus::Broadcast( - &AzFramework::EntityBoundsUnionRequestBus::Events::ProcessEntityBoundsUnionRequests); + AzFramework::IEntityBoundsUnionRequestBus::Broadcast( + &AzFramework::IEntityBoundsUnionRequestBus::Events::ProcessEntityBoundsUnionRequests); entityVisibilityQuery.UpdateVisibility(cameraState); 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/ComponentAddRemove.cpp b/Code/Framework/Tests/ComponentAddRemove.cpp index e47b69c977..4fd6db7dde 100644 --- a/Code/Framework/Tests/ComponentAddRemove.cpp +++ b/Code/Framework/Tests/ComponentAddRemove.cpp @@ -1100,6 +1100,10 @@ namespace UnitTest void UnregisterComponentDescriptor(const ComponentDescriptor*) override {} void RegisterEntityAddedEventHandler(EntityAddedEvent::Handler&) override {} void RegisterEntityRemovedEventHandler(EntityRemovedEvent::Handler&) override {} + void RegisterEntityActivatedEventHandler(EntityActivatedEvent::Handler&) override {} + void RegisterEntityDeactivatedEventHandler(EntityDeactivatedEvent::Handler&) override {} + void SignalEntityActivated(Entity*) override {} + void SignalEntityDeactivated(Entity*) override {} bool AddEntity(Entity*) override { return true; } bool RemoveEntity(Entity*) override { return true; } bool DeleteEntity(const EntityId&) override { return true; } @@ -1125,6 +1129,7 @@ namespace UnitTest AllocatorsFixture::SetUp(); ComponentApplicationBus::Handler::BusConnect(); + AZ::Interface::Register(this); m_serializeContext.reset(aznew AZ::SerializeContext(true, true)); Entity::Reflect(m_serializeContext.get()); @@ -1139,6 +1144,7 @@ namespace UnitTest m_descriptors.set_capacity(0); m_serializeContext.reset(); + AZ::Interface::Unregister(this); ComponentApplicationBus::Handler::BusDisconnect(); AllocatorsFixture::TearDown(); 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 a07cae0077..0000000000 --- a/Code/Framework/Tests/NetBindingMocks.h +++ /dev/null @@ -1,331 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or 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(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 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/2DViewport.cpp b/Code/Sandbox/Editor/2DViewport.cpp index 0487c9381f..9eab4df16d 100644 --- a/Code/Sandbox/Editor/2DViewport.cpp +++ b/Code/Sandbox/Editor/2DViewport.cpp @@ -86,7 +86,6 @@ inline Vec3 SnapToSize(Vec3 v, double size) ////////////////////////////////////////////////////////////////////// Q2DViewport::Q2DViewport(QWidget* parent) : QtViewport(parent) - , m_renderer(nullptr) { // Scroll offset equals origin m_rcSelect.setRect(0, 0, 0, 0); @@ -528,15 +527,6 @@ void Q2DViewport::paintEvent([[maybe_unused]] QPaintEvent* event) ////////////////////////////////////////////////////////////////////////// int Q2DViewport::OnCreate() { - m_renderer = GetIEditor()->GetRenderer(); - assert (m_renderer != NULL); - if (m_renderer) - { - WIN_HWND previousContext = m_renderer->GetCurrentContextHWND(); - m_renderer->CreateContext(renderOverlayHWND()); - m_renderer->SetCurrentContext(previousContext); - } - // Calculate the View transformation matrix. CalculateViewTM(); @@ -641,10 +631,6 @@ void Q2DViewport::OnTitleMenu(QMenu* menu) ////////////////////////////////////////////////////////////////////////// void Q2DViewport::OnDestroy() { - if (m_renderer) - { - m_renderer->DeleteContext(renderOverlayHWND()); - } } ////////////////////////////////////////////////////////////////////////// @@ -674,9 +660,7 @@ void Q2DViewport::Draw(DisplayContext& dc) ////////////////////////////////////////////////////////////////////////// void Q2DViewport::DrawGrid(DisplayContext& dc, bool bNoXNumbers) { - CGrid* pGrid = GetIEditor()->GetViewManager()->GetGrid(); - float gridSize = pGrid->size; - + float gridSize = 1.0f; if (gridSize < 0.00001f) { return; @@ -707,8 +691,6 @@ void Q2DViewport::DrawGrid(DisplayContext& dc, bool bNoXNumbers) pixelsPerGrid = gridSize * fScale; while (pixelsPerGrid <= 5 && griditers++ < 20) { - m_fGridZoom *= pGrid->majorLine; - gridSize = gridSize * pGrid->majorLine; pixelsPerGrid = gridSize * fScale; } } @@ -757,7 +739,7 @@ void Q2DViewport::DrawGrid(DisplayContext& dc, bool bNoXNumbers) ////////////////////////////////////////////////////////////////////////// // Draw Major grid lines. ////////////////////////////////////////////////////////////////////////// - gridSize = gridSize * pGrid->majorLine; + gridSize = gridSize * 1.0f; if (m_bAutoAdjustGrids) { diff --git a/Code/Sandbox/Editor/2DViewport.h b/Code/Sandbox/Editor/2DViewport.h index 818f01064c..d7e6ee17f4 100644 --- a/Code/Sandbox/Editor/2DViewport.h +++ b/Code/Sandbox/Editor/2DViewport.h @@ -159,7 +159,6 @@ protected: ////////////////////////////////////////////////////////////////////////// // Variables. ////////////////////////////////////////////////////////////////////////// - IRenderer* m_renderer; //! XY/XZ/YZ mode of this 2D viewport. EViewportType m_viewType; diff --git a/Code/Sandbox/Editor/ActionManager.h b/Code/Sandbox/Editor/ActionManager.h index d536fd4121..3f599ecf82 100644 --- a/Code/Sandbox/Editor/ActionManager.h +++ b/Code/Sandbox/Editor/ActionManager.h @@ -169,6 +169,13 @@ public: return *this; } + template + ActionWrapper& RegisterUpdateCallback(Fn&& fn) + { + m_actionManager->RegisterUpdateCallback(m_action->data().toInt(), AZStd::forward(fn)); + return *this; + } + private: friend ActionManager; friend DynamicMenu; @@ -315,11 +322,17 @@ public: void DetachOverride() override; template - void RegisterUpdateCallback(int id, T* object, void (T::* method)(QAction*)) + void RegisterUpdateCallback(int id, T* object, void (T::*method)(QAction*)) { Q_ASSERT(m_actions.contains(id)); - auto f = std::bind(method, object, m_actions.value(id)); - m_updateCallbacks[id] = f; + m_updateCallbacks[id] = [action = m_actions.value(id), object, method] { AZStd::invoke(method, object, action); }; + } + + template + void RegisterUpdateCallback(int id, Fn&& fn) + { + Q_ASSERT(m_actions.contains(id)); + m_updateCallbacks[id] = [action = m_actions.value(id), fn] { fn(action); }; } template 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/Controls/ConsoleSCB.cpp b/Code/Sandbox/Editor/Controls/ConsoleSCB.cpp index 590f7941c4..f6616197aa 100644 --- a/Code/Sandbox/Editor/Controls/ConsoleSCB.cpp +++ b/Code/Sandbox/Editor/Controls/ConsoleSCB.cpp @@ -26,6 +26,7 @@ // AzQtComponents #include #include +#include #include #include @@ -314,7 +315,10 @@ CConsoleSCB::CConsoleSCB(QWidget* parent) setMinimumHeight(120); ui->findBar->setVisible(false); - + ui->lineEditFind->setPlaceholderText(QObject::tr("Search...")); + ui->lineEditFind->setClearButtonEnabled(true); + AzQtComponents::LineEdit::applySearchStyle(ui->lineEditFind); + // Setup the color table for the default (light) theme m_colorTable << QColor(0, 0, 0) << QColor(0, 0, 0) 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/Controls/ReflectedPropertyControl/PropertyCtrl.cpp b/Code/Sandbox/Editor/Controls/ReflectedPropertyControl/PropertyCtrl.cpp index f0367ffdc1..3f7a3142e9 100644 --- a/Code/Sandbox/Editor/Controls/ReflectedPropertyControl/PropertyCtrl.cpp +++ b/Code/Sandbox/Editor/Controls/ReflectedPropertyControl/PropertyCtrl.cpp @@ -28,7 +28,6 @@ void RegisterReflectedVarHandlers() registered = true; EBUS_EVENT(AzToolsFramework::PropertyTypeRegistrationMessages::Bus, RegisterPropertyType, aznew AnimationPropertyWidgetHandler()); EBUS_EVENT(AzToolsFramework::PropertyTypeRegistrationMessages::Bus, RegisterPropertyType, aznew FileResourceSelectorWidgetHandler()); - EBUS_EVENT(AzToolsFramework::PropertyTypeRegistrationMessages::Bus, RegisterPropertyType, aznew ShaderPropertyHandler()); EBUS_EVENT(AzToolsFramework::PropertyTypeRegistrationMessages::Bus, RegisterPropertyType, aznew ReverbPresetPropertyHandler()); EBUS_EVENT(AzToolsFramework::PropertyTypeRegistrationMessages::Bus, RegisterPropertyType, aznew SequencePropertyHandler()); EBUS_EVENT(AzToolsFramework::PropertyTypeRegistrationMessages::Bus, RegisterPropertyType, aznew SequenceIdPropertyHandler()); diff --git a/Code/Sandbox/Editor/Controls/ReflectedPropertyControl/PropertyGenericCtrl.cpp b/Code/Sandbox/Editor/Controls/ReflectedPropertyControl/PropertyGenericCtrl.cpp index 75344b2172..5fde2c39a5 100644 --- a/Code/Sandbox/Editor/Controls/ReflectedPropertyControl/PropertyGenericCtrl.cpp +++ b/Code/Sandbox/Editor/Controls/ReflectedPropertyControl/PropertyGenericCtrl.cpp @@ -26,7 +26,6 @@ #include // Editor -#include "ShadersDialog.h" #include "SelectLightAnimationDialog.h" #include "SelectSequenceDialog.h" #include "SelectEAXPresetDlg.h" @@ -78,16 +77,6 @@ void GenericPopupPropertyEditor::SetPropertyType(PropertyType type) m_propertyType = type; } -void ShaderPropertyEditor::onEditClicked() -{ - CShadersDialog cShaders(GetValue()); - if (cShaders.exec() == QDialog::Accepted) - { - SetValue(cShaders.GetSelection()); - } - -} - void ReverbPresetPropertyEditor::onEditClicked() { CSelectEAXPresetDlg PresetDlg(this); diff --git a/Code/Sandbox/Editor/Controls/ReflectedPropertyControl/PropertyGenericCtrl.h b/Code/Sandbox/Editor/Controls/ReflectedPropertyControl/PropertyGenericCtrl.h index cdbb18ae12..f0d5ed4db7 100644 --- a/Code/Sandbox/Editor/Controls/ReflectedPropertyControl/PropertyGenericCtrl.h +++ b/Code/Sandbox/Editor/Controls/ReflectedPropertyControl/PropertyGenericCtrl.h @@ -100,15 +100,6 @@ public: } }; -class ShaderPropertyEditor - : public GenericPopupPropertyEditor -{ -public: - ShaderPropertyEditor(QWidget* pParent = nullptr) - : GenericPopupPropertyEditor(pParent){} - void onEditClicked() override; -}; - class ReverbPresetPropertyEditor : public GenericPopupPropertyEditor { @@ -168,7 +159,6 @@ public: // So we use our own #define CONST_AZ_CRC(name, value) AZ::u32(value) -using ShaderPropertyHandler = GenericPopupWidgetHandler; using ReverbPresetPropertyHandler = GenericPopupWidgetHandler; using MissionObjPropertyHandler = GenericPopupWidgetHandler; using SequencePropertyHandler = GenericPopupWidgetHandler; diff --git a/Code/Sandbox/Editor/Controls/ReflectedPropertyControl/ReflectedPropertyItem.cpp b/Code/Sandbox/Editor/Controls/ReflectedPropertyControl/ReflectedPropertyItem.cpp index 13584d9b82..4ac5733401 100644 --- a/Code/Sandbox/Editor/Controls/ReflectedPropertyControl/ReflectedPropertyItem.cpp +++ b/Code/Sandbox/Editor/Controls/ReflectedPropertyControl/ReflectedPropertyItem.cpp @@ -268,7 +268,6 @@ void ReflectedPropertyItem::SetVariable(IVariable *var) case ePropertyUser: m_reflectedVarAdapter = new ReflectedVarUserAdapter; break; - case ePropertyShader: case ePropertyEquip: case ePropertyReverbPreset: case ePropertyGameToken: diff --git a/Code/Sandbox/Editor/Core/LevelEditorMenuHandler.cpp b/Code/Sandbox/Editor/Core/LevelEditorMenuHandler.cpp index 869fa2fe25..0ce3fa55f5 100644 --- a/Code/Sandbox/Editor/Core/LevelEditorMenuHandler.cpp +++ b/Code/Sandbox/Editor/Core/LevelEditorMenuHandler.cpp @@ -514,7 +514,7 @@ void LevelEditorMenuHandler::PopulateEditMenu(ActionManager::MenuWrapper& editMe /* * The following block of code is part of the feature "Isolation Mode" and is temporarily * disabled for 1.10 release. - * Jira: https://jira.agscollab.com/browse/LY-49532 + * Jira: LY-49532 // Isolate Selected QAction* isolateSelectedAction = editMenu->addAction(tr("Isolate Selected")); @@ -729,9 +729,6 @@ QMenu* LevelEditorMenuHandler::CreateViewMenu() viewportViewsMenuWrapper.AddAction(ID_WIREFRAME); viewportViewsMenuWrapper.AddSeparator(); - viewportViewsMenuWrapper.AddAction(ID_VIEW_GRIDSETTINGS); - viewportViewsMenuWrapper.AddSeparator(); - if (CViewManager::IsMultiViewportEnabled()) { viewportViewsMenuWrapper.AddAction(ID_VIEW_CONFIGURELAYOUT); diff --git a/Code/Sandbox/Editor/CryEdit.cpp b/Code/Sandbox/Editor/CryEdit.cpp index b88aee8bd9..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" @@ -95,7 +94,6 @@ AZ_POP_DISABLE_WARNING #include "Core/QtEditorApplication.h" #include "StringDlg.h" #include "NewLevelDialog.h" -#include "GridSettingsDialog.h" #include "LayoutConfigDialog.h" #include "ViewManager.h" #include "FileTypeUtils.h" @@ -132,7 +130,6 @@ AZ_POP_DISABLE_WARNING #include "Util/AutoDirectoryRestoreFileDialog.h" #include "Util/EditorAutoLevelLoadTest.h" -#include "Util/Ruler.h" #include "Util/IndexedFiles.h" #include "AboutDialog.h" #include @@ -390,7 +387,6 @@ void CCryEditApp::RegisterActionHandlers() ON_COMMAND(ID_PREFERENCES, OnPreferences) ON_COMMAND(ID_REDO, OnRedo) ON_COMMAND(ID_TOOLBAR_WIDGET_REDO, OnRedo) - ON_COMMAND(ID_RELOAD_TEXTURES, OnReloadTextures) ON_COMMAND(ID_FILE_OPEN_LEVEL, OnOpenLevel) #ifdef ENABLE_SLICE_EDITOR ON_COMMAND(ID_FILE_NEW_SLICE, OnCreateSlice) @@ -400,11 +396,8 @@ void CCryEditApp::RegisterActionHandlers() ON_COMMAND(ID_GAME_SYNCPLAYER, OnSyncPlayer) ON_COMMAND(ID_RESOURCES_REDUCEWORKINGSET, OnResourcesReduceworkingset) - ON_COMMAND(ID_SNAP_TO_GRID, OnSnap) - ON_COMMAND(ID_WIREFRAME, OnWireframe) - ON_COMMAND(ID_VIEW_GRIDSETTINGS, OnViewGridsettings) ON_COMMAND(ID_VIEW_CONFIGURELAYOUT, OnViewConfigureLayout) ON_COMMAND(IDC_SELECTION, OnDummyCommand) @@ -444,7 +437,6 @@ void CCryEditApp::RegisterActionHandlers() ON_COMMAND(ID_VIEW_CYCLE2DVIEWPORT, OnViewCycle2dviewport) #endif ON_COMMAND(ID_DISPLAY_GOTOPOSITION, OnDisplayGotoPosition) - ON_COMMAND(ID_SNAPANGLE, OnSnapangle) ON_COMMAND(ID_CHANGEMOVESPEED_INCREASE, OnChangemovespeedIncrease) ON_COMMAND(ID_CHANGEMOVESPEED_DECREASE, OnChangemovespeedDecrease) ON_COMMAND(ID_CHANGEMOVESPEED_CHANGESTEP, OnChangemovespeedChangestep) @@ -527,12 +519,6 @@ public: bool m_bExportTexture = false; bool m_bMatEditMode = false; - bool m_bPrecacheShaders = false; - bool m_bPrecacheShadersLevels = false; - bool m_bPrecacheShaderList = false; - bool m_bStatsShaders = false; - bool m_bStatsShaderList = false; - bool m_bMergeShaders = false; bool m_bConsoleMode = false; bool m_bNullRenderer = false; @@ -574,12 +560,6 @@ public: { "exportTexture", m_bExportTexture }, { "test", m_bTest }, { "auto_level_load", m_bAutoLoadLevel }, - { "PrecacheShaders", m_bPrecacheShaders }, - { "PrecacheShadersLevels", m_bPrecacheShadersLevels }, - { "PrecacheShaderList", m_bPrecacheShaderList }, - { "StatsShaders", m_bStatsShaders }, - { "StatsShaderList", m_bStatsShaderList }, - { "MergeShaders", m_bMergeShaders }, { "MatEdit", m_bMatEditMode }, { "BatchMode", m_bConsoleMode }, { "NullRenderer", m_bNullRenderer }, @@ -1024,26 +1004,12 @@ void CCryEditApp::OutputStartupMessage(QString str) ////////////////////////////////////////////////////////////////////////// void CCryEditApp::InitFromCommandLine(CEditCommandLineInfo& cmdInfo) { - //! Setup flags from command line - if (cmdInfo.m_bPrecacheShaders || cmdInfo.m_bPrecacheShadersLevels || cmdInfo.m_bMergeShaders - || cmdInfo.m_bPrecacheShaderList || cmdInfo.m_bStatsShaderList || cmdInfo.m_bStatsShaders) - { - m_bPreviewMode = true; - m_bConsoleMode = true; - m_bTestMode = true; - } m_bConsoleMode |= cmdInfo.m_bConsoleMode; inEditorBatchMode = AZ::Environment::CreateVariable("InEditorBatchMode", m_bConsoleMode); m_bTestMode |= cmdInfo.m_bTest; m_bSkipWelcomeScreenDialog = cmdInfo.m_bSkipWelcomeScreenDialog || !cmdInfo.m_execFile.isEmpty() || !cmdInfo.m_execLineCmd.isEmpty() || cmdInfo.m_bAutotestMode; - m_bPrecacheShaderList = cmdInfo.m_bPrecacheShaderList; - m_bStatsShaderList = cmdInfo.m_bStatsShaderList; - m_bStatsShaders = cmdInfo.m_bStatsShaders; - m_bPrecacheShaders = cmdInfo.m_bPrecacheShaders; - m_bPrecacheShadersLevels = cmdInfo.m_bPrecacheShadersLevels; - m_bMergeShaders = cmdInfo.m_bMergeShaders; m_bExportMode = cmdInfo.m_bExport; m_bRunPythonTestScript = cmdInfo.m_bRunPythonTestScript; m_bRunPythonScript = cmdInfo.m_bRunPythonScript || cmdInfo.m_bRunPythonTestScript; @@ -1079,11 +1045,9 @@ void CCryEditApp::InitFromCommandLine(CEditCommandLineInfo& cmdInfo) ///////////////////////////////////////////////////////////////////////////// AZ::Outcome CCryEditApp::InitGameSystem(HWND hwndForInputSystem) { - bool bShaderCacheGen = m_bPrecacheShaderList | m_bPrecacheShaders | m_bPrecacheShadersLevels; - CGameEngine* pGameEngine = new CGameEngine; - AZ::Outcome initOutcome = pGameEngine->Init(m_bPreviewMode, m_bTestMode, bShaderCacheGen, qApp->arguments().join(" ").toUtf8().data(), g_pInitializeUIInfo, hwndForInputSystem); + AZ::Outcome initOutcome = pGameEngine->Init(m_bPreviewMode, m_bTestMode, qApp->arguments().join(" ").toUtf8().data(), g_pInitializeUIInfo, hwndForInputSystem); if (!initOutcome.IsSuccess()) { return initOutcome; @@ -1124,8 +1088,7 @@ BOOL CCryEditApp::CheckIfAlreadyRunning() } } - // Shader pre-caching may start multiple editor copies - if (!FirstInstance(bForceNewInstance) && !m_bPrecacheShaderList) + if (!FirstInstance(bForceNewInstance)) { return false; } @@ -1347,37 +1310,6 @@ void CCryEditApp::InitLevel(const CEditCommandLineInfo& cmdInfo) ///////////////////////////////////////////////////////////////////////////// BOOL CCryEditApp::InitConsole() { - if (m_bPrecacheShaderList) - { - GetIEditor()->GetSystem()->GetIConsole()->ExecuteString("r_PrecacheShaderList"); - return false; - } - else if (m_bStatsShaderList) - { - GetIEditor()->GetSystem()->GetIConsole()->ExecuteString("r_StatsShaderList"); - return false; - } - else if (m_bStatsShaders) - { - GetIEditor()->GetSystem()->GetIConsole()->ExecuteString("r_StatsShaders"); - return false; - } - else if (m_bPrecacheShaders) - { - GetIEditor()->GetSystem()->GetIConsole()->ExecuteString("r_PrecacheShaders"); - return false; - } - else if (m_bPrecacheShadersLevels) - { - GetIEditor()->GetSystem()->GetIConsole()->ExecuteString("r_PrecacheShadersLevels"); - return false; - } - else if (m_bMergeShaders) - { - GetIEditor()->GetSystem()->GetIConsole()->ExecuteString("r_MergeShaders"); - return false; - } - // Execute command from cmdline -exec_line if applicable if (!m_execLineCmd.isEmpty()) { @@ -2381,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(); @@ -2930,14 +2853,6 @@ void CCryEditApp::OnPreferences() */ } -void CCryEditApp::OnReloadTextures() -{ - QWaitCursor wait; - CLogFile::WriteLine("Reloading Static objects textures and shaders."); - GetIEditor()->GetObjectManager()->SendEvent(EVENT_RELOAD_TEXTURES); - GetIEditor()->GetRenderer()->EF_ReloadTextures(); -} - ////////////////////////////////////////////////////////////////////////// void CCryEditApp::OnUndo() { @@ -3493,14 +3408,6 @@ void CCryEditApp::OnResourcesReduceworkingset() #endif } -////////////////////////////////////////////////////////////////////////// -void CCryEditApp::OnSnap() -{ - // Switch current snap to grid state. - bool bGridEnabled = gSettings.pGrid->IsEnabled(); - gSettings.pGrid->Enable(!bGridEnabled); -} - void CCryEditApp::OnWireframe() { int nWireframe(R_SOLID_MODE); @@ -3540,14 +3447,6 @@ void CCryEditApp::OnUpdateWireframe(QAction* action) action->setChecked(nWireframe == R_WIREFRAME_MODE); } - -////////////////////////////////////////////////////////////////////////// -void CCryEditApp::OnViewGridsettings() -{ - CGridSettingsDialog dlg; - dlg.exec(); -} - ////////////////////////////////////////////////////////////////////////// void CCryEditApp::OnViewConfigureLayout() { @@ -3749,19 +3648,6 @@ void CCryEditApp::OnDisplayGotoPosition() dlg.exec(); } -////////////////////////////////////////////////////////////////////////// -void CCryEditApp::OnSnapangle() -{ - gSettings.pGrid->EnableAngleSnap(!gSettings.pGrid->IsAngleSnapEnabled()); -} - -////////////////////////////////////////////////////////////////////////// -void CCryEditApp::OnUpdateSnapangle(QAction* action) -{ - Q_ASSERT(action->isCheckable()); - action->setChecked(gSettings.pGrid->IsAngleSnapEnabled()); -} - ////////////////////////////////////////////////////////////////////////// void CCryEditApp::OnChangemovespeedIncrease() { diff --git a/Code/Sandbox/Editor/CryEdit.h b/Code/Sandbox/Editor/CryEdit.h index c0b26a9405..2e71ca6a58 100644 --- a/Code/Sandbox/Editor/CryEdit.h +++ b/Code/Sandbox/Editor/CryEdit.h @@ -229,7 +229,6 @@ public: void OnFileResaveSlices(); void OnFileEditEditorini(); void OnPreferences(); - void OnReloadTextures(); void OnRedo(); void OnUpdateRedo(QAction* action); void OnUpdateUndo(QAction* action); @@ -284,12 +283,6 @@ private: //! Test mode is a special mode enabled when Editor ran with /test command line. //! In this mode editor starts up, but exit immediately after all initialization. bool m_bTestMode = false; - bool m_bPrecacheShaderList = false; - bool m_bPrecacheShaders = false; - bool m_bPrecacheShadersLevels = false; - bool m_bMergeShaders = false; - bool m_bStatsShaderList = false; - bool m_bStatsShaders = false; //! In this mode editor will load specified cry file, export t, and then close. bool m_bExportMode = false; QString m_exportFile; @@ -371,10 +364,8 @@ private: AZ_POP_DISABLE_DLL_EXPORT_MEMBER_WARNING friend struct PythonTestOutputHandler; - void OnSnap(); void OnWireframe(); void OnUpdateWireframe(QAction* action); - void OnViewGridsettings(); void OnViewConfigureLayout(); // Tag Locations. @@ -409,8 +400,6 @@ private: void OnToolsScriptHelp(); void OnViewCycle2dviewport(); void OnDisplayGotoPosition(); - void OnSnapangle(); - void OnUpdateSnapangle(QAction* action); void OnChangemovespeedIncrease(); void OnChangemovespeedDecrease(); void OnChangemovespeedChangestep(); diff --git a/Code/Sandbox/Editor/CryEditDoc.cpp b/Code/Sandbox/Editor/CryEditDoc.cpp index ffcbd00a5f..a6c5f73c7f 100644 --- a/Code/Sandbox/Editor/CryEditDoc.cpp +++ b/Code/Sandbox/Editor/CryEditDoc.cpp @@ -51,7 +51,6 @@ #include "Include/IObjectManager.h" #include "ErrorReportDialog.h" #include "SurfaceTypeValidator.h" -#include "ShaderCache.h" #include "Util/AutoLogTime.h" #include "CheckOutDialog.h" #include "GameExporter.h" @@ -143,7 +142,6 @@ CCryEditDoc::CCryEditDoc() m_environmentTemplate = XmlHelpers::CreateXmlNode("Environment"); } - m_pLevelShaderCache = new CLevelShaderCache; m_bDocumentReady = false; GetIEditor()->SetDocument(this); CLogFile::WriteLine("Document created"); @@ -156,8 +154,6 @@ CCryEditDoc::~CCryEditDoc() { GetIEditor()->SetDocument(nullptr); - delete m_pLevelShaderCache; - CLogFile::WriteLine("Document destroyed"); AzToolsFramework::SliceEditorEntityOwnershipServiceNotificationBus::Handler::BusDisconnect(); @@ -337,7 +333,6 @@ void CCryEditDoc::Save(TDocMultiArchive& arrXmlAr) // Fog settings /////////////////////////////////////////////////////// SerializeFogSettings((*arrXmlAr[DMAS_GENERAL])); - SerializeShaderCache((*arrXmlAr[DMAS_GENERAL_NAMED_DATA])); SerializeNameSelection((*arrXmlAr[DMAS_GENERAL])); } } @@ -486,7 +481,6 @@ void CCryEditDoc::Load(TDocMultiArchive& arrXmlAr, const QString& szFilename) { // Serialize Shader Cache. CAutoLogTime logtime("Load Level Shader Cache"); - SerializeShaderCache((*arrXmlAr[DMAS_GENERAL_NAMED_DATA])); } { @@ -585,23 +579,13 @@ void CCryEditDoc::SerializeViewSettings(CXmlArchive& xmlAr) view->getAttr(viewerAnglesName.toUtf8().constData(), va); } - CViewport* pVP = GetIEditor()->GetViewManager()->GetView(i); + Matrix34 tm = Matrix34::CreateRotationXYZ(va); + tm.SetTranslation(vp); - - if (pVP) + auto viewportContextManager = AZ::Interface::Get(); + if (auto viewportContext = viewportContextManager->GetViewportContextById(i)) { - Matrix34 tm = Matrix34::CreateRotationXYZ(va); - tm.SetTranslation(vp); - pVP->SetViewTM(tm); - } - - // Load grid. - auto gridName = QString("Grid%1").arg(useOldViewFormat ? "" : QString::number(i)); - XmlNodeRef gridNode = xmlAr.root->newChild(gridName.toUtf8().constData()); - - if (gridNode) - { - GetIEditor()->GetViewManager()->GetGrid()->Serialize(gridNode, xmlAr.bLoading); + viewportContext->SetCameraTransform(LYTransformToAZTransform(tm)); } } } @@ -628,11 +612,6 @@ void CCryEditDoc::SerializeViewSettings(CXmlArchive& xmlAr) auto viewerAnglesName = QString("ViewerAngles%1").arg(i); view->setAttr(viewerAnglesName.toUtf8().constData(), angles); } - - // Save grid. - auto gridName = QString("Grid%1").arg(i); - XmlNodeRef gridNode = xmlAr.root->newChild(gridName.toUtf8().constData()); - GetIEditor()->GetViewManager()->GetGrid()->Serialize(gridNode, xmlAr.bLoading); } } } @@ -668,39 +647,6 @@ void CCryEditDoc::SerializeFogSettings(CXmlArchive& xmlAr) } } -void CCryEditDoc::SerializeShaderCache(CXmlArchive& xmlAr) -{ - if (xmlAr.bLoading) - { - void* pData = 0; - int nSize = 0; - - if (xmlAr.pNamedData->GetDataBlock("ShaderCache", pData, nSize)) - { - if (nSize <= 0) - { - return; - } - - QByteArray str(nSize + 1, 0); - memcpy(str.data(), pData, nSize); - str[nSize] = 0; - m_pLevelShaderCache->LoadBuffer(str); - } - } - else - { - QString buf; - - m_pLevelShaderCache->SaveBuffer(buf); - - if (!buf.isEmpty()) - { - xmlAr.pNamedData->AddDataBlock("ShaderCache", buf.toUtf8().data(), buf.toUtf8().count()); - } - } -} - void CCryEditDoc::SerializeNameSelection(CXmlArchive& xmlAr) { IObjectManager* pObjManager = GetIEditor()->GetObjectManager(); diff --git a/Code/Sandbox/Editor/CryEditDoc.h b/Code/Sandbox/Editor/CryEditDoc.h index be8a5fcec7..1ca3dc85f4 100644 --- a/Code/Sandbox/Editor/CryEditDoc.h +++ b/Code/Sandbox/Editor/CryEditDoc.h @@ -22,7 +22,6 @@ #include #endif -class CLevelShaderCache; class CClouds; struct LightingSettings; struct IVariable; @@ -123,7 +122,6 @@ public: // Create from serialization only const char* GetTemporaryLevelName() const; void DeleteTemporaryLevel(); - CLevelShaderCache* GetShaderCache() { return m_pLevelShaderCache; } CClouds* GetClouds() { return m_pClouds; } void SetWaterColor(const QColor& col) { m_waterColor = col; } QColor GetWaterColor() { return m_waterColor; } @@ -165,7 +163,6 @@ protected: bool LoadEntitiesFromSlice(const QString& sliceFile); void SerializeFogSettings(CXmlArchive& xmlAr); virtual void SerializeViewSettings(CXmlArchive& xmlAr); - void SerializeShaderCache(CXmlArchive& xmlAr); void SerializeNameSelection(CXmlArchive& xmlAr); void LogLoadTime(int time); @@ -201,7 +198,6 @@ protected: CClouds* m_pClouds; std::list m_listeners; bool m_bDocumentReady; - CLevelShaderCache* m_pLevelShaderCache; ICVar* doc_validate_surface_types; int m_modifiedModuleFlags; bool m_boLevelExported; diff --git a/Code/Sandbox/Editor/EditorFileMonitor.cpp b/Code/Sandbox/Editor/EditorFileMonitor.cpp index 1898ae5f7a..f627b61255 100644 --- a/Code/Sandbox/Editor/EditorFileMonitor.cpp +++ b/Code/Sandbox/Editor/EditorFileMonitor.cpp @@ -35,9 +35,6 @@ void CEditorFileMonitor::OnEditorNotifyEvent(EEditorNotifyEvent ev) { if (ev == eNotify_OnInit) { - // Setup file change monitoring - gEnv->pSystem->SetIFileChangeMonitor(this); - // We don't want the file monitor to be enabled while // in console mode... if (!GetIEditor()->IsInConsolewMode()) @@ -49,7 +46,6 @@ void CEditorFileMonitor::OnEditorNotifyEvent(EEditorNotifyEvent ev) } else if (ev == eNotify_OnQuit) { - gEnv->pSystem->SetIFileChangeMonitor(NULL); CFileChangeMonitor::Instance()->StopMonitor(); GetIEditor()->UnregisterNotifyListener(this); } diff --git a/Code/Sandbox/Editor/EditorFileMonitor.h b/Code/Sandbox/Editor/EditorFileMonitor.h index 9af68a6179..916c0cb11a 100644 --- a/Code/Sandbox/Editor/EditorFileMonitor.h +++ b/Code/Sandbox/Editor/EditorFileMonitor.h @@ -15,7 +15,6 @@ #define CRYINCLUDE_EDITOR_EDITORFILEMONITOR_H #pragma once #include "Include/IEditorFileMonitor.h" -#include "IFileChangeMonitor.h" #include "Util/FileChangeMonitor.h" class CEditorFileMonitor diff --git a/Code/Sandbox/Editor/EditorViewportSettings.cpp b/Code/Sandbox/Editor/EditorViewportSettings.cpp new file mode 100644 index 0000000000..362d0fab48 --- /dev/null +++ b/Code/Sandbox/Editor/EditorViewportSettings.cpp @@ -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. + * + */ + +#include + +#include +#include +#include + +namespace Editor +{ + constexpr AZStd::string_view GridSnappingSetting = "/Amazon/Preferences/Editor/GridSnapping"; + constexpr AZStd::string_view GridSizeSetting = "/Amazon/Preferences/Editor/GridSize"; + constexpr AZStd::string_view AngleSnappingSetting = "/Amazon/Preferences/Editor/AngleSnapping"; + constexpr AZStd::string_view AngleSizeSetting = "/Amazon/Preferences/Editor/AngleSize"; + constexpr AZStd::string_view ShowGridSetting = "/Amazon/Preferences/Editor/ShowGrid"; + + bool GridSnappingEnabled() + { + bool enabled = false; + if (auto* registry = AZ::SettingsRegistry::Get()) + { + registry->Get(enabled, GridSnappingSetting); + } + return enabled; + } + + float GridSnappingSize() + { + double gridSize = 0.1; + if (auto* registry = AZ::SettingsRegistry::Get()) + { + registry->Get(gridSize, GridSizeSetting); + } + return aznumeric_cast(gridSize); + } + + bool AngleSnappingEnabled() + { + bool enabled = false; + if (auto* registry = AZ::SettingsRegistry::Get()) + { + registry->Get(enabled, AngleSnappingSetting); + } + return enabled; + } + + float AngleSnappingSize() + { + double angleSize = 5.0; + if (auto* registry = AZ::SettingsRegistry::Get()) + { + registry->Get(angleSize, AngleSizeSetting); + } + return aznumeric_cast(angleSize); + } + + bool ShowingGrid() + { + bool enabled = false; + if (auto* registry = AZ::SettingsRegistry::Get()) + { + registry->Get(enabled, ShowGridSetting); + } + return enabled; + } + + void SetGridSnapping(const bool enabled) + { + if (auto* registry = AZ::SettingsRegistry::Get()) + { + registry->Set(GridSnappingSetting, enabled); + } + } + + void SetGridSnappingSize(const float size) + { + if (auto* registry = AZ::SettingsRegistry::Get()) + { + registry->Set(GridSizeSetting, size); + } + } + + void SetAngleSnapping(const bool enabled) + { + if (auto* registry = AZ::SettingsRegistry::Get()) + { + registry->Set(AngleSnappingSetting, enabled); + } + } + + void SetAngleSnappingSize(const float size) + { + if (auto* registry = AZ::SettingsRegistry::Get()) + { + registry->Set(AngleSizeSetting, size); + } + } + + void SetShowingGrid(const bool showing) + { + if (auto* registry = AZ::SettingsRegistry::Get()) + { + registry->Set(ShowGridSetting, showing); + } + } +} // namespace Editor diff --git a/Code/Sandbox/Editor/EditorViewportSettings.h b/Code/Sandbox/Editor/EditorViewportSettings.h new file mode 100644 index 0000000000..ca6a5f0797 --- /dev/null +++ b/Code/Sandbox/Editor/EditorViewportSettings.h @@ -0,0 +1,38 @@ +/* + * All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or + * its licensors. + * + * For complete copyright and license terms please see the LICENSE at the root of this + * distribution (the "License"). All use of this software is governed by the License, + * or, if provided, by the license below or the license accompanying this file. Do not + * remove or 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 Editor +{ + EDITOR_CORE_API bool GridSnappingEnabled(); + + EDITOR_CORE_API float GridSnappingSize(); + + EDITOR_CORE_API bool AngleSnappingEnabled(); + + EDITOR_CORE_API float AngleSnappingSize(); + + EDITOR_CORE_API bool ShowingGrid(); + + EDITOR_CORE_API void SetGridSnapping(bool enabled); + + EDITOR_CORE_API void SetGridSnappingSize(float size); + + EDITOR_CORE_API void SetAngleSnapping(bool enabled); + + EDITOR_CORE_API void SetAngleSnappingSize(float size); + + EDITOR_CORE_API void SetShowingGrid(bool showing); +} // namespace Editor diff --git a/Code/Sandbox/Editor/EditorViewportWidget.cpp b/Code/Sandbox/Editor/EditorViewportWidget.cpp index 0b3ff87e43..8afcddd144 100644 --- a/Code/Sandbox/Editor/EditorViewportWidget.cpp +++ b/Code/Sandbox/Editor/EditorViewportWidget.cpp @@ -75,6 +75,7 @@ #include "ViewportManipulatorController.h" #include "LegacyViewportCameraController.h" #include "ModernViewportCameraController.h" +#include "EditorViewportSettings.h" #include "ViewPane.h" #include "CustomResolutionDlg.h" @@ -127,6 +128,18 @@ AZ_CVAR( bool, ed_useNewCameraSystem, false, nullptr, AZ::ConsoleFunctorFlags::Null, "Use the new Editor camera system (the Atom-native Editor viewport (experimental) must also be enabled)"); +//! Viewport settings for the EditorViewportWidget +struct EditorViewportSettings : public AzToolsFramework::ViewportInteraction::ViewportSettings +{ + bool GridSnappingEnabled() const override; + float GridSize() const override; + bool ShowGrid() const override; + bool AngleSnappingEnabled() const override; + float AngleStep() const override; +}; + +static const EditorViewportSettings g_EditorViewportSettings; + namespace AZ::ViewportHelpers { static const char TextCantCreateCameraNoLevel[] = "Cannot create camera when no level is loaded."; @@ -170,7 +183,6 @@ EditorViewportWidget::EditorViewportWidget(const QString& name, QWidget* parent) , m_camFOV(gSettings.viewports.fDefaultFov) , m_defaultViewName(name) , m_renderViewport(nullptr) //m_renderViewport is initialized later, in SetViewportId - , m_editorViewportSettings(this) { // need this to be set in order to allow for language switching on Windows setAttribute(Qt::WA_InputMethodEnabled); @@ -441,8 +453,11 @@ void EditorViewportWidget::Update() } m_updatingCameraPosition = true; - auto transform = LYTransformToAZTransform(m_Camera.GetMatrix()); - m_renderViewport->GetViewportContext()->SetCameraTransform(transform); + if (!ed_useNewCameraSystem) + { + m_renderViewport->GetViewportContext()->SetCameraTransform(LYTransformToAZTransform(m_Camera.GetMatrix())); + } + AZ::Matrix4x4 clipMatrix; AZ::MakePerspectiveFovMatrixRH( clipMatrix, @@ -644,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: @@ -668,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); @@ -688,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; @@ -791,10 +798,6 @@ void EditorViewportWidget::OnRender() // This is necessary so that automated editor tests using the null renderer to test systems like dynamic vegetation // are still able to manipulate the current logical camera position, even if nothing is rendered. GetIEditor()->GetSystem()->SetViewCamera(m_Camera); - if (GetIEditor()->GetRenderer()) - { - GetIEditor()->GetRenderer()->SetCamera(gEnv->pSystem->GetViewCamera()); - } return; } @@ -1250,7 +1253,7 @@ void EditorViewportWidget::SetViewportId(int id) m_renderViewport->GetControllerList()->Add(AZStd::make_shared()); } - m_renderViewport->SetViewportSettings(&m_editorViewportSettings); + m_renderViewport->SetViewportSettings(&g_EditorViewportSettings); UpdateScene(); @@ -2871,35 +2874,29 @@ void EditorViewportWidget::SetAsActiveViewport() } } -EditorViewportSettings::EditorViewportSettings(const EditorViewportWidget* editorViewportWidget) - : m_editorViewportWidget(editorViewportWidget) -{ -} - bool EditorViewportSettings::GridSnappingEnabled() const { - return m_editorViewportWidget->GetViewManager()->GetGrid()->IsEnabled(); + return Editor::GridSnappingEnabled(); } float EditorViewportSettings::GridSize() const { - const CGrid* grid = m_editorViewportWidget->GetViewManager()->GetGrid(); - return grid->scale * grid->size; + return Editor::GridSnappingSize(); } bool EditorViewportSettings::ShowGrid() const { - return gSettings.viewports.bShowGridGuide; + return Editor::ShowingGrid(); } bool EditorViewportSettings::AngleSnappingEnabled() const { - return m_editorViewportWidget->GetViewManager()->GetGrid()->IsAngleSnapEnabled(); + return Editor::AngleSnappingEnabled(); } float EditorViewportSettings::AngleStep() const { - return m_editorViewportWidget->GetViewManager()->GetGrid()->GetAngleSnap(); + return Editor::AngleSnappingSize(); } #include diff --git a/Code/Sandbox/Editor/EditorViewportWidget.h b/Code/Sandbox/Editor/EditorViewportWidget.h index 8675c035f6..4062a3c801 100644 --- a/Code/Sandbox/Editor/EditorViewportWidget.h +++ b/Code/Sandbox/Editor/EditorViewportWidget.h @@ -65,23 +65,6 @@ namespace AzToolsFramework class ManipulatorManager; } -class EditorViewportWidget; - -//! Viewport settings for the EditorViewportWidget -struct EditorViewportSettings : public AzToolsFramework::ViewportInteraction::ViewportSettings -{ - explicit EditorViewportSettings(const EditorViewportWidget* editorViewportWidget); - - bool GridSnappingEnabled() const override; - float GridSize() const override; - bool ShowGrid() const override; - bool AngleSnappingEnabled() const override; - float AngleStep() const override; - -private: - const EditorViewportWidget* m_editorViewportWidget = nullptr; -}; - // EditorViewportWidget window AZ_PUSH_DISABLE_DLL_EXPORT_BASECLASS_WARNING AZ_PUSH_DISABLE_DLL_EXPORT_MEMBER_WARNING @@ -607,7 +590,5 @@ private: AZ::Name m_defaultViewportContextName; - EditorViewportSettings m_editorViewportSettings; - AZ_POP_DISABLE_DLL_EXPORT_MEMBER_WARNING }; diff --git a/Code/Sandbox/Editor/GameEngine.cpp b/Code/Sandbox/Editor/GameEngine.cpp index 073684eaad..2112d00d64 100644 --- a/Code/Sandbox/Editor/GameEngine.cpp +++ b/Code/Sandbox/Editor/GameEngine.cpp @@ -38,7 +38,6 @@ // CryCommon #include -#include #include #include @@ -46,7 +45,6 @@ #include "CryEdit.h" #include "ViewManager.h" -#include "Util/Ruler.h" #include "AnimationContext.h" #include "UndoViewPosition.h" #include "UndoViewRotation.h" @@ -386,7 +384,6 @@ void CGameEngine::SetCurrentViewRotation(const AZ::Vector3& rotation) AZ::Outcome CGameEngine::Init( bool bPreviewMode, bool bTestMode, - bool bShaderCacheGen, const char* sInCmdLine, IInitializeUIInfo* logo, HWND hwndForInputSystem) @@ -423,7 +420,6 @@ AZ::Outcome CGameEngine::Init( #else sip.hWnd = hwndForInputSystem; #endif - sip.hWndForInputSystem = hwndForInputSystem; sip.pLogCallback = &m_logFile; sip.sLogFileName = "@log@/Editor.log"; @@ -444,10 +440,6 @@ AZ::Outcome CGameEngine::Init( m_modalWindowDismisser = AZStd::make_unique(); } - if (bShaderCacheGen) - { - sip.bSkipFont = true; - } AssetProcessConnectionStatus apConnectionStatus; m_pISystem = pfnCreateSystemInterface(sip); @@ -510,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; @@ -615,17 +606,9 @@ void CGameEngine::SwitchToInGame() GetIEditor()->Notify(eNotify_OnBeginGameMode); - m_pISystem->SetThreadState(ESubsys_Physics, false); - m_pISystem->GetIMovieSystem()->EnablePhysicsEvents(true); m_bInGameMode = true; - CRuler* pRuler = GetIEditor()->GetRuler(); - if (pRuler) - { - pRuler->SetActive(false); - } - gEnv->pSystem->GetViewCamera().SetMatrix(m_playerViewTM); // Disable accelerators. @@ -659,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); @@ -792,12 +773,6 @@ void CGameEngine::SetSimulationMode(bool enabled, bool bOnlyPhysics) if (enabled) { - CRuler* pRuler = GetIEditor()->GetRuler(); - if (pRuler) - { - pRuler->SetActive(false); - } - GetIEditor()->Notify(eNotify_OnBeginSimulationMode); } else @@ -810,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), @@ -922,22 +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; - - CRuler* pRuler = GetIEditor()->GetRuler(); - const bool bRulerNeedsUpdate = (pRuler && pRuler->HasQueuedPaths()); - - 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/GameEngine.h b/Code/Sandbox/Editor/GameEngine.h index b59e2c9ac8..669b37bbb3 100644 --- a/Code/Sandbox/Editor/GameEngine.h +++ b/Code/Sandbox/Editor/GameEngine.h @@ -79,7 +79,6 @@ public: AZ::Outcome Init( bool bPreviewMode, bool bTestMode, - bool bShaderCacheGen, const char* sCmdLine, IInitializeUIInfo* logo, HWND hwndForInputSystem); diff --git a/Code/Sandbox/Editor/GameExporter.cpp b/Code/Sandbox/Editor/GameExporter.cpp index 31f3fafe84..60746041a7 100644 --- a/Code/Sandbox/Editor/GameExporter.cpp +++ b/Code/Sandbox/Editor/GameExporter.cpp @@ -24,7 +24,6 @@ #include "GameExporter.h" #include "GameEngine.h" #include "CryEditDoc.h" -#include "ShaderCache.h" #include "UsedResources.h" #include "WaitProgress.h" #include "Util/CryMemFile.h" @@ -197,7 +196,6 @@ bool CGameExporter::Export(unsigned int flags, [[maybe_unused]] EEndian eExportE ExportLevelResourceList(sLevelPath); ExportLevelUsedResourceList(sLevelPath); - ExportLevelShaderCache(sLevelPath); ////////////////////////////////////////////////////////////////////////// // End Exporting Game data. @@ -295,6 +293,17 @@ void CGameExporter::ExportLevelData(const QString& path, bool /*bExportMission*/ CCryMemFile fileAction; fileAction.Write(xmlDataAction.c_str(), xmlDataAction.length()); m_levelPak.m_pakFile.UpdateFile(levelDataActionFile.toUtf8().data(), fileAction); + + AZStd::vector entitySaveBuffer; + AZ::IO::ByteContainerStream > entitySaveStream(&entitySaveBuffer); + bool savedEntities = false; + EBUS_EVENT_RESULT(savedEntities, AzToolsFramework::EditorEntityContextRequestBus, SaveToStreamForGame, entitySaveStream, AZ::DataStream::ST_BINARY); + if (savedEntities) + { + QString entitiesFile; + entitiesFile = QStringLiteral("%1%2.entities_xml").arg(path, "Mission0"); + m_levelPak.m_pakFile.UpdateFile(entitiesFile.toUtf8().data(), entitySaveBuffer.begin(), entitySaveBuffer.size()); + } } ////////////////////////////////////////////////////////////////////////// @@ -368,18 +377,6 @@ void CGameExporter::ExportLevelUsedResourceList(const QString& path) m_levelPak.m_pakFile.UpdateFile(resFile.toUtf8().data(), memFile, true); } -////////////////////////////////////////////////////////////////////////// -void CGameExporter::ExportLevelShaderCache(const QString& path) -{ - QString buf; - GetIEditor()->GetDocument()->GetShaderCache()->SaveBuffer(buf); - CCryMemFile memFile; - memFile.Write(buf.toUtf8().data(), buf.toUtf8().length()); - - QString filename = Path::Make(path, SHADER_LIST_FILE); - m_levelPak.m_pakFile.UpdateFile(filename.toUtf8().data(), memFile, true); -} - ////////////////////////////////////////////////////////////////////////// void CGameExporter::ExportFileList(const QString& path, const QString& levelName) { diff --git a/Code/Sandbox/Editor/GameExporter.h b/Code/Sandbox/Editor/GameExporter.h index 18ec79189a..08af3e7473 100644 --- a/Code/Sandbox/Editor/GameExporter.h +++ b/Code/Sandbox/Editor/GameExporter.h @@ -95,8 +95,6 @@ private: void ExportLevelResourceList(const QString& path); void ExportLevelUsedResourceList(const QString& path); - void ExportLevelShaderCache(const QString& path); - void ExportGameData(const QString& path); void ExportFileList(const QString& path, const QString& levelName); void Error(const QString& error); diff --git a/Code/Sandbox/Editor/Grid.cpp b/Code/Sandbox/Editor/Grid.cpp deleted file mode 100644 index 50702f8cb2..0000000000 --- a/Code/Sandbox/Editor/Grid.cpp +++ /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. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#include "EditorDefs.h" - -#include "Grid.h" - -// Editor -#include "Settings.h" -#include "Objects/SelectionGroup.h" - -////////////////////////////////////////////////////////////////////////// -CGrid::CGrid() -{ - scale = 1; - size = 1; - majorLine = 16; - bEnabled = true; - rotationAngles = Ang3(0.0f, 0.0f, 0.0f); - translation = Vec3(0.0f, 0.0f, 0.0f); - - bAngleSnapEnabled = true; - angleSnap = 5; -} - -////////////////////////////////////////////////////////////////////////// -Vec3 CGrid::Snap(const Vec3& vec) const -{ - if (!bEnabled || size < 0.001) - { - return vec; - } - Vec3 snapped; - snapped.x = floor((vec.x / size) / scale + 0.5) * size * scale; - snapped.y = floor((vec.y / size) / scale + 0.5) * size * scale; - snapped.z = floor((vec.z / size) / scale + 0.5) * size * scale; - return snapped; -} - -////////////////////////////////////////////////////////////////////////// -Vec3 CGrid::Snap(const Vec3& vec, double fZoom) const -{ - if (!bEnabled || size < 0.001f) - { - return vec; - } - - Matrix34 tm = GetMatrix(); - - double zoomscale = scale * fZoom; - Vec3 snapped; - - Matrix34 invtm = tm.GetInverted(); - - snapped = invtm * vec; - - snapped.x = floor((snapped.x / size) / zoomscale + 0.5) * size * zoomscale; - snapped.y = floor((snapped.y / size) / zoomscale + 0.5) * size * zoomscale; - snapped.z = floor((snapped.z / size) / zoomscale + 0.5) * size * zoomscale; - - snapped = tm * snapped; - - return snapped; -} - -////////////////////////////////////////////////////////////////////////// -double CGrid::SnapAngle(double angle) const -{ - if (!bAngleSnapEnabled) - { - return angle; - } - return floor(angle / angleSnap + 0.5) * angleSnap; -} - -////////////////////////////////////////////////////////////////////////// -Ang3 CGrid::SnapAngle(const Ang3& vec) const -{ - if (!bAngleSnapEnabled) - { - return vec; - } - Ang3 snapped; - snapped.x = floor(vec.x / angleSnap + 0.5) * angleSnap; - snapped.y = floor(vec.y / angleSnap + 0.5) * angleSnap; - snapped.z = floor(vec.z / angleSnap + 0.5) * angleSnap; - return snapped; -} - -////////////////////////////////////////////////////////////////////////// -void CGrid::Serialize(XmlNodeRef& xmlNode, bool bLoading) -{ - if (bLoading) - { - // Loading. - xmlNode->getAttr("Size", size); - xmlNode->getAttr("Scale", scale); - xmlNode->getAttr("Enabled", bEnabled); - xmlNode->getAttr("MajorSize", majorLine); - xmlNode->getAttr("AngleSnap", angleSnap); - xmlNode->getAttr("AngleSnapEnabled", bAngleSnapEnabled); - if (size < 0.01) - { - size = 0.01; - } - } - else - { - // Saving. - xmlNode->setAttr("Size", size); - xmlNode->setAttr("Scale", scale); - xmlNode->setAttr("Enabled", bEnabled); - xmlNode->setAttr("MajorSize", majorLine); - xmlNode->setAttr("AngleSnap", angleSnap); - xmlNode->setAttr("AngleSnapEnabled", bAngleSnapEnabled); - } -} - -////////////////////////////////////////////////////////////////////////// -Matrix34 CGrid::GetMatrix() const -{ - Matrix34 tm; - - if (gSettings.snap.bGridUserDefined) - { - Ang3 angles = Ang3(rotationAngles.x * gf_PI / 180.0, rotationAngles.y * gf_PI / 180.0, rotationAngles.z * gf_PI / 180.0); - - tm = Matrix33::CreateRotationXYZ(angles); - } - else if (GetIEditor()->GetReferenceCoordSys() == COORDS_LOCAL) - { - tm.SetIdentity(); - } - else - { - tm.SetIdentity(); - } - - return tm; -} diff --git a/Code/Sandbox/Editor/Grid.h b/Code/Sandbox/Editor/Grid.h deleted file mode 100644 index dd761ad058..0000000000 --- a/Code/Sandbox/Editor/Grid.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_EDITOR_GRID_H -#define CRYINCLUDE_EDITOR_GRID_H - -#pragma once - -/** Definition of grid used in 2D viewports. -*/ -class SANDBOX_API CGrid -{ -public: - //! Resolution of grid, it must be multiply of 2. - double size; - //! Draw major lines every Nth grid line. - int majorLine; - //! True if grid enabled. - bool bEnabled; - //! Meters per grid unit. - double scale; - - AZ_PUSH_DISABLE_DLL_EXPORT_MEMBER_WARNING - Ang3 rotationAngles; - Vec3 translation; - AZ_POP_DISABLE_DLL_EXPORT_MEMBER_WARNING - - //! If snap to angle. - bool bAngleSnapEnabled; - double angleSnap; - - ////////////////////////////////////////////////////////////////////////// - CGrid(); - - //! Snap vector to this grid. - Vec3 Snap(const Vec3& vec) const; - Vec3 Snap(const Vec3& vec, double fZoom) const; - - //! Snap angle to current angle snapping value. - double SnapAngle(double angle) const; - //! Snap angle to current angle snapping value. - Ang3 SnapAngle(const Ang3& angle) const; - - //! Enable or disable grid. - void Enable(bool enable) { bEnabled = enable; } - //! Check if grid enabled. - bool IsEnabled() const { return bEnabled; } - - //! Enables or disable angle snapping. - void EnableAngleSnap(bool enable) { bAngleSnapEnabled = enable; }; - - //! Return if snapping of angle is enabled. - bool IsAngleSnapEnabled() const { return bAngleSnapEnabled; }; - //! Returns ammount of snapping for angle in degrees. - double GetAngleSnap() const { return angleSnap; }; - - void Serialize(XmlNodeRef& xmlNode, bool bLoading); - - //! Get transformation matrix of gird. - Matrix34 GetMatrix() const; -}; - - -#endif // CRYINCLUDE_EDITOR_GRID_H diff --git a/Code/Sandbox/Editor/GridSettingsDialog.cpp b/Code/Sandbox/Editor/GridSettingsDialog.cpp deleted file mode 100644 index ecabdc4e6a..0000000000 --- a/Code/Sandbox/Editor/GridSettingsDialog.cpp +++ /dev/null @@ -1,169 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS 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 "GridSettingsDialog.h" - -// Editor -#include "Settings.h" -#include "Objects/SelectionGroup.h" -#include "ViewManager.h" - - -AZ_PUSH_DISABLE_DLL_EXPORT_MEMBER_WARNING -#include -AZ_POP_DISABLE_DLL_EXPORT_MEMBER_WARNING - -// CGridSettingsDialog dialog - -CGridSettingsDialog::CGridSettingsDialog(QWidget* pParent /*=NULL*/) - : QDialog(pParent) - , ui(new Ui::CGridSettingsDialog) -{ - ui->setupUi(this); - - setWindowTitle(tr("Grid/Snap Settings")); - - OnInitDialog(); - - connect(ui->m_userDefined, &QCheckBox::clicked, this, &CGridSettingsDialog::OnBnUserDefined); - connect(ui->m_getFromObject, &QCheckBox::clicked, this, &CGridSettingsDialog::OnBnGetFromObject); - - auto doubleSpinBoxValueChanged = static_cast(&QDoubleSpinBox::valueChanged); - - connect(ui->m_angleX, doubleSpinBoxValueChanged, this, &CGridSettingsDialog::OnValueUpdate); - connect(ui->m_angleY, doubleSpinBoxValueChanged, this, &CGridSettingsDialog::OnValueUpdate); - connect(ui->m_angleZ, doubleSpinBoxValueChanged, this, &CGridSettingsDialog::OnValueUpdate); - - connect(ui->m_gridSize, doubleSpinBoxValueChanged, this, &CGridSettingsDialog::OnValueUpdate); - connect(ui->m_gridScale, doubleSpinBoxValueChanged, this, &CGridSettingsDialog::OnValueUpdate); - connect(ui->m_CPSize, doubleSpinBoxValueChanged, this, &CGridSettingsDialog::OnValueUpdate); - - connect(ui->m_displayCP, &QCheckBox::clicked, this, &CGridSettingsDialog::OnValueUpdate); - connect(ui->m_getFromObject, &QCheckBox::clicked, this, &CGridSettingsDialog::OnValueUpdate); - - connect(ui->m_buttonBox, &QDialogButtonBox::accepted, this, &CGridSettingsDialog::accept); - connect(ui->m_buttonBox, &QDialogButtonBox::rejected, this, &CGridSettingsDialog::reject); -} - -CGridSettingsDialog::~CGridSettingsDialog() -{ -} - -////////////////////////////////////////////////////////////////////////// -void CGridSettingsDialog::OnInitDialog() -{ - CGrid* pGrid = GetIEditor()->GetViewManager()->GetGrid(); - - ui->m_userDefined->setChecked(gSettings.snap.bGridUserDefined); - ui->m_getFromObject->setChecked(gSettings.snap.bGridGetFromSelected); - - ui->m_angleX->setValue(pGrid->rotationAngles.x); - ui->m_angleY->setValue(pGrid->rotationAngles.y); - ui->m_angleZ->setValue(pGrid->rotationAngles.z); - - ui->m_translationX->setValue(pGrid->translation.x); - ui->m_translationY->setValue(pGrid->translation.y); - ui->m_translationZ->setValue(pGrid->translation.z); - - ui->m_gridSize->setValue(pGrid->size); - ui->m_gridScale->setValue(pGrid->scale); - ui->m_snapToGrid->setChecked(pGrid->IsEnabled()); - - ui->m_angleSnap->setChecked(pGrid->IsAngleSnapEnabled()); - ui->m_angleSnapScale->setValue(pGrid->GetAngleSnap()); - ui->m_displayCP->setChecked(gSettings.snap.constructPlaneDisplay); - - ui->m_CPSize->setValue(gSettings.snap.constructPlaneSize); - ui->m_displaySnapMarker->setChecked(gSettings.snap.markerDisplay); - ui->m_snapMarkerSize->setValue(gSettings.snap.markerSize); - - ui->m_snapMarkerColor->SetColor(gSettings.snap.markerColor); - - EnableGridPropertyControls(gSettings.snap.bGridUserDefined, gSettings.snap.bGridGetFromSelected); -} - -////////////////////////////////////////////////////////////////////////// -void CGridSettingsDialog::accept() -{ - UpdateValues(); - gSettings.Save(); - QDialog::accept(); -} - -void CGridSettingsDialog::OnBnUserDefined() -{ - EnableGridPropertyControls(ui->m_userDefined->isChecked(), ui->m_getFromObject->isChecked()); - OnValueUpdate(); -} - -void CGridSettingsDialog::OnBnGetFromObject() -{ - EnableGridPropertyControls(ui->m_userDefined->isChecked(), ui->m_getFromObject->isChecked()); -} - -void CGridSettingsDialog::EnableGridPropertyControls(const bool isUserDefined, const bool isGetFromObject) -{ - ui->m_getFromObject->setEnabled(isUserDefined == true); - - ui->m_angleX->setEnabled(isUserDefined == true && isGetFromObject == false); - ui->m_angleY->setEnabled(isUserDefined == true && isGetFromObject == false); - ui->m_angleZ->setEnabled(isUserDefined == true && isGetFromObject == false); - ui->m_translationX->setEnabled(isUserDefined == true && isGetFromObject == false); - ui->m_translationY->setEnabled(isUserDefined == true && isGetFromObject == false); - ui->m_translationZ->setEnabled(isUserDefined == true && isGetFromObject == false); - ui->m_getAnglesFromObject->setEnabled(isUserDefined == true && isGetFromObject == false); - ui->m_getTranslationFromObject->setEnabled(isUserDefined == true && isGetFromObject == false); -} - -////////////////////////////////////////////////////////////////////////// -void CGridSettingsDialog::UpdateValues() -{ - CGrid* pGrid = GetIEditor()->GetViewManager()->GetGrid(); - - pGrid->Enable(ui->m_snapToGrid->isChecked()); - pGrid->size = ui->m_gridSize->value(); - pGrid->scale = ui->m_gridScale->value(); - - gSettings.snap.bGridUserDefined = ui->m_userDefined->isChecked(); - gSettings.snap.bGridGetFromSelected = ui->m_getFromObject->isChecked(); - pGrid->rotationAngles.x = ui->m_angleX->value(); - pGrid->rotationAngles.y = ui->m_angleY->value(); - pGrid->rotationAngles.z = ui->m_angleZ->value(); - pGrid->translation.x = ui->m_translationX->value(); - pGrid->translation.y = ui->m_translationY->value(); - pGrid->translation.z = ui->m_translationZ->value(); - - pGrid->bAngleSnapEnabled = ui->m_angleSnap->isChecked(); - pGrid->angleSnap = ui->m_angleSnapScale->value(); - - gSettings.snap.constructPlaneDisplay = ui->m_displayCP->isChecked(); - gSettings.snap.constructPlaneSize = ui->m_CPSize->value(); - - gSettings.snap.markerDisplay = ui->m_displaySnapMarker->isChecked(); - gSettings.snap.markerSize = ui->m_snapMarkerSize->value(); - gSettings.snap.markerColor = ui->m_snapMarkerColor->Color(); - - NotificationBus::Broadcast(&Notifications::OnGridValuesUpdated); -} - - -////////////////////////////////////////////////////////////////////////// -void CGridSettingsDialog::OnValueUpdate() -{ - UpdateValues(); - GetIEditor()->UpdateViews(eRedrawViewports); -} - -#include diff --git a/Code/Sandbox/Editor/GridSettingsDialog.h b/Code/Sandbox/Editor/GridSettingsDialog.h deleted file mode 100644 index fe5934ec7e..0000000000 --- a/Code/Sandbox/Editor/GridSettingsDialog.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_EDITOR_GRIDSETTINGSDIALOG_H -#define CRYINCLUDE_EDITOR_GRIDSETTINGSDIALOG_H - -#pragma once - -#if !defined(Q_MOC_RUN) -#include -#include -#endif - -// CGridSettingsDialog dialog - -namespace Ui { - class CGridSettingsDialog; -} - -class CGridSettingsDialog - : public QDialog -{ - Q_OBJECT -public: - - class Notifications - : public AZ::EBusTraits - { - public: - static const AZ::EBusAddressPolicy AddressPolicy = AZ::EBusAddressPolicy::Single; - - virtual void OnGridValuesUpdated() {} - }; - - using NotificationBus = AZ::EBus; - - CGridSettingsDialog(QWidget* pParent = nullptr); // standard constructor - virtual ~CGridSettingsDialog(); - -private slots: - void accept() override; - void OnBnUserDefined(); - void OnBnGetFromObject(); - void OnValueUpdate(); - -private: - void EnableGridPropertyControls(const bool isUserDefined, const bool isGetFromObject); - - void OnInitDialog(); - void UpdateValues(); - - QScopedPointer ui; -}; - -#endif // CRYINCLUDE_EDITOR_GRIDSETTINGSDIALOG_H diff --git a/Code/Sandbox/Editor/GridSettingsDialog.ui b/Code/Sandbox/Editor/GridSettingsDialog.ui deleted file mode 100644 index f77abbece7..0000000000 --- a/Code/Sandbox/Editor/GridSettingsDialog.ui +++ /dev/null @@ -1,505 +0,0 @@ - - - CGridSettingsDialog - - - - 0 - 0 - 307 - 707 - - - - - - - - - Grid - - - - - - Snap to Grid - - - - - - - Grid Lines Every: - - - Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter - - - - - - - Qt::AlignLeading|Qt::AlignLeft|Qt::AlignVCenter - - - 0.010000000000000 - - - 1024.000000000000000 - - - 0.010000000000000 - - - - - - - units - - - - - - - Units Per Meter: - - - Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter - - - - - - - Qt::AlignLeading|Qt::AlignLeft|Qt::AlignVCenter - - - 0.010000000000000 - - - 1024.000000000000000 - - - 0.010000000000000 - - - - - - - meters - - - - - - - User Defined Grid - - - - - - - Get Angles And Trans. From Selected - - - - - - - Rotation by X: - - - Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter - - - - - - - Qt::AlignLeading|Qt::AlignLeft|Qt::AlignVCenter - - - -180.000000000000000 - - - 180.000000000000000 - - - 0.010000000000000 - - - - - - - degrees - - - Qt::AlignLeading|Qt::AlignLeft|Qt::AlignVCenter - - - - - - - Rotation by Y: - - - Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter - - - - - - - Qt::AlignLeading|Qt::AlignLeft|Qt::AlignVCenter - - - -180.000000000000000 - - - 180.000000000000000 - - - 0.010000000000000 - - - - - - - degrees - - - Qt::AlignLeading|Qt::AlignLeft|Qt::AlignVCenter - - - - - - - Rotation by Z: - - - Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter - - - - - - - Qt::AlignLeading|Qt::AlignLeft|Qt::AlignVCenter - - - -180.000000000000000 - - - 180.000000000000000 - - - 0.010000000000000 - - - - - - - degrees - - - Qt::AlignLeading|Qt::AlignLeft|Qt::AlignVCenter - - - - - - - Translation by X: - - - Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter - - - - - - - Qt::AlignLeading|Qt::AlignLeft|Qt::AlignVCenter - - - 0.010000000000000 - - - - - - - Translation by Y: - - - Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter - - - - - - - Qt::AlignLeading|Qt::AlignLeft|Qt::AlignVCenter - - - 0.010000000000000 - - - - - - - Translation by Z: - - - Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter - - - - - - - Qt::AlignLeading|Qt::AlignLeft|Qt::AlignVCenter - - - 0.010000000000000 - - - - - - - Get Angles From Selected - - - - - - - Get Translation From Selected - - - - - - - - - - Angle Snapping - - - - - - Qt::AlignLeading|Qt::AlignLeft|Qt::AlignVCenter - - - - - - - - 80 - 0 - - - - degrees - - - Qt::AlignLeading|Qt::AlignLeft|Qt::AlignVCenter - - - - - - - Angle Snap - - - - - - - Angle Snap: - - - Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter - - - - - - - Qt::Horizontal - - - - 40 - 0 - - - - - - - - - - - Construction Plane - - - - - - Size: - - - Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter - - - - - - - Display - - - - - - - Qt::AlignLeading|Qt::AlignLeft|Qt::AlignVCenter - - - 0.010000000000000 - - - - - - - Qt::Horizontal - - - QSizePolicy::Minimum - - - - 80 - 0 - - - - - - - - Qt::Horizontal - - - - 40 - 20 - - - - - - m_displayCP - m_CPSize - - - - - - Snap Marker - - - - - - Qt::AlignLeading|Qt::AlignLeft|Qt::AlignVCenter - - - 0.010000000000000 - - - - - - - Display - - - - - - - - 80 - 0 - - - - Color - - - - - - - Size: - - - Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter - - - - - - - Qt::Horizontal - - - - 40 - 20 - - - - - - - - - - - QDialogButtonBox::Cancel|QDialogButtonBox::Ok - - - - - - - - - - ColorButton - QToolButton -
QtUI/ColorButton.h
-
-
- - -
diff --git a/Code/Sandbox/Editor/IEditor.h b/Code/Sandbox/Editor/IEditor.h index f11beacf10..af98158037 100644 --- a/Code/Sandbox/Editor/IEditor.h +++ b/Code/Sandbox/Editor/IEditor.h @@ -66,7 +66,6 @@ class CDialog; #if defined(AZ_PLATFORM_WINDOWS) class C3DConnexionDriver; #endif -class CRuler; class CSettingsManager; struct IExportManager; class CDisplaySettings; @@ -425,7 +424,6 @@ struct IEditor virtual void DeleteThis() = 0; //! Access to Editor ISystem interface. virtual ISystem* GetSystem() = 0; - virtual IRenderer* GetRenderer() = 0; //! Access to class factory. virtual IEditorClassFactory* GetClassFactory() = 0; //! Access to commands manager. @@ -552,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: @@ -589,8 +586,6 @@ struct IEditor virtual void SetSelectedRegion(const AABB& box) = 0; //! Get currently selected region. virtual void GetSelectedRegion(AABB& box) = 0; - //! Get current ruler - virtual CRuler* GetRuler() = 0; virtual void SetOperationMode(EOperationMode mode) = 0; virtual EOperationMode GetOperationMode() = 0; @@ -635,7 +630,6 @@ struct IEditor //! Returns true if selection is made and false if selection is canceled. virtual bool SelectColor(QColor& color, QWidget* parent = 0) = 0; //! Get shader enumerator. - virtual class CShaderEnum* GetShaderEnum() = 0; virtual class CUndoManager* GetUndoManager() = 0; //! Begin operation requiring undo //! Undo manager enters holding state. @@ -725,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 53a2c120c4..380fc80e66 100644 --- a/Code/Sandbox/Editor/IEditorImpl.cpp +++ b/Code/Sandbox/Editor/IEditorImpl.cpp @@ -49,7 +49,6 @@ AZ_POP_DISABLE_WARNING #include "Objects/GizmoManager.h" #include "Objects/AxisGizmo.h" #include "DisplaySettings.h" -#include "ShaderEnum.h" #include "KeyboardCustomizationSettings.h" #include "Export/ExportManager.h" #include "LevelIndependentFileMan.h" @@ -60,7 +59,6 @@ AZ_POP_DISABLE_WARNING #include "MainWindow.h" #include "Alembic/AlembicCompiler.h" #include "UIEnumsDatabase.h" -#include "Util/Ruler.h" #include "RenderHelpers/AxisHelper.h" #include "Settings.h" #include "Include/IObjectManager.h" @@ -68,12 +66,9 @@ AZ_POP_DISABLE_WARNING #include "Objects/SelectionGroup.h" #include "Objects/ObjectManager.h" -#include "BackgroundTaskManager.h" -#include "BackgroundScheduleManager.h" #include "EditorFileMonitor.h" #include "MainStatusBar.h" -#include "SettingsBlock.h" #include "ResourceSelectorHost.h" #include "Util/FileUtil_impl.h" #include "Util/ImageUtil_impl.h" @@ -134,7 +129,6 @@ CEditorImpl::CEditorImpl() , m_bUpdates(true) , m_bTerrainAxisIgnoreObjects(false) , m_pDisplaySettings(nullptr) - , m_pShaderEnum(nullptr) , m_pIconManager(nullptr) , m_bSelectionLocked(true) , m_pAxisGizmo(nullptr) @@ -149,7 +143,6 @@ CEditorImpl::CEditorImpl() , m_pSourceControl(nullptr) , m_pSelectionTreeManager(nullptr) , m_pUIEnumsDatabase(nullptr) - , m_pRuler(nullptr) , m_pConsoleSync(nullptr) , m_pSettingsManager(nullptr) , m_pLevelIndependentFileMan(nullptr) @@ -181,11 +174,8 @@ 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_pShaderEnum = new CShaderEnum; m_pDisplaySettings->LoadRegistry(); m_pPluginManager = new CPluginManager; @@ -202,7 +192,6 @@ CEditorImpl::CEditorImpl() m_pImageUtil = new CImageUtil_impl(); m_pResourceSelectorHost.reset(CreateResourceSelectorHost()); - m_pRuler = new CRuler; m_selectedRegion.min = Vec3(0, 0, 0); m_selectedRegion.max = Vec3(0, 0, 0); DetectVersion(); @@ -335,8 +324,6 @@ CEditorImpl::~CEditorImpl() } SAFE_DELETE(m_pDisplaySettings) - SAFE_DELETE(m_pRuler) - SAFE_DELETE(m_pShaderEnum) SAFE_DELETE(m_pToolBoxManager) SAFE_DELETE(m_pCommandManager) SAFE_DELETE(m_pClassFactory) @@ -419,7 +406,6 @@ void CEditorImpl::Update() m_bUpdates = false; FUNCTION_PROFILER(GetSystem(), PROFILE_EDITOR); - m_pRuler->Update(); //@FIXME: Restore this latter. //if (GetGameEngine() && GetGameEngine()->IsLevelLoaded()) @@ -440,15 +426,6 @@ ISystem* CEditorImpl::GetSystem() return m_pSystem; } -IRenderer* CEditorImpl::GetRenderer() -{ - if (gEnv) - { - return gEnv->pRenderer; - } - return nullptr; -} - IEditorClassFactory* CEditorImpl::GetClassFactory() { return m_pClassFactory; @@ -862,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(); @@ -1182,11 +1149,6 @@ void CEditorImpl::AddTemplate(const QString& templateName, XmlNodeRef& tmpl) m_templateRegistry.AddTemplate(templateName, tmpl); } -CShaderEnum* CEditorImpl::GetShaderEnum() -{ - return m_pShaderEnum; -} - bool CEditorImpl::ExecuteConsoleApp(const QString& CommandLine, QString& OutputText, [[maybe_unused]] bool bNoTimeOut, bool bShowWindow) { CLogFile::FormatLine("Executing console application '%s'", CommandLine.toUtf8().data()); @@ -1569,7 +1531,6 @@ void CEditorImpl::ReduceMemory() GetIEditor()->GetUndoManager()->ClearRedoStack(); GetIEditor()->GetUndoManager()->ClearUndoStack(); GetIEditor()->GetObjectManager()->SendEvent(EVENT_FREE_GAME_DATA); - gEnv->pRenderer->FreeResources(FRR_TEXTURES); #if defined(AZ_PLATFORM_WINDOWS) HANDLE hHeap = GetProcessHeap(); @@ -1648,8 +1609,6 @@ ESystemConfigPlatform CEditorImpl::GetEditorConfigPlatform() const void CEditorImpl::InitFinished() { - SProjectSettingsBlock::Load(); - if (!m_bInitialized) { m_bInitialized = true; diff --git a/Code/Sandbox/Editor/IEditorImpl.h b/Code/Sandbox/Editor/IEditorImpl.h index bbef338cb2..0ebd02b5fd 100644 --- a/Code/Sandbox/Editor/IEditorImpl.h +++ b/Code/Sandbox/Editor/IEditorImpl.h @@ -43,17 +43,13 @@ 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 CShaderEnum; class CVegetationMap; @@ -62,16 +58,6 @@ namespace Editor class EditorQtApplication; } -namespace BackgroundScheduleManager -{ - class CScheduleManager; -} - -namespace BackgroundTaskManager -{ - class CTaskManager; -} - namespace WinWidget { class WinWidgetManager; @@ -116,7 +102,6 @@ public: bool IsInitialized() const{ return m_bInitialized; } bool SaveDocument(); ISystem* GetSystem(); - IRenderer* GetRenderer(); void WriteToConsole(const char* string) { CLogFile::WriteLine(string); }; void WriteToConsole(const QString& string) { CLogFile::WriteLine(string); }; // Change the message in the status bar @@ -181,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; @@ -215,7 +198,6 @@ public: void SetMarkerPosition(const Vec3& pos) { m_marker = pos; }; void SetSelectedRegion(const AABB& box); void GetSelectedRegion(AABB& box); - CRuler* GetRuler() { return m_pRuler; } bool AddToolbarItem(uint8 iId, IUIEvent* pIHandler); void SetDataModified(); void SetOperationMode(EOperationMode mode); @@ -256,7 +238,6 @@ public: SFileVersion GetFileVersion() { return m_fileVersion; }; SFileVersion GetProductVersion() { return m_productVersion; }; //! Get shader enumerator. - CShaderEnum* GetShaderEnum(); CUndoManager* GetUndoManager() { return m_pUndoManager; }; void BeginUndo(); void RestoreUndo(bool undo); @@ -365,7 +346,6 @@ protected: SFileVersion m_productVersion; CXmlTemplateRegistry m_templateRegistry; CDisplaySettings* m_pDisplaySettings; - CShaderEnum* m_pShaderEnum; CIconManager* m_pIconManager; std::unique_ptr m_pGizmoParameters; QString m_primaryCDFolder; @@ -390,8 +370,6 @@ protected: CSelectionTreeManager* m_pSelectionTreeManager; CUIEnumsDatabase* m_pUIEnumsDatabase; - //! Currently used ruler - CRuler* m_pRuler; //! CConsole Synchronization CConsoleSynchronization* m_pConsoleSync; //! Editor Settings Manager @@ -401,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/Include/IEditorFileMonitor.h b/Code/Sandbox/Editor/Include/IEditorFileMonitor.h index 670e4fdf7e..cfd14f8942 100644 --- a/Code/Sandbox/Editor/Include/IEditorFileMonitor.h +++ b/Code/Sandbox/Editor/Include/IEditorFileMonitor.h @@ -15,9 +15,43 @@ #define CRYINCLUDE_EDITOR_INCLUDE_IEDITORFILEMONITOR_H #pragma once -#include +struct IFileChangeListener +{ + enum EChangeType + { + //! error or unknown change type + eChangeType_Unknown, + //! the file was created + eChangeType_Created, + //! the file was deleted + eChangeType_Deleted, + //! the file was modified (size changed,write) + eChangeType_Modified, + //! this is the old name of a renamed file + eChangeType_RenamedOldName, + //! this is the new name of a renamed file + eChangeType_RenamedNewName + }; -struct IFileChangeListener; + virtual ~IFileChangeListener() = default; + + virtual void OnFileChange(const char* sFilename, EChangeType eType) = 0; +}; + +struct IFileChangeMonitor +{ + virtual ~IFileChangeMonitor() = default; + + // + // Register the path of a file or directory to monitor + // Path is relative to game directory, e.g. "Libs/WoundSystem/" or "Libs/WoundSystem/HitLocations.xml" + virtual bool RegisterListener(IFileChangeListener* pListener, const char* sMonitorItem) = 0; + // This function can be used to monitor files of specific type, e.g. + // RegisterListener(pListener, "Animations", "caf") + virtual bool RegisterListener(IFileChangeListener* pListener, const char* sFolder, const char* sExtension) = 0; + virtual bool UnregisterListener(IFileChangeListener* pListener) = 0; + // +}; struct IEditorFileMonitor : public IFileChangeMonitor 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/Include/ObjectEvent.h b/Code/Sandbox/Editor/Include/ObjectEvent.h index 3f6addb736..e90610872f 100644 --- a/Code/Sandbox/Editor/Include/ObjectEvent.h +++ b/Code/Sandbox/Editor/Include/ObjectEvent.h @@ -33,7 +33,6 @@ enum ObjectEvent EVENT_DBLCLICK, //!< Signals that object have been double clicked. EVENT_KEEP_HEIGHT, //!< Signals that object must preserve its height over changed terrain. EVENT_RELOAD_ENTITY,//!< Signals that entities scripts must be reloaded. - EVENT_RELOAD_TEXTURES,//!< Signals that all possible textures in objects should be reloaded. EVENT_RELOAD_GEOM, //!< Signals that all possible geometries should be reloaded. EVENT_UNLOAD_GEOM, //!< Signals that all possible geometries should be unloaded. EVENT_MISSION_CHANGE, //!< Signals that mission have been changed. 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 4a20bd6b60..949bc72e03 100644 --- a/Code/Sandbox/Editor/Lib/Tests/IEditorMock.h +++ b/Code/Sandbox/Editor/Lib/Tests/IEditorMock.h @@ -32,7 +32,6 @@ public: public: MOCK_METHOD0(DeleteThis, void()); MOCK_METHOD0(GetSystem, ISystem*()); - MOCK_METHOD0(GetRenderer, IRenderer* ()); MOCK_METHOD0(GetClassFactory, IEditorClassFactory* ()); MOCK_METHOD0(GetCommandManager, CEditorCommandManager*()); MOCK_METHOD0(GetICommandManager, ICommandManager* ()); @@ -103,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* )); @@ -117,7 +115,6 @@ public: MOCK_METHOD1(SetMarkerPosition, void(const Vec3&)); MOCK_METHOD1(SetSelectedRegion, void(const AABB& box)); MOCK_METHOD1(GetSelectedRegion, void(AABB& box)); - MOCK_METHOD0(GetRuler, CRuler* ()); MOCK_METHOD1(SetOperationMode, void(EOperationMode )); MOCK_METHOD0(GetOperationMode, EOperationMode()); MOCK_METHOD1(ShowTransformManipulator, ITransformManipulator* (bool)); @@ -140,7 +137,6 @@ public: MOCK_METHOD1(OpenWinWidget, QWidget* (WinWidgetId )); MOCK_CONST_METHOD0(GetWinWidgetManager, WinWidget::WinWidgetManager* ()); MOCK_METHOD2(SelectColor, bool(QColor &, QWidget *)); - MOCK_METHOD0(GetShaderEnum, class CShaderEnum* ()); MOCK_METHOD0(GetUndoManager, class CUndoManager* ()); MOCK_METHOD0(BeginUndo, void()); MOCK_METHOD1(RestoreUndo, void(bool)); @@ -187,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 e9bfd96a1d..6f6b600a84 100644 --- a/Code/Sandbox/Editor/MainWindow.cpp +++ b/Code/Sandbox/Editor/MainWindow.cpp @@ -66,7 +66,6 @@ AZ_POP_DISABLE_WARNING #include "AssetImporter/AssetImporterManager/AssetImporterDragAndDropHandler.h" #include "CryEdit.h" #include "Controls/ConsoleSCB.h" -#include "Grid.h" #include "ViewManager.h" #include "CryEditDoc.h" #include "ToolBox.h" @@ -78,6 +77,7 @@ AZ_POP_DISABLE_WARNING #include "Core/QtEditorApplication.h" #include "UndoDropDown.h" #include "CVarMenu.h" +#include "EditorViewportSettings.h" #include "KeyboardCustomizationSettings.h" #include "CustomizeKeyboardDialog.h" @@ -92,11 +92,9 @@ AZ_POP_DISABLE_WARNING #include "ErrorReportDialog.h" #include "Dialogs/PythonScriptsDialog.h" -#include "EngineSettingsManager.h" #include "AzAssetBrowser/AzAssetBrowserWindow.h" #include "AssetEditor/AssetEditorWindow.h" -#include "GridSettingsDialog.h" #include "ActionManager.h" // uncomment this to show thumbnail demo widget @@ -122,12 +120,6 @@ static const char* g_openLocationAttributeName = "OpenLocation"; //Indicates whe static const char* g_assetImporterName = "AssetImporter"; -static const char* g_snapToGridEnabled = "mainwindow/snapGridEnabled"; -static const char* g_snapToGridSize = "mainwindow/snapGridSize"; -static const char* g_snapAngleEnabled = "mainwindow/snapAngleEnabled"; -static const char* g_snapAngle = "mainwindow/snapAngle"; -static const char* g_terrainFollow = "mainwindow/terrainFollow"; - class CEditorOpenViewCommand : public _i_reference_target_t { @@ -307,10 +299,8 @@ namespace class SnapToWidget : public QWidget - , public CGridSettingsDialog::NotificationBus::Handler { public: - typedef AZStd::function SetValueCallback; typedef AZStd::function GetValueCallback; @@ -334,12 +324,13 @@ public: m_spinBox->setEnabled(defaultAction->isChecked()); m_spinBox->setMinimum(1e-2f); - OnGridValuesUpdated(); + { + QSignalBlocker signalBlocker(m_spinBox); + m_spinBox->setValue(m_getValueCallback()); + } QObject::connect(m_spinBox, QOverload::of(&AzQtComponents::DoubleSpinBox::valueChanged), this, &SnapToWidget::OnValueChanged); QObject::connect(defaultAction, &QAction::changed, this, &SnapToWidget::OnActionChanged); - - CGridSettingsDialog::NotificationBus::Handler::BusConnect(); } void SetIcon(QIcon icon) @@ -347,14 +338,6 @@ public: m_toolButton->setIcon(icon); } - void OnGridValuesUpdated() override - { - // Blocking signals to not trigger the valueChanged callback when we set the value on the spin box. - QSignalBlocker signalBlocker(m_spinBox); - double value = m_getValueCallback(); - m_spinBox->setValue(value); - } - protected: void OnValueChanged(double value) @@ -542,7 +525,6 @@ void MainWindow::Initialize() RegisterStdViewClasses(); InitCentralWidget(); - LoadConfig(); InitActions(); // load toolbars ("shelves") and macros @@ -672,31 +654,8 @@ void MainWindow::closeEvent(QCloseEvent* event) QMainWindow::closeEvent(event); } -void MainWindow::LoadConfig() -{ - CGrid* grid = gSettings.pGrid; - Q_ASSERT(grid); - bool terrainValue; - - ReadConfigValue(g_snapAngleEnabled, grid->bAngleSnapEnabled); - ReadConfigValue(g_snapAngle, grid->angleSnap); - ReadConfigValue(g_snapToGridEnabled, grid->bEnabled); - ReadConfigValue(g_snapToGridSize, grid->size); - ReadConfigValue(g_terrainFollow, terrainValue); - GetIEditor()->SetTerrainAxisIgnoreObjects(terrainValue); -} - void MainWindow::SaveConfig() { - CGrid* grid = gSettings.pGrid; - Q_ASSERT(grid); - - m_settings.setValue(g_snapAngleEnabled, grid->bAngleSnapEnabled); - m_settings.setValue(g_snapAngle, grid->angleSnap); - m_settings.setValue(g_snapToGridEnabled, grid->bEnabled); - m_settings.setValue(g_snapToGridSize, grid->size); - m_settings.setValue(g_terrainFollow, GetIEditor()->IsTerrainAxisIgnoreObjects()); - m_settings.setValue("mainWindowState", saveState()); QtViewPaneManager::instance()->SaveLayout(); if (m_pLayoutWnd) @@ -735,8 +694,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 @@ -915,13 +872,22 @@ void MainWindow::InitActions() .SetToolTip(tr("Snap to grid (G)")) .SetStatusTip(tr("Toggles snap to grid")) .SetCheckable(true) - .RegisterUpdateCallback(this, &MainWindow::OnUpdateSnapToGrid); + .RegisterUpdateCallback([](QAction* action) { + Q_ASSERT(action->isCheckable()); + action->setChecked(Editor::GridSnappingEnabled()); + }) + .Connect(&QAction::triggered, []() { Editor::SetGridSnapping(!Editor::GridSnappingEnabled()); }); + am->AddAction(ID_SNAPANGLE, tr("Snap angle")) .SetIcon(Style::icon("Angle")) .SetApplyHoverEffect() .SetStatusTip(tr("Snap angle")) .SetCheckable(true) - .RegisterUpdateCallback(cryEdit, &CCryEditApp::OnUpdateSnapangle); + .RegisterUpdateCallback([](QAction* action) { + Q_ASSERT(action->isCheckable()); + action->setChecked(Editor::AngleSnappingEnabled()); + }) + .Connect(&QAction::triggered, []() { Editor::SetAngleSnapping(!Editor::AngleSnappingEnabled()); }); // Display actions am->AddAction(ID_WIREFRAME, tr("&Wireframe")) @@ -931,7 +897,6 @@ void MainWindow::InitActions() .SetStatusTip(tr("Render in Wireframe Mode.")) .RegisterUpdateCallback(cryEdit, &CCryEditApp::OnUpdateWireframe); - am->AddAction(ID_VIEW_GRIDSETTINGS, tr("Grid Settings...")); am->AddAction(ID_SWITCHCAMERA_DEFAULTCAMERA, tr("Default Camera")).SetCheckable(true) .RegisterUpdateCallback(cryEdit, &CCryEditApp::OnUpdateSwitchToDefaultCamera); am->AddAction(ID_SWITCHCAMERA_SEQUENCECAMERA, tr("Sequence Camera")).SetCheckable(true) @@ -1075,8 +1040,6 @@ void MainWindow::InitActions() .RegisterUpdateCallback(cryEdit, &CCryEditApp::OnUpdateSelected); // Tools actions - am->AddAction(ID_RELOAD_TEXTURES, tr("Reload Textures/Shaders")) - .SetStatusTip(tr("Reload all textures.")); am->AddAction(ID_TOOLS_ENABLEFILECHANGEMONITORING, tr("Enable File Change Monitoring")); am->AddAction(ID_CLEAR_REGISTRY, tr("Clear Registry Data")) .SetStatusTip(tr("Clear Registry Data")); @@ -1287,44 +1250,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); @@ -1333,93 +1258,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) { @@ -1434,12 +1272,12 @@ QWidget* MainWindow::CreateSnapToGridWidget() { SnapToWidget::SetValueCallback setCallback = [](double snapStep) { - GetIEditor()->GetViewManager()->GetGrid()->size = snapStep; + Editor::SetGridSnappingSize(snapStep); }; SnapToWidget::GetValueCallback getCallback = []() { - return GetIEditor()->GetViewManager()->GetGrid()->size; + return Editor::GridSnappingSize(); }; return new SnapToWidget(m_actionManager->GetAction(ID_SNAP_TO_GRID), setCallback, getCallback); @@ -1449,12 +1287,12 @@ QWidget* MainWindow::CreateSnapToAngleWidget() { SnapToWidget::SetValueCallback setCallback = [](double snapAngle) { - GetIEditor()->GetViewManager()->GetGrid()->angleSnap = snapAngle; + Editor::SetAngleSnappingSize(snapAngle); }; SnapToWidget::GetValueCallback getCallback = []() { - return GetIEditor()->GetViewManager()->GetGrid()->angleSnap; + return Editor::AngleSnappingSize(); }; return new SnapToWidget(m_actionManager->GetAction(ID_SNAPANGLE), setCallback, getCallback); @@ -1471,15 +1309,6 @@ MainStatusBar* MainWindow::StatusBar() const return static_cast(statusBar()); } -void MainWindow::OnUpdateSnapToGrid(QAction* action) -{ - Q_ASSERT(action->isCheckable()); - bool bEnabled = gSettings.pGrid->IsEnabled(); - action->setChecked(bEnabled); - - action->setText(QObject::tr("Snap To Grid")); -} - KeyboardCustomizationSettings* MainWindow::GetShortcutManager() const { return m_keyboardCustomization; @@ -2111,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); } @@ -2193,12 +2016,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 adf271b383..ab60b0e0d4 100644 --- a/Code/Sandbox/Editor/MainWindow.h +++ b/Code/Sandbox/Editor/MainWindow.h @@ -191,9 +191,7 @@ private: void InitToolActionHandlers(); void InitToolBars(); void InitStatusBar(); - void OnUpdateSnapToGrid(QAction* action); void OnViewPaneCreated(const QtViewPane* pane); - void LoadConfig(); template void ReadConfigValue(const QString& key, TValue& value) @@ -210,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/ModernViewportCameraController.cpp b/Code/Sandbox/Editor/ModernViewportCameraController.cpp index 1c2771514f..f5df8d48ca 100644 --- a/Code/Sandbox/Editor/ModernViewportCameraController.cpp +++ b/Code/Sandbox/Editor/ModernViewportCameraController.cpp @@ -19,6 +19,7 @@ #include #include #include +#include #include #include @@ -64,17 +65,20 @@ namespace SandboxEditor } } - ModernViewportCameraControllerInstance::ModernViewportCameraControllerInstance(const AzFramework::ViewportId viewportId, ModernViewportCameraController* controller) + ModernViewportCameraControllerInstance::ModernViewportCameraControllerInstance( + const AzFramework::ViewportId viewportId, ModernViewportCameraController* controller) : MultiViewportControllerInstanceInterface(viewportId, controller) { controller->SetupCameras(m_cameraSystem.m_cameras); if (auto viewportContext = RetrieveViewportContext(GetViewportId())) { - auto handleCameraChange = [this](const AZ::Matrix4x4& matrix) { - UpdateCameraFromTransform( - m_targetCamera, - AZ::Transform::CreateFromMatrix3x3AndTranslation(AZ::Matrix3x3::CreateFromMatrix4x4(matrix), matrix.GetTranslation())); + auto handleCameraChange = [this, viewportContext](const AZ::Matrix4x4&) { + if (!m_updatingTransform) + { + UpdateCameraFromTransform(m_targetCamera, viewportContext->GetCameraTransform()); + m_camera = m_targetCamera; + } }; m_cameraViewMatrixChangeHandler = AZ::RPI::ViewportContext::MatrixChangedEvent::Handler(handleCameraChange); @@ -124,6 +128,8 @@ namespace SandboxEditor { if (auto viewportContext = RetrieveViewportContext(GetViewportId())) { + m_updatingTransform = true; + if (m_cameraMode == CameraMode::Control) { m_targetCamera = m_cameraSystem.StepCamera(m_targetCamera, event.m_deltaTime.count()); @@ -155,6 +161,8 @@ namespace SandboxEditor viewportContext->SetCameraTransform(current); } + + m_updatingTransform = false; } } diff --git a/Code/Sandbox/Editor/ModernViewportCameraController.h b/Code/Sandbox/Editor/ModernViewportCameraController.h index b1ff8d1039..edc034a78a 100644 --- a/Code/Sandbox/Editor/ModernViewportCameraController.h +++ b/Code/Sandbox/Editor/ModernViewportCameraController.h @@ -20,14 +20,13 @@ namespace SandboxEditor { class ModernViewportCameraControllerInstance; - class ModernViewportCameraController - : public AzFramework::MultiViewportController + class ModernViewportCameraController : public AzFramework::MultiViewportController { public: using CameraListBuilder = AZStd::function; + //! Sets the camera list builder callback used to populate new ModernViewportCameraControllerInstances void SetCameraListBuilderCallback(const CameraListBuilder& builder); - //! Sets up a camera list based on this controller's CameraListBuilderCallback void SetupCameras(AzFramework::Cameras& cameras); @@ -35,9 +34,9 @@ namespace SandboxEditor CameraListBuilder m_cameraListBuilder; }; - class ModernViewportCameraControllerInstance final - : public AzFramework::MultiViewportControllerInstanceInterface - , private AzFramework::ViewportDebugDisplayEventBus::Handler + class ModernViewportCameraControllerInstance final + : public AzFramework::MultiViewportControllerInstanceInterface, + private AzFramework::ViewportDebugDisplayEventBus::Handler { public: explicit ModernViewportCameraControllerInstance(AzFramework::ViewportId viewportId, ModernViewportCameraController* controller); @@ -65,6 +64,7 @@ namespace SandboxEditor AZ::Transform m_transformEnd = AZ::Transform::CreateIdentity(); float m_animationT = 0.0f; CameraMode m_cameraMode = CameraMode::Control; + bool m_updatingTransform = false; AZ::RPI::ViewportContext::MatrixChangedEvent::Handler m_cameraViewMatrixChangeHandler; }; diff --git a/Code/Sandbox/Editor/Objects/AxisGizmo.cpp b/Code/Sandbox/Editor/Objects/AxisGizmo.cpp index ef2b91685a..8e10d03080 100644 --- a/Code/Sandbox/Editor/Objects/AxisGizmo.cpp +++ b/Code/Sandbox/Editor/Objects/AxisGizmo.cpp @@ -18,7 +18,6 @@ // Editor #include "Viewport.h" #include "GizmoManager.h" -#include "Grid.h" #include "ViewManager.h" #include "Settings.h" #include "RenderHelpers/AxisHelper.h" @@ -244,7 +243,8 @@ Matrix34 CAxisGizmo::GetTransformation(RefCoordSys coordSys, IDisplayViewport* v break; case COORDS_USERDEFINED: { - Matrix34 userTM = GetIEditor()->GetViewManager()->GetGrid()->GetMatrix(); + Matrix34 userTM; + userTM.SetIdentity(); userTM.SetTranslation(m_object->GetWorldTM().GetTranslation()); return userTM; } diff --git a/Code/Sandbox/Editor/Objects/BaseObject.cpp b/Code/Sandbox/Editor/Objects/BaseObject.cpp index 3ec505172e..4c76f68f2f 100644 --- a/Code/Sandbox/Editor/Objects/BaseObject.cpp +++ b/Code/Sandbox/Editor/Objects/BaseObject.cpp @@ -894,314 +894,10 @@ void CBaseObject::DrawDefault(DisplayContext& dc, const QColor& labelColor) } ////////////////////////////////////////////////////////////////////////// -void CBaseObject::DrawDimensions(DisplayContext& dc, AABB* pMergedBoundBox) +void CBaseObject::DrawDimensions(DisplayContext&, AABB*) { - if (HasMeasurementAxis() && GetIEditor()->GetDisplaySettings()->IsDisplayDimensionFigures()) - { - AABB localBoundBox; - GetLocalBounds(localBoundBox); - DrawDimensionsImpl(dc, localBoundBox, pMergedBoundBox); - } } -////////////////////////////////////////////////////////////////////////// -void CBaseObject::DrawDimensionsImpl(DisplayContext& dc, const AABB& localBoundBox, AABB* pMergedBoundBox) -{ - AABB boundBox; - Matrix34 rotatedTM; - bool bHave2Axis(false); - float xLength(0); - float yLength(0); - float zLength(0); - - if (pMergedBoundBox) - { - rotatedTM = Matrix34::CreateIdentity(); - boundBox = *pMergedBoundBox; - xLength = boundBox.max.x - boundBox.min.x; - zLength = boundBox.max.z - boundBox.min.z; - yLength = boundBox.max.y - boundBox.min.y; - } - else - { - rotatedTM = GetWorldRotTM(); - Matrix34 scaledTranslatedTM = GetWorldScaleTM(); - scaledTranslatedTM.SetTranslation(GetWorldPos()); - boundBox.SetTransformedAABB(scaledTranslatedTM, localBoundBox); - - IVariable* pVarXLength(NULL); - IVariable* pVarYLength(NULL); - IVariable* pVarZLength(NULL); - - IVariable* pVarDimX(NULL); - IVariable* pVarDimY(NULL); - IVariable* pVarDimZ(NULL); - - CVarBlock* pVarBlock(GetVarBlock()); - if (pVarBlock) - { - pVarXLength = pVarBlock->FindVariable("Width"); - pVarYLength = pVarBlock->FindVariable("Length"); - pVarZLength = pVarBlock->FindVariable("Height"); - pVarDimX = pVarBlock->FindVariable("DimX"); - pVarDimY = pVarBlock->FindVariable("DimY"); - pVarDimZ = pVarBlock->FindVariable("DimZ"); - } - - xLength = boundBox.max.x - boundBox.min.x; - zLength = boundBox.max.z - boundBox.min.z; - yLength = boundBox.max.y - boundBox.min.y; - - if (pVarDimX && pVarDimY && pVarDimZ) - { - pVarDimX->Get(xLength); - pVarDimZ->Get(zLength); - pVarDimY->Get(yLength); - xLength *= m_scale.x; - zLength *= m_scale.z; - yLength *= m_scale.y; - } - else if (pVarXLength && pVarYLength && pVarZLength) - { - // A case of an area box. - pVarXLength->Get(xLength); - pVarZLength->Get(zLength); - pVarYLength->Get(yLength); - xLength *= m_scale.x; - zLength *= m_scale.z; - yLength *= m_scale.y; - } - else if (!pVarXLength && !pVarYLength && pVarZLength) - { - // A case of an area shape. - pVarZLength->Get(zLength); - zLength *= m_scale.z; - } - } - - const float kMinimumLimitation(0.4f); - if (xLength < kMinimumLimitation && yLength < kMinimumLimitation && zLength < kMinimumLimitation) - { - return; - } - - const float kEpsilon(0.001f); - bHave2Axis = fabs(zLength) < kEpsilon; - - Vec3 basePoints[] = { - Vec3(boundBox.min.x, boundBox.min.y, boundBox.min.z), - Vec3(boundBox.min.x, boundBox.max.y, boundBox.min.z), - Vec3(boundBox.max.x, boundBox.max.y, boundBox.min.z), - Vec3(boundBox.max.x, boundBox.min.y, boundBox.min.z), - Vec3(boundBox.min.x, boundBox.min.y, boundBox.max.z), - Vec3(boundBox.min.x, boundBox.max.y, boundBox.max.z), - Vec3(boundBox.max.x, boundBox.max.y, boundBox.max.z), - Vec3(boundBox.max.x, boundBox.min.y, boundBox.max.z) - }; - const int kElementSize(sizeof(basePoints) / sizeof(*basePoints)); - Vec3 axisDirections[kElementSize] = { Vec3(1, 1, 1), Vec3(1, -1, 1), Vec3(-1, -1, 1), Vec3(-1, 1, 1), Vec3(1, 1, -1), Vec3(1, -1, -1), Vec3(-1, -1, -1), Vec3(-1, 1, -1) }; - int nLoopCount = bHave2Axis ? (kElementSize / 2) : kElementSize; - if (bHave2Axis) - { - for (int i = 0; i < nLoopCount; ++i) - { - basePoints[i].z = 0.5f * (boundBox.min.z + boundBox.max.z); - } - } - - // Find out the nearest base point of a bounding box from a camera position and use it as a pivot. - const CCamera& camera = gEnv->pRenderer->GetCamera(); - Vec3 cameraPos(camera.GetPosition()); - Vec3 pivot(rotatedTM.TransformVector(basePoints[0] - GetWorldPos()) + GetWorldPos()); - float fNearestDist = (cameraPos - pivot).GetLength(); - int nNearestAxisIndex(0); - bool bPrevVisible(camera.IsPointVisible(pivot)); - - for (int i = 1; i < nLoopCount; ++i) - { - Vec3 candidatePivot(rotatedTM.TransformVector(basePoints[i] - GetWorldPos()) + GetWorldPos()); - float candidateLength = (candidatePivot - cameraPos).GetLength(); - bool bVisible = camera.IsPointVisible(candidatePivot); - if (bVisible) - { - if (!bPrevVisible || candidateLength < fNearestDist) - { - fNearestDist = candidateLength; - pivot = candidatePivot; - nNearestAxisIndex = i; - } - bPrevVisible = bVisible; - } - } - - float fScale = dc.view->GetScreenScaleFactor(pivot); - float fArrowScale = fScale * 0.04f; - - Vec3 vX(xLength, 0, 0); - Vec3 vY(0, yLength, 0); - Vec3 vZ(0, 0, zLength); - - vX = vX * axisDirections[nNearestAxisIndex].x; - vY = vY * axisDirections[nNearestAxisIndex].y; - vZ = vZ * axisDirections[nNearestAxisIndex].z; - vX = rotatedTM.TransformVector(vX); - vY = rotatedTM.TransformVector(vY); - vZ = rotatedTM.TransformVector(vZ); - - const float kArrowPivotOffset = 0.1f; - pivot = pivot + (-(vX + vY + vZ)).GetNormalized() * kArrowPivotOffset; - - Vec3 centerPt(boundBox.GetCenter()); - - // Display texts of width, height and depth - float fTextScale(1.3f); - dc.SetColor(QColor(200, 200, 200)); - QString str; - - const float kBrightness(0.35f); - const ColorF kXColor(1.0f, kBrightness, kBrightness, 0.9f); - const ColorF kYColor(kBrightness, 1.0f, kBrightness, 0.9f); - const ColorF kZColor(kBrightness, kBrightness, 1.0f, 0.9f); - const ColorF TextBoxColor(0, 0, 0, 0.75f); - - ColorB backupcolor = dc.GetColor(); - uint32 backupstate = dc.GetState(); - int backupThickness = dc.GetLineWidth(); - - dc.SetState(backupstate | e_DepthTestOff); - - Vec3 vNX = vX.GetNormalized(); - Vec3 vNY = vY.GetNormalized(); - Vec3 vNZ = vZ.GetNormalized(); - - const float kMinimumOffset(0.20f); - const float kMaximumOffset(30.0f); - float fMaximumOffset[3] = { kMaximumOffset, kMaximumOffset, kMaximumOffset }; - if (xLength > kMaximumOffset * 0.5f) - { - fMaximumOffset[0] = xLength * 3.0f; - } - if (yLength > kMaximumOffset * 0.5f) - { - fMaximumOffset[1] = yLength * 3.0f; - } - if (zLength > kMaximumOffset * 0.5f) - { - fMaximumOffset[2] = zLength * 3.0f; - } - Vec3 textPos[3] = {pivot, pivot, pivot}; - Vec3 textMinPos[3] = { pivot + vNX * kMinimumOffset, pivot + vNY * kMinimumOffset, pivot + vNZ * kMinimumOffset }; - Vec3 textCenterPos[3] = { pivot + vX * 0.5f, pivot + vY * 0.5f, pivot + vZ * 0.5f }; - Vec3 textMaxPos[3] = { pivot + vNX * fMaximumOffset[0], pivot + vNY * fMaximumOffset[1], pivot + vNZ * fMaximumOffset[2] }; - - const Vec3& cameraDir(camera.GetViewdir()); - - for (int i = 0; i < 3; ++i) - { - Vec3 d = (textMaxPos[i] - cameraPos).GetNormalized(); - float fCameraDir = d.Dot(cameraDir); - if (fCameraDir < 0) - { - fCameraDir = 0; - } - textPos[i] = textMinPos[i] + (textCenterPos[i] - textPos[i]) * fCameraDir; - } - - str = QString::number(xLength, 'f', 3); - DrawTextOn2DBox(dc, textPos[0], str.toUtf8().data(), fTextScale, kXColor, TextBoxColor); - - if (!bHave2Axis) - { - str = QString::number(zLength, 'f', 3); - DrawTextOn2DBox(dc, textPos[2], str.toUtf8().data(), fTextScale, kZColor, TextBoxColor); - } - - str = QString::number(yLength, 'f', 3); - DrawTextOn2DBox(dc, textPos[1], str.toUtf8().data(), fTextScale, kYColor, TextBoxColor); - - dc.SetState(backupstate | e_DepthTestOn); - dc.SetLineWidth(4); - - // Draw arrows of each axis. - dc.SetColor(kXColor); - dc.DrawArrow(pivot, pivot + vX, fArrowScale, true); - if (!bHave2Axis) - { - dc.SetColor(kZColor); - dc.DrawArrow(pivot, pivot + vZ, fArrowScale, true); - } - dc.SetColor(kYColor); - dc.DrawArrow(pivot, pivot + vY, fArrowScale, true); - - dc.SetState(backupstate); - dc.SetColor(backupcolor); - dc.SetLineWidth(backupThickness); -} - -////////////////////////////////////////////////////////////////////////// -void CBaseObject::DrawTextOn2DBox(DisplayContext& dc, const Vec3& pos, const char* text, float textScale, const ColorF& TextColor, const ColorF& TextBackColor) -{ - Vec3 worldPos = dc.ToWorldSpacePosition(pos); - int vx, vy, vw, vh; - gEnv->pRenderer->GetViewport(&vx, &vy, &vw, &vh); - - const CCamera& camera = gEnv->pRenderer->GetCamera(); - Vec3 screenPos; - camera.Project(worldPos, screenPos, Vec2i(0, 0), Vec2i(0, 0)); - - //! Font size information doesn't seem to exist so the proper size is used - int textlen = strlen(text); - float fontsize = 7.5f; - float textwidth = fontsize * textlen; - float textheight = 16.0f; - - screenPos.x = screenPos.x - textwidth * 0.5f; - - Vec3 textregion[4] = { - Vec3(screenPos.x, screenPos.y, screenPos.z), - Vec3(screenPos.x + textwidth, screenPos.y, screenPos.z), - Vec3(screenPos.x + textwidth, screenPos.y + textheight, screenPos.z), - Vec3(screenPos.x, screenPos.y + textheight, screenPos.z) - }; - - Vec3 textworldreign[4]; - Matrix34 dcInvTm = dc.GetMatrix().GetInverted(); - - Matrix44A mProj, mView; - mathMatrixPerspectiveFov(&mProj, camera.GetFov(), camera.GetProjRatio(), camera.GetNearPlane(), camera.GetFarPlane()); - mathMatrixLookAt(&mView, camera.GetPosition(), camera.GetPosition() + camera.GetViewdir(), Vec3(0, 0, 1)); - Matrix44A mInvViewProj = (mView * mProj).GetInverted(); - - for (int i = 0; i < 4; ++i) - { - Vec4 projectedpos = Vec4((textregion[i].x - vx) / vw * 2.0f - 1.0f, - -((textregion[i].y - vy) / vh) * 2.0f + 1.0f, - textregion[i].z, - 1.0f); - - Vec4 wp = projectedpos * mInvViewProj; - wp.x /= wp.w; - wp.y /= wp.w; - wp.z /= wp.w; - textworldreign[i] = dcInvTm.TransformPoint(Vec3(wp.x, wp.y, wp.z)); - } - - ColorB backupcolor = dc.GetColor(); - uint32 backupstate = dc.GetState(); - - dc.SetColor(TextBackColor); - dc.SetDrawInFrontMode(true); - - dc.DrawQuad(textworldreign[3], textworldreign[2], textworldreign[1], textworldreign[0]); - dc.SetColor(TextColor); - dc.DrawTextLabel(pos, textScale, text); - - dc.SetDrawInFrontMode(false); - dc.SetColor(backupcolor); - dc.SetState(backupstate); -} - - ////////////////////////////////////////////////////////////////////////// void CBaseObject::DrawSelectionHelper(DisplayContext& dc, const Vec3& pos, const QColor& labelColor, [[maybe_unused]] float alpha) { @@ -1572,12 +1268,6 @@ int CBaseObject::MouseCreateCallback(CViewport* view, EMouseEvent event, QPoint& if (event == eMouseWheel) { double angle = 1; - - if (view->GetViewManager()->GetGrid()->IsAngleSnapEnabled()) - { - angle = view->GetViewManager()->GetGrid()->GetAngleSnap(); - } - Quat rot = GetRotation(); rot.SetRotationXYZ(Ang3(0, 0, rot.GetRotZ() + DEG2RAD(flags > 0 ? angle * (-1) : angle))); SetRotation(rot); diff --git a/Code/Sandbox/Editor/Objects/BaseObject.h b/Code/Sandbox/Editor/Objects/BaseObject.h index 5d6f800a58..73e2394f6c 100644 --- a/Code/Sandbox/Editor/Objects/BaseObject.h +++ b/Code/Sandbox/Editor/Objects/BaseObject.h @@ -604,9 +604,6 @@ public: virtual IStatObj* GetIStatObj() { return NULL; } - //! Display length of each axis. - void DrawDimensionsImpl(DisplayContext& dc, const AABB& localBoundBox, AABB* pMergedBoundBox = NULL); - // Invalidates cached transformation matrix. // nWhyFlags - Flags that indicate the reason for matrix invalidation. virtual void InvalidateTM(int nWhyFlags); @@ -678,8 +675,6 @@ protected: virtual void DrawTextureIcon(DisplayContext& dc, const Vec3& pos, float alpha = 1.0f); //! Draw warning icons virtual void DrawWarningIcons(DisplayContext& dc, const Vec3& pos); - //! Display text with a 3d world coordinate. - void DrawTextOn2DBox(DisplayContext& dc, const Vec3& pos, const char* text, float textScale, const ColorF& TextColor, const ColorF& TextBackColor); //! Check if dimension's figures can be displayed before draw them. virtual void DrawDimensions(DisplayContext& dc, AABB* pMergedBoundBox = NULL); diff --git a/Code/Sandbox/Editor/Objects/DisplayContext.h b/Code/Sandbox/Editor/Objects/DisplayContext.h index 13363a923e..de33388eb4 100644 --- a/Code/Sandbox/Editor/Objects/DisplayContext.h +++ b/Code/Sandbox/Editor/Objects/DisplayContext.h @@ -227,7 +227,6 @@ struct SANDBOX_API DisplayContext void DrawTextLabel(const Vec3& pos, float size, const char* text, const bool bCenter = false, int srcOffsetX = 0, int scrOffsetY = 0); void Draw2dTextLabel(float x, float y, float size, const char* text, bool bCenter = false); - void DrawTextOn2DBox(const Vec3& pos, const char* text, float textScale, const ColorF& TextColor, const ColorF& TextBackColor); void SetLineWidth(float width); //! Is given bbox visible in this display context. diff --git a/Code/Sandbox/Editor/Objects/DisplayContextShared.inl b/Code/Sandbox/Editor/Objects/DisplayContextShared.inl index 4d284faea7..419b7c0406 100644 --- a/Code/Sandbox/Editor/Objects/DisplayContextShared.inl +++ b/Code/Sandbox/Editor/Objects/DisplayContextShared.inl @@ -37,7 +37,7 @@ DisplayContext::DisplayContext() m_currentMatrix = 0; m_matrixStack[m_currentMatrix].SetIdentity(); - pRenderAuxGeom = gEnv->pRenderer ? gEnv->pRenderer->GetIRenderAuxGeom() : nullptr; + pRenderAuxGeom = nullptr; // ToDo: Remove DisplayContext or update to work with Atom: LYN-3670 m_thickness = 0; m_width = 0; @@ -1105,85 +1105,6 @@ void DisplayContext::Draw2dTextLabel(float x, float y, float size, const char* t renderer->Draw2dLabel(x, y, size, col, bCenter, "%s", text); } -void DisplayContext::DrawTextOn2DBox(const Vec3& pos, const char* text, float textScale, const ColorF& TextColor, const ColorF& TextBackColor) -{ - Vec3 worldPos = ToWorldSpacePosition(pos); - int vx, vy, vw, vh; - gEnv->pRenderer->GetViewport(&vx, &vy, &vw, &vh); - uint32 backupstate = GetState(); - - SetState(backupstate | e_DepthTestOff); - - const CCamera& renderCamera = gEnv->pRenderer->GetCamera(); - Vec3 screenPos; - - renderCamera.Project(worldPos, screenPos, Vec2i(0, 0), Vec2i(0, 0)); - - //! Font size information doesn't seem to exist so the proper size is used - int textlen = strlen(text); - float fontsize = 7.5f * textScale; - float textwidth = fontsize * textlen; - float textheight = 16.0f * textScale; - - screenPos.x = screenPos.x - (textwidth * 0.5f); - - Vec3 textregion[4] = { - Vec3(screenPos.x, screenPos.y, screenPos.z), - Vec3(screenPos.x + textwidth, screenPos.y, screenPos.z), - Vec3(screenPos.x + textwidth, screenPos.y + textheight, screenPos.z), - Vec3(screenPos.x, screenPos.y + textheight, screenPos.z) - }; - - Vec3 textworldreign[4]; - Matrix34 dcInvTm = GetMatrix().GetInverted(); - - Matrix44A mProj, mView; - mathMatrixPerspectiveFov(&mProj, renderCamera.GetFov(), renderCamera.GetProjRatio(), renderCamera.GetNearPlane(), renderCamera.GetFarPlane()); - mathMatrixLookAt(&mView, renderCamera.GetPosition(), renderCamera.GetPosition() + renderCamera.GetViewdir(), Vec3(0, 0, 1)); - Matrix44A mInvViewProj = (mView * mProj).GetInverted(); - - if (vw == 0) - { - vw = 1; - } - - if (vh == 0) - { - vh = 1; - } - - for (int i = 0; i < 4; ++i) - { - Vec4 projectedpos = Vec4((textregion[i].x - vx) / vw * 2.0f - 1.0f, - -((textregion[i].y - vy) / vh) * 2.0f + 1.0f, - textregion[i].z, - 1.0f); - - Vec4 wp = projectedpos * mInvViewProj; - - if (wp.w == 0.0f) - { - wp.w = 0.0001f; - } - - wp.x /= wp.w; - wp.y /= wp.w; - wp.z /= wp.w; - textworldreign[i] = dcInvTm.TransformPoint(Vec3(wp.x, wp.y, wp.z)); - } - - ColorB backupcolor = GetColor(); - - SetColor(TextBackColor); - SetDrawInFrontMode(true); - DrawQuad(textworldreign[3], textworldreign[2], textworldreign[1], textworldreign[0]); - SetColor(TextColor); - DrawTextLabel(pos, textScale, text); - SetDrawInFrontMode(false); - SetColor(backupcolor); - SetState(backupstate); -} - ////////////////////////////////////////////////////////////////////////// void DisplayContext::SetLineWidth(float width) { 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/Objects/SelectionGroup.cpp b/Code/Sandbox/Editor/Objects/SelectionGroup.cpp index 98e00645ee..a2c88c7302 100644 --- a/Code/Sandbox/Editor/Objects/SelectionGroup.cpp +++ b/Code/Sandbox/Editor/Objects/SelectionGroup.cpp @@ -342,7 +342,8 @@ void CSelectionGroup::Rotate(const Matrix34& rotateTM, int referenceCoordSys) if (referenceCoordSys == COORDS_USERDEFINED) { - Matrix34 userTM = GetIEditor()->GetViewManager()->GetGrid()->GetMatrix(); + Matrix34 userTM; + userTM.SetIdentity(); Matrix34 invUserTM = userTM.GetInvertedFast(); ToOrigin = invUserTM * ToOrigin; diff --git a/Code/Sandbox/Editor/PythonEditorFuncs.cpp b/Code/Sandbox/Editor/PythonEditorFuncs.cpp index 29cb8eb478..afd28f7070 100644 --- a/Code/Sandbox/Editor/PythonEditorFuncs.cpp +++ b/Code/Sandbox/Editor/PythonEditorFuncs.cpp @@ -31,7 +31,6 @@ #include "ViewManager.h" #include "StringDlg.h" #include "GenericSelectItemDialog.h" -#include "Util/Ruler.h" #include "Objects/BaseObject.h" #include "Commands/CommandManager.h" @@ -608,8 +607,9 @@ namespace } else { - float color[] = {r, g, b, a}; - gEnv->pRenderer->Draw2dLabel(x, y, size, color, false, pLabel); + // ToDo: Remove function or update to work with Atom? LYN-3672 + // float color[] = {r, g, b, a}; + // ???->Draw2dLabel(x, y, size, color, false, pLabel); } } diff --git a/Code/Sandbox/Editor/RenderViewport.cpp b/Code/Sandbox/Editor/RenderViewport.cpp index 49064b5bc5..f199590e4f 100644 --- a/Code/Sandbox/Editor/RenderViewport.cpp +++ b/Code/Sandbox/Editor/RenderViewport.cpp @@ -1993,28 +1993,27 @@ AzFramework::CameraState CRenderViewport::GetCameraState() bool CRenderViewport::GridSnappingEnabled() { - return GetViewManager()->GetGrid()->IsEnabled(); + return false; } float CRenderViewport::GridSize() { - const CGrid* grid = GetViewManager()->GetGrid(); - return grid->scale * grid->size; + return 0.0f; } bool CRenderViewport::ShowGrid() { - return gSettings.viewports.bShowGridGuide; + return false; } bool CRenderViewport::AngleSnappingEnabled() { - return GetViewManager()->GetGrid()->IsAngleSnapEnabled(); + return false; } float CRenderViewport::AngleStep() { - return GetViewManager()->GetGrid()->GetAngleSnap(); + return 0.0f; } AZ::Vector3 CRenderViewport::PickTerrain(const AzFramework::ScreenPoint& point) @@ -3890,94 +3889,13 @@ void CRenderViewport::ActivateWindowAndSetFocus() ////////////////////////////////////////////////////////////////////////// void CRenderViewport::RenderConstructionPlane() { - DisplayContext& dc = m_displayContext; - - int prevState = dc.GetState(); - dc.DepthWriteOff(); - // Draw Construction plane. - - CGrid* pGrid = GetViewManager()->GetGrid(); - - RefCoordSys coordSys = COORDS_WORLD; - - Vec3 p = m_constructionMatrix[coordSys].GetTranslation(); - Vec3 n = m_constructionPlane.n; - - Vec3 u = Vec3(1, 0, 0); - Vec3 v = Vec3(0, 1, 0); - - - if (gSettings.snap.bGridUserDefined) - { - Ang3 angles = Ang3(pGrid->rotationAngles.x * gf_PI / 180.0, pGrid->rotationAngles.y * gf_PI / 180.0, pGrid->rotationAngles.z * gf_PI / 180.0); - Matrix34 tm = Matrix33::CreateRotationXYZ(angles); - - u = tm * u; - v = tm * v; - } - - float step = pGrid->scale * pGrid->size; - float size = gSettings.snap.constructPlaneSize; - - dc.SetColor(0, 0, 1, 0.1f); - - float s = size; - - dc.DrawQuad(p - u * s - v * s, p + u * s - v * s, p + u * s + v * s, p - u * s + v * s); - - int nSteps = int(size / step); - int i; - // Draw X lines. - dc.SetColor(1, 0, 0.2f, 0.3f); - - for (i = -nSteps; i <= nSteps; i++) - { - dc.DrawLine(p - u * size + v * (step * i), p + u * size + v * (step * i)); - } - // Draw Y lines. - dc.SetColor(0.2f, 1.0f, 0, 0.3f); - for (i = -nSteps; i <= nSteps; i++) - { - dc.DrawLine(p - v * size + u * (step * i), p + v * size + u * (step * i)); - } - - // Draw origin lines. - - dc.SetLineWidth(2); - - //X - dc.SetColor(1, 0, 0); - dc.DrawLine(p - u * s, p + u * s); - - //Y - dc.SetColor(0, 1, 0); - dc.DrawLine(p - v * s, p + v * s); - - //Z - dc.SetColor(0, 0, 1); - dc.DrawLine(p - n * s, p + n * s); - - dc.SetLineWidth(0); - - dc.SetState(prevState); + // noop } ////////////////////////////////////////////////////////////////////////// void CRenderViewport::RenderSnappingGrid() { - // First, Check whether we should draw the grid or not. - CGrid* pGrid = GetViewManager()->GetGrid(); - if (pGrid->IsEnabled() == false && pGrid->IsAngleSnapEnabled() == false) - { - return; - } - - DisplayContext& dc = m_displayContext; - - int prevState = dc.GetState(); - dc.DepthWriteOff(); - - dc.SetState(prevState); + // noop } ////////////////////////////////////////////////////////////////////////// diff --git a/Code/Sandbox/Editor/Resource.h b/Code/Sandbox/Editor/Resource.h index ea8ec828cf..31fc9909f1 100644 --- a/Code/Sandbox/Editor/Resource.h +++ b/Code/Sandbox/Editor/Resource.h @@ -79,7 +79,6 @@ #define ID_EDIT_HIDE 32898 #define ID_EDIT_UNHIDEALL 32899 #define ID_RELOAD_TERRAIN 32902 -#define ID_VIEW_GRIDSETTINGS 32904 #define ID_VIEW_CONFIGURELAYOUT 32906 #define ID_TOOLS_LOGMEMORYUSAGE 32908 #define ID_TERRAIN_EXPORTBLOCK 32909 @@ -99,7 +98,6 @@ #define ID_FILE_SAVELEVELRESOURCES 32942 #define ID_VALIDATELEVEL 32943 #define ID_TERRAIN_RESIZE 32944 -#define ID_RELOAD_TEXTURES 32952 #define ID_TERRAIN_COLLISION 32960 #define ID_TOOL_FIRST 32972 #define ID_EDIT_UNFREEZE 32973 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/Settings.h b/Code/Sandbox/Editor/Settings.h index 93e61bc1ed..b4609555df 100644 --- a/Code/Sandbox/Editor/Settings.h +++ b/Code/Sandbox/Editor/Settings.h @@ -40,8 +40,6 @@ #include -class CGrid; - struct SGizmoSettings { float axisGizmoSize; @@ -393,9 +391,6 @@ AZ_POP_DISABLE_DLL_EXPORT_BASECLASS_WARNING //! Keeps the editor active even if no focus is set int keepEditorActive; - //! Pointer to currently used grid. - CGrid* pGrid; - SGizmoSettings gizmo; // Settings of the snapping. 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/ShaderCache.cpp b/Code/Sandbox/Editor/ShaderCache.cpp deleted file mode 100644 index 3beeb9a7c4..0000000000 --- a/Code/Sandbox/Editor/ShaderCache.cpp +++ /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. - -#include "EditorDefs.h" - -#include "ShaderCache.h" - -// Editor -#include "GameEngine.h" - - -////////////////////////////////////////////////////////////////////////// -bool CLevelShaderCache::Reload() -{ - return Load(m_filename.toUtf8().data()); -} - -////////////////////////////////////////////////////////////////////////// -bool CLevelShaderCache::Load(const char* filename) -{ - FILE* f = nullptr; - azfopen(&f, filename, "rt"); - if (!f) - { - return false; - } - - int nNumLines = 0; - m_entries.clear(); - m_filename = filename; - char str[65535]; - while (fgets(str, sizeof(str), f) != NULL) - { - if (str[0] == '<') - { - m_entries.insert(str); - nNumLines++; - } - } - fclose(f); - if (nNumLines == m_entries.size()) - { - m_bModified = false; - } - else - { - m_bModified = true; - } - return true; -} - -////////////////////////////////////////////////////////////////////////// -bool CLevelShaderCache::LoadBuffer(const QString& textBuffer, bool bClearOld) -{ - const char* separators = "\r\n,"; - - int nNumLines = 0; - if (bClearOld) - { - m_entries.clear(); - } - m_filename = ""; - - for (auto resToken : textBuffer.split(QRegularExpression(QStringLiteral("[%1]").arg(separators)), Qt::SkipEmptyParts)) - { - if (!resToken.isEmpty() && resToken[0] == '<') - { - m_entries.insert(resToken); - nNumLines++; - } - } - if (nNumLines == m_entries.size() && !bClearOld) - { - m_bModified = false; - } - else - { - m_bModified = true; - } - - int numShaders = m_entries.size(); - CLogFile::FormatLine("%d shader combination loaded for level %s", numShaders, GetIEditor()->GetGameEngine()->GetLevelPath().toUtf8().data()); - - return true; -} - -////////////////////////////////////////////////////////////////////////// -bool CLevelShaderCache::Save() -{ - if (m_filename.isEmpty()) - { - return false; - } - - Update(); - - FILE* f = nullptr; - azfopen(&f, m_filename.toUtf8().data(), "wt"); - if (f) - { - for (Entries::iterator it = m_entries.begin(); it != m_entries.end(); ++it) - { - fputs(it->toLatin1().data(), f); - } - fclose(f); - } - m_bModified = false; - return true; -} - -////////////////////////////////////////////////////////////////////////// -bool CLevelShaderCache::SaveBuffer(QString& textBuffer) -{ - Update(); - - textBuffer.reserve(m_entries.size() * 1024); - for (Entries::iterator it = m_entries.begin(); it != m_entries.end(); ++it) - { - textBuffer += (*it); - textBuffer += "\n"; - } - m_bModified = false; - - return true; -} - -////////////////////////////////////////////////////////////////////////// -void CLevelShaderCache::Update() -{ - IRenderer* pRenderer = gEnv->pRenderer; - if (pRenderer) - { - QString buf; - char* str = NULL; - pRenderer->EF_Query(EFQ_GetShaderCombinations, str); - if (str) - { - buf = str; - pRenderer->EF_Query(EFQ_DeleteMemoryArrayPtr, str); - } - LoadBuffer(buf, true); - } -} - -////////////////////////////////////////////////////////////////////////// -void CLevelShaderCache::Clear() -{ - m_entries.clear(); - m_bModified = true; -} - -////////////////////////////////////////////////////////////////////////// -void CLevelShaderCache::ActivateShaders() -{ - bool bPreload = false; - ICVar* pSysPreload = gEnv->pConsole->GetCVar("sys_preload"); - if (pSysPreload && pSysPreload->GetIVal() != 0) - { - bPreload = true; - } - - if (bPreload) - { - QString textBuffer; - textBuffer.reserve(m_entries.size() * 1024); - for (Entries::iterator it = m_entries.begin(); it != m_entries.end(); ++it) - { - textBuffer += (*it); - textBuffer += "\n"; - } - gEnv->pRenderer->EF_Query(EFQ_SetShaderCombinations, textBuffer); - } -} diff --git a/Code/Sandbox/Editor/ShaderCache.h b/Code/Sandbox/Editor/ShaderCache.h deleted file mode 100644 index c75ab1554f..0000000000 --- a/Code/Sandbox/Editor/ShaderCache.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_EDITOR_SHADERCACHE_H -#define CRYINCLUDE_EDITOR_SHADERCACHE_H -#pragma once - -////////////////////////////////////////////////////////////////////////// -class CLevelShaderCache -{ -public: - CLevelShaderCache() - { - m_bModified = false; - } - bool Load(const char* filename); - bool LoadBuffer(const QString& textBuffer, bool bClearOld = true); - bool SaveBuffer(QString& textBuffer); - bool Save(); - bool Reload(); - void Clear(); - - void Update(); - void ActivateShaders(); - -private: - ////////////////////////////////////////////////////////////////////////// - bool m_bModified; - QString m_filename; - typedef std::set Entries; - Entries m_entries; -}; - - -#endif // CRYINCLUDE_EDITOR_SHADERCACHE_H diff --git a/Code/Sandbox/Editor/ShaderEnum.cpp b/Code/Sandbox/Editor/ShaderEnum.cpp deleted file mode 100644 index 65518303ce..0000000000 --- a/Code/Sandbox/Editor/ShaderEnum.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. - -// Description : Enumerate Installed Shaders. - - -#include "EditorDefs.h" - -#include "ShaderEnum.h" - -////////////////////////////////////////////////////////////////////////// -CShaderEnum::CShaderEnum() -{ - m_bEnumerated = false; -} - -CShaderEnum::~CShaderEnum() -{ -} - - -inline bool ShaderLess(const CShaderEnum::ShaderDesc& s1, const CShaderEnum::ShaderDesc& s2) -{ - return QString::compare(s1.name, s2.name, Qt::CaseInsensitive) < 0; -} -/* -struct StringLess { - bool operator()( const CString &s1,const CString &s2 ) - { - return _stricmp( s1,s2 ) < 0; - } -}; -*/ - -//! Enum shaders. -int CShaderEnum::EnumShaders() -{ - IRenderer* renderer = GetIEditor()->GetSystem()->GetIRenderer(); - if (!renderer) - { - return 0; - } - - m_bEnumerated = true; - - m_shaders.clear(); - m_shaders.reserve(100); - //! Enumerate Shaders. - int nNumShaders = 0; - string* files = renderer->EF_GetShaderNames(nNumShaders); - for (int i = 0; i < nNumShaders; i++) - { - ShaderDesc sd; - sd.name = files[i].c_str(); - sd.file = files[i].c_str(); - if (!sd.name.isEmpty()) - { - // Capitalize first character of the string. - sd.name[0] = sd.name[0].toUpper(); - } - m_shaders.push_back(sd); - } - - XmlNodeRef root = GetISystem()->GetXmlUtils()->LoadXmlFromFile("Materials/ShaderList.xml"); - if (root) - { - for (int i = 0; i < root->getChildCount(); ++i) - { - XmlNodeRef ChildNode = root->getChild(i); - const char* pTagName = ChildNode->getTag(); - if (!_stricmp(pTagName, "Shader")) - { - QString name; - if (ChildNode->getAttr("name", name) && !name.isEmpty()) - { - // make sure there is no duplication - bool isUnique = true; - for (std::vector::iterator pSD = m_shaders.begin(); pSD != m_shaders.end(); ++pSD) - { - if (!QString::compare((*pSD).file, name, Qt::CaseInsensitive)) - { - isUnique = false; - break; - } - } - if (isUnique) - { - ShaderDesc sd; - sd.name = name; - sd.file = name.toLower(); - m_shaders.push_back(sd); - } - } - } - } - } - - std::sort(m_shaders.begin(), m_shaders.end(), ShaderLess); - return m_shaders.size(); -} - -int CShaderEnum::GetShaderCount() const -{ - return m_shaders.size(); -} - -QString CShaderEnum::GetShader(int i) const -{ - return m_shaders[i].name; -} - -QString CShaderEnum::GetShaderFile(int i) const -{ - return m_shaders[i].file; -} diff --git a/Code/Sandbox/Editor/ShaderEnum.h b/Code/Sandbox/Editor/ShaderEnum.h deleted file mode 100644 index ccc86bd089..0000000000 --- a/Code/Sandbox/Editor/ShaderEnum.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. - -// Description : Enumerate Installed Shaders. - - -#ifndef CRYINCLUDE_EDITOR_SHADERENUM_H -#define CRYINCLUDE_EDITOR_SHADERENUM_H - -#pragma once - -/*! - * CShaderEnum class enumerates shaders installed on system. - * It scans all effector files, and gather from them all defined effectors. - */ -class CShaderEnum -{ -public: - struct ShaderDesc - { - QString name; - QString file; - }; - - CShaderEnum(); - virtual ~CShaderEnum(); - - //! Enumerate shaders installed on system. - //! @return Number of enumerated shaders. - virtual int EnumShaders(); - - //! Get number of shaders in system. - //! @return Number of installed shaders. - virtual int GetShaderCount() const; - - //! Get name of shader by index. - //! index must be between 0 and number returned by EnumShaders. - //! @return Name of shader. - virtual QString GetShader(int i) const; - virtual QString GetShaderFile(int i) const; - -private: - bool m_bEnumerated; - - //! Array of shader names. - std::vector m_shaders; -}; - - -#endif // CRYINCLUDE_EDITOR_SHADERENUM_H diff --git a/Code/Sandbox/Editor/ShadersDialog.cpp b/Code/Sandbox/Editor/ShadersDialog.cpp deleted file mode 100644 index 6a09d00232..0000000000 --- a/Code/Sandbox/Editor/ShadersDialog.cpp +++ /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. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#include "EditorDefs.h" - -#include "ShadersDialog.h" - -// Qt -#include - -// Editor -#include "ShaderEnum.h" - - -AZ_PUSH_DISABLE_DLL_EXPORT_MEMBER_WARNING -#include -AZ_POP_DISABLE_DLL_EXPORT_MEMBER_WARNING - -///////////////////////////////////////////////////////////////////////////// -// CShadersDialog dialog - - -CShadersDialog::CShadersDialog(const QString& selection, QWidget* pParent /*=NULL*/) - : QDialog(pParent) - , m_shadersModel(new QStringListModel(this)) - , ui(new Ui::CShadersDialog) - , m_selection(selection) -{ - ui->setupUi(this); - ui->m_shaders->setModel(m_shadersModel); - OnInitDialog(); - - connect(ui->m_shaders->selectionModel(), &QItemSelectionModel::selectionChanged, this, &CShadersDialog::OnSelchangeShaders); - connect(ui->m_shaders, &QListView::doubleClicked, this, &CShadersDialog::OnDblclkShaders); - connect(ui->m_shaderText, &QTextEdit::textChanged, this, &CShadersDialog::OnEnChangeText); - connect(ui->buttonBox, &QDialogButtonBox::accepted, this, &QDialog::accept); - connect(ui->buttonBox, &QDialogButtonBox::rejected, this, &QDialog::reject); - connect(ui->m_saveButton, &QPushButton::clicked, this, &CShadersDialog::OnBnClickedSave); - connect(ui->m_editButton, &QPushButton::clicked, this, &CShadersDialog::OnBnClickedEdit); -} - - -CShadersDialog::~CShadersDialog() -{ -} - - -void CShadersDialog::OnSelchangeShaders() -{ - // When shader changes. - // Edit shader file. - auto index = ui->m_shaders->currentIndex(); - if (index.isValid()) - { - QString file = GetIEditor()->GetShaderEnum()->GetShaderFile(index.row()); - file.replace('/', '\\'); - ui->m_shaderText->LoadFile(file); - // Just loaded file.. Not savable. - ui->m_saveButton->setEnabled(false); - - QString shaderName = QStringLiteral("'%1'").arg(index.data().toString()); - - if (ui->m_shaderText->find(shaderName)) - { - auto cursor = ui->m_shaderText->textCursor(); - cursor.movePosition(QTextCursor::Right, QTextCursor::KeepAnchor, shaderName.size()); - } - - m_selection = index.data().toString(); - } -} - -void CShadersDialog::OnInitDialog() -{ - QWaitCursor wait; - - // Fill with shaders. - CShaderEnum* shaderEnum = GetIEditor()->GetShaderEnum(); - int numShaders = shaderEnum->EnumShaders(); - - QStringList shaders; - for (int i = 0; i < numShaders; i++) - { - shaders.append(shaderEnum->GetShader(i)); - } - m_shadersModel->setStringList(shaders); - - /* - if (numShaders > 0) - { - int i = m_shaders.FindString(m_sel); - if (i != LB_ERR) - m_shaders.SetCurSel( i ); - } - */ -} - -void CShadersDialog::OnDblclkShaders() -{ - // Same as IDOK. - accept(); -} - -void CShadersDialog::OnBnClickedEdit() -{ - // Edit shader file. - auto index = ui->m_shaders->currentIndex(); - if (index.isValid()) - { - CShaderEnum* shaderEnum = GetIEditor()->GetShaderEnum(); - QString file = shaderEnum->GetShaderFile(index.row()); - CFileUtil::EditTextFile(file.toUtf8().data(), IFileUtil::FILE_TYPE_SHADER); - } -} - -////////////////////////////////////////////////////////////////////////// -void CShadersDialog::OnBnClickedSave() -{ - if (ui->m_shaderText->IsModified()) - { - ui->m_shaderText->SaveFile(ui->m_shaderText->GetFilename()); - if (ui->m_shaderText->IsModified()) - { - ui->m_saveButton->setEnabled(true); - } - else - { - ui->m_saveButton->setEnabled(false); - } - } -} - -////////////////////////////////////////////////////////////////////////// -void CShadersDialog::OnEnChangeText() -{ - // File can be saved. - ui->m_saveButton->setEnabled(true); -} - -#include diff --git a/Code/Sandbox/Editor/ShadersDialog.h b/Code/Sandbox/Editor/ShadersDialog.h deleted file mode 100644 index bafad56a8f..0000000000 --- a/Code/Sandbox/Editor/ShadersDialog.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_EDITOR_SHADERSDIALOG_H -#define CRYINCLUDE_EDITOR_SHADERSDIALOG_H - -#pragma once -// ShadersDialog.h : header file -// - -#if !defined(Q_MOC_RUN) -#include -#endif - -class QStringListModel; - -namespace Ui { - class CShadersDialog; -} - -///////////////////////////////////////////////////////////////////////////// -// CShadersDialog dialog - -class CShadersDialog - : public QDialog -{ - Q_OBJECT - - // Construction -public: - CShadersDialog(const QString& selection, QWidget* pParent = nullptr); // standard constructor - ~CShadersDialog(); - - QString m_selection; - - QString GetSelection() { return m_selection; }; - -protected: - void OnSelchangeShaders(); - virtual void OnInitDialog(); - void OnDblclkShaders(); - -public: - void OnBnClickedEdit(); - void OnBnClickedSave(); - void OnEnChangeText(); - - QStringListModel* m_shadersModel; - QScopedPointer ui; -}; - -#endif // CRYINCLUDE_EDITOR_SHADERSDIALOG_H diff --git a/Code/Sandbox/Editor/ShadersDialog.ui b/Code/Sandbox/Editor/ShadersDialog.ui deleted file mode 100644 index c103cd0dec..0000000000 --- a/Code/Sandbox/Editor/ShadersDialog.ui +++ /dev/null @@ -1,118 +0,0 @@ - - - CShadersDialog - - - - 0 - 0 - 615 - 458 - - - - Select Shader - - - - - - - - - - Select Shader - - - Qt::AlignLeading|Qt::AlignLeft|Qt::AlignTop - - - - - - - - - - - - - - Shader Script - - - Qt::AlignLeading|Qt::AlignLeft|Qt::AlignTop - - - - - - - - - - - - - - - - - - QFrame::HLine - - - QFrame::Sunken - - - - - - - - - QDialogButtonBox::Cancel|QDialogButtonBox::Ok - - - - - - - Qt::Horizontal - - - - 40 - 20 - - - - - - - - Save - - - - - - - External Edit - - - - - - - - - - CTextEditorCtrl - QTextEdit -
Controls/TextEditorCtrl.h
-
-
- - -
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; } diff --git a/Code/Sandbox/Editor/TopRendererWnd.cpp b/Code/Sandbox/Editor/TopRendererWnd.cpp index bc979902e7..78fce1bc24 100644 --- a/Code/Sandbox/Editor/TopRendererWnd.cpp +++ b/Code/Sandbox/Editor/TopRendererWnd.cpp @@ -150,7 +150,7 @@ void QTopRendererWnd::UpdateContent(int flags) } ////////////////////////////////////////////////////////////////////////// -void QTopRendererWnd::Draw(DisplayContext& dc) +void QTopRendererWnd::Draw([[maybe_unused]] DisplayContext& dc) { FUNCTION_PROFILER(GetIEditor()->GetSystem(), PROFILE_EDITOR); @@ -165,7 +165,8 @@ void QTopRendererWnd::Draw(DisplayContext& dc) //////////////////////////////////////////////////////////////////////// // Render the 2D map //////////////////////////////////////////////////////////////////////// - if (!m_terrainTextureId) + // ToDo: Remove TopRendererWnd or update to work with Atom: LYN-3671 + /*if (!m_terrainTextureId) { //GL_BGRA_EXT if (m_terrainTexture.IsValid()) @@ -238,7 +239,7 @@ void QTopRendererWnd::Draw(DisplayContext& dc) dc.DepthTestOn(); - Q2DViewport::Draw(dc); + Q2DViewport::Draw(dc);*/ } ////////////////////////////////////////////////////////////////////////// diff --git a/Code/Sandbox/Editor/TrackView/SequenceBatchRenderDialog.cpp b/Code/Sandbox/Editor/TrackView/SequenceBatchRenderDialog.cpp index 73f8ce7344..69322c481c 100644 --- a/Code/Sandbox/Editor/TrackView/SequenceBatchRenderDialog.cpp +++ b/Code/Sandbox/Editor/TrackView/SequenceBatchRenderDialog.cpp @@ -643,7 +643,7 @@ void CSequenceBatchRenderDialog::OnResolutionSelected() CCustomResolutionDlg resDlg(defaultW, defaultH, this); if (resDlg.exec() == QDialog::Accepted) { - const int maxRes = GetIEditor()->GetRenderer()->GetMaxSquareRasterDimension(); + const int maxRes = 8192; m_customResW = min(resDlg.GetWidth(), maxRes); m_customResH = min(resDlg.GetHeight(), maxRes); const QString resText = QString(customResFormat).arg(m_customResW).arg(m_customResH); 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/Util/ArcBall.cpp b/Code/Sandbox/Editor/Util/ArcBall.cpp deleted file mode 100644 index 25607e392b..0000000000 --- a/Code/Sandbox/Editor/Util/ArcBall.cpp +++ /dev/null @@ -1,769 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS 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 "ArcBall.h" - -bool CArcBall3D::ArcControl(const Matrix34& reference, const Ray& ray, uint32 mouseleft) -{ - RotControl <<= 1; - - if (mouseleft) - { - RotControl |= 1; - } - - Quat WObjectRotation = Quat(reference * Matrix34(ObjectRotation)); - Matrix34 WMat = reference * Matrix34(Matrix33(DragRotation * ObjectRotation), sphere.center); - Sphere WSphere(WMat.GetTranslation(), sphere.radius); - - Mouse_CutFlag = 0; - Vec3 Mouse_CutOn3DSphere(0, 0, 0); - Mouse_CutOnUnitSphere = Vec3(ZERO); - Mouse_CutFlag = Intersect::Ray_SphereFirst(ray, WSphere, Mouse_CutOn3DSphere); - - if (Mouse_CutFlag) - { - Mouse_CutOnUnitSphere = WObjectRotation.GetInverted() * (Mouse_CutOn3DSphere - WSphere.center).GetNormalized(); - } - - if (RotControl & 3) - { - if (Mouse_CutFlag) - { - if ((RotControl & 3) == 0x01) - { - Mouse_CutFlagStart = 1; - LineStart3D = Mouse_CutOnUnitSphere; - AxisSnap = 0; - - Matrix33 bym33; - - //get the distance to the axis - f32 xdist = fabsf(Mouse_CutOnUnitSphere.x); - f32 ydist = fabsf(Mouse_CutOnUnitSphere.y); - f32 zdist = fabsf(Mouse_CutOnUnitSphere.z); - - //if to close to an axis-crossing, disable axis choosing - if ((xdist < CrossDist) && (zdist < CrossDist)) - { - xdist = 1.0f; - ydist = 1.0f; - zdist = 1.0f; - } - if ((xdist < CrossDist) && (ydist < CrossDist)) - { - xdist = 1.0f; - ydist = 1.0f; - zdist = 1.0f; - } - if ((ydist < CrossDist) && (zdist < CrossDist)) - { - xdist = 1.0f; - ydist = 1.0f; - zdist = 1.0f; - } - - //check snap with YZ-plane - if (xdist < AxisDist) - { - bym33.SetIdentity(); - - if ((LineStart3D.x) || (LineStart3D.z)) - { - Vec3 n = Vec3(LineStart3D.x, 0, LineStart3D.z).GetNormalized(); - bym33.SetRotationY(acos_tpl(fabsf(n.z))); - } - - Vec3 SnapLineStart3D = bym33 * Vec3(fabsf(LineStart3D.x), LineStart3D.y, -fabsf(LineStart3D.z)); - - if (LineStart3D.z > 0.0f) - { - SnapLineStart3D.z = -SnapLineStart3D.z; - } - - LineStart3D = SnapLineStart3D; - AxisSnap = 1; - } - - //check snap with XZ-plane - if (ydist < AxisDist) - { - bym33.SetIdentity(); - - if ((LineStart3D.y) || (LineStart3D.z)) - { - Vec3 bn_xz = Vec3(0, LineStart3D.y, LineStart3D.z).GetNormalized(); - bym33.SetRotationX(-acos_tpl(fabsf(bn_xz.z))); - } - - Vec3 SnapLineStart3D = bym33 * Vec3((LineStart3D.x), fabsf(LineStart3D.y), -fabsf(LineStart3D.z)); - - if (LineStart3D.z > 0.0f) - { - SnapLineStart3D.z = -SnapLineStart3D.z; - } - - LineStart3D = SnapLineStart3D; - AxisSnap = 2; - } - - //check snap with XY-plane - if (zdist < AxisDist) - { - bym33.SetIdentity(); - - if ((LineStart3D.x) || (LineStart3D.z)) - { - Vec3 bn_xz = Vec3(LineStart3D.x, 0, LineStart3D.z).GetNormalized(); - bym33.SetRotationY(-acos_tpl(fabsf(bn_xz.x))); - } - - Vec3 SnapLineStart3D = bym33 * Vec3(fabsf(LineStart3D.x), LineStart3D.y, -fabsf(LineStart3D.z)); - - if (LineStart3D.x < 0.0f) - { - SnapLineStart3D.x = -SnapLineStart3D.x; - } - - LineStart3D = SnapLineStart3D; - AxisSnap = 3; - } - } - - if ((RotControl & 3) == 0x03) - { - ArcRotation(); - } - - if ((RotControl & 3) == 0x02) - { - ObjectRotation = (DragRotation * ObjectRotation).GetNormalized(); - DragRotation.SetIdentity(); - Mouse_CutFlagStart = 0; - LineStart3D = Vec3(0, -1, 0); - AxisSnap = 0; - - return true; - } - } - else - { - Vec3 ClostestPointOnLine; - IntersectSphereLineSegment(WSphere, ray.origin, ray.origin + ray.direction * 1000.0f, ClostestPointOnLine); - - Mouse_CutOn3DSphere = ((ClostestPointOnLine - WSphere.center).GetNormalized() * WSphere.radius) + WSphere.center; - Mouse_CutOnUnitSphere = WObjectRotation.GetInverted() * (Mouse_CutOn3DSphere - WSphere.center).GetNormalized(); - - if ((RotControl & 3) == 0x01) - { - LineStart3D = Mouse_CutOnUnitSphere; - Mouse_CutFlagStart = 0; - AxisSnap = 0; - } - - if ((RotControl & 3) == 0x03) - { - ArcRotation(); - } - - if ((RotControl & 3) == 0x02) - { - ObjectRotation = (DragRotation * ObjectRotation).GetNormalized(); - DragRotation.SetIdentity(); - Mouse_CutFlagStart = 0; - LineStart3D = Vec3(0, -1, 0); - AxisSnap = 0; - - return true; - } - } - } - - return false; -} - -void CArcBall3D::ArcRotation() -{ - Vec3 rv; - f32 gradius = 0; - f32 distance_YZ = 0; - f32 bias = 0; - f32 cosine = 0; - Vec3 XYVector; - - DragRotation.SetIdentity(); - - //first we calculate an ordinary drag-quaternion - cosine = (LineStart3D | Mouse_CutOnUnitSphere); - - if (fabsf(cosine) < 0.99999f) - { - DragRotation.SetRotationAA(acos_tpl(cosine), (LineStart3D % Mouse_CutOnUnitSphere).GetNormalized()); - } - - if (AxisSnap == 1) - { - //m_ButtonArcRotate an UpVector with our drag-quaternion - rv = (DragRotation) * Vec3(0, -1, 0); - DragRotation.SetIdentity(); - - //project rotated UpVector into XY_Plane (this is a simple y_axis rotation) - Matrix33 ym33; - ym33.SetIdentity(); - - if ((rv.x) || (rv.z)) - { - Vec3 n_xz = Vec3(rv.x, 0, rv.z).GetNormalized(); - ym33.SetRotationY(-acos_tpl(fabsf(n_xz.z))); - } - - XYVector = ym33 * Vec3(-fabsf(rv.x), rv.y, -fabsf(rv.z)); - - //find the rotation direction around z-axis - if (rv.z > 0) - { - XYVector.z = -XYVector.z; - } - - //calculate the xy-constrained quaternion - cosine = (Vec3(0, -1, 0) | XYVector); - - if (fabsf(cosine) < 0.99999f) - { - gradius = Vec3(rv.x, 0, rv.z).GetLength(); - distance_YZ = fabsf(rv.z); - bias = distance_YZ / gradius; - DragRotation.SetRotationAA(acos_tpl(cosine) * bias, (Vec3(0, -1, 0) % XYVector).GetNormalized()); - } - } - - if (AxisSnap == 2) - { - //m_ButtonArcRotate an UpVector with our DRAG-QUATERNION - rv = DragRotation * Vec3(-1, 0, 0); - DragRotation.SetIdentity(); - - //project rotated UpVector into XY_Plane (this is a simple x_axis rotation) - Matrix33 ym33; - ym33.SetIdentity(); - - if ((rv.y) || (rv.z)) - { - Vec3 n_xz = Vec3(0, rv.y, rv.z).GetNormalized(); - ym33.SetRotationX(-acos_tpl(fabsf(n_xz.z))); - } - - XYVector = ym33 * Vec3((rv.x), fabsf(rv.y), -fabsf(rv.z)); - - //find the rotation direction around y-axis - if (rv.z > 0) - { - XYVector.z = -XYVector.z; - } - - //calculate the xz-constrained quaternion - cosine = (Vec3(-1, 0, 0) | XYVector); - - if (fabsf(cosine) < 0.99999f) - { - gradius = Vec3(0, rv.y, rv.z).GetLength(); - distance_YZ = fabsf(rv.z); - bias = distance_YZ / gradius; - DragRotation.SetRotationAA(acos_tpl(cosine) * bias, (Vec3(-1, 0, 0) % XYVector).GetNormalized()); - } - } - - if (AxisSnap == 3) - { - //m_ButtonArcRotate an UpVector with our DRAG-QUATERNION - rv = DragRotation * Vec3(0, -1, 0); - DragRotation.SetIdentity(); - - //project rotated UpVector into XY_Plane (this is a simple y_axis rotation) - Matrix33 ym33; - - ym33.SetIdentity(); - - if ((rv.x) || (rv.z)) - { - Vec3 n_xz = Vec3(rv.x, 0, rv.z).GetNormalized(); - ym33.SetRotationY(-acos_tpl(fabsf(n_xz.x))); - } - - XYVector = ym33 * Vec3(fabsf(rv.x), rv.y, -fabsf(rv.z)); - - //find the rotation direction around z-axis - if (rv.x < 0) - { - XYVector.x = -XYVector.x; - } - - //calculate the xy-constrained quaternion - cosine = (Vec3(0, -1, 0) | XYVector); - - if (fabsf(cosine) < 0.99999f) - { - gradius = Vec3(rv.x, 0, rv.z).GetLength(); - distance_YZ = fabsf(rv.x); - bias = distance_YZ / gradius; - DragRotation.SetRotationAA(acos_tpl(cosine) * bias, (Vec3(0, -1, 0) % XYVector).GetNormalized()); - } - } - - //BINGO!!!! the final drag quaternion - DragRotation = ObjectRotation * DragRotation * ObjectRotation.GetInverted(); -} - -uint32 CArcBall3D::IntersectSphereLineSegment(const Sphere& sphere, const Vec3& LineStart, const Vec3& LineEnd, Vec3& I) -{ - //this is the code to produce a real z-rotation! - Vec3 LineDir = (LineEnd - LineStart).GetNormalized(); - Vec3 ShereCenterDir = (sphere.center - LineStart).GetNormalized(); - f32 LengthToSphereCenter = (sphere.center - LineStart).GetLength(); - - f32 cosine = (ShereCenterDir | LineDir); - - //this vector is perpendicular to the vector "ShereCenterDir" - Vec3 PerpVector = LengthToSphereCenter / cosine * LineDir + LineStart; - Vec3 PerpVectorOnSphere = ((PerpVector - sphere.center).GetNormalized() * sphere.radius) + sphere.center; - I = PerpVectorOnSphere; - - { - //find closest point on Lineseg - Vec3 LineDir2 = (LineEnd - LineStart).GetNormalized(); - f32 proj = LineDir2 | (sphere.center - LineStart); - I = LineDir2 * proj + LineStart; - } - - return 0; -} - -void CArcBall3D::DrawSphere(const Matrix34& reference, const CCamera& cam, IRenderAuxGeom* pRenderer) -{ - f32 thicknessX = 1.0f; - f32 thicknessY = 1.0f; - f32 thicknessZ = 1.0f; - - uint32 start; - Vec3 Vertices3D[64 * 32]; - Vec3 sVertices3D[64 * 32]; - Vec3 tVertices3D[64 * 32]; - uint32 c; - - Matrix34 WMat = reference * Matrix34(Matrix33(DragRotation * ObjectRotation), sphere.center); - Quat WObjectRotation = Quat(reference * Matrix34(ObjectRotation)); - Quat WRotation = Quat(reference * Matrix34(DragRotation * ObjectRotation)); - Sphere WSphere(WMat.GetTranslation(), sphere.radius); - - SAuxGeomRenderFlags renderFlags(e_Def3DPublicRenderflags); - renderFlags.SetDepthWriteFlag(e_DepthWriteOff); - renderFlags.SetFillMode(e_FillModeSolid); - - //------------------------------------------------------------------------------------------------------ - - uint32 s = 0; - uint32 t = 0; - Vec3 CamPos = cam.GetPosition(); - - renderFlags.SetAlphaBlendMode(e_AlphaAdditive); - pRenderer->SetRenderFlags(renderFlags); - pRenderer->DrawSphere(WSphere.center, WSphere.radius, RGBA8(0x3f, 0x3f, 0x3f, 0x00)); - - ColorB col; - f32 xdist = fabsf(Mouse_CutOnUnitSphere.x); - f32 ydist = fabsf(Mouse_CutOnUnitSphere.y); - f32 zdist = fabsf(Mouse_CutOnUnitSphere.z); - - if ((xdist < CrossDist) && (zdist < CrossDist)) - { - xdist = 1.0f; - ydist = 1.0f; - zdist = 1.0f; - } - if ((xdist < CrossDist) && (ydist < CrossDist)) - { - xdist = 1.0f; - ydist = 1.0f; - zdist = 1.0f; - } - if ((ydist < CrossDist) && (zdist < CrossDist)) - { - xdist = 1.0f; - ydist = 1.0f; - zdist = 1.0f; - } - - //---------------------------------------------------------------------------------- - // draw circle around X-axis - //---------------------------------------------------------------------------------- - thicknessX = 1.0f; - - if (AxisSnap == 0) - { - if (Mouse_CutFlag) - { - if (xdist < AxisDist) - { - thicknessX = 5.0f; - } - } - } - else if (AxisSnap == 1) - { - thicknessX = 5.0f; - } - - c = 0; - - for (f32 cz = 0; cz < (gf_PI * 2); cz = cz + (2 * gf_PI / 256.0f), ++c) - { - Vertices3D[c] = WMat * (Vec3(0, -cosf(cz), sinf(cz)) * WSphere.radius); - } - - assert(c == 0x100); - - for (start = 0; start < c; ++start) - { - Vec3 p0 = Vertices3D[(start + 0) & 0xff]; - f32 dot0 = (p0 - CamPos) | (p0 - WSphere.center); - Vec3 p1 = Vertices3D[(start + 1) & 0xff]; - f32 dot1 = (p1 - CamPos) | (p1 - WSphere.center); - - if ((dot0 < 0) && !(dot1 < 0)) - { - break; - } - } - - s = 0; - t = 0; - start = (start + 1) & 0xff; - - for (uint32 i = 0; i < c; ++i) - { - Vec3 p = Vertices3D[start]; - f32 dot = (p - CamPos) | (p - WSphere.center); - - if (dot < 0) - { - sVertices3D[s] = p; - s++; - } - else - { - tVertices3D[t] = p; - t++; - } - - start = (start + 1) & 0xff; - } - - renderFlags.SetAlphaBlendMode(e_AlphaNone); - pRenderer->SetRenderFlags(renderFlags); - - if (s > 2) - { - pRenderer->DrawPolyline(sVertices3D, s, 0, RGBA8(0xff, 0x12, 0x12, 0x00), thicknessX); - } - - renderFlags.SetAlphaBlendMode(e_AlphaAdditive); - pRenderer->SetRenderFlags(renderFlags); - - if (t > 2) - { - pRenderer->DrawPolyline(tVertices3D, t, 0, RGBA8(0x1f, 0x07, 0x07, 0x00), thicknessX); - } - - //---------------------------------------------------------------------------------- - // draw circle around Y-axis - //---------------------------------------------------------------------------------- - thicknessY = 1.0f; - - if (AxisSnap == 0) - { - if (Mouse_CutFlag) - { - if (ydist < AxisDist) - { - thicknessY = 5.0f; - } - } - } - else if (AxisSnap == 2) - { - thicknessY = 5.0f; - } - - c = 0; - - for (f32 cz = 0; cz < (gf_PI * 2); cz = cz + (2 * gf_PI / 256.0f), ++c) - { - Vertices3D[c] = WMat * (Vec3(-cosf(cz), 0, sinf(cz)) * WSphere.radius); - } - - assert(c == 0x100); - - for (start = 0; start < c; ++start) - { - Vec3 p0 = Vertices3D[(start + 0) & 0xff]; - f32 dot0 = (p0 - CamPos) | (p0 - WSphere.center); - Vec3 p1 = Vertices3D[(start + 1) & 0xff]; - f32 dot1 = (p1 - CamPos) | (p1 - WSphere.center); - - if ((dot0 < 0) && !(dot1 < 0)) - { - break; - } - } - - s = 0; - t = 0; - start = (start + 1) & 0xff; - - for (uint32 i = 0; i < c; ++i) - { - Vec3 p = Vertices3D[start]; - f32 dot = (p - CamPos) | (p - WSphere.center); - if (dot < 0) - { - sVertices3D[s] = p; - s++; - } - else - { - tVertices3D[t] = p; - t++; - } - - start = (start + 1) & 0xff; - } - - renderFlags.SetAlphaBlendMode(e_AlphaNone); - pRenderer->SetRenderFlags(renderFlags); - - if (s > 2) - { - pRenderer->DrawPolyline(sVertices3D, s, 0, RGBA8(0x12, 0xff, 0x12, 0x00), thicknessY); - } - - renderFlags.SetAlphaBlendMode(e_AlphaAdditive); - pRenderer->SetRenderFlags(renderFlags); - - if (t > 2) - { - pRenderer->DrawPolyline(tVertices3D, t, 0, RGBA8(0x07, 0x1f, 0x07, 0x00), thicknessY); - } - - //---------------------------------------------------------------------------------- - // draw circle around Z-axis - //---------------------------------------------------------------------------------- - thicknessZ = 1.0f; - - if (AxisSnap == 0) - { - if (Mouse_CutFlag) - { - if (zdist < AxisDist) - { - thicknessZ = 5.0f; - } - } - } - else if (AxisSnap == 3) - { - thicknessZ = 5.0f; - } - - c = 0; - for (f32 cz = 0; cz < (gf_PI * 2); cz = cz + (2 * gf_PI / 256.0f), ++c) - { - Vertices3D[c] = WMat * (Vec3(sinf(cz), -cosf(cz), 0) * WSphere.radius); - } - - assert(c == 0x100); - - for (start = 0; start < c; ++start) - { - Vec3 p0 = Vertices3D[(start + 0) & 0xff]; - f32 dot0 = (p0 - CamPos) | (p0 - WSphere.center); - Vec3 p1 = Vertices3D[(start + 1) & 0xff]; - f32 dot1 = (p1 - CamPos) | (p1 - WSphere.center); - - if ((dot0 < 0) && !(dot1 < 0)) - { - break; - } - } - - s = 0; - t = 0; - start = (start + 1) & 0xff; - - for (uint32 i = 0; i < c; ++i) - { - Vec3 p = Vertices3D[start]; - f32 dot = (p - CamPos) | (p - WSphere.center); - - if (dot < 0) - { - sVertices3D[s] = p; - s++; - } - else - { - tVertices3D[t] = p; - t++; - } - - start = (start + 1) & 0xff; - } - - renderFlags.SetAlphaBlendMode(e_AlphaNone); - pRenderer->SetRenderFlags(renderFlags); - - if (s > 2) - { - pRenderer->DrawPolyline(sVertices3D, s, 0, RGBA8(0x12, 0x12, 0xff, 0x00), thicknessZ); - } - - renderFlags.SetAlphaBlendMode(e_AlphaAdditive); - pRenderer->SetRenderFlags(renderFlags); - - if (t > 2) - { - pRenderer->DrawPolyline(tVertices3D, t, 0, RGBA8(0x07, 0x07, 0x1f, 0x00), thicknessZ); - } - - uint32 v; - - Vec3 VBuffer[1000]; - ColorB CBuffer[1000]; - - if ((RotControl & 3) == 3) - { - Vec3 Blue = WObjectRotation * LineStart3D; - Vec3 Red = WObjectRotation * Mouse_CutOnUnitSphere; - - VBuffer[0] = Vec3(0, 0, 0); - CBuffer[0] = RGBA8(0x00, 0x00, 0x00, 0x00); - - VBuffer[1] = Blue; - CBuffer[1] = RGBA8(0x00, 0x00, 0xff, 0x00); - - VBuffer[102] = Red; - CBuffer[102] = RGBA8(0xff, 0x00, 0x00, 0x00); - - for (v = 0; v < 100; ++v) - { - f32 t0 = (1.0f / 101.0f * v) + 1.0f / 101.0f; - - VBuffer[v + 2] = Vec3::CreateSlerp(Blue, Red, t0); - - f32 t1 = (1.0f / 101.0f * v); - - CBuffer[v + 2].b = uint8((1.0f - t1) * CBuffer[1].b + t1 * CBuffer[102].b); - CBuffer[v + 2].g = uint8((1.0f - t1) * CBuffer[1].g + t1 * CBuffer[102].g); - CBuffer[v + 2].r = uint8((1.0f - t1) * CBuffer[1].r + t1 * CBuffer[102].r); - } - - for (v = 0; v < 103; ++v) - { - VBuffer[v] = VBuffer[v] * WSphere.radius + WSphere.center; - } - - if (AxisSnap == 0) - { - SAuxGeomRenderFlags renderFlags2(e_Def3DPublicRenderflags); - - renderFlags2.SetFillMode(e_FillModeSolid); - renderFlags2.SetAlphaBlendMode(e_AlphaAdditive); - pRenderer->SetRenderFlags(renderFlags2); - - for (v = 0; v < 100; ++v) - { - pRenderer->DrawTriangle(VBuffer[0], CBuffer[0], VBuffer[v + 1], CBuffer[v + 1], VBuffer[v + 2], CBuffer[v + 2]); - pRenderer->DrawTriangle(VBuffer[0], CBuffer[0], VBuffer[v + 2], CBuffer[v + 2], VBuffer[v + 1], CBuffer[v + 1]); - } - } - } - - if (AxisSnap) - { - //project vector into the xy-plane - VBuffer[0] = Vec3(0, 0, 0); - CBuffer[0] = RGBA8(0x00, 0x00, 0x00, 0x00); - - VBuffer[1] = WObjectRotation * LineStart3D; - CBuffer[1] = RGBA8(0x12, 0x1f, 0x12, 0x00); - - VBuffer[102] = WRotation * LineStart3D; - CBuffer[102] = RGBA8(0x22, 0x7f, 0x22, 0x00); - - ColorB c0 = CBuffer[1]; - ColorB c1 = CBuffer[102]; - - for (v = 0; v < 100; ++v) - { - f32 t0 = (1.0f / 101.0f * v) + 1.0f / 101.0f; - - VBuffer[v + 2] = Vec3::CreateSlerp(VBuffer[1], VBuffer[102], t0); - - f32 t1 = (1.0f / 101.0f * v); - CBuffer[v + 2].r = uint8((1.0f - t1) * c0.r + t1 * c1.r); - CBuffer[v + 2].g = uint8((1.0f - t1) * c0.g + t1 * c1.g); - CBuffer[v + 2].b = uint8((1.0f - t1) * c0.b + t1 * c1.b); - } - - for (v = 0; v < 103; ++v) - { - VBuffer[v] = VBuffer[v] * WSphere.radius + WSphere.center; - } - - SAuxGeomRenderFlags renderFlags2(e_Def3DPublicRenderflags); - renderFlags2.SetFillMode(e_FillModeSolid); - renderFlags2.SetAlphaBlendMode(e_AlphaAdditive); - pRenderer->SetRenderFlags(renderFlags2); - - for (v = 0; v < 100; ++v) - { - pRenderer->DrawTriangle(VBuffer[0], CBuffer[0], VBuffer[v + 1], CBuffer[v + 1], VBuffer[v + 2], CBuffer[v + 2]); - pRenderer->DrawTriangle(VBuffer[0], CBuffer[0], VBuffer[v + 2], CBuffer[v + 2], VBuffer[v + 1], CBuffer[v + 1]); - } - } - - renderFlags = e_Def3DPublicRenderflags; - renderFlags.SetFillMode(e_FillModeSolid); - renderFlags.SetAlphaBlendMode(e_AlphaNone); - pRenderer->SetRenderFlags(renderFlags); - - #define CROSS (0.25f) - - Vec3 rmin = WMat * Vec3(0, 0.0f, 0.0f); - Vec3 rmax = WMat * Vec3(CROSS, 0.0f, 0.0f); - - pRenderer->DrawLine(rmin, RGBA8(0xff, 0x00, 0x00, 0x00), rmax, RGBA8(0xff, 0x7f, 0x7f, 0x00), thicknessX); - - Vec3 gmin = WMat * Vec3(0.0f, 0, 0.0f); - Vec3 gmax = WMat * Vec3(0.0f, CROSS, 0.0f); - - pRenderer->DrawLine(gmin, RGBA8(0x00, 0xff, 0x00, 0x00), gmax, RGBA8(0x7f, 0xff, 0x7f, 0x00), thicknessY); - - Vec3 bmin = WMat * Vec3(0.0f, 0.0f, 0); - Vec3 bmax = WMat * Vec3(0.0f, 0.0f, CROSS); - - pRenderer->DrawLine(bmin, RGBA8(0x00, 0x00, 0xff, 0x00), bmax, RGBA8(0x7f, 0x7f, 0xff, 0x00), thicknessZ); - renderFlags.SetDepthWriteFlag(e_DepthWriteOn); - pRenderer->SetRenderFlags(renderFlags); -} diff --git a/Code/Sandbox/Editor/Util/ArcBall.h b/Code/Sandbox/Editor/Util/ArcBall.h deleted file mode 100644 index 5adf02216c..0000000000 --- a/Code/Sandbox/Editor/Util/ArcBall.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_EDITOR_UTIL_ARCBALL_H -#define CRYINCLUDE_EDITOR_UTIL_ARCBALL_H -#pragma once -#include -#include - -#define CrossDist (0.05f) -#define AxisDist (0.05f) - -class SANDBOX_API CArcBall3D -{ -public: - AZ_PUSH_DISABLE_DLL_EXPORT_MEMBER_WARNING - uint32 RotControl; - Sphere sphere; - uint32 Mouse_CutFlag; - uint32 Mouse_CutFlagStart; - uint32 AxisSnap; - Vec3 LineStart3D; - Vec3 Mouse_CutOnUnitSphere; - Quat DragRotation; - Quat ObjectRotation; - AZ_POP_DISABLE_DLL_EXPORT_MEMBER_WARNING - - CArcBall3D() - { - InitArcBall(); - }; - - void InitArcBall() - { - RotControl = 0; - sphere(Vec3(ZERO), 0.25f); - Mouse_CutFlag = 0; - Mouse_CutOnUnitSphere(0, 0, 0); - LineStart3D(0, -1, 0); - AxisSnap = 0; - DragRotation.SetIdentity(); - ObjectRotation.SetIdentity(); - } - - //--------------------------------------------------------------- - // ArcControl - // Returns true if the rotation has changed - //--------------------------------------------------------------- - bool ArcControl(const Matrix34& reference, const Ray& ray, uint32 mouseleft); - void ArcRotation(); - void DrawSphere(const Matrix34& reference, const CCamera& cam, struct IRenderAuxGeom* pRenderer); - static uint32 IntersectSphereLineSegment(const Sphere& s, const Vec3& LineStart, const Vec3& LineEnd, Vec3& I); -}; -#endif // CRYINCLUDE_EDITOR_UTIL_ARCBALL_H diff --git a/Code/Sandbox/Editor/Util/CubemapUtils.cpp b/Code/Sandbox/Editor/Util/CubemapUtils.cpp deleted file mode 100644 index bd650abaa8..0000000000 --- a/Code/Sandbox/Editor/Util/CubemapUtils.cpp +++ /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. - -#include "EditorDefs.h" - -#include "CubemapUtils.h" - -// Qt -#include -#include -#include -#include -#include -#include - -// AzToolsFramework -#include - -// Editor -#include "Util/ImageTIF.h" -#include "Objects/BaseObject.h" - -#include - -class CubemapSizeModel - : public QAbstractListModel -{ -public: - CubemapSizeModel(QObject* parent = nullptr) - : QAbstractListModel(parent) - { } - - int rowCount(const QModelIndex& parent = {}) const override - { - return parent.isValid() ? 0 : kNumResolutions; - } - - QVariant data(const QModelIndex& index, int role = Qt::DisplayRole) const override - { - if (!index.isValid() || index.row() >= kNumResolutions) - { - return {}; - } - - switch (role) - { - case Qt::DisplayRole: - case Qt::UserRole: - return 32 << index.row(); - } - - return {}; - } - -private: - static const int kNumResolutions = 6; -}; - -class CubemapSizeDialog - : public QDialog -{ -public: - CubemapSizeDialog(QWidget* parent = nullptr) - : QDialog(parent) - , m_model(new CubemapSizeModel(this)) - { - setWindowTitle(tr("Enter Cubemap Resolution")); - - m_comboBox = new QComboBox; - m_comboBox->setModel(m_model); - m_comboBox->setCurrentIndex(3); - - auto horLine = new QLabel; - horLine->setFrameShape(QFrame::HLine); - horLine->setFrameShadow(QFrame::Sunken); - - auto buttonBox = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel); - connect(buttonBox, &QDialogButtonBox::accepted, this, &QDialog::accept); - connect(buttonBox, &QDialogButtonBox::rejected, this, &QDialog::reject); - - auto layout = new QVBoxLayout; - layout->addWidget(m_comboBox); - layout->addWidget(horLine); - layout->addWidget(buttonBox); - - setLayout(layout); - } - - int GetValue() const - { - return m_comboBox->currentData().toInt(); - } - -private: - CubemapSizeModel* m_model; - QComboBox* m_comboBox; -}; - -/////////////////////////////////////////////////////////////////////////////////// -bool CubemapUtils::GenCubemapWithObjectPathAndSize(QString& filename, CBaseObject* pObject, const int size, const bool hideObject) -{ - if (!pObject) - { - Warning("Select One Entity to Generate Cubemap"); - return false; - } - - if (pObject->GetType() != OBJTYPE_AZENTITY) - { - Warning("Only Entities are allowed as a selected object. Please Select Entity objects"); - return false; - } - - int res = 1; - // Make size power of 2. - for (int i = 0; i < 16; i++) - { - if (res * 2 > size) - { - break; - } - res *= 2; - } - if (res > 4096) - { - Warning("Bad texture resolution.\nMust be power of 2 and less or equal to 4096"); - return false; - } - - IRenderNode* pRenderNode = pObject->GetEngineNode(); - - // Hide the object before Cubemap generation (maybe). This is useful for when generating a cubemap at an entity's position, like the player, - // and you don't want their model showing up in the cubemap. But you want to leave the entity alone if it's a light or something that - // has a desired contribution to the cubemap. - bool bIsHidden = false; - if (pRenderNode) - { - bIsHidden = (pRenderNode->GetRndFlags() & ERF_HIDDEN) != 0; - if (hideObject) - { - pRenderNode->SetRndFlags(ERF_HIDDEN, true); - } - } - - QString texname = Path::GetFileName(filename); - QString path = Path::GetPath(filename); - - // Add _CM suffix if missing - int32 nCMSufixCheck = texname.indexOf("_cm"); - texname = Path::Make(path, texname + ((nCMSufixCheck == -1) ? "_cm.tif" : ".tif")); - - // Assign this texname to current material. - texname = Path::ToUnixPath(texname); - - // Temporary solution to save both dds and tiff hdr cubemap - AABB pObjAABB; - pObject->GetBoundBox(pObjAABB); - - Vec3 pObjCenter = pObjAABB.GetCenter(); - - bool success = GenHDRCubemapTiff(texname, res, pObjCenter); - - // restore object's visibility - if (pRenderNode) - { - pRenderNode->SetRndFlags(ERF_HIDDEN, bIsHidden); - } - - filename = Path::ToUnixPath(texname); - - return success; -} - -////////////////////////////////////////////////////////////////////////// -bool CubemapUtils::GenHDRCubemapTiff(const QString& fileName, int nDstSize, Vec3& pos) -{ - int nSrcSize = nDstSize * 4; // Render 16x bigger cubemap (4x4) - 16x SSAA - - TArray vecData; - vecData.Reserve(nSrcSize * nSrcSize * 6 * 4); - vecData.SetUse(0); - - if (!GetIEditor()->GetRenderer()->EF_RenderEnvironmentCubeHDR(nSrcSize, pos, vecData)) - { - assert(0); - return false; - } - - assert(vecData.size() == nSrcSize * nSrcSize * 6 * 4); - - // todo: such big downsampling should be on gpu - - // save data to tiff - // resample the image at the original size - CWordImage img; - img.Allocate(nDstSize * 4 * 6, nDstSize); - - size_t srcPitch = nSrcSize * 4; - size_t srcSlideSize = nSrcSize * srcPitch; - - size_t dstPitch = nDstSize * 4; - for (int side = 0; side < 6; ++side) - { - for (uint32 y = 0; y < nDstSize; ++y) - { - CryHalf4* pSrcSide = (CryHalf4*)&vecData[side * srcSlideSize]; - CryHalf4* pDst = (CryHalf4*)&img.ValueAt(side * dstPitch, y); - for (uint32 x = 0; x < nDstSize; ++x) - { - Vec4 cResampledColor(0.f, 0.f, 0.f, 0.f); - - // resample the image at the original size - for (uint32 yres = 0; yres < 4; ++yres) - { - for (uint32 xres = 0; xres < 4; ++xres) - { - const CryHalf4& pSrc = pSrcSide[(y * 4 + yres) * nSrcSize + (x * 4 + xres)]; - cResampledColor += Vec4(CryConvertHalfToFloat(pSrc.x), CryConvertHalfToFloat(pSrc.y), CryConvertHalfToFloat(pSrc.z), CryConvertHalfToFloat(pSrc.w)); - } - } - - cResampledColor /= 16.f; - - *pDst++ = CryHalf4(cResampledColor.x, cResampledColor.y, cResampledColor.z, cResampledColor.w); - } - } - } - - assert(CryMemory::IsHeapValid()); - - CImageTIF tif; - const bool res = tif.SaveRAW(fileName, img.GetData(), nDstSize * 6, nDstSize, 2, 4, true, "HDRCubemap_highQ"); - assert(res); - return res; -} - -//function will recurse all probes and generate a cubemap for each -void CubemapUtils::RegenerateAllEnvironmentProbeCubemaps() -{ - EBUS_EVENT(AzToolsFramework::EditorRequests::Bus, GenerateAllCubemaps); -} diff --git a/Code/Sandbox/Editor/Util/CubemapUtils.h b/Code/Sandbox/Editor/Util/CubemapUtils.h deleted file mode 100644 index dfc2d47306..0000000000 --- a/Code/Sandbox/Editor/Util/CubemapUtils.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_EDITOR_UTIL_CUBEMAPUTILS_H -#define CRYINCLUDE_EDITOR_UTIL_CUBEMAPUTILS_H -#pragma once - - -namespace CubemapUtils -{ - //! Generate a cubemap - //! \param filename - //! \param pObject The cubemap will be generated at this object's location - //! \param size Texel dimension of the cubemap - //! \param hideObject If true, pObject will be hidden when rendering the cubemap. For example, set this to true if pObject is a model that shouldn't - //! show up in the cubemap, or set to false if pObject is a light or probe that should contribute to the cubemap. - SANDBOX_API bool GenCubemapWithObjectPathAndSize(QString& filename, CBaseObject* pObject, const int size, const bool hideObject); - - SANDBOX_API bool GenHDRCubemapTiff(const QString& fileName, int size, Vec3& pos); - SANDBOX_API void RegenerateAllEnvironmentProbeCubemaps(); -} - -#endif // CRYINCLUDE_EDITOR_UTIL_CUBEMAPUTILS_H diff --git a/Code/Sandbox/Editor/Util/ImageUtil.cpp b/Code/Sandbox/Editor/Util/ImageUtil.cpp index ae44833a75..874d74e9bb 100644 --- a/Code/Sandbox/Editor/Util/ImageUtil.cpp +++ b/Code/Sandbox/Editor/Util/ImageUtil.cpp @@ -22,7 +22,6 @@ #include "Util/ImageGif.h" #include "Util/ImageTIF.h" #include "Util/ImageHDR.h" -#include "Util/Image_DXTC.h" ////////////////////////////////////////////////////////////////////////// bool CImageUtil::Save(const QString& strFileName, CImageEx& inImage) @@ -272,10 +271,6 @@ bool CImageUtil::LoadImage(const QString& fileName, CImageEx& image, bool* pQual { return LoadPGM(fileName, image); } - else if (azstricmp(ext, ".dds") == 0) - { - return CImage_DXTC().Load(fileName.toUtf8().data(), image, pQualityLoss); - } else if (azstricmp(ext, ".png") == 0) { return CImageUtil::Load(fileName, image); diff --git a/Code/Sandbox/Editor/Util/Image_DXTC.cpp b/Code/Sandbox/Editor/Util/Image_DXTC.cpp deleted file mode 100644 index 834da7b5a3..0000000000 --- a/Code/Sandbox/Editor/Util/Image_DXTC.cpp +++ /dev/null @@ -1,806 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS 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 "Image_DXTC.h" - -// CryCommon -#include -#include - -// Editor -#include "Util/Image.h" -#include "BitFiddling.h" - - -#ifndef MAKEFOURCC -#define MAKEFOURCC(ch0, ch1, ch2, ch3) \ - ((DWORD)(BYTE)(ch0) | ((DWORD)(BYTE)(ch1) << 8) | \ - ((DWORD)(BYTE)(ch2) << 16) | ((DWORD)(BYTE)(ch3) << 24)) -#endif //defined(MAKEFOURCC) - - -////////////////////////////////////////////////////////////////////////// -// HDR_UPPERNORM -> factor used when converting from [0,32768] high dynamic range images -// to [0,1] low dynamic range images; 32768 = 2^(2^4-1), 4 exponent bits -// LDR_UPPERNORM -> factor used when converting from [0,1] low dynamic range images -// to 8bit outputs - -#define HDR_UPPERNORM 1.0f // factor set to 1.0, to be able to see content in our rather dark HDR images -#define LDR_UPPERNORM 255.0f - -static float GammaToLinear(float x) -{ - return (x <= 0.04045f) ? x / 12.92f : powf((x + 0.055f) / 1.055f, 2.4f); -} - -static float LinearToGamma(float x) -{ - return (x <= 0.0031308f) ? x * 12.92f : 1.055f * powf(x, 1.0f / 2.4f) - 0.055f; -} - -////////////////////////////////////////////////////////////////////////// - -// Squish uses non-standard inline friend templates which Recode cannot parse -#ifndef __RECODE__ -AZ_PUSH_DISABLE_WARNING(4819 4828, "-Wunknown-warning-option") // Invalid character not in default code page -#include -AZ_POP_DISABLE_WARNING -#endif - -// number of bytes per block per type -#define BLOCKSIZE_BC1 8 -#define BLOCKSIZE_BC2 16 -#define BLOCKSIZE_BC3 16 -#define BLOCKSIZE_BC4 8 -#define BLOCKSIZE_BC5 16 -#define BLOCKSIZE_BC6 16 -#define BLOCKSIZE_BC7 16 - -CImage_DXTC::COMPRESSOR_ERROR CImage_DXTC::DecompressTextureBTC( - int width, - int height, - ETEX_Format sourceFormat, - CImage_DXTC::UNCOMPRESSED_FORMAT destinationFormat, - [[maybe_unused]] const int imageFlags, - const void* sourceData, - void* destinationData, - int destinationDataSize, - int destinationPageOffset) -{ - // Squish uses non-standard inline friend templates which Recode cannot parse -#ifndef __RECODE__ - { - const COMPRESSOR_ERROR result = CheckParameters( - width, - height, - destinationFormat, - sourceData, - destinationData, - destinationDataSize); - - if (result != COMPRESSOR_ERROR_NONE) - { - return result; - } - } - - int flags = 0; - int offs = 0; - int sourceChannels = 4; - switch (sourceFormat) - { - case eTF_BC1: - sourceChannels = 4; - flags = squish::kBtc1; - break; - case eTF_BC2: - sourceChannels = 4; - flags = squish::kBtc2; - break; - case eTF_BC3: - sourceChannels = 4; - flags = squish::kBtc3; - break; - case eTF_BC4U: - sourceChannels = 1; - flags = squish::kBtc4; - break; - case eTF_BC5U: - sourceChannels = 2; - flags = squish::kBtc5 + squish::kColourMetricUnit; - break; - case eTF_BC6UH: - sourceChannels = 3; - flags = squish::kBtc6; - break; - case eTF_BC7: - sourceChannels = 4; - flags = squish::kBtc7; - break; - - case eTF_BC4S: - sourceChannels = 1; - flags = squish::kBtc4 + squish::kSignedInternal + squish::kSignedExternal; - offs = 0x80; - break; - case eTF_BC5S: - sourceChannels = 2; - flags = squish::kBtc5 + squish::kSignedInternal + squish::kSignedExternal + squish::kColourMetricUnit; - offs = 0x80; - break; - case eTF_BC6SH: - sourceChannels = 3; - flags = squish::kBtc6 + squish::kSignedInternal + squish::kSignedExternal; - offs = 0x80; - break; - - default: - return COMPRESSOR_ERROR_UNSUPPORTED_SOURCE_FORMAT; - } - - squish::sqio::dtp datatype = !IsLimitedHDR(sourceFormat) ? squish::sqio::dtp::DT_U8 : squish::sqio::dtp::DT_F23; - switch (destinationFormat) - { - case FORMAT_ARGB_8888: /*datatype = squish::sqio::dtp::DT_U8;*/ - break; - // case FORMAT_ARGB_16161616: datatype = squish::sqio::dtp::DT_U16; break; - // case FORMAT_ARGB_32323232F: datatype = squish::sqio::dtp::DT_F23; break; - default: - return COMPRESSOR_ERROR_UNSUPPORTED_DESTINATION_FORMAT; - } - - struct squish::sqio sqio = squish::GetSquishIO(width, height, datatype, flags); - - const int blockChannels = 4; - const int blockWidth = 4; - const int blockHeight = 4; - - const int pixelStride = blockChannels * sizeof(uint8); - const int rowStride = (destinationPageOffset ? destinationPageOffset : pixelStride * width); - - if ((datatype == squish::sqio::dtp::DT_U8) && (destinationFormat == FORMAT_ARGB_8888)) - { - const char* src = (const char*)sourceData; - for (int y = 0; y < height; y += blockHeight) - { - uint8* dst = ((uint8*)destinationData) + (y * rowStride); - - for (int x = 0; x < width; x += blockWidth) - { - uint8 values[blockHeight][blockWidth][blockChannels] = { { { 0 } } }; - - // decode - sqio.decoder((uint8*)values, src, sqio.flags); - - // transfer - for (int by = 0; by < blockHeight; by += 1) - { - uint8* bdst = ((uint8*)dst) + (by * rowStride); - - for (int bx = 0; bx < blockWidth; bx += 1) - { - bdst[bx * pixelStride + 0] = sourceChannels <= 0 ? 0U : (values[by][bx][0] + offs); - bdst[bx * pixelStride + 1] = sourceChannels <= 1 ? bdst[bx * pixelStride + 0] : (values[by][bx][1] + offs); - bdst[bx * pixelStride + 2] = sourceChannels <= 1 ? bdst[bx * pixelStride + 0] : (values[by][bx][2] + offs); - bdst[bx * pixelStride + 3] = sourceChannels <= 3 ? 255U : (values[by][bx][3]); - } - } - - dst += blockWidth * pixelStride; - src += sqio.blocksize; - } - } - } - else if ((datatype == squish::sqio::dtp::DT_F23) && (destinationFormat == FORMAT_ARGB_8888)) - { - const char* src = (const char*)sourceData; - for (int y = 0; y < height; y += blockHeight) - { - uint8* dst = ((uint8*)destinationData) + (y * rowStride); - - for (int x = 0; x < width; x += blockWidth) - { - float values[blockHeight][blockWidth][blockChannels] = { { { 0 } } }; - - // decode - sqio.decoder((float*)values, src, sqio.flags); - - // transfer - for (int by = 0; by < blockHeight; by += 1) - { - uint8* bdst = ((uint8*)dst) + (by * rowStride); - - for (int bx = 0; bx < blockWidth; bx += 1) - { - bdst[bx * pixelStride + 0] = sourceChannels <= 0 ? 0U : std::min((uint8)255, (uint8)floorf(values[by][bx][0] * LDR_UPPERNORM / HDR_UPPERNORM + 0.5f)); - bdst[bx * pixelStride + 1] = sourceChannels <= 1 ? bdst[bx * pixelStride + 0] : std::min((uint8)255, (uint8)floorf(values[by][bx][1] * LDR_UPPERNORM / HDR_UPPERNORM + 0.5f)); - bdst[bx * pixelStride + 2] = sourceChannels <= 1 ? bdst[bx * pixelStride + 0] : std::min((uint8)255, (uint8)floorf(values[by][bx][2] * LDR_UPPERNORM / HDR_UPPERNORM + 0.5f)); - bdst[bx * pixelStride + 3] = sourceChannels <= 3 ? 255U : 255U; - } - } - - dst += blockWidth * pixelStride; - src += sqio.blocksize; - } - } - } -#endif - - return COMPRESSOR_ERROR_NONE; -} - -////////////////////////////////////////////////////////////////////////// -CImage_DXTC::CImage_DXTC() -{ -} -////////////////////////////////////////////////////////////////////////// -CImage_DXTC::~CImage_DXTC() -{ -} -////////////////////////////////////////////////////////////////////////// -bool CImage_DXTC::Load(const char* filename, CImageEx& outImage, bool* pQualityLoss) -{ - if (pQualityLoss) - { - *pQualityLoss = false; - } - - _smart_ptr pImage = gEnv->pRenderer->EF_LoadImage(filename, 0); - - if (!pImage) - { - return(false); - } - - BYTE* pDecompBytes; - - ETEX_Format eFormat = pImage->mfGetFormat(); - int imageFlags = pImage->mfGet_Flags(); - - if (eFormat == eTF_Unknown) - { - return false; - } - - _smart_ptr pAlphaImage; - - ETEX_Format eAttachedFormat = eTF_Unknown; - - if (imageFlags & FIM_HAS_ATTACHED_ALPHA) - { - if (pAlphaImage = gEnv->pRenderer->EF_LoadImage(filename, FIM_ALPHA)) - { - eAttachedFormat = pAlphaImage->mfGetFormat(); - } - } - - const bool bIsSRGB = (imageFlags & FIM_SRGB_READ) != 0; - outImage.SetSRGB(bIsSRGB); - - const uint32 imageWidth = pImage->mfGet_width(); - const uint32 imageHeight = pImage->mfGet_height(); - const uint32 numMips = pImage->mfGet_numMips(); - - int nHorizontalFaces(1); - int nVerticalFaces(1); - int nTargetPitch(imageWidth * 4); - int nTargetPageSize(nTargetPitch * imageHeight); - - int nHorizontalPageOffset(nTargetPitch); - int nVerticalPageOffset(0); - bool boIsCubemap = pImage->mfGet_NumSides() == 6; - if (boIsCubemap) - { - nHorizontalFaces = 3; - nVerticalFaces = 2; - nHorizontalPageOffset = nTargetPitch * nHorizontalFaces; - nVerticalPageOffset = nTargetPageSize * nHorizontalFaces; - } - - outImage.Allocate(imageWidth * nHorizontalFaces, imageHeight * nVerticalFaces); - pDecompBytes = (BYTE*)outImage.GetData(); - if (!pDecompBytes) - { - Warning("Cannot allocate image %dx%d, Out of memory", imageWidth, imageHeight); - return false; - } - - if (pQualityLoss) - { - *pQualityLoss = CImageExtensionHelper::IsQuantized(eFormat); - } - - bool bOk = true; - - int nCurrentFace(0); - int nCurrentHorizontalFace(0); - int nCurrentVerticalFace(0); - unsigned char* dest(NULL); - const unsigned char* src(NULL); - - unsigned char* basedest(NULL); - const unsigned char* basesrc(NULL); - - for (nCurrentHorizontalFace = 0; nCurrentHorizontalFace < nHorizontalFaces; ++nCurrentHorizontalFace) - { - basedest = &pDecompBytes[nTargetPitch * nCurrentHorizontalFace]; // Horizontal offset. - for (nCurrentVerticalFace = 0; nCurrentVerticalFace < nVerticalFaces; ++nCurrentVerticalFace, ++nCurrentFace) - { - basedest += nVerticalPageOffset * nCurrentVerticalFace; // Vertical offset. - - basesrc = src = pImage->mfGet_image(nCurrentFace); - - if (eFormat == eTF_R8G8B8A8 || eFormat == eTF_R8G8B8A8S) - { - for (int y = 0; y < imageHeight; y++) - { - dest = basedest + nHorizontalPageOffset * y; // Pixel position. - - for (int x = 0; x < imageWidth; x++) - { - dest[0] = src[0]; - dest[1] = src[1]; - dest[2] = src[2]; - dest[3] = src[3]; - - dest += 4; - src += 4; - } - } - } - else if (eFormat == eTF_B8G8R8A8) - { - for (int y = 0; y < imageHeight; y++) - { - dest = basedest + nHorizontalPageOffset * y; // Pixel position. - - for (int x = 0; x < imageWidth; x++) - { - dest[0] = src[2]; - dest[1] = src[1]; - dest[2] = src[0]; - dest[3] = src[3]; - - dest += 4; - src += 4; - } - } - } - else if (eFormat == eTF_B8G8R8X8) - { - for (int y = 0; y < imageHeight; y++) - { - dest = basedest + nHorizontalPageOffset * y; // Pixel position. - - for (int x = 0; x < imageWidth; x++) - { - dest[0] = src[2]; - dest[1] = src[1]; - dest[2] = src[0]; - dest[3] = 255; - - dest += 4; - src += 4; - } - } - } - else if (eFormat == eTF_B8G8R8) - { - for (int y = 0; y < imageHeight; y++) - { - dest = basedest + nHorizontalPageOffset * y; // Pixel position. - - for (int x = 0; x < imageWidth; x++) - { - dest[0] = src[2]; - dest[1] = src[1]; - dest[2] = src[0]; - dest[3] = 255; - - dest += 4; - src += 3; - } - } - } - else if (eFormat == eTF_L8) - { - for (int y = 0; y < imageHeight; y++) - { - dest = basedest + nHorizontalPageOffset * y; // Pixel position. - - for (int x = 0; x < imageWidth; x++) - { - dest[0] = *src; - dest[1] = *src; - dest[2] = *src; - dest[3] = 255; - - dest += 4; - src += 1; - } - } - } - else if (eFormat == eTF_A8) - { - for (int y = 0; y < imageHeight; y++) - { - dest = basedest + nHorizontalPageOffset * y; // Pixel position. - - for (int x = 0; x < imageWidth; x++) - { - dest[0] = 0; - dest[1] = 0; - dest[2] = 0; - dest[3] = *src; - - dest += 4; - src += 1; - } - } - } - else if (eFormat == eTF_A8L8) - { - for (int y = 0; y < imageHeight; y++) - { - dest = basedest + nHorizontalPageOffset * y; // Pixel position. - - for (int x = 0; x < imageWidth; x++) - { - dest[0] = src[0]; - dest[1] = src[0]; - dest[2] = src[0]; - dest[3] = src[1]; - - dest += 4; - src += 2; - } - } - } - else if (eFormat == eTF_R9G9B9E5) - { - const int nSourcePitch = imageWidth * 4; - - for (int y = 0; y < imageHeight; y++) - { - src = basesrc + nSourcePitch * y; //Scanline position. - dest = basedest + nHorizontalPageOffset * y; // Pixel position. - - for (int x = 0; x < imageWidth; x++) - { - const struct RgbE - { - unsigned int r : 9, g : 9, b : 9, e : 5; - }* srcv = (const struct RgbE*)src; - - const float escale = powf(2.0f, int(srcv->e) - 15 - 9) * LDR_UPPERNORM / HDR_UPPERNORM; - - dest[0] = std::min((uint8)255, (uint8)floorf(srcv->r * escale + 0.5f)); - dest[1] = std::min((uint8)255, (uint8)floorf(srcv->g * escale + 0.5f)); - dest[2] = std::min((uint8)255, (uint8)floorf(srcv->b * escale + 0.5f)); - dest[3] = 255U; - - dest += 4; - src += 4; - } - } - } - else - { - const int pixelCount = imageWidth * imageHeight; - const int outputBufferSize = pixelCount * 4; - const int mipCount = numMips; - - const COMPRESSOR_ERROR err = DecompressTextureBTC(imageWidth, imageHeight, eFormat, FORMAT_ARGB_8888, imageFlags, basesrc, basedest, outputBufferSize, nHorizontalPageOffset); - if (err != COMPRESSOR_ERROR_NONE) - { - return false; - } - } - - // alpha channel might be attached - if (imageFlags & FIM_HAS_ATTACHED_ALPHA) - { - if (IsBlockCompressed(eAttachedFormat)) - { - const byte* const basealpha = pAlphaImage->mfGet_image(0); - const int alphaImageWidth = pAlphaImage->mfGet_width(); - const int alphaImageHeight = pAlphaImage->mfGet_height(); - const int alphaImageFlags = pAlphaImage->mfGet_Flags(); - const int tmpOutputBufferSize = imageWidth * imageHeight * 4; - uint8* tmpOutputBuffer = new uint8[tmpOutputBufferSize]; - - const COMPRESSOR_ERROR err = DecompressTextureBTC(alphaImageWidth, alphaImageHeight, eAttachedFormat, FORMAT_ARGB_8888, alphaImageFlags, basealpha, tmpOutputBuffer, tmpOutputBufferSize, 0); - if (err != COMPRESSOR_ERROR_NONE) - { - delete []tmpOutputBuffer; - return false; - } - - // assuming attached image can have lower res and difference is power of two - const uint32 reducex = IntegerLog2((uint32)(imageWidth / alphaImageWidth)); - const uint32 reducey = IntegerLog2((uint32)(imageHeight / alphaImageHeight)); - - for (int y = 0; y < imageHeight; ++y) - { - dest = basedest + nHorizontalPageOffset * y; // Pixel position. - - for (int x = 0; x < imageWidth; ++x) - { - dest[3] = tmpOutputBuffer[((x >> reducex) + (y >> reducey) * alphaImageWidth) * 4]; - dest += 4; - } - } - - delete []tmpOutputBuffer; - } - else if (eAttachedFormat != eTF_Unknown) - { - const byte* const basealpha = pAlphaImage->mfGet_image(0); // assuming it's A8 format (ensured with assets when loading) - const int alphaImageWidth = pAlphaImage->mfGet_width(); - const int alphaImageHeight = pAlphaImage->mfGet_height(); - const int alphaImageFlags = pAlphaImage->mfGet_Flags(); - - // assuming attached image can have lower res and difference is power of two - const uint32 reducex = IntegerLog2((uint32)(imageWidth / alphaImageWidth)); - const uint32 reducey = IntegerLog2((uint32)(imageHeight / alphaImageHeight)); - - for (int y = 0; y < imageHeight; ++y) - { - dest = basedest + nHorizontalPageOffset * y; // Pixel position. - - for (int x = 0; x < imageWidth; ++x) - { - dest[3] = basealpha[(x >> reducex) + (y >> reducey) * alphaImageWidth]; - dest += 4; - } - } - } - } - } - } - - ////////////////////////////////////////////////////////////////////////// - // destination range is 8bits - // rescale in linear space - float cScaleR = 1.0f; - float cScaleG = 1.0f; - float cScaleB = 1.0f; - float cScaleA = 1.0f; - float cLowR = 0.0f; - float cLowG = 0.0f; - float cLowB = 0.0f; - float cLowA = 0.0f; - - if (imageFlags & FIM_RENORMALIZED_TEXTURE) - { - const ColorF cMinColor = pImage->mfGet_minColor(); - const ColorF cMaxColor = pImage->mfGet_maxColor(); - - // base range after normalization, fe. [0,1] for 8bit images, or [0,2^15] for RGBE/HDR data - float cUprValue = 1.0f; - if ((eFormat == eTF_R9G9B9E5) || (eFormat == eTF_BC6UH) || (eFormat == eTF_BC6SH)) - { - cUprValue = cMaxColor.a / HDR_UPPERNORM; - } - - // original range before normalization, fe. [0,1.83567] - cScaleR = (cMaxColor.r - cMinColor.r) / cUprValue; - cScaleG = (cMaxColor.g - cMinColor.g) / cUprValue; - cScaleB = (cMaxColor.b - cMinColor.b) / cUprValue; - // original offset before normalization, fe. [0.0001204] - cLowR = cMinColor.r; - cLowG = cMinColor.g; - cLowB = cMinColor.b; - } - - if (imageFlags & FIM_HAS_ATTACHED_ALPHA) - { - if (pAlphaImage) - { - const int alphaImageFlags = pAlphaImage->mfGet_Flags(); - - if (alphaImageFlags & FIM_RENORMALIZED_TEXTURE) - { - const ColorF cMinColor = pAlphaImage->mfGet_minColor(); - const ColorF cMaxColor = pAlphaImage->mfGet_maxColor(); - - // base range after normalization, fe. [0,1] for 8bit images, or [0,2^15] for RGBE/HDR data - float cUprValue = 1.0f; - if ((eFormat == eTF_R9G9B9E5) || (eFormat == eTF_BC6UH) || (eFormat == eTF_BC6SH)) - { - cUprValue = cMaxColor.a / HDR_UPPERNORM; - } - - // original range before normalization, fe. [0,1.83567] - cScaleA = (cMaxColor.r - cMinColor.r) / cUprValue; - // original offset before normalization, fe. [0.0001204] - cLowA = cMinColor.r; - } - } - } - - if (cScaleR != 1.0f || cScaleG != 1.0f || cScaleB != 1.0f || cScaleA != 1.0f || - cLowR != 0.0f || cLowG != 0.0f || cLowB != 0.0f || cLowA != 0.0f) - { - if ((eFormat == eTF_R9G9B9E5) || (eFormat == eTF_BC6UH) || (eFormat == eTF_BC6SH)) - { - imageFlags &= ~FIM_SRGB_READ; - } - - if (imageFlags & FIM_SRGB_READ) - { - for (int s = 0; s < (imageWidth * nHorizontalFaces * imageHeight * nVerticalFaces * 4); s += 4) - { - pDecompBytes[s + 0] = std::min((uint8)255, uint8(LinearToGamma(GammaToLinear(pDecompBytes[s + 0] / LDR_UPPERNORM) * cScaleR + cLowR) * LDR_UPPERNORM + 0.5f)); - pDecompBytes[s + 1] = std::min((uint8)255, uint8(LinearToGamma(GammaToLinear(pDecompBytes[s + 1] / LDR_UPPERNORM) * cScaleG + cLowG) * LDR_UPPERNORM + 0.5f)); - pDecompBytes[s + 2] = std::min((uint8)255, uint8(LinearToGamma(GammaToLinear(pDecompBytes[s + 2] / LDR_UPPERNORM) * cScaleB + cLowB) * LDR_UPPERNORM + 0.5f)); - pDecompBytes[s + 3] = std::min((uint8)255, uint8(LinearToGamma(GammaToLinear(pDecompBytes[s + 3] / LDR_UPPERNORM) * cScaleA + cLowA) * LDR_UPPERNORM + 0.5f)); - } - } - else - { - for (int s = 0; s < (imageWidth * nHorizontalFaces * imageHeight * nVerticalFaces * 4); s += 4) - { - pDecompBytes[s + 0] = std::min((uint8)255, uint8(pDecompBytes[s + 0] * cScaleR + cLowR * LDR_UPPERNORM + 0.5f)); - pDecompBytes[s + 1] = std::min((uint8)255, uint8(pDecompBytes[s + 1] * cScaleG + cLowG * LDR_UPPERNORM + 0.5f)); - pDecompBytes[s + 2] = std::min((uint8)255, uint8(pDecompBytes[s + 2] * cScaleB + cLowB * LDR_UPPERNORM + 0.5f)); - pDecompBytes[s + 3] = std::min((uint8)255, uint8(pDecompBytes[s + 3] * cScaleA + cLowA * LDR_UPPERNORM + 0.5f)); - } - } - } - - bool hasAlpha = (eAttachedFormat != eTF_Unknown) /*|| CImageExtensionHelper::HasAlphaForTextureFormat(eFormat)*/; - for (int s = 0; s < (imageWidth * nHorizontalFaces * imageHeight * nVerticalFaces); s += 4) - { - hasAlpha |= (pDecompBytes[s + 3] != 0xFF); - } - - ////////////////////////////////////////////////////////////////////////// - QString strFormat = NameForTextureFormat(eFormat); - QString mips; - mips = QStringLiteral(" Mips:%1").arg(numMips); - - if (eAttachedFormat != eTF_Unknown) - { - strFormat += " + "; - strFormat += NameForTextureFormat(eAttachedFormat); - } - - strFormat += mips; - - // Check whether it's gamma-corrected or not and add a description accordingly. - if (imageFlags & FIM_SRGB_READ) - { - strFormat += ", SRGB/Gamma corrected"; - } - if (imageFlags & FIM_RENORMALIZED_TEXTURE) - { - strFormat += ", Renormalized"; - } - if (IsLimitedHDR(eFormat)) - { - strFormat += ", HDR"; - } - - outImage.SetFormatDescription(strFormat); - outImage.SetNumberOfMipMaps(numMips); - outImage.SetHasAlphaChannel(hasAlpha); - outImage.SetIsLimitedHDR(IsLimitedHDR(eFormat)); - outImage.SetIsCubemap(boIsCubemap); - outImage.SetFormat(eFormat); - outImage.SetSRGB(imageFlags & FIM_SRGB_READ); - - // done reading file - return bOk; -} - -////////////////////////////////////////////////////////////////////////// -int CImage_DXTC::TextureDataSize(int nWidth, int nHeight, int nDepth, int nMips, ETEX_Format eTF) -{ - if (eTF == eTF_Unknown) - { - return 0; - } - - if (nMips <= 0) - { - nMips = 0; - } - int nSize = 0; - int nM = 0; - while (nWidth || nHeight || nDepth) - { - if (!nWidth) - { - nWidth = 1; - } - if (!nHeight) - { - nHeight = 1; - } - if (!nDepth) - { - nDepth = 1; - } - nM++; - - int nSingleMipSize; - if (IsBlockCompressed(eTF)) - { - int blockSize = CImageExtensionHelper::BytesPerBlock(eTF); - const Vec2i blockDim = CImageExtensionHelper::GetBlockDim(eTF); - nSingleMipSize = ((nWidth + blockDim.x - 1) / blockDim.x) * ((nHeight + blockDim.y - 1) / blockDim.y) * nDepth * blockSize; - } - else - { - nSingleMipSize = nWidth * nHeight * nDepth * CImageExtensionHelper::BytesPerBlock(eTF); - } - nSize += nSingleMipSize; - - nWidth >>= 1; - nHeight >>= 1; - nDepth >>= 1; - if (nMips == nM) - { - break; - } - } - //assert (nM == nMips); - - return nSize; -} - -////////////////////////////////////////////////////////////////////////// -CImage_DXTC::COMPRESSOR_ERROR CImage_DXTC::CheckParameters( - int width, - int height, - CImage_DXTC::UNCOMPRESSED_FORMAT destinationFormat, - const void* sourceData, - void* destinationData, - int destinationDataSize) -{ - const int blockWidth = 4; - const int blockHeight = 4; - - const int bgraPixelSize = 4 * sizeof(uint8); - const int bgraRowSize = bgraPixelSize * width; - - if ((width <= 0) || (height <= 0) || (!sourceData)) - { - return COMPRESSOR_ERROR_NO_INPUT_DATA; - } - - if ((width % blockWidth) || (height % blockHeight)) - { - return COMPRESSOR_ERROR_GENERIC; - } - - if ((destinationData == 0) || (destinationDataSize <= 0)) - { - return COMPRESSOR_ERROR_NO_OUTPUT_POINTER; - } - - if (destinationFormat != FORMAT_ARGB_8888) - { - return COMPRESSOR_ERROR_UNSUPPORTED_DESTINATION_FORMAT; - } - - if ((height * bgraRowSize <= 0) || (height * bgraRowSize > destinationDataSize)) - { - return COMPRESSOR_ERROR_GENERIC; - } - - return COMPRESSOR_ERROR_NONE; -} diff --git a/Code/Sandbox/Editor/Util/Image_DXTC.h b/Code/Sandbox/Editor/Util/Image_DXTC.h deleted file mode 100644 index 507d0232f1..0000000000 --- a/Code/Sandbox/Editor/Util/Image_DXTC.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. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_EDITOR_UTIL_IMAGE_DXTC_H -#define CRYINCLUDE_EDITOR_UTIL_IMAGE_DXTC_H -#pragma once - -#include "ImageExtensionHelper.h" - -class CImageEx; - -class CImage_DXTC -{ - // Typedefs -public: -protected: - ////////////////////////////////////////////////////////////////////////// - // Extracted from Compressorlib.h on SDKs\CompressATI directory. - // Added here because we are not really using the elements inside - // this header file apart from those definitions as we are currently - // loading the DLL CompressATI2.dll manually as recommended by the rendering - // team. - typedef enum - { - FORMAT_ARGB_8888, - FORMAT_ARGB_TOOBIG - } UNCOMPRESSED_FORMAT; - - typedef enum - { - COMPRESSOR_ERROR_NONE, - COMPRESSOR_ERROR_NO_INPUT_DATA, - COMPRESSOR_ERROR_NO_OUTPUT_POINTER, - COMPRESSOR_ERROR_UNSUPPORTED_SOURCE_FORMAT, - COMPRESSOR_ERROR_UNSUPPORTED_DESTINATION_FORMAT, - COMPRESSOR_ERROR_UNABLE_TO_INIT_CODEC, - COMPRESSOR_ERROR_GENERIC - } COMPRESSOR_ERROR; - ////////////////////////////////////////////////////////////////////////// - - // Methods -public: - CImage_DXTC(); - ~CImage_DXTC(); - - // Arguments: - // pQualityLoss - 0 if info is not needed, pointer to the result otherwise - not need to preinitialize - bool Load(const char* filename, CImageEx& outImage, bool* pQualityLoss = 0); // true if success - - static inline const char* NameForTextureFormat(ETEX_Format ETF) { return CImageExtensionHelper::NameForTextureFormat(ETF); } - static inline bool IsBlockCompressed(ETEX_Format ETF) { return CImageExtensionHelper::IsBlockCompressed(ETF); } - static inline bool IsLimitedHDR(ETEX_Format ETF) { return CImageExtensionHelper::IsRangeless(ETF); } - - int TextureDataSize(int nWidth, int nHeight, int nDepth, int nMips, ETEX_Format eTF); - -private: - static COMPRESSOR_ERROR CheckParameters( - int width, - int height, - UNCOMPRESSED_FORMAT destinationFormat, - const void* sourceData, - void* destinationData, - int destinationDataSize); - - static COMPRESSOR_ERROR DecompressTextureBTC( - int width, - int height, - ETEX_Format sourceFormat, - UNCOMPRESSED_FORMAT destinationFormat, - const int imageFlags, - const void* sourceData, - void* destinationData, - int destinationDataSize, - int destinationPageOffset); -}; - -#endif // CRYINCLUDE_EDITOR_UTIL_IMAGE_DXTC_H diff --git a/Code/Sandbox/Editor/Util/Ruler.cpp b/Code/Sandbox/Editor/Util/Ruler.cpp deleted file mode 100644 index 9f802b8b5e..0000000000 --- a/Code/Sandbox/Editor/Util/Ruler.cpp +++ /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. - -// Description : Ruler helper for Editor to determine distances - - -#include "EditorDefs.h" - -#include "Ruler.h" - -// Editor -#include "Settings.h" -#include "Viewport.h" -#include "Include/HitContext.h" -#include "Include/IObjectManager.h" -#include "Objects/BaseObject.h" - -// Qt -#include - -////////////////////////////////////////////////////////////////////////// -CRuler::CRuler() - : m_bActive(false) - , m_MouseOverObject(GUID_NULL) - , m_sphereScale(0.5f) - , m_sphereTrans(0.5f) -{ -} - -////////////////////////////////////////////////////////////////////////// -CRuler::~CRuler() -{ - SetActive(false); -} - -////////////////////////////////////////////////////////////////////////// -bool CRuler::HasQueuedPaths() const -{ - return false; -} - -////////////////////////////////////////////////////////////////////////// -void CRuler::SetActive(bool bActive) -{ - if (m_bActive != bActive) - { - m_bActive = bActive; - - if (m_bActive) - { - m_sphereScale = gSettings.gizmo.rulerSphereScale; - m_sphereTrans = gSettings.gizmo.rulerSphereTrans; - } - - // Reset - m_startPoint.Reset(); - m_endPoint.Reset(); - - CBaseObject* pObject = GetIEditor()->GetObjectManager()->FindObject(m_MouseOverObject); - if (pObject) - { - pObject->SetHighlight(false); - } - m_MouseOverObject = GUID_NULL; - } -} - -////////////////////////////////////////////////////////////////////////// -void CRuler::Update() -{ - if (!IsActive()) - { - return; - } - - if (CheckVirtualKey(Qt::Key_Escape)) - { - SetActive(false); - return; - } - - static const ColorF colours[] = - { - Col_Blue, - Col_Green, - Col_Red, - Col_Yellow, - Col_Magenta, - Col_Black, - }; - - IRenderer* pRenderer = GetIEditor()->GetSystem()->GetIRenderer(); - CRY_ASSERT(pRenderer); - IRenderAuxGeom* pAuxGeom = pRenderer->GetIRenderAuxGeom(); - CRY_ASSERT(pAuxGeom); - - CViewport* pActiveView = GetIEditor()->GetActiveView(); - if (pActiveView) - { - // Draw where cursor currently is - if (!IsObjectSelectMode(pActiveView)) - { - QPoint vCursorPoint = QCursor::pos(); - pActiveView->ScreenToClient(vCursorPoint); - vCursorPoint = QHighDpi::toNativePixels(vCursorPoint, QGuiApplication::screenAt(vCursorPoint)); - Vec3 vCursorWorldPos = pActiveView->SnapToGrid(pActiveView->ViewToWorld(vCursorPoint)); - Vec3 vOffset(0.1f, 0.1f, 0.1f); - pAuxGeom->SetRenderFlags(e_Def3DPublicRenderflags | e_AlphaBlended); - pAuxGeom->DrawSphere(vCursorWorldPos, m_sphereScale, ColorF(0.5, 0.5, 0.5, m_sphereTrans)); - pAuxGeom->DrawAABB(AABB(vCursorWorldPos - vOffset * m_sphereScale, vCursorWorldPos + vOffset * m_sphereScale), false, ColorF(1.0f, 0.0f, 0.0f, 1.0f), eBBD_Faceted); - } - - uint32 x = 12, y = 60; - - if (!m_startPoint.IsEmpty()) - { - //pAuxGeom->DrawSphere(m_startPoint.GetPos(), 1.0f, ColorB(255,255,255,255)); - m_startPoint.Render(pRenderer); - } - if (!m_endPoint.IsEmpty()) - { - //pAuxGeom->DrawSphere(m_endPoint.GetPos(), 1.0f, ColorB(255,255,255,255)); - m_endPoint.Render(pRenderer); - - pAuxGeom->DrawLine(m_startPoint.GetPos(), ColorB(255, 255, 255, 255), m_endPoint.GetPos(), ColorB(255, 255, 255, 255)); - - string sTempText; - - // Compute distance and output results - // TODO: Consider movement speed outputs here as well? - const float fDistance = m_startPoint.GetDistance(m_endPoint); - sTempText.Format("Straight-line distance: %.3f", fDistance); - - // Draw mid text - float white[] = {1.0f, 1.0f, 1.0f, 1.0f}; - pRenderer->Draw2dLabel(x, y, 2.0f, white, false, sTempText.c_str()); - y += 18; - } - } -} - -////////////////////////////////////////////////////////////////////////// -bool CRuler::IsObjectSelectMode([[maybe_unused]] CViewport* pView) const -{ - const bool bShiftDown = CheckVirtualKey(Qt::Key_Shift); - - return (bShiftDown); -} - -////////////////////////////////////////////////////////////////////////// -void CRuler::UpdateRulerPoint(CViewport* pView, const QPoint& point, CRulerPoint& rulerPoint, bool bRequestPath) -{ - CRY_ASSERT(pView); - - const bool bObjectSelect = IsObjectSelectMode(pView); - - rulerPoint.SetHelperSettings(m_sphereScale, m_sphereTrans); - - // Do entity hit check - if (bObjectSelect) - { - HitContext hitInfo; - pView->HitTest(point, hitInfo); - - CBaseObject* pHitObj = hitInfo.object; - rulerPoint.Set(pHitObj); - } - else - { - Vec3 vWorldPoint = pView->SnapToGrid(pView->ViewToWorld(point)); - rulerPoint.Set(vWorldPoint); - } - - if (bRequestPath) - { - RequestPath(); - } -} - -////////////////////////////////////////////////////////////////////////// -void CRuler::RequestPath() -{ -} - -////////////////////////////////////////////////////////////////////////// -bool CRuler::MouseCallback(CViewport* pView, EMouseEvent event, QPoint& point, int flags) -{ - bool bResult = IsActive(); - - if (bResult) - { - switch (event) - { - case eMouseMove: - OnMouseMove(pView, point, flags); - break; - case eMouseLUp: - OnLButtonUp(pView, point, flags); - break; - } - } - - return bResult; -} - -////////////////////////////////////////////////////////////////////////// -void CRuler::OnMouseMove(CViewport* pView, QPoint& point, [[maybe_unused]] int flags) -{ - GUID hitGUID = GUID_NULL; - - if (IsObjectSelectMode(pView)) - { - // Check for hit entity - HitContext hitInfo; - pView->HitTest(point, hitInfo); - CBaseObject* pHitObj = hitInfo.object; - if (pHitObj) - { - hitGUID = pHitObj->GetId(); - } - } - - if (hitGUID != m_MouseOverObject) - { - // Kill highlight on old - CBaseObject* pOldObj = GetIEditor()->GetObjectManager()->FindObject(m_MouseOverObject); - if (pOldObj) - { - pOldObj->SetHighlight(false); - } - - CBaseObject* pHitObj = GetIEditor()->GetObjectManager()->FindObject(hitGUID); - if (pHitObj) - { - pHitObj->SetHighlight(true); - } - - m_MouseOverObject = hitGUID; - } -} - -////////////////////////////////////////////////////////////////////////// -void CRuler::OnLButtonUp(CViewport* pView, QPoint& point, [[maybe_unused]] int flags) -{ - if (m_startPoint.IsEmpty()) - { - UpdateRulerPoint(pView, point, m_startPoint, false); - } - else if (m_endPoint.IsEmpty()) - { - UpdateRulerPoint(pView, point, m_endPoint, true); - } - else - { - UpdateRulerPoint(pView, point, m_startPoint, false); - m_endPoint.Reset(); - } -} diff --git a/Code/Sandbox/Editor/Util/Ruler.h b/Code/Sandbox/Editor/Util/Ruler.h deleted file mode 100644 index 1e04e2a1f9..0000000000 --- a/Code/Sandbox/Editor/Util/Ruler.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. - -// Description : Ruler helper for Editor to determine distances - - -#ifndef CRYINCLUDE_EDITOR_UTIL_RULER_H -#define CRYINCLUDE_EDITOR_UTIL_RULER_H -#pragma once - - -#include "RulerPoint.h" - -//! The Ruler utility helps to determine distances between user-specified points -class CRuler -{ -public: - CRuler(); - ~CRuler(); - - //! Returns if ruler has queued paths in the path agent - bool HasQueuedPaths() const; - - //! Activate the ruler - void SetActive(bool bActive); - bool IsActive() const { return m_bActive; } - - //! Update - void Update(); - - //! Mouse callback handling from viewport - bool MouseCallback(CViewport* pView, EMouseEvent event, QPoint& point, int flags); - -private: - //! Mouse callback helpers - void OnMouseMove(CViewport* pView, QPoint& point, int flags); - void OnLButtonUp(CViewport* pView, QPoint& point, int flags); - - //! Returns world point based on mouse point - void UpdateRulerPoint(CViewport* pView, const QPoint& point, CRulerPoint& rulerPoint, bool bRequestPath); - - //! Request a path using the path agent - void RequestPath(); - - bool IsObjectSelectMode(CViewport* pView) const; - -private: - bool m_bActive; - GUID m_MouseOverObject; - - // Base point - CRulerPoint m_startPoint; - CRulerPoint m_endPoint; - - float m_sphereScale; - float m_sphereTrans; -}; - -#endif // CRYINCLUDE_EDITOR_UTIL_RULER_H diff --git a/Code/Sandbox/Editor/Util/RulerPoint.cpp b/Code/Sandbox/Editor/Util/RulerPoint.cpp deleted file mode 100644 index d9f148d26a..0000000000 --- a/Code/Sandbox/Editor/Util/RulerPoint.cpp +++ /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. - -// Description : Ruler helper for Editor to determine distances - - -#include "EditorDefs.h" - -#include "RulerPoint.h" - -// Editor -#include "Objects/BaseObject.h" -#include "Include/IObjectManager.h" - -////////////////////////////////////////////////////////////////////////// -CRulerPoint::CRulerPoint() - : m_type(eType_Invalid) - , m_vPoint(ZERO) - , m_ObjectGUID(GUID_NULL) -{ - Reset(); -} - -////////////////////////////////////////////////////////////////////////// -CRulerPoint& CRulerPoint::operator =(CRulerPoint const& other) -{ - if (this != &other) - { - Reset(); // Manage deselect of current object, etc. - - m_type = other.m_type; - m_vPoint = other.m_vPoint; - m_ObjectGUID = other.m_ObjectGUID; - m_sphereScale = other.m_sphereScale; - m_sphereTrans = other.m_sphereTrans; - } - - return *this; -} - -////////////////////////////////////////////////////////////////////////// -void CRulerPoint::Reset() -{ - // Kill highlight of current object - CBaseObject* pObject = GetObject(); - if (pObject) - { - pObject->SetHighlight(false); - } - - m_type = eType_Invalid; - m_vPoint.zero(); - m_ObjectGUID = GUID_NULL; -} - -////////////////////////////////////////////////////////////////////////// -void CRulerPoint::Render(IRenderer* pRenderer) -{ - CRY_ASSERT(pRenderer); - IRenderAuxGeom* pAuxGeom = pRenderer->GetIRenderAuxGeom(); - - switch (m_type) - { - case eType_Point: - { - Vec3 vOffset(0.1f, 0.1f, 0.1f); - pAuxGeom->SetRenderFlags(e_Def3DPublicRenderflags | e_AlphaBlended); - pAuxGeom->DrawSphere(m_vPoint, m_sphereScale, ColorF(1, 1, 1, m_sphereTrans)); - pAuxGeom->DrawAABB(AABB(m_vPoint - vOffset * m_sphereScale, m_vPoint + vOffset * m_sphereScale), false, ColorF(0.0f, 1.0f, 0.0f, 1.0f), eBBD_Faceted); - } - break; - - case eType_Object: - { - CBaseObject* pObject = GetObject(); - if (pObject) - { - pObject->SetHighlight(true); - } - } - break; - - default: - return; // No extra drawing - } -} - -////////////////////////////////////////////////////////////////////////// -void CRulerPoint::Set(const Vec3& vPos) -{ - Reset(); - - m_type = eType_Point; - m_vPoint = vPos; -} - -////////////////////////////////////////////////////////////////////////// -void CRulerPoint::Set(CBaseObject* pObject) -{ - Reset(); - - m_type = eType_Object; - m_ObjectGUID = (pObject ? pObject->GetId() : GUID_NULL); -} - -////////////////////////////////////////////////////////////////////////// -void CRulerPoint::SetHelperSettings(float scale, float trans) -{ - m_sphereScale = scale; - m_sphereTrans = trans; -} - -////////////////////////////////////////////////////////////////////////// -bool CRulerPoint::IsEmpty() const -{ - bool bResult = true; - - switch (m_type) - { - case eType_Invalid: - bResult = true; - break; - - case eType_Point: - bResult = m_vPoint.IsZero(); - break; - - case eType_Object: - bResult = (GetObject() == 0); - break; - } - - return bResult; -} - -////////////////////////////////////////////////////////////////////////// -Vec3 CRulerPoint::GetPos() const -{ - Vec3 vResult(ZERO); - - switch (m_type) - { - case eType_Point: - vResult = m_vPoint; - break; - - case eType_Object: - { - CBaseObject* pObject = GetObject(); - if (pObject) - { - vResult = pObject->GetWorldPos(); - } - } - break; - } - - return vResult; -} - -////////////////////////////////////////////////////////////////////////// -Vec3 CRulerPoint::GetMidPoint(const CRulerPoint& otherPoint) const -{ - Vec3 vResult(ZERO); - - if (!IsEmpty() && !otherPoint.IsEmpty()) - { - vResult = GetPos() + (otherPoint.GetPos() - GetPos()) * 0.5f; - } - else if (!IsEmpty()) - { - vResult = GetPos(); - } - else - { - vResult = otherPoint.GetPos(); - } - - return vResult; -} - -////////////////////////////////////////////////////////////////////////// -float CRulerPoint::GetDistance(const CRulerPoint& otherPoint) const -{ - float fResult = 0.0f; - - if (!IsEmpty() && !otherPoint.IsEmpty()) - { - fResult = GetPos().GetDistance(otherPoint.GetPos()); - } - - return fResult; -} - -////////////////////////////////////////////////////////////////////////// -CBaseObject* CRulerPoint::GetObject() const -{ - CBaseObject* pResult = NULL; - - if (m_type == eType_Object) - { - pResult = GetIEditor()->GetObjectManager()->FindObject(m_ObjectGUID); - } - - return pResult; -} diff --git a/Code/Sandbox/Editor/Util/RulerPoint.h b/Code/Sandbox/Editor/Util/RulerPoint.h deleted file mode 100644 index 0d68c9450c..0000000000 --- a/Code/Sandbox/Editor/Util/RulerPoint.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. - -// Description : Ruler point helper, used by CRuler - - -#ifndef CRYINCLUDE_EDITOR_UTIL_RULERPOINT_H -#define CRYINCLUDE_EDITOR_UTIL_RULERPOINT_H -#pragma once - - -class CRuler; - -//! Ruler point helper - Defines a point for the ruler -class CRulerPoint -{ -public: - CRulerPoint(); - CRulerPoint& operator =(CRulerPoint const& other); - - void Reset(); - void Render(IRenderer* pRenderer); - - //! Set helpers - void Set(const Vec3& vPos); - void Set(CBaseObject* pObject); - void SetHelperSettings(float scale, float trans); - - //! Returns is point has valid data in it (in use) - bool IsEmpty() const; - - //! Helpers to get correct data out - Vec3 GetPos() const; - Vec3 GetMidPoint(const CRulerPoint& otherPoint) const; - float GetDistance(const CRulerPoint& otherPoint) const; - CBaseObject* GetObject() const; - -private: - enum EType - { - eType_Invalid, - eType_Point, - eType_Object, - - eType_COUNT, - }; - EType m_type; - - Vec3 m_vPoint; - GUID m_ObjectGUID; - float m_sphereScale; - float m_sphereTrans; -}; - -#endif // CRYINCLUDE_EDITOR_UTIL_RULERPOINT_H diff --git a/Code/Sandbox/Editor/ViewManager.cpp b/Code/Sandbox/Editor/ViewManager.cpp index 334e78a826..8bb14a3aca 100644 --- a/Code/Sandbox/Editor/ViewManager.cpp +++ b/Code/Sandbox/Editor/ViewManager.cpp @@ -49,8 +49,6 @@ bool CViewManager::IsMultiViewportEnabled() ////////////////////////////////////////////////////////////////////// CViewManager::CViewManager() { - gSettings.pGrid = &m_grid; - m_zoomFactor = 1; m_origin2D(0, 0, 0); diff --git a/Code/Sandbox/Editor/ViewManager.h b/Code/Sandbox/Editor/ViewManager.h index d617b5c54e..e2b42573d5 100644 --- a/Code/Sandbox/Editor/ViewManager.h +++ b/Code/Sandbox/Editor/ViewManager.h @@ -20,7 +20,6 @@ #pragma once #include "Cry_Geo.h" -#include "Grid.h" #include "Viewport.h" #include "Include/IViewPane.h" #include "QtViewPaneManager.h" @@ -67,10 +66,6 @@ public: void SetUpdateRegion(const AABB& updateRegion) { m_updateRegion = updateRegion; }; const AABB& GetUpdateRegion() { return m_updateRegion; }; - /** Retrieve Grid used for viewes. - */ - CGrid* GetGrid() { return &m_grid; }; - /** Get 2D viewports origin. */ Vec3 GetOrigin2D() const { return m_origin2D; } @@ -137,7 +132,6 @@ private: AZ_PUSH_DISABLE_DLL_EXPORT_MEMBER_WARNING AABB m_updateRegion; - CGrid m_grid; //! Origin of 2d viewports. Vec3 m_origin2D; //! Zoom of 2d viewports. diff --git a/Code/Sandbox/Editor/ViewPane.cpp b/Code/Sandbox/Editor/ViewPane.cpp index 480e39bedf..eda0f390fa 100644 --- a/Code/Sandbox/Editor/ViewPane.cpp +++ b/Code/Sandbox/Editor/ViewPane.cpp @@ -643,27 +643,6 @@ void CLayoutViewPane::SetFullscren(bool f) m_bFullscreen = f; } -////////////////////////////////////////////////////////////////////////// -void CLayoutViewPane::SetFullscreenViewport(bool b) -{ - if (!m_viewport) - { - return; - } - - if (b) - { - m_viewport->setParent(0); - - GetIEditor()->GetRenderer()->ChangeResolution(800, 600, 32, 80, true, false); - } - else - { - m_viewport->setParent(this); - GetIEditor()->GetRenderer()->ChangeResolution(800, 600, 32, 80, false, false); - } -} - ////////////////////////////////////////////////////////////////////////// void CLayoutViewPane::SetFocusToViewport() { diff --git a/Code/Sandbox/Editor/ViewPane.h b/Code/Sandbox/Editor/ViewPane.h index 53d13c105d..80647e7a15 100644 --- a/Code/Sandbox/Editor/ViewPane.h +++ b/Code/Sandbox/Editor/ViewPane.h @@ -63,8 +63,6 @@ public: void SetFullscren(bool f); bool IsFullscreen() const { return m_bFullscreen; } - void SetFullscreenViewport(bool b); - QWidget* GetViewport() { return m_viewport; } ////////////////////////////////////////////////////////////////////////// diff --git a/Code/Sandbox/Editor/Viewport.cpp b/Code/Sandbox/Editor/Viewport.cpp index 37a9ee5f29..da4a389aa0 100644 --- a/Code/Sandbox/Editor/Viewport.cpp +++ b/Code/Sandbox/Editor/Viewport.cpp @@ -30,7 +30,6 @@ #include "Include/HitContext.h" #include "Objects/ObjectManager.h" #include "Util/3DConnexionDriver.h" -#include "Util/Ruler.h" #include "PluginManager.h" #include "Include/IRenderListener.h" #include "GameEngine.h" @@ -1183,12 +1182,12 @@ float QtViewport::GetZoomFactor() const ////////////////////////////////////////////////////////////////////////// Vec3 QtViewport::SnapToGrid(const Vec3& vec) { - return m_viewManager->GetGrid()->Snap(vec, m_fGridZoom); + return vec; } float QtViewport::GetGridStep() const { - return m_viewManager->GetGrid()->scale * m_viewManager->GetGrid()->size; + return 0.0f; } ////////////////////////////////////////////////////////////////////////// @@ -1414,17 +1413,7 @@ bool QtViewport::MouseCallback(EMouseEvent event, const QPoint& point, Qt::Keybo break; } - ////////////////////////////////////////////////////////////////////////// - // Asks Ruler to handle mouse callback. - CRuler* pRuler = GetIEditor()->GetRuler(); QPoint tempPoint(point.x(), point.y()); - if (pRuler) - { - if (pRuler->MouseCallback(this, event, tempPoint, flags)) - { - return true; - } - } ////////////////////////////////////////////////////////////////////////// // Handle viewport manipulators. 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) - { - 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; -} - -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) - { - return false; } - using InteractionBus = AzToolsFramework::EditorInteractionSystemViewportSelectionRequestBus; - using namespace AzToolsFramework::ViewportInteraction; - using AzFramework::InputChannel; - - bool interactionHandled = false; - 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; - - if (IsMouseMove(event.m_inputChannel)) + AzToolsFramework::ViewportInteraction::MouseButton ViewportManipulatorControllerInstance::GetMouseButton( + const AzFramework::InputChannel& inputChannel) { - // Cache the ray trace results when doing manipulator interaction checks, no need to recalculate after - if (event.m_priority == ManipulatorPriority) + using AzToolsFramework::ViewportInteraction::MouseButton; + using InputButton = AzFramework::InputDeviceMouse::Button; + const auto& id = inputChannel.GetInputChannelId(); + if (id == InputButton::Left) { - 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); - - if (ray.has_value()) - { - m_state.m_mousePick.m_rayOrigin = ray.value().origin; - m_state.m_mousePick.m_rayDirection = ray.value().direction; - } + return MouseButton::Left; } - 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) + if (id == InputButton::Middle) { - m_state.m_mouseButtons.m_mouseButtons |= mouseButtonValue; - if (IsDoubleClick(mouseButton)) + 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) + { + 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; + } + + 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) + { + return false; + } + + using InteractionBus = AzToolsFramework::EditorInteractionSystemViewportSelectionRequestBus; + using namespace AzToolsFramework::ViewportInteraction; + using AzFramework::InputChannel; + + 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; + + const auto state = event.m_inputChannel.GetState(); + 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) { - // Only remove the double click flag once we're done processing both Manipulator and Interaction events - if (event.m_priority == InteractionPriority) + AzFramework::ScreenPoint screenPosition = AzFramework::ScreenPoint(0, 0); + ViewportMouseCursorRequestBus::EventResult( + screenPosition, GetViewportId(), &ViewportMouseCursorRequestBus::Events::ViewportCursorScreenPosition); + + m_mouseInteraction.m_mousePick.m_screenCoordinates = screenPosition; + AZStd::optional ray; + ViewportInteractionRequestBus::EventResult( + ray, GetViewportId(), &ViewportInteractionRequestBus::Events::ViewportScreenToWorldRay, screenPosition); + + if (ray.has_value()) { - m_pendingDoubleClicks.erase(mouseButton); + m_mouseInteraction.m_mousePick.m_rayOrigin = ray.value().origin; + m_mouseInteraction.m_mousePick.m_rayDirection = ray.value().direction; } - eventType = MouseEvent::DoubleClick; } - else + eventType = MouseEvent::Move; + } + else if (auto mouseButton = GetMouseButton(event.m_inputChannel); mouseButton != MouseButton::None) + { + const AZ::u32 mouseButtonValue = static_cast(mouseButton); + overrideButton = mouseButton; + if (state == InputChannel::State::Began) { - // Only insert the double click timing once we're done processing events, to avoid a false IsDoubleClick positive - if (finishedProcessingEvents) + m_mouseInteraction.m_mouseButtons.m_mouseButtons |= mouseButtonValue; + if (IsDoubleClick(mouseButton)) { - m_pendingDoubleClicks[mouseButton] = m_curTime; + // 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 + { + // 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::Down; } - } - else if (event.m_inputChannel.GetState() == InputChannel::State::Ended) - { - // 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) + else if (state == InputChannel::State::Ended) { - // Erase the button from our state if we're done processing events. - if (event.m_priority == InteractionPriority) + // 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_state.m_mouseButtons.m_mouseButtons &= ~mouseButtonValue; + // 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::Up; } } - } - 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 (auto keyboardModifier = GetKeyboardModifier(event.m_inputChannel); keyboardModifier != KeyboardModifier::None) { - m_state.m_keyboardModifiers.m_keyModifiers |= static_cast(keyboardModifier); + if (state == InputChannel::State::Began || state == InputChannel::State::Updated) + { + 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 (event.m_inputChannel.GetState() == InputChannel::State::Ended) + 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(); + } } - } - if (eventType) - { - MouseInteraction mouseInteraction = m_state; - if (overrideButton) + if (eventType) { - mouseInteraction.m_mouseButtons.m_mouseButtons = static_cast(overrideButton.value()); + 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); } - 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())); + return interactionHandled; } - 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::ResetInputChannels() { - return false; + m_pendingDoubleClicks.clear(); + m_mouseInteraction = AzToolsFramework::ViewportInteraction::MouseInteraction(); } - const double doubleClickThresholdMilliseconds = qApp->doubleClickInterval(); - return (m_curTime.GetMilliseconds() - clickIt->second.GetMilliseconds()) < doubleClickThresholdMilliseconds; -} + 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()) + { + 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/Code/Sandbox/Editor/ViewportTitleDlg.cpp b/Code/Sandbox/Editor/ViewportTitleDlg.cpp index 427a5c32e8..95531e117c 100644 --- a/Code/Sandbox/Editor/ViewportTitleDlg.cpp +++ b/Code/Sandbox/Editor/ViewportTitleDlg.cpp @@ -95,8 +95,6 @@ CViewportTitleDlg::~CViewportTitleDlg() { GetISystem()->GetISystemEventDispatcher()->RemoveListener(this); GetIEditor()->UnregisterNotifyListener(this); - ICVar* pDisplayInfo(gEnv->pConsole->GetCVar("r_displayInfo")); - pDisplayInfo->RemoveOnChangeFunctor(m_displayInfoCallbackIndex); } ////////////////////////////////////////////////////////////////////////// @@ -158,8 +156,6 @@ void CViewportTitleDlg::OnToggleHelpers() ////////////////////////////////////////////////////////////////////////// void CViewportTitleDlg::OnToggleDisplayInfo() { - int currentDisplayInfo = gEnv->pConsole->GetCVar("r_displayInfo")->GetIVal(); - gEnv->pConsole->GetCVar("r_displayInfo")->Set(currentDisplayInfo >= 3 ? 0 : currentDisplayInfo + 1); } ////////////////////////////////////////////////////////////////////////// @@ -548,12 +544,8 @@ void CViewportTitleDlg::UpdateCustomPresets(const QString& text, QStringList& cu } } -void CViewportTitleDlg::OnChangedDisplayInfo([[maybe_unused]] ICVar* pDisplayInfo, QAbstractButton* pDisplayInfoButton) +void CViewportTitleDlg::OnChangedDisplayInfo([[maybe_unused]] ICVar* pDisplayInfo, [[maybe_unused]] QAbstractButton* pDisplayInfoButton) { - if (pDisplayInfoButton) - { - pDisplayInfoButton->setChecked(gEnv->pConsole->GetCVar("r_displayInfo")->GetIVal()); - } } bool CViewportTitleDlg::eventFilter(QObject* object, QEvent* event) diff --git a/Code/Sandbox/Editor/editor_core_files.cmake b/Code/Sandbox/Editor/editor_core_files.cmake index 1aecbd03f6..486408159a 100644 --- a/Code/Sandbox/Editor/editor_core_files.cmake +++ b/Code/Sandbox/Editor/editor_core_files.cmake @@ -22,6 +22,8 @@ set(FILES Include/IEditorMaterial.h Include/IEditorMaterialManager.h Include/IImageUtil.h + EditorViewportSettings.cpp + EditorViewportSettings.h Controls/ReflectedPropertyControl/ReflectedPropertyCtrl.qrc Controls/ReflectedPropertyControl/ReflectedPropertyCtrl.cpp Controls/ReflectedPropertyControl/ReflectedPropertyCtrl.h diff --git a/Code/Sandbox/Editor/editor_lib_files.cmake b/Code/Sandbox/Editor/editor_lib_files.cmake index f6537909e9..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 @@ -357,8 +351,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 @@ -437,9 +429,6 @@ set(FILES GotoPositionDlg.cpp GotoPositionDlg.h GotoPositionDlg.ui - GridSettingsDialog.cpp - GridSettingsDialog.h - GridSettingsDialog.ui InfoBar.cpp InfoBar.qrc InfoBar.h @@ -465,9 +454,6 @@ set(FILES SelectLightAnimationDialog.h SelectSequenceDialog.cpp SelectSequenceDialog.h - ShadersDialog.cpp - ShadersDialog.h - ShadersDialog.ui StartupLogoDialog.cpp StartupLogoDialog.h StartupLogoDialog.ui @@ -581,11 +567,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 @@ -659,10 +640,6 @@ set(FILES ProcessInfo.cpp ProcessInfo.h Report.h - ShaderCache.cpp - ShaderCache.h - ShaderEnum.cpp - ShaderEnum.h SurfaceTypeValidator.cpp SurfaceTypeValidator.h TrackView/AtomOutputFrameCapture.cpp @@ -748,18 +725,12 @@ set(FILES TrackView/TrackViewEventNode.h ConfigGroup.cpp ConfigGroup.h - SettingsBlock.cpp - SettingsBlock.h Util/AffineParts.h - Util/ArcBall.cpp - Util/ArcBall.h Util/AutoLogTime.cpp Util/AutoLogTime.h Util/AutoDirectoryRestoreFileDialog.h Util/AutoDirectoryRestoreFileDialog.cpp Util/CryMemFile.h - Util/CubemapUtils.cpp - Util/CubemapUtils.h Util/DynamicArray2D.cpp Util/DynamicArray2D.h Util/EditorAutoLevelLoadTest.cpp @@ -833,17 +804,11 @@ set(FILES Util/ImageASC.h Util/ImageBT.cpp Util/ImageBT.h - Util/Image_DXTC.cpp - Util/Image_DXTC.h Util/ImageGif.cpp Util/ImageGif.h Util/ImageTIF.cpp Util/ImageTIF.h Util/Math.h - Util/Ruler.cpp - Util/RulerPoint.cpp - Util/Ruler.h - Util/RulerPoint.h Util/UIEnumerations.cpp Util/UIEnumerations.h WelcomeScreen/WelcomeScreenDialog.h @@ -852,8 +817,6 @@ set(FILES WelcomeScreen/WelcomeScreenDialog.qrc 2DViewport.cpp 2DViewport.h - Grid.cpp - Grid.h LayoutWnd.cpp LayoutWnd.h EditorViewportWidget.cpp diff --git a/Code/Sandbox/Plugins/ComponentEntityEditorPlugin/ComponentEntityDebugPrinter.cpp b/Code/Sandbox/Plugins/ComponentEntityEditorPlugin/ComponentEntityDebugPrinter.cpp deleted file mode 100644 index 2eff76c738..0000000000 --- a/Code/Sandbox/Plugins/ComponentEntityEditorPlugin/ComponentEntityDebugPrinter.cpp +++ /dev/null @@ -1,71 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -#include "ComponentEntityEditorPlugin_precompiled.h" -#include "ComponentEntityDebugPrinter.h" - -#include -#include - -ComponentEntityDebugPrinter::ComponentEntityDebugPrinter() -{ - AZ::TickBus::Handler::BusConnect(); -} - -void ComponentEntityDebugPrinter::OnTick(float /*deltaTime*/, AZ::ScriptTimePoint /*time*/) -{ - if (!GetIEditor()->GetRenderer()) - { - return; - } - - ICVar* displayInfo = GetIEditor()->GetSystem()->GetIConsole()->GetCVar("r_DisplayInfo"); - if (!displayInfo || displayInfo->GetIVal() == 0) - { - return; - } - - float x = 2.f; - float y = 2.f; - - SDrawTextInfo textInfo; - textInfo.xscale = 1.25f; - textInfo.yscale = textInfo.xscale; - textInfo.flags = eDrawText_2D | eDrawText_FixedSize | eDrawText_800x600 | eDrawText_Monospace; - - // Figure out whether we're querying the Game or Editor entity context - AzFramework::EntityContextId entityContextId = AzFramework::EntityContextId::CreateNull(); - if (GetIEditor()->IsInGameMode()) - { - AzFramework::GameEntityContextRequestBus::BroadcastResult(entityContextId, &AzFramework::GameEntityContextRequestBus::Events::GetGameEntityContextId); - } - else - { - AzToolsFramework::EditorEntityContextRequestBus::BroadcastResult(entityContextId, &AzToolsFramework::EditorEntityContextRequestBus::Events::GetEditorEntityContextId); - } - if (entityContextId.IsNull()) - { - return; - } - - // Print the number of entities in the level - AZ::SliceComponent* rootSlice = nullptr; - AzFramework::SliceEntityOwnershipServiceRequestBus::EventResult(rootSlice, entityContextId, - &AzFramework::SliceEntityOwnershipServiceRequestBus::Events::GetRootSlice); - if (rootSlice) - { - size_t numEntities = rootSlice->GetInstantiatedEntityCount(); - if (numEntities > 0) - { - GetIEditor()->GetRenderer()->DrawTextQueued(Vec3(x, y, 0), textInfo, AZStd::string::format("Entities: %zu", numEntities).c_str()); - } - } -} diff --git a/Code/Sandbox/Plugins/ComponentEntityEditorPlugin/ComponentEntityDebugPrinter.h b/Code/Sandbox/Plugins/ComponentEntityEditorPlugin/ComponentEntityDebugPrinter.h deleted file mode 100644 index 5a8c1d4856..0000000000 --- a/Code/Sandbox/Plugins/ComponentEntityEditorPlugin/ComponentEntityDebugPrinter.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. -* -*/ -#pragma once - -#include - -/** - * Prints debug statistics about Component Entities to screen - */ -class ComponentEntityDebugPrinter - : private AZ::TickBus::Handler -{ -public: - AZ_CLASS_ALLOCATOR(ComponentEntityDebugPrinter, AZ::SystemAllocator, 0); - - ComponentEntityDebugPrinter(); - -private: - ////////////////////////////////////////////////////////////////////////// - // TickBus - void OnTick(float deltaTime, AZ::ScriptTimePoint time) override; - ////////////////////////////////////////////////////////////////////////// -}; 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/ComponentEntityEditorPlugin/Objects/ComponentEntityObject.cpp b/Code/Sandbox/Plugins/ComponentEntityEditorPlugin/Objects/ComponentEntityObject.cpp index 20ae0a74cd..053cfb45c9 100644 --- a/Code/Sandbox/Plugins/ComponentEntityEditorPlugin/Objects/ComponentEntityObject.cpp +++ b/Code/Sandbox/Plugins/ComponentEntityEditorPlugin/Objects/ComponentEntityObject.cpp @@ -907,14 +907,6 @@ void CComponentEntityObject::Display(DisplayContext& dc) m_entityId, &AzFramework::EntityDebugDisplayEvents::DisplayEntityViewport, AzFramework::ViewportInfo{ dc.GetView()->asCViewport()->GetViewportId() }, *debugDisplay); - - if (showIcons) - { - if (!displaySelectionHelper && !IsSelected()) - { - m_entityIconVisible = DisplayEntityIcon(dc, *debugDisplay); - } - } } } } @@ -976,38 +968,6 @@ void CComponentEntityObject::OnContextMenu(QMenu* /*pMenu*/) // Deliberately bypass the base class implementation (CEntityObject::OnContextMenu()). } -bool CComponentEntityObject::DisplayEntityIcon( - DisplayContext& displayContext, AzFramework::DebugDisplayRequests& debugDisplay) -{ - if (!m_hasIcon) - { - return false; - } - - const QPoint entityScreenPos = displayContext.GetView()->WorldToView(GetWorldPos()); - - const Vec3 worldPos = GetWorldPos(); - const CCamera& camera = gEnv->pRenderer->GetCamera(); - const Vec3 cameraToEntity = (worldPos - camera.GetMatrix().GetTranslation()); - const float distSq = cameraToEntity.GetLengthSquared(); - if (distSq > square(s_kIconMaxWorldDist)) - { - return false; - } - - // Draw component icons on top of meshes (no depth testing) - int iconFlags = (int) DisplayContext::ETextureIconFlags::TEXICON_ON_TOP; - SetDrawTextureIconProperties(displayContext, worldPos, 1.0f, iconFlags); - - const float iconScale = s_kIconMinScale + (s_kIconMaxScale - s_kIconMinScale) * (1.0f - clamp_tpl(max(0.0f, sqrt_tpl(distSq) - s_kIconCloseDist) / s_kIconFarDist, 0.0f, 1.0f)); - const float worldDistToScreenScaleFraction = 0.045f; - const float screenScale = displayContext.GetView()->GetScreenScaleFactor(GetWorldPos()) * worldDistToScreenScaleFraction; - - debugDisplay.DrawTextureLabel(m_iconTexture, LYVec3ToAZVec3(worldPos), s_kIconSize * iconScale, s_kIconSize * iconScale, GetTextureIconFlags()); - - return true; -} - void CComponentEntityObject::SetupEntityIcon() { bool hideIconInViewport = false; @@ -1023,8 +983,9 @@ void CComponentEntityObject::SetupEntityIcon() { m_hasIcon = true; - int textureId = GetIEditor()->GetIconManager()->GetIconTexture(m_icon.c_str()); - m_iconTexture = GetIEditor()->GetRenderer() ? GetIEditor()->GetRenderer()->EF_GetTextureByID(textureId) : nullptr; + // ToDo: Get from Atom? + // int textureId = GetIEditor()->GetIconManager()->GetIconTexture(m_icon.c_str()); + m_iconTexture = nullptr; } } } diff --git a/Code/Sandbox/Plugins/ComponentEntityEditorPlugin/SandboxIntegration.cpp b/Code/Sandbox/Plugins/ComponentEntityEditorPlugin/SandboxIntegration.cpp index c7c501c70a..f38b295128 100644 --- a/Code/Sandbox/Plugins/ComponentEntityEditorPlugin/SandboxIntegration.cpp +++ b/Code/Sandbox/Plugins/ComponentEntityEditorPlugin/SandboxIntegration.cpp @@ -59,7 +59,6 @@ #include #include "Objects/ComponentEntityObject.h" -#include "ComponentEntityDebugPrinter.h" #include "ISourceControl.h" #include "UI/QComponentEntityEditorMainWindow.h" @@ -72,7 +71,6 @@ #include #include #include -#include #include #include #include @@ -141,7 +139,6 @@ SandboxIntegrationManager::SandboxIntegrationManager() , m_startedUndoRecordingNestingLevel(0) , m_dc(nullptr) , m_notificationWindowManager(new AzToolsFramework::SliceOverridesNotificationWindowManager()) - , m_entityDebugPrinter(aznew ComponentEntityDebugPrinter()) { // Required to receive events from the Cry Engine undo system GetIEditor()->GetUndoManager()->AddListener(this); @@ -163,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); @@ -1929,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); @@ -1998,92 +1970,6 @@ void SandboxIntegrationManager::BrowseForAssets(AssetSelectionModel& selection) AssetBrowserComponentRequestBus::Broadcast(&AssetBrowserComponentRequests::PickAssets, selection, GetMainWindow()); } -void SandboxIntegrationManager::GenerateCubemapForEntity(AZ::EntityId entityId, AZStd::string* cubemapOutputPath, bool hideEntity) -{ - GenerateCubemapWithIDForEntity(entityId, AZ::Uuid::CreateNull(), cubemapOutputPath, hideEntity, false); -} - -void SandboxIntegrationManager::GenerateCubemapWithIDForEntity(AZ::EntityId entityId, AZ::Uuid cubemapId, - AZStd::string* cubemapOutputPath, bool hideEntity, bool hasCubemapId) -{ - AZ::u32 resolution = 0; - EBUS_EVENT_ID_RESULT(resolution, entityId, LmbrCentral::EditorLightComponentRequestBus, GetCubemapResolution); - - if (resolution > 0) - { - CComponentEntityObject* componentEntity = CComponentEntityObject::FindObjectForEntity(entityId); - - if (componentEntity) - { - QString levelfolder = GetIEditor()->GetGameEngine()->GetLevelPath(); - QString levelname = Path::GetFile(levelfolder).toLower(); - QString fullGameFolder = QString(Path::GetEditingGameDataFolder().c_str()); - QString texturename; - if (hasCubemapId) - { - texturename = QStringLiteral("%1_cm.tif").arg(cubemapId.ToString(false, false)); - } - else - { - texturename = QStringLiteral("%1_cm.tif").arg(static_cast(componentEntity->GetAssociatedEntityId())); - } - texturename = texturename.toLower(); - - QString fullFolder = Path::SubDirectoryCaseInsensitive(fullGameFolder, {"textures", "cubemaps", levelname}); - QString fullFilename = QDir(fullFolder).absoluteFilePath(texturename); - QString relFilename = QDir(fullGameFolder).relativeFilePath(fullFilename); - - bool directlyExists = CFileUtil::CreateDirectory(fullFolder.toUtf8().data()); - if (!directlyExists) - { - QMessageBox::warning(GetMainWindow(), QObject::tr("Cubemap Generation Failed"), QString(QObject::tr("Failed to create destination path '%1'")).arg(fullFolder)); - return; - } - - if (CubemapUtils::GenCubemapWithObjectPathAndSize(fullFilename, componentEntity, static_cast(resolution), hideEntity)) - { - AZStd::string assetPath = relFilename.toUtf8().data(); - AzFramework::StringFunc::Path::ReplaceExtension(assetPath, ".dds"); - - EBUS_EVENT_ID(entityId, LmbrCentral::EditorLightComponentRequestBus, SetCubemap, assetPath); - - if (cubemapOutputPath) - { - *cubemapOutputPath = AZStd::move(assetPath); - } - } - else - { - QMessageBox::warning(GetMainWindow(), QObject::tr("Cubemap Generation Failed"), QObject::tr("Unspecified error")); - } - } - } -} - -void SandboxIntegrationManager::GenerateAllCubemaps() -{ - AZStd::string cubemapOutputPath; - - std::vector results; - results.reserve(128); - GetIEditor()->GetObjectManager()->FindObjectsOfType(OBJTYPE_AZENTITY, results); - for (std::vector::iterator end = results.end(), item = results.begin(); item != end; ++item) - { - CComponentEntityObject* componentEntity = static_cast(*item); - - //check if it's customized cubemap, only generate it if it's not. - bool isCustomizedCubemap = true; - EBUS_EVENT_ID_RESULT(isCustomizedCubemap, componentEntity->GetAssociatedEntityId(), LmbrCentral::EditorLightComponentRequestBus, UseCustomizedCubemap); - - if (isCustomizedCubemap) - { - continue; - } - - GenerateCubemapForEntity(componentEntity->GetAssociatedEntityId(), nullptr, true); - } -} - void SandboxIntegrationManager::SetColor(float r, float g, float b, float a) { if (m_dc) @@ -2575,19 +2461,6 @@ void SandboxIntegrationManager::Draw2dTextLabel(float x, float y, float size, co } } -void SandboxIntegrationManager::DrawTextOn2DBox(const AZ::Vector3& pos, const char* text, float textScale, const AZ::Vector4& textColor, const AZ::Vector4& textBackColor) -{ - if (m_dc) - { - m_dc->DrawTextOn2DBox( - AZVec3ToLYVec3(pos), - text, - textScale, - ColorF(AZVec3ToLYVec3(textColor.GetAsVector3()), textColor.GetW()), - ColorF(AZVec3ToLYVec3(textBackColor.GetAsVector3()), textBackColor.GetW())); - } -} - void SandboxIntegrationManager::DrawTextureLabel(ITexture* texture, const AZ::Vector3& pos, float sizeX, float sizeY, int texIconFlags) { if (m_dc) @@ -2614,8 +2487,12 @@ void SandboxIntegrationManager::DrawTextureLabel(ITexture* texture, const AZ::Ve void SandboxIntegrationManager::DrawTextureLabel(int textureId, const AZ::Vector3& pos, float sizeX, float sizeY, int texIconFlags) { - ITexture* texture = GetIEditor()->GetRenderer()->EF_GetTextureByID(textureId); - DrawTextureLabel(texture, pos, sizeX, sizeY, texIconFlags); + // ToDo: With Atom? + AZ_UNUSED(textureId); + AZ_UNUSED(pos); + AZ_UNUSED(sizeX); + AZ_UNUSED(sizeY); + AZ_UNUSED(texIconFlags); } void SandboxIntegrationManager::SetLineWidth(float width) diff --git a/Code/Sandbox/Plugins/ComponentEntityEditorPlugin/SandboxIntegration.h b/Code/Sandbox/Plugins/ComponentEntityEditorPlugin/SandboxIntegration.h index 0cbfe1df93..14f52591a4 100644 --- a/Code/Sandbox/Plugins/ComponentEntityEditorPlugin/SandboxIntegration.h +++ b/Code/Sandbox/Plugins/ComponentEntityEditorPlugin/SandboxIntegration.h @@ -143,9 +143,6 @@ private: QDockWidget* InstanceViewPane(const char* paneName) override; void CloseViewPane(const char* paneName) override; void BrowseForAssets(AzToolsFramework::AssetBrowser::AssetSelectionModel& selection) override; - void GenerateAllCubemaps() override; - void GenerateCubemapForEntity(AZ::EntityId entityId, AZStd::string* cubemapOutputPath, bool hideEntity) override; - void GenerateCubemapWithIDForEntity(AZ::EntityId entityId, AZ::Uuid cubemapId, AZStd::string* cubemapOutputPath, bool hideEntity, bool hasCubemapId) override; void HandleObjectModeSelection(const AZ::Vector2& point, int flags, bool& handled) override; void UpdateObjectModeCursor(AZ::u32& cursorId, AZStd::string& cursorStr) override; void CreateEditorRepresentation(AZ::Entity* entity) override; @@ -249,7 +246,6 @@ private: void DrawArrow(const AZ::Vector3& src, const AZ::Vector3& trg, float fHeadScale, bool b2SidedArrow) override; void DrawTextLabel(const AZ::Vector3& pos, float size, const char* text, const bool bCenter, int srcOffsetX, int scrOffsetY) override; void Draw2dTextLabel(float x, float y, float size, const char* text, bool bCenter) override; - void DrawTextOn2DBox(const AZ::Vector3& pos, const char* text, float textScale, const AZ::Vector4& TextColor, const AZ::Vector4& TextBackColor) override; void DrawTextureLabel(ITexture* texture, const AZ::Vector3& pos, float sizeX, float sizeY, int texIconFlags) override; void DrawTextureLabel(int textureId, const AZ::Vector3& pos, float sizeX, float sizeY, int texIconFlags) override; void SetLineWidth(float width) override; @@ -323,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); @@ -352,9 +346,6 @@ private: }; private: - typedef AZStd::unordered_map ExtensionMap; - ExtensionMap m_extensionToFileType; - AZ::Vector2 m_contextMenuViewPoint; AZ::Vector3 m_sliceWorldPos; @@ -365,8 +356,6 @@ private: DisplayContext* m_dc; - AZStd::unique_ptr m_entityDebugPrinter; - AZStd::vector m_sliceAssetDeletionErrorRestoreInfos; // Tracks new entities that have not yet been saved. diff --git a/Code/Sandbox/Plugins/ComponentEntityEditorPlugin/componententityeditorplugin_files.cmake b/Code/Sandbox/Plugins/ComponentEntityEditorPlugin/componententityeditorplugin_files.cmake index 26998a5bda..6672bc8b47 100644 --- a/Code/Sandbox/Plugins/ComponentEntityEditorPlugin/componententityeditorplugin_files.cmake +++ b/Code/Sandbox/Plugins/ComponentEntityEditorPlugin/componententityeditorplugin_files.cmake @@ -17,8 +17,6 @@ set(FILES SandboxIntegration.cpp ComponentEntityEditorPlugin_precompiled.cpp ComponentEntityEditorPlugin_precompiled.h - ComponentEntityDebugPrinter.h - ComponentEntityDebugPrinter.cpp UI/ComponentEntityEditorOutlinerWindow.qrc UI/QComponentEntityEditorMainWindow.h UI/QComponentEntityEditorMainWindow.cpp 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/ManipScene.cpp b/Code/Sandbox/Plugins/EditorCommon/ManipScene.cpp deleted file mode 100644 index 5b76ca8804..0000000000 --- a/Code/Sandbox/Plugins/EditorCommon/ManipScene.cpp +++ /dev/null @@ -1,1739 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS 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 "ManipScene.h" - -#include "Serialization.h" -#include "QViewportEvents.h" - -#include -#include -#include -#include -#include - -#include "../EditorCommon/QViewport.h" - -#include - -// from Sandbox/Editor: -#include "Include/IDisplayViewport.h" -#include "Include/HitContext.h" -#include "Objects/DisplayContext.h" -#include "RenderHelpers/AxisHelper.h" -#include "Util/EditorUtils.h" -#include "Util/Math.h" -// ^^^ - -#include "DisplayViewportAdapter.h" -#include - -namespace Manip -{ - static unsigned int GetLayerBits(const SElements& elements) - { - unsigned int result = 0; - for (size_t i = 0; i < elements.size(); ++i) - { - result |= 1 << elements[i].layer; - } - return result; - } - - - static unsigned int GetLayerBits(const SElements& elements, const SSelectionSet& selection) - { - unsigned int result = 0; - for (size_t i = 0; i < elements.size(); ++i) - { - if (selection.Contains(elements[i].id)) - { - result |= 1 << elements[i].layer; - } - } - return result; - } - - - static QuatT GetGizmoOrientation(const QuatT& transform, [[maybe_unused]] const CCamera* camera, ETransformationSpace space) - { - if (space == SPACE_LOCAL) - { - return transform; - } - else - { - return QuatT(IDENTITY, transform.t); - } - } - // --------------------------------------------------------------------------- - - SERIALIZATION_ENUM_BEGIN(ETransformationMode, "Transformation Mode") - SERIALIZATION_ENUM(MODE_TRANSLATE, "translate", "Translate") - SERIALIZATION_ENUM(MODE_ROTATE, "rotate", "Rotate") - SERIALIZATION_ENUM(MODE_SCALE, "scale", "Scale") - SERIALIZATION_ENUM_END() - - // --------------------------------------------------------------------------- - - CScene::CScene() - : m_axisHelper(new CAxisHelper()) - , m_showGizmo(true) - , m_transformationMode(MODE_TRANSLATE) - , m_transformationSpace(SPACE_LOCAL) - , m_customDrawer(0) - , m_customTracer(0) - , m_spaceProvider(0) - , m_temporaryLocalDelta(IDENTITY) - , m_visibleLayerMask(0xffffffff) - { - m_axisHelper->SetMode(CAxisHelper::MOVE_MODE); - } - - - CScene::~CScene() - { - } - - static void DrawElement([[maybe_unused]] const SRenderContext& rc, const SElement& element, ElementId highlightedItem, bool isSelected, bool xRay, IElementDrawer* customDrawer, CScene* spaceProvider, const SLookSettings& lookSettings) - { - if (element.hidden) - { - return; - } - - IRenderer* renderer = GetIEditor()->GetRenderer(); - IRenderAuxGeom* aux = renderer->GetIRenderAuxGeom(); - - SAuxGeomRenderFlags defaultFlags(e_Mode3D | e_AlphaBlended | e_DrawInFrontOff | e_FillModeSolid | e_CullModeNone | e_DepthWriteOn | e_DepthTestOn); - SAuxGeomRenderFlags xRayFlags(e_Mode3D | e_AlphaBlended | e_DrawInFrontOn | e_FillModeSolid | e_CullModeNone | e_DepthWriteOff | e_DepthTestOff); - aux->SetRenderFlags(xRay ? xRayFlags : defaultFlags); - - QuatT transform = spaceProvider->ElementToWorldSpace(element); - Matrix34 transformM(transform); - - if (element.shape == SHAPE_BOX) - { - OBB obb; - obb.m33 = Matrix33(IDENTITY); - obb.c = element.placement.center; - obb.h = element.placement.size * 0.5f; - - bool isHighlighted2 = highlightedItem == element.id; - ColorB color; - if (isHighlighted2) - { - color = lookSettings.proxyHighlightColor; - } - else if (isSelected) - { - color = lookSettings.proxySelectionColor; - } - else if (element.colorGroup == ELEMENT_COLOR_CLOTH) - { - color = lookSettings.clothProxyColor; - } - else - { - color = lookSettings.proxyColor; - } - - ColorB innerColor = color; - - ColorB edgeColor(innerColor.r, innerColor.g, innerColor.b, 255); - - bool drawBB = false; - if (!customDrawer || !customDrawer->Draw(element)) - { - drawBB = true; - } - - if (isSelected || isHighlighted2) - { - drawBB = true; - } - - if (drawBB) - { - aux->DrawOBB(obb, transformM, false, edgeColor, eBBD_Faceted); - } - } - else if (element.shape == SHAPE_AXES) - { - OBB obb; - obb.m33 = Matrix33(IDENTITY); - obb.c = element.placement.center; - obb.h = Vec3(0.01f, 0.01f, 0.01f); - - bool isHighlighted2 = highlightedItem == element.id; - ColorB color; - if (isHighlighted2) - { - color = lookSettings.proxyHighlightColor; - } - else if (isSelected) - { - color = lookSettings.proxySelectionColor; - } - else - { - color = lookSettings.proxyColor; - } - - ColorB innerColor = color; - - ColorB edgeColor(innerColor.r, innerColor.g, innerColor.b, 255); - - bool drawBB = false; - if (!customDrawer || !customDrawer->Draw(element)) - { - drawBB = true; - } - if (isSelected || isHighlighted2) - { - drawBB = true; - } - - if (drawBB) - { - aux->DrawOBB(obb, transformM, false, edgeColor, eBBD_Faceted); - } - } - } - - void CScene::OnViewportRender(const SRenderContext& rc) - { - SignalRenderElements(m_elements, rc); - - for (int xRayPass = 0; xRayPass < 2; ++xRayPass) - { - size_t numElements = m_elements.size(); - for (size_t i = 0; i < numElements; ++i) - { - SElement& element = m_elements[i]; - bool isSelected = m_selection.Contains(element.id); - if (!isSelected && !IsLayerVisible(element.layer)) - { - continue; - } - - bool xRay = isSelected || element.id == m_highlightedItem || element.alwaysXRay; - - if (int(xRay) != xRayPass) - { - continue; - } - - DrawElement(rc, element, m_highlightedItem, m_selection.Contains(element.id), xRay, m_customDrawer, this, m_lookSettings); - } - } - - if (m_mouseDragHandler.get()) - { - m_mouseDragHandler->Render(rc); - } - - bool hasSelection = !m_selection.IsEmpty(); - - if (m_showGizmo && hasSelection) - { - int selectionCaps = GetSelectionCaps(); - Matrix34 m = Matrix34(GetGizmoOrientation(GetSelectionTransform(SPACE_WORLD), rc.viewport->Camera(), m_transformationSpace)); - DisplayContext dc; - CDisplayViewportAdapter view(rc.viewport); - dc.SetView(&view); - - SGizmoParameters gizmoParameters; - gizmoParameters.axisGizmoScale = 0.2f; - - if (m_axisHelper.get()) - { - switch (m_transformationMode) - { - case MODE_TRANSLATE: - m_axisHelper->SetMode(CAxisHelper::MOVE_MODE); - gizmoParameters.enabled = (selectionCaps & CAP_MOVE) != 0; - break; - case MODE_ROTATE: - m_axisHelper->SetMode(CAxisHelper::ROTATE_MODE); - gizmoParameters.enabled = (selectionCaps & CAP_ROTATE) != 0; - break; - case MODE_SCALE: - m_axisHelper->SetMode(CAxisHelper::SCALE_MODE); - gizmoParameters.enabled = (selectionCaps & CAP_SCALE) != 0; - break; - } - m_axisHelper->DrawAxis(m, gizmoParameters, dc); - } - } - } - - void CScene::SetTransformationMode(ETransformationMode mode) - { - m_transformationMode = mode; - } - - void CScene::SetTransformationSpace(ETransformationSpace space) - { - m_transformationSpace = space; - } - - ETransformationMode CScene::TransformationMode() const - { - return m_transformationMode; - } - - void CScene::SetSelection(const SSelectionSet& selection) - { - if (m_selection != selection) - { - m_selection = selection; - SignalSelectionChanged(); - } - } - - void CScene::AddToSelection(ElementId elementId) - { - m_selection.Add(elementId); - SignalSelectionChanged(); - } - - void CScene::ApplyToAll(EElementAction action) - { - size_t count = m_elements.size(); - for (size_t i = 0; i < count; ++i) - { - SElement& m = m_elements[i]; - if (m.hidden) - { - m.action = action; - //m.hidden = false; - } - } - SignalElementsChanged(GetLayerBits(m_elements)); - } - - void CScene::ApplyToSelection(EElementAction action) - { - size_t count = m_elements.size(); - for (size_t i = 0; i < count; ++i) - { - SElement& m = m_elements[i]; - if (m_selection.Contains(m.id)) - { - m.action = action; - //m.hidden = true; - } - } - SignalElementsChanged(GetLayerBits(m_elements, m_selection)); - } - - void CScene::OnViewportKey(const SKeyEvent& ev) - { - QKeySequence key(ev.key); - if (ev.type == SKeyEvent::TYPE_PRESS) - { - if (key == QKeySequence(Qt::Key_U) || 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 if (key == QKeySequence(Qt::ALT | Qt::Key_H) || key == QKeySequence(Qt::SHIFT | Qt::Key_H)) - { - ApplyToAll(ACTION_UNHIDE); - } - else if (key == QKeySequence(Qt::Key_H)) - { - ApplyToSelection(ACTION_HIDE); - } - else if (key == QKeySequence(Qt::Key_Delete)) - { - ApplyToSelection(ACTION_DELETE); - } - else if (key == QKeySequence(Qt::Key_1)) - { - m_transformationMode = MODE_TRANSLATE; - SignalManipulationModeChanged(); - SignalPropertiesChanged(); - } - else if (key == QKeySequence(Qt::Key_2)) - { - m_transformationMode = MODE_ROTATE; - SignalManipulationModeChanged(); - SignalPropertiesChanged(); - } - else if (key == QKeySequence(Qt::Key_3)) - { - m_transformationMode = MODE_SCALE; - SignalManipulationModeChanged(); - SignalPropertiesChanged(); - } - } - } - - bool CScene::ProcessesViewportKey(const QKeySequence& key) - { - static QSet overriddenKeys = { - QKeySequence(Qt::Key_U), - QKeySequence(Qt::Key_Z | Qt::CTRL), - QKeySequence(Qt::Key_Y | Qt::CTRL), - QKeySequence(Qt::Key_Z | Qt::CTRL | Qt::SHIFT), - QKeySequence(Qt::ALT | Qt::Key_H), - QKeySequence(Qt::SHIFT | Qt::Key_H), - QKeySequence(Qt::Key_H), - QKeySequence(Qt::Key_Delete), - QKeySequence(Qt::Key_1), - QKeySequence(Qt::Key_2), - QKeySequence(Qt::Key_3) - }; - - // Check if the parameter key is one that we care about in OnViewportKey - // If we don't, matching shortcuts attached to the widget will get processed - // instead, and CScene::OnViewportKey will never get called - return overriddenKeys.contains(key); - } - - bool RayHitsElement(Vec3* intersectionPoint, const Ray& ray, const SElement& element, IElementTracer* customTracer, CScene* spaceProvider) - { - QuatT parentSpace(IDENTITY); - if (spaceProvider) - { - parentSpace = spaceProvider->GetParentSpace(element); - } - - OBB obb; - if (element.shape == SHAPE_BOX) - { - obb.m33 = Matrix33((parentSpace * element.placement.transform).q); - obb.c = element.placement.center; - obb.h = element.placement.size * 0.5f; - } - else - { - obb.m33 = IDENTITY; - obb.c = Vec3(ZERO); - obb.h = element.placement.size * 0.5f; - } - - if (Intersect::Ray_OBB(ray, (parentSpace * element.placement.transform).t, obb, *intersectionPoint) != 0) - { - if (customTracer) - { - return customTracer->HitRay(intersectionPoint, ray, element); - } - - return true; - } - return false; - } - - static SElement* HitElementWithRay(Vec3* hitPoint, SElements& elements, const Ray& ray, IElementTracer* customTracer, CScene* spaceProvider) - { - const float BIG_VALUE = 1e20f; - float closestDistanceSquare = BIG_VALUE; - int hitPickPriority = INT_MIN; - SElement* closestElement = 0; - - size_t numElements = elements.size(); - for (size_t i = 0; i < numElements; ++i) - { - SElement& element = elements[i]; - if (element.hidden) - { - continue; - } - if (!spaceProvider->IsLayerVisible(element.layer) && - !spaceProvider->Selection().Contains(element.id)) - { - continue; - } - - Vec3 intersectionPoint; - if (RayHitsElement(&intersectionPoint, ray, element, customTracer, spaceProvider)) - { - float distanceSquare = (intersectionPoint - ray.origin).GetLengthSquared(); - if (distanceSquare < closestDistanceSquare || int(element.mousePickPriority) > hitPickPriority) - { - closestDistanceSquare = distanceSquare; - closestElement = &element; - hitPickPriority = element.mousePickPriority; - *hitPoint = intersectionPoint; - } - } - } - return closestElement; - } - - static ElementId HitSelectionWithRay(Vec3* hitPoint, SElements& elements, const Ray& ray, IElementTracer* customTracer, CScene* spaceProvider) - { - SElement* element = HitElementWithRay(hitPoint, elements, ray, customTracer, spaceProvider); - if (element) - { - return element->id; - } - - return 0; - } - - struct STransformConstraint - { - enum EType - { - NONE, - AXIS, - PLANE - }; - - EType type; - Plane plane; - Vec3 axis; - Vec3 localAxis; - - Vec3 GetAxis(ETransformationSpace space) - { - switch (space) - { - case SPACE_LOCAL: - return localAxis; - default: - return axis; - } - } - - STransformConstraint() - : type(NONE) - { - } - }; - - struct CScene::SMoveHandler - : IMouseDragHandler - { - CScene* m_scene; - Vec3 m_lastPoint; - Vec3 m_startPoint; - Vec2i m_startMousePosition; - STransformConstraint m_constraint; - SElements m_elements; - SElements m_transformedElements; - int m_layerBits; - - SMoveHandler(CScene* scene, const STransformConstraint& constraint) - : m_scene(scene) - , m_constraint(constraint) - , m_layerBits(0) - , m_lastPoint(ZERO) - , m_startPoint(ZERO) - { - } - - bool Begin(const SMouseEvent& ev, Vec3 hitPoint) override - { - m_startMousePosition = Vec2i(ev.x, ev.y); - m_startPoint = hitPoint; - - m_scene->GetSelectedElements(&m_elements); - m_layerBits = GetLayerBits(m_elements); - - if (!ReprojectStartPoint(ev.viewport)) - { - return false; - } - return true; - } - - - bool ReprojectStartPoint(QViewport* viewport) - { - Ray ray; - MAKE_SURE(viewport->ScreenToWorldRay(&ray, m_startMousePosition.x, m_startMousePosition.y), return false); - - if (m_constraint.type == STransformConstraint::PLANE) - { - Intersect::Ray_Plane(ray, m_constraint.plane, m_startPoint, false); - } - else if (m_constraint.type == STransformConstraint::AXIS) - { - Vec3 point; - Vec3 axis = m_constraint.GetAxis(m_scene->TransformationSpace()); - RayToLineDistance(ray.origin, ray.origin + ray.direction, - m_startPoint - axis * 10000.0f, m_startPoint + axis * 10000.0f, point); - m_startPoint = m_startPoint + axis * axis.dot(point - m_startPoint); - } - return true; - } - - void Update(const SMouseEvent& ev) override - { - ReprojectStartPoint(ev.viewport); - - Ray ray; - MAKE_SURE(ev.viewport->ScreenToWorldRay(&ray, ev.x, ev.y), return ); - - if (m_constraint.type == STransformConstraint::PLANE) - { - Vec3 point(0.0f, 0.0f, 0.0f); - Intersect::Ray_Plane(ray, m_constraint.plane, point, false); - - Vec3 delta = point - m_startPoint; - Move(delta); - } - else if (m_constraint.type == STransformConstraint::AXIS) - { - Vec3 point = m_startPoint; - Vec3 axis = m_constraint.GetAxis(m_scene->TransformationSpace()); - RayToLineDistance(ray.origin, ray.origin + ray.direction, - m_startPoint - axis * 10000.0f, m_startPoint + axis * 10000.0f, point); - Vec3 newPoint = m_startPoint + axis * axis.dot(point - m_startPoint); - Vec3 delta = newPoint - m_startPoint; - Move(delta); - } - } - - void Move(Vec3 delta) - { - m_transformedElements = m_elements; - for (size_t i = 0; i < m_transformedElements.size(); ++i) - { - SElement& e = m_transformedElements[i]; - QuatT parentSpace = m_scene->GetParentSpace(e) * QuatT(e.placement.transform.q, ZERO); - QuatT localDelta = parentSpace.GetInverted() * (QuatT(IDENTITY, delta) * parentSpace); - m_scene->m_temporaryLocalDelta = localDelta; - e.placement.transform = e.placement.transform * localDelta; - e.placement.transform.q.Normalize(); - } - m_scene->UpdateElements(m_transformedElements); - m_scene->SignalElementContinousChange(m_layerBits); - } - - void End([[maybe_unused]] const SMouseEvent& ev) override - { - m_scene->m_temporaryLocalDelta = QuatT(IDENTITY); - m_scene->SignalElementsChanged(m_layerBits); - } - }; - - struct CScene::SRotationHandler - : public IMouseDragHandler - { - CScene* m_scene; - STransformConstraint m_constraint; - SElements m_elements; - SElements m_transformedElements; - int m_layerBits; - Vec3 m_origin; - Vec2i m_startPoint; - - SRotationHandler(CScene* scene, const STransformConstraint& constraint) - : m_scene(scene) - , m_constraint(constraint) - , m_layerBits(0) - , m_origin(ZERO) - , m_startPoint(ZERO) - { - if (m_constraint.type == STransformConstraint::PLANE) - { - // TODO: Apart from having rotation around axis of gizmo (as Sandbox does) it - // is possible here to rotate around viewer axis. This part can be considerably - // improved by making sure that picked point on the proxy keeps touching the - // mouse pointer. - - m_constraint.localAxis = m_constraint.plane.n; - m_constraint.axis = Vec3(0.0f, 0.0f, 1.0f); - m_constraint.type = STransformConstraint::AXIS; - } - - m_scene->GetSelectedElements(&m_elements); - m_layerBits = GetLayerBits(m_elements); - - m_origin = m_scene->GetSelectionTransform(SPACE_WORLD).t; - } - - bool Begin(const SMouseEvent& ev, [[maybe_unused]] Vec3 hitPoint) override - { - m_startPoint = Vec2i(ev.x, ev.y); - return true; - } - - void Update(const SMouseEvent& ev) override - { - if (ev.y != m_startPoint.y) - { - float angle = ((ev.y - m_startPoint.y) * 0.01f) * 3.1415926f; - QuatT rotation; - float cos, sin; - sin = sinf(angle); - cos = cosf(angle); - Vec3 axis = m_constraint.GetAxis(m_scene->TransformationSpace()); - rotation.SetRotationAA(cos, sin, axis); - - m_transformedElements = m_elements; - for (size_t i = 0; i < m_elements.size(); ++i) - { - SElement& e = m_transformedElements[i]; - QuatT t = m_scene->ElementToWorldSpace(e); - t.t -= m_origin; - t = rotation * t; - t.t += m_origin; - m_scene->m_temporaryLocalDelta = m_scene->ElementToWorldSpace(m_elements[i]).GetInverted() * t; - m_scene->WorldSpaceToElement(&e, t); - } - m_scene->UpdateElements(m_transformedElements); - m_scene->SignalElementContinousChange(m_layerBits); - } - } - - void End([[maybe_unused]] const SMouseEvent& ev) override - { - m_scene->m_temporaryLocalDelta = QuatT(IDENTITY); - m_scene->SignalElementsChanged(m_layerBits); - } - }; - - static Vec3 ScaleAround(Vec3 p, Vec3 origin, float scale) - { - return (p - origin) * scale + origin; - } - - struct CScene::SScalingHandler - : public IMouseDragHandler - { - CScene* m_scene; - STransformConstraint m_constraint; - SElements m_elements; - SElements m_transformedElements; - Vec3 m_origin; - Vec3 m_size; - Vec3 m_hitPoint; - Vec2i m_startPoint; - unsigned int m_layerBits; - - SScalingHandler(CScene* scene, const STransformConstraint& constraint) - : m_scene(scene) - , m_constraint(constraint) - , m_layerBits(0) - , m_origin(ZERO) - , m_size(ZERO) - , m_hitPoint(ZERO) - , m_startPoint(ZERO) - { - } - - bool Begin(const SMouseEvent& ev, Vec3 hitPoint) override - { - m_hitPoint = hitPoint; - m_startPoint = Vec2i(ev.x, ev.y); - m_scene->GetSelectedElements(&m_elements); - m_layerBits = GetLayerBits(m_elements); - m_origin = m_scene->GetSelectionTransform(SPACE_WORLD).t; - m_size = m_scene->GetSelectionSize(); - return true; - } - - void Update(const SMouseEvent& ev) override - { - float screenScaleFactor = 0.0f; - if (const CCamera* camera = ev.viewport->Camera()) - { - screenScaleFactor = camera->GetPosition().GetDistance(m_hitPoint); - if (screenScaleFactor < camera->GetNearPlane()) - { - screenScaleFactor = camera->GetNearPlane(); - } - } - - m_transformedElements = m_elements; - - if (m_transformedElements.size() == 1) - { - Vec3& size = m_transformedElements[0].placement.size; - float difference = -(ev.y - m_startPoint.y) * 0.01f * screenScaleFactor; - Vec3 axis = m_constraint.GetAxis(m_scene->TransformationSpace()); - size = (size + size.CompMul(axis * difference)).abs(); - } - else - { - float difference = -(ev.y - m_startPoint.y) * 0.01f * screenScaleFactor; - float sizeDifference = max(0.01f, fabsf(1.0f + difference)); - - for (size_t i = 0; i < m_transformedElements.size(); ++i) - { - SElement& g = m_transformedElements[i]; - g.placement.transform.t = ScaleAround(g.placement.transform.t, m_origin, sizeDifference); - g.placement.size = g.placement.size * sizeDifference; - } - } - - m_scene->UpdateElements(m_transformedElements); - m_scene->SignalElementContinousChange(m_layerBits); - } - - void End([[maybe_unused]] const SMouseEvent& ev) override - { - m_scene->SignalElementsChanged(m_layerBits); - } - }; - - template - struct SRange - { - T low; - T high; - - SRange(T low, T high) - : low(low) - , high(high) - { - } - - SRange() - : low(T(0)) - , high(T(0)) - { - } - - void Add(T value) - { - if (value < low) - { - low = value; - } - if (value > high) - { - high = value; - } - } - - bool Intersects(const SRange& r) const - { - if (high < r.low) - { - return false; - } - if (low > r.high) - { - return false; - } - return true; - } - }; - - static bool RectsIntersect(Vec2i amin, Vec2i amax, Vec2i bmin, Vec2i bmax) - { - if (!SRange(amin.x, amax.x).Intersects(SRange(bmin.x, bmax.x))) - { - return false; - } - - if (!SRange(amin.y, amax.y).Intersects(SRange(bmin.y, bmax.y))) - { - return false; - } - - return true; - } - - static bool OBBOverlapsSelectionFrustum(const OBB& box, Vec2i rectMin, Vec2i rectMax, [[maybe_unused]] const Plane (&frustum)[4], IDisplayViewport* viewport) - { - Vec3 s = box.h; - Vec3 points[8] = { - box.m33 * Vec3(-s.x, -s.y, -s.z) + box.c, - box.m33 * Vec3(s.x, -s.y, -s.z) + box.c, - box.m33 * Vec3(s.x, s.y, -s.z) + box.c, - box.m33 * Vec3(-s.x, s.y, -s.z) + box.c, - box.m33 * Vec3(-s.x, -s.y, s.z) + box.c, - box.m33 * Vec3(s.x, -s.y, s.z) + box.c, - box.m33 * Vec3(s.x, s.y, s.z) + box.c, - box.m33 * Vec3(-s.x, s.y, s.z) + box.c, - }; - - Vec2i projectedPoints[8]; - Vec2i boundMin(INT_MAX, INT_MAX); - Vec2i boundMax(INT_MIN, INT_MIN); - for (int i = 0; i < 8; ++i) - { - Vec2i& p = projectedPoints[i]; - QPoint pt = viewport->WorldToView(points[i]); - p.x = pt.x(); - p.y = pt.y(); - if (p.x < boundMin.x) - { - boundMin.x = p.x; - } - if (p.y < boundMin.y) - { - boundMin.y = p.y; - } - if (p.x > boundMax.x) - { - boundMax.x = p.x; - } - if (p.y > boundMax.y) - { - boundMax.y = p.y; - } - } - - if (boundMin.x > rectMin.x && - boundMax.x < rectMax.x && - boundMin.y > rectMin.y && - boundMax.y < rectMax.y) - { - return true; - } - - if (!RectsIntersect(boundMin, boundMax, rectMin, rectMax)) - { - return false; - } - - struct Edge - { - Vec2 a; - Vec2 b; - }; - - Edge boxEdges[12] = { - { projectedPoints[0], projectedPoints[1] }, - { projectedPoints[1], projectedPoints[2] }, - { projectedPoints[2], projectedPoints[3] }, - { projectedPoints[3], projectedPoints[0] }, - { projectedPoints[4], projectedPoints[5] }, - { projectedPoints[5], projectedPoints[6] }, - { projectedPoints[6], projectedPoints[7] }, - { projectedPoints[7], projectedPoints[4] }, - { projectedPoints[0], projectedPoints[4] }, - { projectedPoints[1], projectedPoints[5] }, - { projectedPoints[2], projectedPoints[6] }, - { projectedPoints[3], projectedPoints[7] } - }; - - Vec2 rectPoints[4] = { - Vec2(float(rectMin.x), float(rectMin.y)), - Vec2(float(rectMax.x), float(rectMin.y)), - Vec2(float(rectMin.x), float(rectMax.y)), - Vec2(float(rectMax.x), float(rectMax.y)) - }; - - for (size_t i = 0; i < 12; ++i) - { - const Edge& e = boxEdges[i]; - Vec2 dir = e.b - e.a; - if (dir.GetLength2() < 1.0f) - { - continue; - } - dir.Normalize(); - Vec2 ort(dir.y, -dir.x); - - SRange range1; - range1.low = ort.Dot(projectedPoints[0]); - range1.high = range1.low; - for (size_t j = 1; j < 8; ++j) - { - float pos = ort.Dot(projectedPoints[j]); - range1.Add(pos); - } - - SRange range2; - range2.low = ort.Dot(rectPoints[0]); - range2.high = range2.low; - range2.Add(ort.Dot(rectPoints[1])); - range2.Add(ort.Dot(rectPoints[2])); - range2.Add(ort.Dot(rectPoints[3])); - - if (!range1.Intersects(range2)) - { - return false; - } - } - - return true; - } - - static bool ElementInFrustum(const SElement& element, Vec2i rectMin, Vec2i rectMax, const Plane (&frustum)[4], IDisplayViewport* viewport, CScene* scene) - { - OBB obb; - QuatT parentSpace = scene->GetParentSpace(element); - obb.m33 = Matrix33((parentSpace * element.placement.transform).q); - obb.c = Vec3((parentSpace * element.placement.transform).t); - obb.h = element.placement.size * 0.5f; - - return OBBOverlapsSelectionFrustum(obb, rectMin, rectMax, frustum, viewport); - } - - static void FindElementsInRect(vector* out, Vec2i point1, Vec2i point2, QViewport* viewport, - const vector& elements, [[maybe_unused]] ISpaceProvider* spaceProvider, CScene* scene) - { - int minX = min(point1.x, point2.x); - int minY = min(point1.y, point2.y); - int maxX = max(point1.x, point2.x); - int maxY = max(point1.y, point2.y); - Ray ray1; - if (!viewport->ScreenToWorldRay(&ray1, minX, minY)) - { - return; - } - Ray ray2; - if (!viewport->ScreenToWorldRay(&ray2, maxX, maxY)) - { - return; - } - - Matrix34 m = viewport->Camera()->GetMatrix(); - Vec3 xdir = m.GetColumn0().GetNormalized(); - Vec3 zdir = m.GetColumn2().GetNormalized(); - Vec3 pos = m.GetTranslation(); - - Vec3 normals[4] = { - ray1.direction.Cross(xdir).GetNormalized(), - (zdir).Cross(ray2.direction).GetNormalized(), - ray2.direction.Cross(-xdir).GetNormalized(), - (-zdir).Cross(ray1.direction).GetNormalized(), - }; - Plane frustum[4]; - for (int i = 0; i < 4; ++i) - { - frustum[i].SetPlane(-normals[i], pos); - } - - CDisplayViewportAdapter view(viewport); - - for (int j = 0; j < elements.size(); ++j) - { - const SElement& m2 = elements[j]; - if (m2.hidden) - { - continue; - } - if (!scene->IsLayerVisible(m2.layer) && !scene->Selection().Contains(m2.id)) - { - continue; - } - if (ElementInFrustum(m2, Vec2i(minX, minY), Vec2i(maxX, maxY), frustum, &view, scene)) - { - out->push_back(&m2); - } - } - } - - static void GetSelectionInRect(SSelectionSet* selection, Vec2i p1, Vec2i p2, QViewport* viewport, const vector& elements, ISpaceProvider* spaceProvider, CScene* scene) - { - vector elementsIn; - FindElementsInRect(&elementsIn, p1, p2, viewport, elements, spaceProvider, scene); - - for (size_t i = 0; i < elementsIn.size(); ++i) - { - selection->Add(elementsIn[i]->id); - } - } - - static void DrawLine2D(const SRenderContext& rc, Vec2i p1, Vec2i p2, ColorB color) - { - IRenderer* renderer = GetIEditor()->GetRenderer(); - IRenderAuxGeom* aux = renderer->GetIRenderAuxGeom(); - int w = rc.viewport->Width(); - int h = rc.viewport->Height(); - if (w == 0 || h == 0) - { - return; - } - - int renderFlags = aux->GetRenderFlags().m_renderFlags; - aux->SetRenderFlags((renderFlags | e_Mode2D) & ~e_Mode3D); - - Vec3 start(float(p1.x) / w, float(p1.y) / h, 0.0f); - Vec3 end(float(p2.x) / w, float(p2.y) / h, 0.0f); - aux->DrawLine(start, color, end, color); - - aux->SetRenderFlags(renderFlags); - } - - struct CScene::SBlockSelectHandler - : public IMouseDragHandler - { - CScene* m_scene; - Vec2i m_startPoint; - Vec2i m_endPoint; - SSelectionSet m_lastSelection; - - SBlockSelectHandler(CScene* scene) - : m_scene(scene) - { - } - - bool Begin(const SMouseEvent& ev, [[maybe_unused]] Vec3 hitPoint) override - { - m_startPoint = Vec2i(ev.x, ev.y); - m_endPoint = m_startPoint; - m_scene->SignalPushUndo("Selection change", 0); - m_scene->SetSelection(SSelectionSet()); - return true; - } - - void Update(const SMouseEvent& ev) override - { - m_endPoint = Vec2i(ev.x, ev.y); - - SSelectionSet selection; - GetSelectionInRect(&selection, m_startPoint, m_endPoint, ev.viewport, m_scene->Elements(), m_scene->SpaceProvider(), m_scene); - - if (selection != m_lastSelection || (selection.IsEmpty() && !m_scene->Selection().IsEmpty())) - { - m_scene->SetSelection(selection); - } - } - - void Render(const SRenderContext& rc) override - { - ColorB color(255, 255, 255, 255); - Vec2i points[4] = { m_startPoint, Vec2i(m_startPoint.x, m_endPoint.y), m_endPoint, Vec2i(m_endPoint.x, m_startPoint.y) }; - DrawLine2D(rc, points[0], points[1], color); - DrawLine2D(rc, points[1], points[2], color); - DrawLine2D(rc, points[2], points[3], color); - DrawLine2D(rc, points[3], points[0], color); - } - - void End([[maybe_unused]] const SMouseEvent& ev) override - { - } - }; - - - void CScene::OnMouseMove(const SMouseEvent& ev) - { - SGizmoParameters gizmoParameters; - gizmoParameters.axisGizmoScale = 0.2f; - CDisplayViewportAdapter displayView(ev.viewport); - - QuatT selectionTransform = GetSelectionTransform(SPACE_WORLD); - int selectionCaps = GetSelectionCaps(); - QuatT axesTransform = GetGizmoOrientation(selectionTransform, ev.viewport->Camera(), m_transformationSpace); - - if (m_mouseDragHandler.get()) - { - m_mouseDragHandler->Update(ev); - } - else if (m_showGizmo) - { - bool gizmoEnabled = true; - - switch (m_transformationMode) - { - case MODE_TRANSLATE: - gizmoEnabled = (selectionCaps & CAP_MOVE) != 0; - break; - case MODE_ROTATE: - gizmoEnabled = (selectionCaps & CAP_ROTATE) != 0; - break; - case MODE_SCALE: - gizmoEnabled = (selectionCaps & CAP_SCALE) != 0; - break; - } - - if (gizmoEnabled) - { - HitContext hc; - hc.point2d = QPoint(ev.x, ev.y); - hc.view = &displayView; - m_axisHelper->HitTest(Matrix34(axesTransform), gizmoParameters, hc); - m_axisHelper->SetHighlightAxis(hc.axis); - } - else - { - m_axisHelper->SetHighlightAxis(0); - } - - Ray ray; - if (ev.viewport->ScreenToWorldRay(&ray, ev.x, ev.y)) - { - Vec3 hitPoint; - m_highlightedItem = aznumeric_cast(HitSelectionWithRay(&hitPoint, m_elements, ray, m_customTracer, this)); - } - } - } - - void CScene::OnViewportMouse(const SMouseEvent& ev) - { - if (!ev.viewport) - { - return; - } - - SGizmoParameters gizmoParameters; - gizmoParameters.axisGizmoScale = 0.2f; - CDisplayViewportAdapter displayView(ev.viewport); - - QuatT selectionTransform = GetSelectionTransform(SPACE_WORLD); - int selectionCaps = GetSelectionCaps(); - QuatT axesTransform = GetGizmoOrientation(selectionTransform, ev.viewport->Camera(), m_transformationSpace); - - if (ev.type == SMouseEvent::TYPE_PRESS) - { - int button = ev.button; - if (button == SMouseEvent::BUTTON_LEFT) - { - Ray ray; - if (ev.viewport->ScreenToWorldRay(&ray, ev.x, ev.y)) - { - STransformConstraint constraint; - - Vec3 hitPoint = selectionTransform.t; - if (m_showGizmo) - { - HitContext hc; - hc.point2d = QPoint(ev.x, ev.y); - hc.view = &displayView; - if (!Selection().IsEmpty() && m_axisHelper->HitTest(Matrix34(axesTransform), gizmoParameters, hc)) - { - Quat localRot(selectionTransform.q); - Quat planeRot(GetGizmoOrientation(QuatT(selectionTransform.q, ZERO), ev.viewport->Camera(), m_transformationSpace).q); - switch (hc.axis) - { - case AXIS_X: - constraint.type = STransformConstraint::AXIS; - constraint.axis = Vec3(1.0f, 0.0f, 0.0f); - constraint.localAxis = localRot * constraint.axis; - break; - case AXIS_Y: - constraint.type = STransformConstraint::AXIS; - constraint.axis = Vec3(0.0f, 1.0f, 0.0f); - constraint.localAxis = localRot * constraint.axis; - break; - case AXIS_Z: - constraint.type = STransformConstraint::AXIS; - constraint.axis = Vec3(0.0f, 0.0f, 1.0f); - constraint.localAxis = localRot * constraint.axis; - break; - case AXIS_XY: - constraint.type = STransformConstraint::PLANE; - constraint.plane.SetPlane(planeRot * Vec3(0.0f, 0.0f, 1.0f), hitPoint); - constraint.axis = Vec3(1.0f, 1.0f, 0.0f); - break; - case AXIS_XZ: - constraint.type = STransformConstraint::PLANE; - constraint.plane.SetPlane(planeRot * Vec3(0.0f, 1.0f, 0.0f), hitPoint); - constraint.axis = Vec3(1.0f, 0.0f, 1.0f); - break; - case AXIS_YZ: - constraint.type = STransformConstraint::PLANE; - constraint.plane.SetPlane(planeRot * Vec3(1.0f, 0.0f, 0.0f), hitPoint); - constraint.axis = Vec3(0.0f, 1.0f, 1.0f); - break; - case AXIS_XYZ: - constraint.type = STransformConstraint::AXIS; - constraint.localAxis = Vec3(1.0f, 1.0f, 1.0f); - constraint.axis = Vec3(1.0f, 1.0f, 1.0f); - break; - } - } - } - - if (constraint.type == STransformConstraint::NONE) - { - ElementId selected_id = HitSelectionWithRay(&hitPoint, m_elements, ray, m_customTracer, this); - if (selected_id != 0) - { - if (!m_selection.Contains(aznumeric_cast(selected_id)) || m_selection.Size() > 1) - { - if (ev.control) - { - AddToSelection(selected_id); - } - else - { - SetSelection(SSelectionSet(selected_id)); - } - } - - if (m_transformationMode == MODE_SCALE) - { - constraint.type = STransformConstraint::AXIS; - constraint.axis = Vec3(1.0f, 1.0f, 1.0f); - constraint.localAxis = Vec3(1.0f, 1.0f, 1.0f); - } - else - { - Matrix34 m = ev.viewport->Camera()->GetMatrix(); - Vec3 xdir = m.GetColumn0().GetNormalized(); - Vec3 ydir = m.GetColumn1().GetNormalized(); - Vec3 zdir = m.GetColumn2().GetNormalized(); - Vec3 pos = m.GetTranslation(); - - Vec3 fromScreenToSelection = pos - hitPoint; - float distance = ydir.Dot(fromScreenToSelection); - Vec3 planeCenter = pos + -ydir * distance; - - constraint.type = STransformConstraint::PLANE; - constraint.plane.SetPlane(-ydir, planeCenter); - constraint.axis = Vec3(1.0f, 0.0f, 1.0f); - } - } - else - { - m_mouseDragHandler.reset(new SBlockSelectHandler(this)); - } - } - - if (constraint.type != STransformConstraint::NONE) - { - switch (m_transformationMode) - { - case MODE_TRANSLATE: - if (selectionCaps & CAP_MOVE) - { - m_mouseDragHandler.reset(new SMoveHandler(this, constraint)); - } - break; - case MODE_ROTATE: - if (selectionCaps & CAP_ROTATE) - { - m_mouseDragHandler.reset(new SRotationHandler(this, constraint)); - } - break; - case MODE_SCALE: - if (selectionCaps & CAP_SCALE) - { - m_mouseDragHandler.reset(new SScalingHandler(this, constraint)); - } - break; - default: - break; - } - } - - if (m_mouseDragHandler.get()) - { - if (!m_mouseDragHandler->Begin(ev, hitPoint)) - { - m_mouseDragHandler.reset(); - } - } - } - } - } - else if (ev.type == SMouseEvent::TYPE_RELEASE) - { - if (m_mouseDragHandler.get()) - { - m_mouseDragHandler->End(ev); - m_mouseDragHandler.reset(); - ev.viewport->ReleaseMouse(); - } - } - else if (ev.type == SMouseEvent::TYPE_MOVE) - { - OnMouseMove(ev); - } - } - - struct CScene::STransformBox - { - CScene* m_scene; - - STransformBox(CScene* scene) - : m_scene(scene) - { - } - - void Serialize(IArchive& ar) - { - QuatT transform = m_scene->GetSelectionTransform(SPACE_WORLD); - int caps = m_scene->GetSelectionCaps(); - - Vec3 position = transform.t; - if ((caps & CAP_MOVE)) - { - ar(position, "position", "GetSelectionSize(); - Vec3 sizeOld = size; - if ((caps & CAP_SCALE)) - { - ar(size, "size", "SetSelectionTransform(SPACE_WORLD, transform); - } - - if (sizeChanged) - { - m_scene->SetSelectionSize(size); - } - } - } - }; - - struct SSpaceSelector - { - ETransformationSpace& space; - - SSpaceSelector(ETransformationSpace& space) - : space(space) - { - } - - void Serialize(Serialization::IArchive& ar) - { - using Serialization::RadioButton; - ar(RadioButton((int&)space, SPACE_WORLD), "transformWorld", "^Global"); - ar(RadioButton((int&)space, SPACE_LOCAL), "transformLocal", "^Local"); - } - }; - - - void CScene::Serialize(IArchive& ar) - { - ar(m_transformationMode, "transformationMode", 0); - if (ar.IsEdit()) - { - ar(SSpaceSelector(m_transformationSpace), "transformationSpace", "clear(); - size_t numElements = m_elements.size(); - for (size_t i = 0; i < numElements; ++i) - { - const SElement& element = m_elements[i]; - if (m_selection.Contains(element.id)) - { - elements->push_back(element); - } - } - } - - void CScene::UpdateElements(const SElements& elements) - { - // TODO: remove quadratic complexity here - size_t numElements = m_elements.size(); - for (size_t i = 0; i < numElements; ++i) - { - for (size_t j = 0; j < elements.size(); ++j) - { - if (m_elements[i].id == elements[j].id) - { - m_elements[i].placement = elements[j].placement; - m_elements[i].changed = true; - } - } - } - } - - void CScene::Clear() - { - m_elements.clear(); - m_lastIdByLayer.clear(); - } - - void CScene::ClearLayer(int layer) - { - auto newEnd = std::remove_if(m_elements.begin(), m_elements.end(), [=](const SElement& e){ return e.layer == layer; }); - m_elements.erase(newEnd, m_elements.end()); - if (layer < m_lastIdByLayer.size()) - { - m_lastIdByLayer[layer] = layer << 24; - } - } - - - void CScene::AddElement(const SElement& element) - { - ElementId& lastId = m_lastIdByLayer[element.layer]; - AddElement(element, lastId); - ++lastId; - } - - void CScene::AddElement(const SElement& element, ElementId id) - { - m_elements.push_back(element); - if (element.layer >= m_lastIdByLayer.size()) - { - while (m_lastIdByLayer.size() <= element.layer) - { - m_lastIdByLayer.push_back(m_lastIdByLayer.size() << 24); - } - } - m_elements.back().id = aznumeric_cast(id); - - ElementId& lastId = m_lastIdByLayer[element.layer]; - lastId = max(lastId, id) + 1; - } - - QuatT CScene::GetSelectionTransform(ETransformationSpace space) const - { - if (space == SPACE_WORLD) - { - QuatT r(IDENTITY); - - vector selectedElements; - GetSelectedElements(&selectedElements); - - if (selectedElements.size() == 1) - { - r = ElementToWorldSpace(selectedElements[0]); - } - else if (selectedElements.size() > 1) - { - r = GetParentSpace(selectedElements[0]) * selectedElements[0].placement.transform; - for (size_t i = 1; i < selectedElements.size(); ++i) - { - SElement& e = selectedElements[i]; - QuatT parentSpace = GetParentSpace(e); - r.t = r.t + ElementToWorldSpace(e).t; - } - r.SetTranslation(r.t / float(selectedElements.size())); - } - - if (!_finite(r.t.x) || - !_finite(r.t.y) || - !_finite(r.t.z)) - { - Q_ASSERT(false); - r.SetIdentity(); - } - return r; - } - else if (space == SPACE_LOCAL) - { - return m_temporaryLocalDelta; - } - - return IDENTITY; - } - - bool CScene::SelectionCanBeMoved() const - { - return (GetSelectionCaps() & CAP_MOVE) != 0; - } - - bool CScene::SelectionCanBeRotated() const - { - return (GetSelectionCaps() & CAP_ROTATE) != 0; - } - - int CScene::GetSelectionCaps() const - { - int caps = 0; - vector selectedElements; - GetSelectedElements(&selectedElements); - for (size_t i = 0; i < selectedElements.size(); ++i) - { - if (selectedElements[i].caps & CAP_MOVE && (caps & CAP_MOVE) != 0) - { - // enable rotation and scale of two or more positions - caps |= CAP_ROTATE | CAP_SCALE; - } - - caps |= selectedElements[i].caps; - } - ; - - return caps; - } - - bool CScene::SetSelectionTransform(ETransformationSpace space, const QuatT& newTransform) - { - QuatT transform = GetSelectionTransform(SPACE_WORLD); - QuatT deltaWorld; - if (space == SPACE_WORLD) - { - deltaWorld = transform.GetInverted() * newTransform; - } - else - { - deltaWorld = newTransform; - } - - bool hasElementsChanged = false; - - size_t numElements = m_elements.size(); - for (size_t i = 0; i < numElements; ++i) - { - SElement& element = m_elements[i]; - if (m_selection.Contains(element.id)) - { - QuatT parentSpace = GetParentSpace(element); - QuatT newWorldTransform = parentSpace * element.placement.transform * deltaWorld; - element.placement.transform = parentSpace.GetInverted() * newWorldTransform; - element.changed = true; - hasElementsChanged = true; - } - } - - return hasElementsChanged; - } - - Vec3 CScene::GetSelectionSize() const - { - Vec3 size(1.0f, 1.0f, 1.0f); - - vector selectedElements; - GetSelectedElements(&selectedElements); - - if (selectedElements.size() == 1) - { - size = selectedElements[0].placement.size; - } - else if (selectedElements.size() > 1) - { - AABB combinedSize(AABB::RESET); - - for (size_t i = 0; i < selectedElements.size(); ++i) - { - const SElement& element = m_elements[i]; - AABB box(element.placement.size * -0.5f, element.placement.size * 0.5f); - AABB transformedBox = AABB::CreateTransformedAABB(Matrix34(element.placement.transform), box); - combinedSize.Add(transformedBox); - } - size = combinedSize.IsReset() ? Vec3(1.0f, 1.0f, 1.0f) : combinedSize.GetSize(); - } - - return size; - } - - - bool CScene::SetSelectionSize(const Vec3& size) - { - bool hasElementsChanged = false; - - vector selectedElements; - GetSelectedElements(&selectedElements); - - if (selectedElements.size() == 1) - { - selectedElements[0].placement.size = size; - selectedElements[0].changed = true; - hasElementsChanged = true; - } - - return hasElementsChanged; - } - - void CScene::SetSpaceProvider(ISpaceProvider* provider) - { - m_spaceProvider = provider; - } - - QuatT CScene::GetParentSpace(const SElement& e) const - { - if (!m_spaceProvider) - { - return QuatT(IDENTITY); - } - QuatT result = m_spaceProvider->GetTransform(e.parentSpaceIndex); - return result; - } - - QuatT CScene::ElementToWorldSpace(const SElement& e) const - { - if (!m_spaceProvider) - { - return e.placement.transform; - } - QuatT parent = m_spaceProvider->GetTransform(e.parentSpaceIndex); - if (e.parentOrientationSpaceIndex.m_attachmentCRC32 == -1 && e.parentOrientationSpaceIndex.m_jointCRC32 == -1) - { - return parent * e.placement.transform; - } - - QuatT parentOrientation = m_spaceProvider->GetTransform(e.parentOrientationSpaceIndex); - QuatT result = parent * e.placement.transform; - result.q = parentOrientation.q * e.placement.transform.q; - return result; - } - - - void CScene::WorldSpaceToElement(SElement* e, const QuatT& worldSpaceTransform) - { - if (!e) - { - return; - } - if (!m_spaceProvider) - { - e->placement.transform = worldSpaceTransform; - return; - } - - QuatT parent = m_spaceProvider->GetTransform(e->parentSpaceIndex); - - if (e->parentOrientationSpaceIndex.m_attachmentCRC32 == -1 && e->parentOrientationSpaceIndex.m_jointCRC32 == -1) - { - e->placement.transform = parent.GetInverted() * worldSpaceTransform; - return; - } - QuatT parentOrientation = m_spaceProvider->GetTransform(e->parentOrientationSpaceIndex); - e->placement.transform = parent.GetInverted() * worldSpaceTransform; - e->placement.transform.q = parentOrientation.GetInverted().q * worldSpaceTransform.q; - } - - bool CScene::IsLayerVisible(int layer) const - { - return (m_visibleLayerMask & (1 << layer)) != 0; - } - - void CScene::SetVisibleLayerMask(unsigned int layerMask) - { - m_visibleLayerMask = layerMask; - } -} diff --git a/Code/Sandbox/Plugins/EditorCommon/ManipScene.h b/Code/Sandbox/Plugins/EditorCommon/ManipScene.h deleted file mode 100644 index dbb735d493..0000000000 --- a/Code/Sandbox/Plugins/EditorCommon/ManipScene.h +++ /dev/null @@ -1,336 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS 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_MANIPSCENE_H -#define CRYINCLUDE_EDITORCOMMON_MANIPSCENE_H -#pragma once - -#include -#include -#include -#include "EditorCommonAPI.h" -#include -#include "QViewportConsumer.h" - - -namespace Serialization { - class IArchive; -} - -class CAxisHelper; - -// Manip is a set of reusable utilities for creating interactive 3d scene that -// can be manipulated with gizmos. -namespace Manip -{ - using std::unique_ptr; - using std::set; - using std::vector; - - enum EElementCaps - { - CAP_SELECT = 1 << 0, - CAP_HIDE = 1 << 1, - CAP_MOVE = 1 << 2, - CAP_ROTATE = 1 << 3, - CAP_SCALE = 1 << 4, - CAP_DELETE = 1 << 5, - }; - - enum EElementShape - { - SHAPE_AXES, - SHAPE_BOX - }; - - enum EElementAction - { - ACTION_NONE, - ACTION_DELETE, - ACTION_HIDE, - ACTION_UNHIDE - }; - - enum EElementColorGroup - { - ELEMENT_COLOR_PROXY, - ELEMENT_COLOR_CLOTH - }; - - struct SElementPlacement - { - QuatT transform; - QuatT startTransform; - Vec3 center; - Vec3 size; - - SElementPlacement() - : transform(IDENTITY) - , startTransform(IDENTITY) - , size(1.0f, 1.0f, 1.0f) - , center(0.0f, 0.0f, 0.0f) - {} - - void Serialize(Serialization::IArchive& ar); - }; - - typedef uint64 ElementId; - - struct SSpaceAndIndex - { - int m_space; - int m_jointCRC32; - int m_attachmentCRC32; - SSpaceAndIndex() - { - m_space = -1; - m_jointCRC32 = -1; - m_attachmentCRC32 = -1; - }; - }; - - struct SElement - { - int id; - union - { - int originalId; - const void* originalHandle; - }; - int layer; - SElementPlacement placement; - int caps; - EElementAction action; - EElementShape shape; - EElementColorGroup colorGroup; - SSpaceAndIndex parentSpaceIndex; - SSpaceAndIndex parentOrientationSpaceIndex; - QuatT parentSpaceConcatenation; - int mousePickPriority; - bool hidden; - bool changed; - bool alwaysXRay; - - SElement() - : id() - , layer(0) - , originalHandle(0) - , action(ACTION_NONE) - , shape(SHAPE_AXES) - , hidden(false) - , changed(false) - , colorGroup(ELEMENT_COLOR_PROXY) - , mousePickPriority(0) - , alwaysXRay(false) - , parentSpaceIndex() - , parentOrientationSpaceIndex() - , parentSpaceConcatenation(IDENTITY) - { - } - }; - typedef std::vector SElements; - - struct SElementData {}; - - struct IMouseDragHandler - { - virtual ~IMouseDragHandler() = default; - virtual bool Begin(const SMouseEvent& ev, Vec3 hitPoint) = 0; - virtual void Update(const SMouseEvent& ev) = 0; - virtual void Render([[maybe_unused]] const SRenderContext& rc) {} - virtual void End(const SMouseEvent& ev) = 0; - }; - - struct SSelectionSet - { - SSelectionSet() {} - SSelectionSet(ElementId id) { items.push_back(id); } - void Clear(); - void Add(ElementId elementId) - { - items.erase(std::remove(items.begin(), items.end(), elementId), items.end()); - items.push_back(elementId); - std::sort(items.begin(), items.end()); - } - void Remove(int elementId); - bool IsEmpty() const{ return items.empty(); } - bool Contains(int id) const{ return std::find(items.begin(), items.end(), id) != items.end(); } - size_t Size() const{ return items.size(); } - - bool operator==(const SSelectionSet& rhs) const - { - return items == rhs.items; - } - - bool operator!=(const SSelectionSet& rhs) const{ return !operator==(rhs); } - - std::vector items; - }; - - struct ICommand {}; - - struct IElementTracer - { - virtual bool HitRay(Vec3* intersectionPoint, const Ray& ray, const SElement& element) const = 0; - }; - - struct IElementDrawer - { - virtual bool Draw(const SElement& element); - }; - - enum ETransformationSpace - { - SPACE_WORLD, - SPACE_LOCAL - }; - - enum ETransformationMode - { - MODE_TRANSLATE, - MODE_ROTATE, - MODE_SCALE - }; - - struct SLookSettings - { - ColorB proxyColor; - ColorB proxySelectionColor; - ColorB proxyHighlightColor; - ColorB clothProxyColor; - - ColorB jointColor; - ColorB jointHighlightColor; - ColorB jointSelectionColor; - - SLookSettings() - : proxyColor(126, 159, 243, 128) - , proxySelectionColor(255, 255, 255, 128) - , proxyHighlightColor(233, 255, 122, 128) - , clothProxyColor(243, 159, 126, 128) - , jointColor(0, 249, 48, 255) - , jointHighlightColor(255, 248, 0, 128) - , jointSelectionColor(255, 255, 255, 128) - { - } - }; - - struct ISpaceProvider - { - virtual ~ISpaceProvider() = default; - virtual SSpaceAndIndex FindSpaceIndexByName(int spaceType, const char* name, int parentsUp) const = 0; - virtual QuatT GetTransform(const SSpaceAndIndex& index) const = 0; - }; - - AZ_PUSH_DISABLE_DLL_EXPORT_BASECLASS_WARNING - class EDITOR_COMMON_API CScene - : public QObject - , public QViewportConsumer - { - AZ_POP_DISABLE_DLL_EXPORT_BASECLASS_WARNING - Q_OBJECT - public: - CScene(); - ~CScene(); - - void OnViewportKey(const SKeyEvent& ev) override; - bool ProcessesViewportKey(const QKeySequence& key) override; - void OnViewportMouse(const SMouseEvent& ev) override; - void OnViewportRender(const SRenderContext& rc) override; - - void SetTransformationMode(ETransformationMode mode); - ETransformationMode TransformationMode() const; - void SetTransformationSpace(ETransformationSpace space); - ETransformationSpace TransformationSpace() const { return m_transformationSpace; } - void SetVisibleLayerMask(unsigned int layerMask); - unsigned int VisibleLayerMask() const { return m_visibleLayerMask; } - bool IsLayerVisible(int layer) const; - - void Clear(); - void ClearLayer(int layer); - void AddElement(const SElement& element); - void AddElement(const SElement& element, ElementId id); - void ApplyToAll(EElementAction); - void ApplyToSelection(EElementAction); - - void SetSpaceProvider(ISpaceProvider* spaceProvider); - ISpaceProvider* SpaceProvider() const{ return m_spaceProvider; } - QuatT GetParentSpace(const SElement& e) const; - QuatT ElementToWorldSpace(const SElement& e) const; - void WorldSpaceToElement(SElement* e, const QuatT& worldSpaceTransform); - - void SetCustomTracer(IElementTracer* tracer); - - const SElements& Elements() const{ return m_elements; } - SElements& Elements() { return m_elements; } - void GetSelectedElements(SElements* elements) const; - const SSelectionSet& Selection() const{ return m_selection; } - void SetSelection(const SSelectionSet& selection); - void AddToSelection(const SSelectionSet& selection); - void AddToSelection(ElementId elementId); - - bool SelectionCanBeMoved() const; - bool SelectionCanBeRotated() const; - QuatT GetSelectionTransform(ETransformationSpace space) const; - bool SetSelectionTransform(ETransformationSpace space, const QuatT& newTransform); - - void Serialize(Serialization::IArchive& ar); - signals: - void SignalUndo(); - void SignalRedo(); - void SignalPushUndo(const char* description, ICommand* cause); - void SignalElementsChanged(unsigned int layerBits); - void SignalElementContinousChange(unsigned int layerBits); - void SignalPropertiesChanged(); - void SignalRenderElements(const SElements& elements, const SRenderContext& rc); - void SignalSelectionChanged(); - void SignalManipulationModeChanged(); - - private: - void UpdateElements(const SElements& elements); - bool SetSelectionTransform(const Matrix34& newMatrix); - Matrix34 GetSelectionTransform() const; - int GetSelectionCaps() const; - Vec3 GetSelectionSize() const; - bool SetSelectionSize(const Vec3& size); - void OnMouseMove(const SMouseEvent& ev); - - struct SBlockSelectHandler; - struct SMoveHandler; - struct SRotationHandler; - struct SScalingHandler; - struct STransformBox; - - IElementTracer* m_customTracer; - IElementDrawer* m_customDrawer; - - AZ_PUSH_DISABLE_DLL_EXPORT_MEMBER_WARNING - SSelectionSet m_selection; - unique_ptr m_mouseDragHandler; - ISpaceProvider* m_spaceProvider; - unique_ptr m_axisHelper; - SElements m_elements; - std::vector m_lastIdByLayer; - ETransformationMode m_transformationMode; - ETransformationSpace m_transformationSpace; - int m_highlightItem; - unsigned int m_visibleLayerMask; - bool m_showGizmo; - SLookSettings m_lookSettings; - int m_highlightedItem; - QuatT m_temporaryLocalDelta; - AZ_POP_DISABLE_DLL_EXPORT_MEMBER_WARNING - }; -} - -#endif // CRYINCLUDE_EDITORCOMMON_MANIPSCENE_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/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/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 2d9598ba83..0000000000 --- a/Code/Sandbox/Plugins/EditorCommon/QViewport.cpp +++ /dev/null @@ -1,1111 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS 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(); - CreateRenderContext(); - - m_camera.reset(new CCamera()); - ResetCamera(); - - m_mousePressPos = QCursor::pos(); - - UpdateBackgroundColor(); - - setUpdatesEnabled(false); - setMouseTracking(true); - m_LightRotationRadian = 0; - m_frameTimer->start(); -} - -QViewport::~QViewport() -{ - DestroyRenderContext(); - - 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) -{ - if (!GetIEditor()->GetEnv()->pRenderer) - { - return false; - } - - SetCurrentContext(); - - Vec3 pos0, pos1; - float wx, wy, wz; - if (!GetIEditor()->GetEnv()->pRenderer->UnProjectFromScreen(float(x), float(m_height - y), 0, &wx, &wy, &wz)) - { - RestorePreviousContext(); - return false; - } - pos0(wx, wy, wz); - if (!GetIEditor()->GetEnv()->pRenderer->UnProjectFromScreen(float(x), float(m_height - y), 1, &wx, &wy, &wz)) - { - RestorePreviousContext(); - return false; - } - pos1(wx, wy, wz); - - RestorePreviousContext(); - - Vec3 v = (pos1 - pos0); - v = v.GetNormalized(); - - ray->origin = pos0; - ray->direction = v; - return true; -} - -QPoint QViewport::ProjectToScreen(const Vec3& wp) -{ - float x, y, z; - - SetCurrentContext(); - GetIEditor()->GetEnv()->pRenderer->ProjectToScreen(wp.x, wp.y, wp.z, &x, &y, &z); - if (_finite(x) || _finite(y)) - { - RestorePreviousContext(); - return QPoint(int((x / 100.0) * Width()), int((y / 100.0) * Height())); - } - RestorePreviousContext(); - - 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(); -} - -bool QViewport::CreateRenderContext() -{ - if (m_creatingRenderContext || !isVisible()) - { - return false; - } - - HWND windowHandle = reinterpret_cast(QWidget::winId()); - - if( m_renderContextCreated && windowHandle == m_lastHwnd) - { - // the hwnd has not changed, no need to destroy and recreate context (and swap chain etc) - return false; - } - - m_creatingRenderContext = true; - DestroyRenderContext(); - if (windowHandle && GetIEditor()->GetEnv()->pRenderer && !m_renderContextCreated) - { - m_renderContextCreated = true; - - m_viewportRequests.get()->BusConnect(windowHandle); - AzFramework::WindowSystemNotificationBus::Broadcast(&AzFramework::WindowSystemNotificationBus::Handler::OnWindowCreated, windowHandle); - - m_lastHwnd = windowHandle; - - StorePreviousContext(); - GetIEditor()->GetEnv()->pRenderer->CreateContext(windowHandle); - RestorePreviousContext(); - - m_creatingRenderContext = false; - return true; - } - m_creatingRenderContext = false; - return false; -} - -void QViewport::DestroyRenderContext() -{ - if (GetIEditor()->GetEnv()->pRenderer && m_renderContextCreated) - { - HWND windowHandle = reinterpret_cast(QWidget::winId()); - - if (windowHandle != GetIEditor()->GetEnv()->pRenderer->GetHWND()) - { - GetIEditor()->GetEnv()->pRenderer->DeleteContext(windowHandle); - } - m_renderContextCreated = false; - - AzFramework::WindowNotificationBus::Event(windowHandle, &AzFramework::WindowNotificationBus::Handler::OnWindowClosed); - m_viewportRequests.get()->BusDisconnect(); - m_lastHwnd = 0; - } -} - -void QViewport::StorePreviousContext() -{ - SPreviousContext previous; - previous.width = GetIEditor()->GetEnv()->pRenderer->GetWidth(); - previous.height = GetIEditor()->GetEnv()->pRenderer->GetHeight(); - previous.window = reinterpret_cast(GetIEditor()->GetEnv()->pRenderer->GetCurrentContextHWND()); - previous.renderCamera = GetIEditor()->GetEnv()->pRenderer->GetCamera(); - previous.systemCamera = GetISystem()->GetViewCamera(); - previous.isMainViewport = GetIEditor()->GetEnv()->pRenderer->IsCurrentContextMainVP(); - m_previousContexts.push_back(previous); -} - -void QViewport::SetCurrentContext() -{ - StorePreviousContext(); - - if (m_camera.get() == 0) - { - return; - } - - HWND windowHandle = reinterpret_cast(QWidget::winId()); - GetIEditor()->GetEnv()->pRenderer->SetCurrentContext(windowHandle); - GetIEditor()->GetEnv()->pRenderer->ChangeViewport(0, 0, m_width, m_height); - GetIEditor()->GetEnv()->pRenderer->SetCamera(*m_camera); - GetIEditor()->GetEnv()->pSystem->SetViewCamera(*m_camera); -} - -void QViewport::RestorePreviousContext() -{ - if (m_previousContexts.empty()) - { - assert(0); - return; - } - - SPreviousContext x = m_previousContexts.back(); - m_previousContexts.pop_back(); - GetIEditor()->GetEnv()->pRenderer->SetCurrentContext(x.window); - GetIEditor()->GetEnv()->pRenderer->ChangeViewport(0, 0, x.width, x.height, x.isMainViewport); - GetIEditor()->GetEnv()->pRenderer->SetCamera(x.renderCamera); - GetIEditor()->GetEnv()->pSystem->SetViewCamera(x.systemCamera); -} - -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::GetImageOffscreen(CImageEx& image, const QSize& customSize) -{ - if ((m_width == 0) || (m_height == 0)) - { - // This can occur, for example, if the material editor window is sized to zero OR - // if it is docked as a tab in another view pane window and is not the active tab when the editor starts. - image.Allocate(1, 1); - image.Clear(); - return; - } - - IRenderer* renderer = GetIEditor()->GetRenderer(); - - renderer->EnableSwapBuffers(false); - RenderInternal(); - renderer->EnableSwapBuffers(true); - - int w; - int h; - - if (customSize.isValid()) - { - w = customSize.width(); - h = customSize.height(); - } - else - { - w = width(); - h = height(); - } - - image.Allocate(w, h); - - // the renderer will read the frame buffer of the current render context, so we need to set ours as the current before we execute this command. - SetCurrentContext(); - renderer->ReadFrameBufferFast(image.GetData(), w, h); - RestorePreviousContext(); -} - -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; - - // We queue the window resize event in case the windows is hidden. - // If the QWidget is hidden, the native windows does not resize and the - // swapchain may have the incorrect size. We need to wait - // until it's visible to trigger the resize event. - m_resizeWindowEvent = true; - - GetIEditor()->GetEnv()->pSystem->GetISystemEventDispatcher()->OnSystemEvent(ESYSTEM_EVENT_RESIZE, cx, cy); - SignalUpdate(); - Update(); -} - -void QViewport::showEvent(QShowEvent* ev) -{ - // force a context create once we're shown - // This must be queued, as the showEvent is sent before the widget is actually shown, not after - QMetaObject::invokeMethod(this, "ForceRebuildRenderContext", Qt::QueuedConnection); - - QWidget::showEvent(ev); -} - -void QViewport::ForceRebuildRenderContext() -{ - CreateRenderContext(); -} - -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::WinIdChange) - { - CreateRenderContext(); - } - - 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 72b2024bc4..0000000000 --- a/Code/Sandbox/Plugins/EditorCommon/QViewport.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. - -#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); - void GetImageOffscreen(CImageEx& image, const QSize& customSize); - - // 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(); - void ForceRebuildRenderContext(); -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; - - bool CreateRenderContext(); - void DestroyRenderContext(); - void StorePreviousContext(); -protected: - void SetCurrentContext(); - void RestorePreviousContext(); -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 - HWND m_lastHwnd = 0; - bool m_resizeWindowEvent = false; -}; 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 e1a63b77da..a7b3860905 100644 --- a/Code/Sandbox/Plugins/EditorCommon/editorcommon_files.cmake +++ b/Code/Sandbox/Plugins/EditorCommon/editorcommon_files.cmake @@ -13,18 +13,8 @@ set(FILES EditorCommon.h EditorCommon.cpp EditorCommon.rc - EditorCommon.qrc EditorCommonAPI.h - ManipScene.cpp - ManipScene.h - moc.cpp - QViewportConsumer.h - TimelineContent.h EditorCommon_precompiled.h - CurveEditorControl.cpp - CurveEditorControl.h - DisplayViewportAdapter.cpp - DisplayViewportAdapter.h ActionOutput.h ActionOutput.cpp UiEditorDLLBus.h @@ -32,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 9fc66faa8c..0000000000 --- a/Code/Sandbox/Plugins/EditorCommon/moc.cpp +++ /dev/null @@ -1,23 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#include "EditorCommon_precompiled.h" -#include -#include -#include -#include - -#include -#include -#include -#include 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/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++; } } 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/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/Sandbox/Plugins/EditorCommon/Platform/Linux/platform_linux_files.cmake b/Code/Tools/ProjectManager/Platform/Common/Clang/projectmanager_clang.cmake similarity index 81% rename from Code/Sandbox/Plugins/EditorCommon/Platform/Linux/platform_linux_files.cmake rename to Code/Tools/ProjectManager/Platform/Common/Clang/projectmanager_clang.cmake index 5bfcbe55a6..fb85a6cf2a 100644 --- a/Code/Sandbox/Plugins/EditorCommon/Platform/Linux/platform_linux_files.cmake +++ b/Code/Tools/ProjectManager/Platform/Common/Clang/projectmanager_clang.cmake @@ -9,6 +9,7 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # -set(FILES - ../Common/UnixLike/QPropertyTree/Unicode_UnixLike.cpp +set(LY_COMPILE_OPTIONS + PRIVATE + -fexceptions # The macro PYBIND11_EMBEDDED_MODULE uses a try catch block ) diff --git a/Code/Sandbox/Plugins/EditorCommon/Platform/Mac/platform_mac_files.cmake b/Code/Tools/ProjectManager/Platform/Common/MSVC/projectmanager_msvc.cmake similarity index 82% rename from Code/Sandbox/Plugins/EditorCommon/Platform/Mac/platform_mac_files.cmake rename to Code/Tools/ProjectManager/Platform/Common/MSVC/projectmanager_msvc.cmake index 5bfcbe55a6..669f14eae4 100644 --- a/Code/Sandbox/Plugins/EditorCommon/Platform/Mac/platform_mac_files.cmake +++ b/Code/Tools/ProjectManager/Platform/Common/MSVC/projectmanager_msvc.cmake @@ -9,6 +9,7 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # -set(FILES - ../Common/UnixLike/QPropertyTree/Unicode_UnixLike.cpp +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/Sandbox/Plugins/EditorCommon/Platform/Windows/platform_windows_files.cmake b/Code/Tools/ProjectManager/Platform/Linux/PAL_linux_files.cmake similarity index 93% rename from Code/Sandbox/Plugins/EditorCommon/Platform/Windows/platform_windows_files.cmake rename to Code/Tools/ProjectManager/Platform/Linux/PAL_linux_files.cmake index 4c6a5b0644..a07534ee39 100644 --- a/Code/Sandbox/Plugins/EditorCommon/Platform/Windows/platform_windows_files.cmake +++ b/Code/Tools/ProjectManager/Platform/Linux/PAL_linux_files.cmake @@ -10,5 +10,5 @@ # set(FILES - QPropertyTree/Unicode_Windows.cpp + 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/Gems/ImageProcessing/Code/imageprocessing_headers_files.cmake b/Code/Tools/ProjectManager/Platform/Mac/PAL_mac_files.cmake similarity index 96% rename from Gems/ImageProcessing/Code/imageprocessing_headers_files.cmake rename to Code/Tools/ProjectManager/Platform/Mac/PAL_mac_files.cmake index 5714be5dfb..83124b6315 100644 --- a/Gems/ImageProcessing/Code/imageprocessing_headers_files.cmake +++ b/Code/Tools/ProjectManager/Platform/Mac/PAL_mac_files.cmake @@ -10,4 +10,5 @@ # 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/Resources/Android.svg b/Code/Tools/ProjectManager/Resources/Android.svg new file mode 100644 index 0000000000..a4b610a3d6 --- /dev/null +++ b/Code/Tools/ProjectManager/Resources/Android.svg @@ -0,0 +1,10 @@ + + + Icons / Platform / Android + + + + + + + \ No newline at end of file diff --git a/Code/Tools/ProjectManager/Resources/Linux.svg b/Code/Tools/ProjectManager/Resources/Linux.svg new file mode 100644 index 0000000000..843d60cd82 --- /dev/null +++ b/Code/Tools/ProjectManager/Resources/Linux.svg @@ -0,0 +1,14 @@ + + + Icons / Platform / Linux + + + + + + + + + + + \ No newline at end of file diff --git a/Code/Tools/ProjectManager/Resources/Windows.svg b/Code/Tools/ProjectManager/Resources/Windows.svg new file mode 100644 index 0000000000..46da6693a1 --- /dev/null +++ b/Code/Tools/ProjectManager/Resources/Windows.svg @@ -0,0 +1,7 @@ + + + Icons / Platform / Windows + + + + \ No newline at end of file diff --git a/Code/Tools/ProjectManager/Resources/iOS.svg b/Code/Tools/ProjectManager/Resources/iOS.svg new file mode 100644 index 0000000000..871d36f657 --- /dev/null +++ b/Code/Tools/ProjectManager/Resources/iOS.svg @@ -0,0 +1,3 @@ + + + diff --git a/Code/Tools/ProjectManager/Resources/macOS.svg b/Code/Tools/ProjectManager/Resources/macOS.svg new file mode 100644 index 0000000000..4d433be6a3 --- /dev/null +++ b/Code/Tools/ProjectManager/Resources/macOS.svg @@ -0,0 +1,3 @@ + + + diff --git a/Code/Tools/ProjectManager/Source/GemCatalog/GemCatalog.cpp b/Code/Tools/ProjectManager/Source/GemCatalog/GemCatalog.cpp index 6ceb443df8..6bb1e4959f 100644 --- a/Code/Tools/ProjectManager/Source/GemCatalog/GemCatalog.cpp +++ b/Code/Tools/ProjectManager/Source/GemCatalog/GemCatalog.cpp @@ -21,8 +21,6 @@ namespace O3DE::ProjectManager GemCatalog::GemCatalog(ProjectManagerWindow* window) : ScreenWidget(window) { - ConnectSlotsAndSignals(); - m_gemModel = new GemModel(this); QVBoxLayout* vLayout = new QVBoxLayout(); @@ -56,36 +54,36 @@ namespace O3DE::ProjectManager m_gemModel->AddGem(GemInfo("EMotion FX", "O3DE Foundation", "EMFX is a real-time character animation system. Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.", - (GemInfo::Android | GemInfo::iOS | GemInfo::Windows | GemInfo::Linux), + (GemInfo::Android | GemInfo::iOS | GemInfo::macOS | GemInfo::Windows | GemInfo::Linux), true)); m_gemModel->AddGem(O3DE::ProjectManager::GemInfo("Atom", "O3DE Foundation", "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.", - GemInfo::Android | GemInfo::Windows | GemInfo::Linux, + GemInfo::Android | GemInfo::Windows | GemInfo::Linux | GemInfo::macOS, true)); m_gemModel->AddGem(O3DE::ProjectManager::GemInfo("PhysX", - "O3DE Foundation", + "O3DE London", "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.", - GemInfo::Android | GemInfo::Linux, + GemInfo::Android | GemInfo::Linux | GemInfo::macOS, false)); m_gemModel->AddGem(O3DE::ProjectManager::GemInfo("Certificate Manager", - "O3DE Foundation", + "O3DE Irvine", "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.", GemInfo::Windows, false)); m_gemModel->AddGem(O3DE::ProjectManager::GemInfo("Cloud Gem Framework", - "O3DE Foundation", - "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.", + "O3DE Seattle", + "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.", GemInfo::iOS | GemInfo::Linux, false)); m_gemModel->AddGem(O3DE::ProjectManager::GemInfo("Achievements", "O3DE Foundation", - "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.", + "Lorem ipsum dolor sit amet, consectetur adipiscing elit.", GemInfo::Android | GemInfo::Windows | GemInfo::Linux, false)); } diff --git a/Code/Tools/ProjectManager/Source/GemCatalog/GemInfo.h b/Code/Tools/ProjectManager/Source/GemCatalog/GemInfo.h index e5aa9c41f7..4766187d2a 100644 --- a/Code/Tools/ProjectManager/Source/GemCatalog/GemInfo.h +++ b/Code/Tools/ProjectManager/Source/GemCatalog/GemInfo.h @@ -26,16 +26,18 @@ namespace O3DE::ProjectManager public: enum Platform { - Android = 0x0, - iOS = 0x1, - Linux = 0x2, - macOS = 0x3, - Windows = 0x4 + Android = 1 << 0, + iOS = 1 << 1, + Linux = 1 << 2, + macOS = 1 << 3, + Windows = 1 << 4, + NumPlatforms = 5 }; Q_DECLARE_FLAGS(Platforms, Platform) 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/GemCatalog/GemItemDelegate.cpp b/Code/Tools/ProjectManager/Source/GemCatalog/GemItemDelegate.cpp index 22e77ed40e..434a4aeef2 100644 --- a/Code/Tools/ProjectManager/Source/GemCatalog/GemItemDelegate.cpp +++ b/Code/Tools/ProjectManager/Source/GemCatalog/GemItemDelegate.cpp @@ -22,6 +22,18 @@ namespace O3DE::ProjectManager : QStyledItemDelegate(parent) , m_gemModel(gemModel) { + AddPlatformIcon(GemInfo::Android, ":/Resources/Android.svg"); + AddPlatformIcon(GemInfo::iOS, ":/Resources/iOS.svg"); + AddPlatformIcon(GemInfo::Linux, ":/Resources/Linux.svg"); + AddPlatformIcon(GemInfo::macOS, ":/Resources/macOS.svg"); + AddPlatformIcon(GemInfo::Windows, ":/Resources/Windows.svg"); + } + + void GemItemDelegate::AddPlatformIcon(GemInfo::Platform platform, const QString& iconPath) + { + QPixmap pixmap(iconPath); + qreal aspectRatio = static_cast(pixmap.width()) / pixmap.height(); + m_platformIcons.insert(platform, QIcon(iconPath).pixmap(s_platformIconSize * aspectRatio, s_platformIconSize)); } void GemItemDelegate::paint(QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& modelIndex) const @@ -87,7 +99,7 @@ namespace O3DE::ProjectManager painter->drawText(gemCreatorRect, Qt::TextSingleLine, gemCreator); // Gem summary - const QSize summarySize = QSize(contentRect.width() - s_summaryStartX - s_itemMargins.right() * 4, contentRect.height()); + const QSize summarySize = QSize(contentRect.width() - s_summaryStartX - s_buttonWidth - s_itemMargins.right() * 4, contentRect.height()); const QRect summaryRect = QRect(/*topLeft=*/QPoint(contentRect.left() + s_summaryStartX, contentRect.top()), summarySize); painter->setFont(standardFont); @@ -96,6 +108,10 @@ namespace O3DE::ProjectManager const QString summary = m_gemModel->GetSummary(modelIndex); painter->drawText(summaryRect, Qt::AlignLeft | Qt::TextWordWrap, summary); + + DrawButton(painter, contentRect, modelIndex); + DrawPlatformIcons(painter, contentRect, modelIndex); + painter->restore(); } @@ -105,7 +121,7 @@ namespace O3DE::ProjectManager initStyleOption(&options, modelIndex); int marginsHorizontal = s_itemMargins.left() + s_itemMargins.right() + s_contentMargins.left() + s_contentMargins.right(); - return QSize(marginsHorizontal + s_summaryStartX, s_height); + return QSize(marginsHorizontal + s_buttonWidth + s_summaryStartX, s_height); } bool GemItemDelegate::editorEvent(QEvent* event, QAbstractItemModel* model, const QStyleOptionViewItem& option, const QModelIndex& modelIndex) @@ -132,4 +148,85 @@ namespace O3DE::ProjectManager font.setPixelSize(fontSize); return QFontMetrics(font).boundingRect(text); } + + QRect GemItemDelegate::CalcButtonRect(const QRect& contentRect) const + { + const QPoint topLeft = QPoint(contentRect.right() - s_buttonWidth - s_itemMargins.right(), contentRect.top() + contentRect.height() / 2 - s_buttonHeight / 2); + const QSize size = QSize(s_buttonWidth, s_buttonHeight); + return QRect(topLeft, size); + } + + void GemItemDelegate::DrawPlatformIcons(QPainter* painter, const QRect& contentRect, const QModelIndex& modelIndex) const + { + const GemInfo::Platforms platforms = m_gemModel->GetPlatforms(modelIndex); + int startX = 0; + + // Iterate and draw the platforms in the order they are defined in the enum. + for (int i = 0; i < GemInfo::NumPlatforms; ++i) + { + // Check if the platform is supported by the given gem. + const GemInfo::Platform platform = static_cast(1 << i); + if (platforms & platform) + { + // Get the icon for the platform and draw it. + const auto iterator = m_platformIcons.find(platform); + if (iterator != m_platformIcons.end()) + { + const QPixmap& pixmap = iterator.value(); + painter->drawPixmap(contentRect.left() + startX, contentRect.bottom() - s_platformIconSize, pixmap); + qreal aspectRatio = static_cast(pixmap.width()) / pixmap.height(); + startX += s_platformIconSize * aspectRatio + s_platformIconSize / 2.5; + } + } + } + } + + void GemItemDelegate::DrawButton(QPainter* painter, const QRect& contentRect, const QModelIndex& modelIndex) const + { + painter->save(); + const QRect buttonRect = CalcButtonRect(contentRect); + QPoint circleCenter; + QString buttonText; + + const bool isAdded = m_gemModel->IsAdded(modelIndex); + if (isAdded) + { + painter->setBrush(m_buttonEnabledColor); + painter->setPen(m_buttonEnabledColor); + + circleCenter = buttonRect.center() + QPoint(buttonRect.width() / 2 - s_buttonBorderRadius, 1); + buttonText = "Added"; + } + else + { + circleCenter = buttonRect.center() + QPoint(-buttonRect.width() / 2 + s_buttonBorderRadius + 1, 1); + buttonText = "Get"; + } + + // Rounded rect + painter->drawRoundedRect(buttonRect, s_buttonBorderRadius, s_buttonBorderRadius); + + // Text + QFont font; + QRect textRect = GetTextRect(font, buttonText, s_buttonFontSize); + if (isAdded) + { + textRect = QRect(buttonRect.left(), buttonRect.top(), buttonRect.width() - s_buttonCircleRadius * 2.0, buttonRect.height()); + } + else + { + textRect = QRect(buttonRect.left() + s_buttonCircleRadius * 2.0, buttonRect.top(), buttonRect.width() - s_buttonCircleRadius * 2.0, buttonRect.height()); + } + + font.setPixelSize(s_buttonFontSize); + painter->setFont(font); + painter->setPen(m_textColor); + painter->drawText(textRect, Qt::AlignCenter, buttonText); + + // Circle + painter->setBrush(m_textColor); + painter->drawEllipse(circleCenter, s_buttonCircleRadius, s_buttonCircleRadius); + + painter->restore(); + } } // namespace O3DE::ProjectManager diff --git a/Code/Tools/ProjectManager/Source/GemCatalog/GemItemDelegate.h b/Code/Tools/ProjectManager/Source/GemCatalog/GemItemDelegate.h index 3528d07d78..ee0392e188 100644 --- a/Code/Tools/ProjectManager/Source/GemCatalog/GemItemDelegate.h +++ b/Code/Tools/ProjectManager/Source/GemCatalog/GemItemDelegate.h @@ -16,6 +16,7 @@ #include #include "GemInfo.h" #include "GemModel.h" +#include #endif QT_FORWARD_DECLARE_CLASS(QEvent) @@ -38,6 +39,9 @@ namespace O3DE::ProjectManager private: void CalcRects(const QStyleOptionViewItem& option, const QModelIndex& modelIndex, QRect& outFullRect, QRect& outItemRect, QRect& outContentRect) const; QRect GetTextRect(QFont& font, const QString& text, qreal fontSize) const; + QRect CalcButtonRect(const QRect& contentRect) const; + void DrawPlatformIcons(QPainter* painter, const QRect& contentRect, const QModelIndex& modelIndex) const; + void DrawButton(QPainter* painter, const QRect& contentRect, const QModelIndex& modelIndex) const; GemModel* m_gemModel = nullptr; @@ -47,9 +51,10 @@ namespace O3DE::ProjectManager const QColor m_backgroundColor = QColor("#333333"); // Outside of the actual gem item const QColor m_itemBackgroundColor = QColor("#404040"); // Background color of the gem item const QColor m_borderColor = QColor("#1E70EB"); + const QColor m_buttonEnabledColor = QColor("#00B931"); // Item - inline constexpr static int s_height = 140; // Gem item total height + inline constexpr static int s_height = 135; // Gem item total height inline constexpr static qreal s_gemNameFontSize = 16.0; inline constexpr static qreal s_fontSize = 15.0; inline constexpr static int s_summaryStartX = 200; @@ -58,5 +63,17 @@ namespace O3DE::ProjectManager inline constexpr static QMargins s_itemMargins = QMargins(/*left=*/20, /*top=*/10, /*right=*/20, /*bottom=*/10); // Item border distances inline constexpr static QMargins s_contentMargins = QMargins(/*left=*/15, /*top=*/12, /*right=*/12, /*bottom=*/12); // Distances of the elements within an item to the item borders inline constexpr static int s_borderWidth = 4; + + // Button + inline constexpr static int s_buttonWidth = 70; + inline constexpr static int s_buttonHeight = 24; + inline constexpr static int s_buttonBorderRadius = 12; + inline constexpr static int s_buttonCircleRadius = s_buttonBorderRadius - 3; + inline constexpr static qreal s_buttonFontSize = 12.0; + + // Platform icons + void AddPlatformIcon(GemInfo::Platform platform, const QString& iconPath); + inline constexpr static int s_platformIconSize = 16; + QHash m_platformIcons; }; } // namespace O3DE::ProjectManager diff --git a/Code/Tools/ProjectManager/Source/GemCatalog/GemModel.cpp b/Code/Tools/ProjectManager/Source/GemCatalog/GemModel.cpp index 89e629cf5f..27905fd4d2 100644 --- a/Code/Tools/ProjectManager/Source/GemCatalog/GemModel.cpp +++ b/Code/Tools/ProjectManager/Source/GemCatalog/GemModel.cpp @@ -55,7 +55,7 @@ namespace O3DE::ProjectManager return modelIndex.data(RoleCreator).toString(); } - int GemModel::GetPlatforms(const QModelIndex& modelIndex) const + GemInfo::Platforms GemModel::GetPlatforms(const QModelIndex& modelIndex) const { return static_cast(modelIndex.data(RolePlatforms).toInt()); } diff --git a/Code/Tools/ProjectManager/Source/GemCatalog/GemModel.h b/Code/Tools/ProjectManager/Source/GemCatalog/GemModel.h index 33ae02dc8a..4ce9de32fc 100644 --- a/Code/Tools/ProjectManager/Source/GemCatalog/GemModel.h +++ b/Code/Tools/ProjectManager/Source/GemCatalog/GemModel.h @@ -34,7 +34,7 @@ namespace O3DE::ProjectManager QString GetName(const QModelIndex& modelIndex) const; QString GetCreator(const QModelIndex& modelIndex) const; - int GetPlatforms(const QModelIndex& modelIndex) const; + GemInfo::Platforms GetPlatforms(const QModelIndex& modelIndex) const; QString GetSummary(const QModelIndex& modelIndex) const; bool IsAdded(const QModelIndex& modelIndex) const; diff --git a/Code/Tools/ProjectManager/Source/LinkWidget.cpp b/Code/Tools/ProjectManager/Source/LinkWidget.cpp new file mode 100644 index 0000000000..fddc4cd8c9 --- /dev/null +++ b/Code/Tools/ProjectManager/Source/LinkWidget.cpp @@ -0,0 +1,52 @@ +/* +* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or +* its licensors. +* +* For complete copyright and license terms please see the LICENSE at the root of this +* distribution (the "License"). All use of this software is governed by the License, +* or, if provided, by the license below or the license accompanying this file. Do not +* remove or 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 O3DE::ProjectManager +{ + LinkLabel::LinkLabel(const QString& text, const QUrl& url, QWidget* parent) + : QLabel(text, parent) + , m_url(url) + { + SetDefaultStyle(); + } + + void LinkLabel::mousePressEvent([[maybe_unused]] QMouseEvent* event) + { + QDesktopServices::openUrl(m_url); + } + + void LinkLabel::enterEvent([[maybe_unused]] QEvent* event) + { + setStyleSheet("font-size: 9pt; color: #94D2FF; text-decoration: underline;"); + } + + void LinkLabel::leaveEvent([[maybe_unused]] QEvent* event) + { + SetDefaultStyle(); + } + + void LinkLabel::SetUrl(const QUrl& url) + { + m_url = url; + } + + void LinkLabel::SetDefaultStyle() + { + setStyleSheet("font-size: 9pt; color: #94D2FF;"); + } +} // namespace O3DE::ProjectManager diff --git a/Code/Tools/ProjectManager/Source/LinkWidget.h b/Code/Tools/ProjectManager/Source/LinkWidget.h new file mode 100644 index 0000000000..7055dce2af --- /dev/null +++ b/Code/Tools/ProjectManager/Source/LinkWidget.h @@ -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. +* +*/ + +#pragma once + +#if !defined(Q_MOC_RUN) +#include +#include +#endif + +QT_FORWARD_DECLARE_CLASS(QEvent) +QT_FORWARD_DECLARE_CLASS(QMouseEvent) +QT_FORWARD_DECLARE_CLASS(QWidget) + +namespace O3DE::ProjectManager +{ + class LinkLabel + : public QLabel + { + public: + LinkLabel(const QString& text, const QUrl& url = {}, QWidget* parent = nullptr); + + void SetUrl(const QUrl& url); + private: + void mousePressEvent(QMouseEvent* event) override; + void enterEvent(QEvent* event) override; + void leaveEvent(QEvent* event) override; + void SetDefaultStyle(); + + private: + QUrl m_url; + }; +} // namespace O3DE::ProjectManager diff --git a/Code/CryEngine/CrySystem/Serialization/ArchiveHost.h b/Code/Tools/ProjectManager/Source/ProjectInfo.cpp similarity index 59% rename from Code/CryEngine/CrySystem/Serialization/ArchiveHost.h rename to Code/Tools/ProjectManager/Source/ProjectInfo.cpp index 360dded0c7..b3bdb87224 100644 --- a/Code/CryEngine/CrySystem/Serialization/ArchiveHost.h +++ b/Code/Tools/ProjectManager/Source/ProjectInfo.cpp @@ -9,13 +9,16 @@ * 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 "ProjectInfo.h" -#include - -namespace Serialization +namespace O3DE::ProjectManager { - IArchiveHost* CreateArchiveHost(); -} + 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/Gems/ImageProcessing/Code/Source/Editor/ImagePopup.h b/Code/Tools/ProjectManager/Source/ProjectInfo.h similarity index 52% rename from Gems/ImageProcessing/Code/Source/Editor/ImagePopup.h rename to Code/Tools/ProjectManager/Source/ProjectInfo.h index adc91d9dfe..e5dca97d5e 100644 --- a/Gems/ImageProcessing/Code/Source/Editor/ImagePopup.h +++ b/Code/Tools/ProjectManager/Source/ProjectInfo.h @@ -12,33 +12,25 @@ #pragma once - #if !defined(Q_MOC_RUN) -#include -#include -#include +#include +#include #endif -namespace Ui +namespace O3DE::ProjectManager { - class ImagePopup; -} - -namespace ImageProcessingEditor -{ - class ImagePopup - : public QDialog + class ProjectInfo { - Q_OBJECT public: - AZ_CLASS_ALLOCATOR(ImagePopup, AZ::SystemAllocator, 0); - explicit ImagePopup(QImage previewImage, QWidget* parent = nullptr); - ~ImagePopup(); + ProjectInfo() = default; + ProjectInfo(const QString& path, const QString& projectName, const QString& productName, const AZ::Uuid projectId); - private: - QScopedPointer m_ui; - QImage m_previewImage; - + // 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 ImageProcessingEditor - +} // 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/TagWidget.cpp b/Code/Tools/ProjectManager/Source/TagWidget.cpp new file mode 100644 index 0000000000..3e80944204 --- /dev/null +++ b/Code/Tools/ProjectManager/Source/TagWidget.cpp @@ -0,0 +1,98 @@ +/* +* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or +* its licensors. +* +* For complete copyright and license terms please see the LICENSE at the root of this +* distribution (the "License"). All use of this software is governed by the License, +* or, if provided, by the license below or the license accompanying this file. Do not +* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* +*/ + +#include +#include + +namespace O3DE::ProjectManager +{ + TagWidget::TagWidget(const QString& text, QWidget* parent) + : QLabel(text, parent) + { + setFixedHeight(35); + setMargin(5); + setStyleSheet("font-size: 12pt; background-color: #333333; border-radius: 4px;"); + } + + TagContainerWidget::TagContainerWidget(QWidget* parent) + : QWidget(parent) + { + m_layout = new QVBoxLayout(); + m_layout->setAlignment(Qt::AlignTop); + m_layout->setMargin(0); + setLayout(m_layout); + } + + void TagContainerWidget::Update(const QStringList& tags) + { + QWidget* parentWidget = qobject_cast(parent()); + int width = 250; + if (parentWidget) + { + width = parentWidget->width(); + } + + if (m_widget) + { + // Hide the old widget and request deletion. + m_widget->hide(); + m_widget->deleteLater(); + } + + QVBoxLayout* vLayout = new QVBoxLayout(); + m_widget = new QWidget(this); + m_widget->setLayout(vLayout); + m_layout->addWidget(m_widget); + + vLayout->setAlignment(Qt::AlignTop); + vLayout->setMargin(0); + + QHBoxLayout* hLayout = nullptr; + int usedSpaceInRow = 0; + const int numTags = tags.count(); + + for (int i = 0; i < numTags; ++i) + { + // Create the new tag widget. + TagWidget* tagWidget = new TagWidget(tags[i]); + const int tagWidgetWidth = tagWidget->minimumSizeHint().width(); + + // Calculate the width we're currently using in the current row. Does the new tag still fit in the current row? + const bool isRowFull = width - usedSpaceInRow - tagWidgetWidth < 0; + if (isRowFull || i == 0) + { + // Add a spacer widget after the last tag widget in a row to push the tag widgets to the left. + if (i > 0) + { + QWidget* spacerWidget = new QWidget(); + spacerWidget->setSizePolicy(QSizePolicy::Ignored, QSizePolicy::Fixed); + hLayout->addWidget(spacerWidget); + } + + // Add a new row for the current tag widget. + hLayout = new QHBoxLayout(); + hLayout->setAlignment(Qt::AlignLeft); + hLayout->setMargin(0); + vLayout->addLayout(hLayout); + + // Reset the used space in the row. + usedSpaceInRow = 0; + } + + // Calculate the width of the tag widgets including the spacing between them of the current row. + usedSpaceInRow += tagWidgetWidth + hLayout->spacing(); + + // Add the tag widget to the current row. + hLayout->addWidget(tagWidget); + } + } +} // namespace O3DE::ProjectManager diff --git a/Code/Tools/ProjectManager/Source/TagWidget.h b/Code/Tools/ProjectManager/Source/TagWidget.h new file mode 100644 index 0000000000..5597b302c7 --- /dev/null +++ b/Code/Tools/ProjectManager/Source/TagWidget.h @@ -0,0 +1,52 @@ +/* +* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or +* its licensors. +* +* For complete copyright and license terms please see the LICENSE at the root of this +* distribution (the "License"). All use of this software is governed by the License, +* or, if provided, by the license below or the license accompanying this file. Do not +* remove or 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 + +QT_FORWARD_DECLARE_CLASS(QVBoxLayout) + +namespace O3DE::ProjectManager +{ + // Single tag + class TagWidget + : public QLabel + { + Q_OBJECT // AUTOMOC + + public: + explicit TagWidget(const QString& text, QWidget* parent = nullptr); + ~TagWidget() = default; + }; + + // Widget containing multiple tags, automatically wrapping based on the size + class TagContainerWidget + : public QWidget + { + Q_OBJECT // AUTOMOC + + public: + explicit TagContainerWidget(QWidget* parent = nullptr); + ~TagContainerWidget() = default; + + void Update(const QStringList& tags); + + private: + QVBoxLayout* m_layout = nullptr; + QWidget* m_widget = nullptr; + }; +} // 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); + + O3DE::ProjectManager::ProjectManagerWindow window(nullptr, engineRootPath); + window.show(); + + runSuccess = app.exec(); } + AZ::AllocatorInstance::Destroy(); - AzQtComponents::StyleManager styleManager(&app); - styleManager.initialize(&app, engineRootPath); - - O3DE::ProjectManager::ProjectManagerWindow window(nullptr, engineRootPath); - window.show(); - - return app.exec(); + return runSuccess; } diff --git a/Code/Tools/ProjectManager/project_manager.qrc b/Code/Tools/ProjectManager/project_manager.qrc index 408398584b..6509a9f940 100644 --- a/Code/Tools/ProjectManager/project_manager.qrc +++ b/Code/Tools/ProjectManager/project_manager.qrc @@ -1,8 +1,13 @@ - - + + Resources/ProjectManager.qss Resources/Add.svg Resources/Select_Folder.svg Resources/o3de_editor.ico + Resources/Windows.svg + Resources/Android.svg + Resources/iOS.svg + Resources/Linux.svg + Resources/macOS.svg - \ No newline at end of file + diff --git a/Code/Tools/ProjectManager/project_manager_files.cmake b/Code/Tools/ProjectManager/project_manager_files.cmake index b206cf1456..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 @@ -34,6 +39,10 @@ set(FILES Source/EngineSettings.h Source/EngineSettings.cpp Source/EngineSettings.ui + Source/LinkWidget.h + Source/LinkWidget.cpp + Source/TagWidget.h + Source/TagWidget.cpp Source/GemCatalog/GemCatalog.h Source/GemCatalog/GemCatalog.cpp Source/GemCatalog/GemInfo.h diff --git a/Code/Tools/SceneAPI/SceneCore/Tests/Containers/SceneBehaviorTests.cpp b/Code/Tools/SceneAPI/SceneCore/Tests/Containers/SceneBehaviorTests.cpp index 8d7fb63baf..3b6625ad5e 100644 --- a/Code/Tools/SceneAPI/SceneCore/Tests/Containers/SceneBehaviorTests.cpp +++ b/Code/Tools/SceneAPI/SceneCore/Tests/Containers/SceneBehaviorTests.cpp @@ -364,6 +364,10 @@ namespace AZ 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&)); 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 diff --git a/Gems/AWSClientAuth/Code/Tests/AWSClientAuthGemMock.h b/Gems/AWSClientAuth/Code/Tests/AWSClientAuthGemMock.h index 51fe236171..e40edcc864 100644 --- a/Gems/AWSClientAuth/Code/Tests/AWSClientAuthGemMock.h +++ b/Gems/AWSClientAuth/Code/Tests/AWSClientAuthGemMock.h @@ -577,6 +577,10 @@ namespace AWSClientAuthUnitTest void UnregisterComponentDescriptor(const AZ::ComponentDescriptor*) override { } void RegisterEntityAddedEventHandler(AZ::EntityAddedEvent::Handler&) override { } void RegisterEntityRemovedEventHandler(AZ::EntityRemovedEvent::Handler&) override { } + void RegisterEntityActivatedEventHandler(AZ::EntityActivatedEvent::Handler&) override { } + void RegisterEntityDeactivatedEventHandler(AZ::EntityDeactivatedEvent::Handler&) override { } + void SignalEntityActivated(AZ::Entity*) override { } + void SignalEntityDeactivated(AZ::Entity*) override { } bool AddEntity(AZ::Entity*) override { return true; } bool RemoveEntity(AZ::Entity*) override { return true; } bool DeleteEntity(const AZ::EntityId&) override { return true; } diff --git a/Gems/Atom/Asset/ImageProcessingAtom/Code/Tests/ImageProcessing_Test.cpp b/Gems/Atom/Asset/ImageProcessingAtom/Code/Tests/ImageProcessing_Test.cpp index c1795f7217..540178f4d9 100644 --- a/Gems/Atom/Asset/ImageProcessingAtom/Code/Tests/ImageProcessing_Test.cpp +++ b/Gems/Atom/Asset/ImageProcessingAtom/Code/Tests/ImageProcessing_Test.cpp @@ -95,28 +95,32 @@ namespace UnitTest class ImageProcessingTest : public ::testing::Test , public AllocatorsBase - , public ComponentApplicationBus::Handler + , public AZ::ComponentApplicationBus::Handler { public: ////////////////////////////////////////////////////////////////////////// // ComponentApplicationMessages. - ComponentApplication* GetApplication() override { return nullptr; } - void RegisterComponentDescriptor(const ComponentDescriptor*) override { } - void UnregisterComponentDescriptor(const ComponentDescriptor*) override { } - void RegisterEntityAddedEventHandler(EntityAddedEvent::Handler&) override { } - void RegisterEntityRemovedEventHandler(EntityRemovedEvent::Handler&) override { } - bool AddEntity(Entity*) override { return false; } - bool RemoveEntity(Entity*) override { return false; } - bool DeleteEntity(const EntityId&) override { return false; } - Entity* FindEntity(const EntityId&) override { return nullptr; } - SerializeContext* GetSerializeContext() override { return m_context.get(); } - BehaviorContext* GetBehaviorContext() override { return nullptr; } + AZ::ComponentApplication* GetApplication() override { return nullptr; } + void RegisterComponentDescriptor(const AZ::ComponentDescriptor*) override { } + void UnregisterComponentDescriptor(const AZ::ComponentDescriptor*) override { } + void RegisterEntityAddedEventHandler(AZ::EntityAddedEvent::Handler&) override { } + void RegisterEntityRemovedEventHandler(AZ::EntityRemovedEvent::Handler&) override { } + void RegisterEntityActivatedEventHandler(AZ::EntityActivatedEvent::Handler&) override { } + void RegisterEntityDeactivatedEventHandler(AZ::EntityDeactivatedEvent::Handler&) override { } + void SignalEntityActivated(AZ::Entity*) override { } + void SignalEntityDeactivated(AZ::Entity*) override { } + bool AddEntity(AZ::Entity*) override { return false; } + bool RemoveEntity(AZ::Entity*) override { return false; } + bool DeleteEntity(const AZ::EntityId&) override { return false; } + Entity* FindEntity(const AZ::EntityId&) override { return nullptr; } + AZ::SerializeContext* GetSerializeContext() override { return m_context.get(); } + AZ::BehaviorContext* GetBehaviorContext() override { return nullptr; } AZ::JsonRegistrationContext* GetJsonRegistrationContext() override { return m_jsonRegistrationContext.get(); } const char* GetAppRoot() const override { return nullptr; } const char* GetEngineRoot() const override { return nullptr; } const char* GetExecutableFolder() const override { return nullptr; } - Debug::DrillerManager* GetDrillerManager() override { return nullptr; } - void EnumerateEntities(const EntityCallback& /*callback*/) override {} + AZ::Debug::DrillerManager* GetDrillerManager() override { return nullptr; } + void EnumerateEntities(const AZ::ComponentApplicationRequests::EntityCallback& /*callback*/) override {} void QueryApplicationType(AZ::ApplicationTypeQuery& /*appType*/) const override {} ////////////////////////////////////////////////////////////////////////// @@ -134,6 +138,7 @@ namespace UnitTest // Adding this handler to allow utility functions access the serialize context ComponentApplicationBus::Handler::BusConnect(); + AZ::Interface::Register(this); AZ::AllocatorInstance::Create(); AZ::AllocatorInstance::Create(); @@ -212,6 +217,7 @@ namespace UnitTest AZ::AllocatorInstance::Destroy(); AZ::AllocatorInstance::Destroy(); + AZ::Interface::Unregister(this); ComponentApplicationBus::Handler::BusDisconnect(); AllocatorsBase::TeardownAllocator(); } diff --git a/Gems/Atom/Bootstrap/Code/Source/BootstrapSystemComponent.cpp b/Gems/Atom/Bootstrap/Code/Source/BootstrapSystemComponent.cpp index ddf0ae9274..e3bdb28046 100644 --- a/Gems/Atom/Bootstrap/Code/Source/BootstrapSystemComponent.cpp +++ b/Gems/Atom/Bootstrap/Code/Source/BootstrapSystemComponent.cpp @@ -15,6 +15,7 @@ #include #include #include +#include #include #include @@ -166,6 +167,18 @@ namespace AZ RPI::RPISystemInterface::Get()->InitializeSystemAssets(); + if (!RPI::RPISystemInterface::Get()->IsInitialized()) + { + AZ::OSString msgBoxMessage; + msgBoxMessage.append("RPI System could not initialize correctly. Check log for detail."); + + AZ::NativeUI::NativeUIRequestBus::Broadcast( + &AZ::NativeUI::NativeUIRequestBus::Events::DisplayOkDialog, "O3DE Fatal Error", msgBoxMessage.c_str(), false); + AzFramework::ApplicationRequests::Bus::Broadcast(&AzFramework::ApplicationRequests::ExitMainLoop); + + return; + } + // In the case of the game we want to call create and register the scene as a soon as we can // because a level could be loaded in autoexec.cfg and that will assert if there is no scene registered // to get the feature processors for the components. So we can't wait until the tick (whereas the Editor wants to wait) 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..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_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]; 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 a83ea629e4..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) 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 22751b49bc..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) diff --git a/Gems/Atom/Feature/Common/Assets/ShaderLib/Atom/Features/BlendUtility.azsli b/Gems/Atom/Feature/Common/Assets/ShaderLib/Atom/Features/BlendUtility.azsli index 631a1403d7..5fac839088 100644 --- a/Gems/Atom/Feature/Common/Assets/ShaderLib/Atom/Features/BlendUtility.azsli +++ b/Gems/Atom/Feature/Common/Assets/ShaderLib/Atom/Features/BlendUtility.azsli @@ -37,8 +37,6 @@ float3 TextureBlend_Overlay(float3 target, float3 blend) //! @return the resulting blended color float3 ApplyTextureBlend(float3 color, float3 blendColor, float factor, TextureBlendMode blendMode) { - // More info to help understand some of these blend modes: https://wiki.agscollab.com/pages/viewpage.action?pageId=15764930 - if(blendMode == TextureBlendMode::Multiply) { return factor * color * blendColor; 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..e27cbc2195 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 @@ -25,7 +25,7 @@ class LightCullingTileIterator float viewz = abs(svPosition.w); - // https://jira.agscollab.com/browse/ATOM-4198 + // ATOM-4198 // Replace GetDimensions() with a cbuffer uint read. Reading it from a cbuffer should be faster uint tileWidth, tileHeight; tileLightDataTex.GetDimensions(tileWidth, tileHeight); diff --git a/Gems/Atom/Feature/Common/Assets/ShaderLib/Atom/Features/PBR/Lights/PointLight.azsli b/Gems/Atom/Feature/Common/Assets/ShaderLib/Atom/Features/PBR/Lights/PointLight.azsli index a59eb89dc7..b28f0f1708 100644 --- a/Gems/Atom/Feature/Common/Assets/ShaderLib/Atom/Features/PBR/Lights/PointLight.azsli +++ b/Gems/Atom/Feature/Common/Assets/ShaderLib/Atom/Features/PBR/Lights/PointLight.azsli @@ -13,6 +13,49 @@ #pragma once #include +#include + +// The order should match m_pointShadowTransforms in PointLightFeatureProcessor.h/.cpp +static const float3 PointLightShadowCubemapDirections[6] = {float3(-1,0,0), float3(1,0,0), float3(0,-1,0), float3(0,1,0), float3(0,0,-1), float3(0,0,1)}; + +int GetPointLightShadowCubemapFace(const float3 targetPos, const float3 lightPos) +{ + const float3 toPoint = targetPos - lightPos; + const float maxElement = max(abs(toPoint.z), max(abs(toPoint.x), abs(toPoint.y))); + if (toPoint.x == -maxElement) + { + return 0; + } + else if (toPoint.x == maxElement) + { + return 1; + } + else if (toPoint.y == -maxElement) + { + return 2; + } + else if (toPoint.y == maxElement) + { + return 3; + } + else if (toPoint.z == -maxElement) + { + return 4; + } + else + { + return 5; + } +} + +// PointLight::m_shadowIndices actually consists of uint16_t x 6 on the CPU, but visible as a uint32_t x 3 on the GPU. +// This function returns the proper uint16_t value given an input face in the range 0-5 +int UnpackPointLightShadowIndex(const ViewSrg::PointLight light, const int face) +{ + const int index = face >> 1; + const int shiftAmount = (face & 1) * 16; + return (light.m_shadowIndices[index] >> shiftAmount) & 0xFFFF; +} void ApplyPointLight(ViewSrg::PointLight light, Surface surface, inout LightingData lightingData) { @@ -31,11 +74,38 @@ void ApplyPointLight(ViewSrg::PointLight light, Surface surface, inout LightingD d2 = max(0.001 * 0.001, d2); // clamp the light to at least 1mm away to avoid extreme values. float3 lightIntensity = (light.m_rgbIntensityCandelas / d2) * radiusAttenuation; + // shadow + float litRatio = 1.0; + + // How much is back face shadowed, it's set to the reverse of litRatio to share the same default value with thickness, which should be 0 if no shadow map available + float backShadowRatio = 0.0; + if (o_enableShadows) + { + const int shadowCubemapFace = GetPointLightShadowCubemapFace(surface.position, light.m_position); + const int shadowIndex = UnpackPointLightShadowIndex(light, shadowCubemapFace); + + litRatio *= ProjectedShadow::GetVisibility( + shadowIndex, + light.m_position, + surface.position, + PointLightShadowCubemapDirections[shadowCubemapFace], + surface.normal); + + // Use backShadowRatio to carry thickness from shadow map for thick mode + backShadowRatio = 1.0 - litRatio; + if (o_transmission_mode == TransmissionMode::ThickObject) + { + backShadowRatio = ProjectedShadow::GetThickness( + shadowIndex, + surface.position); + } + } + // Diffuse contribution - lightingData.diffuseLighting += GetDiffuseLighting(surface, lightingData, lightIntensity, normalize(posToLight)); + lightingData.diffuseLighting += GetDiffuseLighting(surface, lightingData, lightIntensity, normalize(posToLight)) * litRatio; // Tranmission contribution - lightingData.translucentBackLighting += GetBackLighting(surface, lightingData, lightIntensity, normalize(posToLight), 0.0); + lightingData.translucentBackLighting += GetBackLighting(surface, lightingData, lightIntensity, normalize(posToLight), backShadowRatio); // Adjust the light direcion for specular based on bulb size 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; } diff --git a/Gems/Atom/Feature/Common/Assets/ShaderLib/Atom/Features/RayTracing/RayTracingSceneSrg.azsli b/Gems/Atom/Feature/Common/Assets/ShaderLib/Atom/Features/RayTracing/RayTracingSceneSrg.azsli index a7bb6cd3b1..fdf7ba92de 100644 --- a/Gems/Atom/Feature/Common/Assets/ShaderLib/Atom/Features/RayTracing/RayTracingSceneSrg.azsli +++ b/Gems/Atom/Feature/Common/Assets/ShaderLib/Atom/Features/RayTracing/RayTracingSceneSrg.azsli @@ -61,6 +61,8 @@ ShaderResourceGroup RayTracingSceneSrg : SRG_RayTracingScene float m_invAttenuationRadiusSquared; float3 m_rgbIntensity; float m_bulbRadius; + uint3 m_shadowIndices; + uint m_padding; }; StructuredBuffer m_pointLights; diff --git a/Gems/Atom/Feature/Common/Assets/ShaderResourceGroups/CoreLights/ViewSrg.azsli b/Gems/Atom/Feature/Common/Assets/ShaderResourceGroups/CoreLights/ViewSrg.azsli index 5404cf8b69..7a51d4c629 100644 --- a/Gems/Atom/Feature/Common/Assets/ShaderResourceGroups/CoreLights/ViewSrg.azsli +++ b/Gems/Atom/Feature/Common/Assets/ShaderResourceGroups/CoreLights/ViewSrg.azsli @@ -73,6 +73,8 @@ partial ShaderResourceGroup ViewSrg float m_invAttenuationRadiusSquared; // For a radius at which this light no longer has an effect, 1 / radius^2. float3 m_rgbIntensityCandelas; float m_bulbRadius; + uint3 m_shadowIndices; + uint m_padding; }; StructuredBuffer m_pointLights; diff --git a/Gems/Atom/Feature/Common/Assets/Shaders/LightCulling/LightCulling.azsl b/Gems/Atom/Feature/Common/Assets/Shaders/LightCulling/LightCulling.azsl index 367720d13b..d08c572867 100644 --- a/Gems/Atom/Feature/Common/Assets/Shaders/LightCulling/LightCulling.azsl +++ b/Gems/Atom/Feature/Common/Assets/Shaders/LightCulling/LightCulling.azsl @@ -17,7 +17,7 @@ #include #include -enum QuadLightFlag // Copied from QuadLight.azsli. See https://jira.agscollab.com/browse/ATOM-3731 +enum QuadLightFlag // Copied from QuadLight.azsli. See ATOM-3731 { None = 0x00, EmitsBothDirections = 0x01, // 1 << 0, // Quad should emit light from both sides @@ -33,7 +33,7 @@ ShaderResourceGroup PassSrg : SRG_PerPass { // Figure out how to remove duplicate struct definitions. // These are also defined in View.srg - // https://jira.agscollab.com/browse/ATOM-3731 + // ATOM-3731 struct SimplePointLight { @@ -59,6 +59,8 @@ ShaderResourceGroup PassSrg : SRG_PerPass float m_invAttenuationRadiusSquared; // For a radius at which this light no longer has an effect, 1 / radius^2. float3 m_rgbIntensityCandelas; float m_bulbRadius; + uint3 m_shadowIndices; + uint m_padding; }; struct DiskLight @@ -370,7 +372,7 @@ void CullDecals(uint groupIndex, TileLightData tileLightData, float3 aabb_center float3 decalPosition = WorldToView_Point(decal.m_position); // just wrapping a bounding sphere around a cube for now to get a minor perf boost. i.e. the sphere radius is sqrt(x*x + y*y + z*z) - // https://jira.agscollab.com/browse/ATOM-4224 - try AABB-AABB and implement depth binning for the decals + // ATOM-4224 - try AABB-AABB and implement depth binning for the decals float maxHalfSize = max(max(decal.m_halfSize.x, decal.m_halfSize.y), decal.m_halfSize.z); float boundingSphereRadiusSqr = maxHalfSize * maxHalfSize * 3; @@ -378,7 +380,7 @@ void CullDecals(uint groupIndex, TileLightData tileLightData, float3 aabb_center if (potentiallyIntersects) { // Implement and profile fine-grained light culling testing - // https://jira.agscollab.com/browse/ATOM-3732 + // ATOM-3732 MarkLightAsVisibleInSharedMemory(decalIndex, 0xFFFF); } } @@ -391,7 +393,7 @@ void CullPointLight(uint lightIndex, float3 lightPosition, float invLightRadius, if (potentiallyIntersects) { // Implement and profile fine-grained light culling testing - // https://jira.agscollab.com/browse/ATOM-3732 + // ATOM-3732 uint inside = 0; float2 minmax = ComputePointLightMinMaxZ(rsqrt(invLightRadius), lightPosition); @@ -432,7 +434,7 @@ void CullSimpleSpotLights(uint groupIndex, TileLightData tileLightData, float3 a if (potentiallyIntersects) { // Implement and profile fine-grained light culling testing - // https://jira.agscollab.com/browse/ATOM-3732 + // ATOM-3732 uint inside = 0; float2 minmax = ComputeSimpleSpotLightMinMax(light, lightPosition); @@ -477,7 +479,7 @@ void CullDiskLights(uint groupIndex, TileLightData tileLightData, float3 aabb_ce if (potentiallyIntersects) { // Implement and profile fine-grained light culling testing - // https://jira.agscollab.com/browse/ATOM-3732 + // ATOM-3732 uint inside = 0; float2 minmax = ComputeDiskLightMinMax(light, lightPosition); @@ -505,7 +507,7 @@ void CullCapsuleLights(uint groupIndex, TileLightData tileLightData, float3 aabb if (potentiallyIntersects) { // Implement and profile fine-grained light culling testing - // https://jira.agscollab.com/browse/ATOM-3732 + // ATOM-3732 uint inside = 0; float2 minmax = ComputeCapsuleLightMinMax(light, lightMiddleView, lightFalloffRadius); @@ -520,7 +522,7 @@ void CullCapsuleLights(uint groupIndex, TileLightData tileLightData, float3 aabb void CullQuadLights(uint groupIndex, TileLightData tileLightData, float3 aabb_center, float3 aabb_extents) { // Implement and profile fine-grained light culling testing - // https://jira.agscollab.com/browse/ATOM-3732 + // ATOM-3732 for (uint lightIndex = groupIndex ; lightIndex < PassSrg::m_quadLightCount ; lightIndex += TILE_DIM_X * TILE_DIM_Y) { diff --git a/Gems/Atom/Feature/Common/Assets/Shaders/LightCulling/LightCullingHeatmap.azsl b/Gems/Atom/Feature/Common/Assets/Shaders/LightCulling/LightCullingHeatmap.azsl index 14a5f810cf..eae2acc0bc 100644 --- a/Gems/Atom/Feature/Common/Assets/Shaders/LightCulling/LightCullingHeatmap.azsl +++ b/Gems/Atom/Feature/Common/Assets/Shaders/LightCulling/LightCullingHeatmap.azsl @@ -242,7 +242,7 @@ PSOutput MainPS(VSOutput IN) // Set this value to > 0 to actually see this pass. It is currently always active. OUT.m_color.w = PassSrg::m_heatmapOpacity; - // https://jira.agscollab.com/browse/ATOM-3682 (improve heatmap integration with the pass system) + // ATOM-3682 (improve heatmap integration with the pass system) return OUT; } diff --git a/Gems/Atom/Feature/Common/Assets/Shaders/LightCulling/LightCullingRemap.azsl b/Gems/Atom/Feature/Common/Assets/Shaders/LightCulling/LightCullingRemap.azsl index abef44f1fd..f56721b614 100644 --- a/Gems/Atom/Feature/Common/Assets/Shaders/LightCulling/LightCullingRemap.azsl +++ b/Gems/Atom/Feature/Common/Assets/Shaders/LightCulling/LightCullingRemap.azsl @@ -186,7 +186,7 @@ void InitWriteIndices(uint3 groupID, uint baseBin, out uint writeIndices[NVLC_MA // light indices until it hits an END_OF_X marker // Note that this code could probably be made faster with wave intrinsics -// https://jira.agscollab.com/browse/ATOM-4104 +// ATOM-4104 [numthreads(NUM_THREADS, 1, 1)] void MainCS( uint3 dispatchThreadID : SV_DispatchThreadID, diff --git a/Gems/Atom/Feature/Common/Assets/Shaders/LightCulling/LightCullingTilePrepare.azsl b/Gems/Atom/Feature/Common/Assets/Shaders/LightCulling/LightCullingTilePrepare.azsl index 7279864b09..fba2175c9b 100644 --- a/Gems/Atom/Feature/Common/Assets/Shaders/LightCulling/LightCullingTilePrepare.azsl +++ b/Gems/Atom/Feature/Common/Assets/Shaders/LightCulling/LightCullingTilePrepare.azsl @@ -181,7 +181,7 @@ void WriteTileLightDataToMainMemory(uint groupIndex, uint3 groupID, float2 minma // Note that Nvidia Light Culling framework has some additional code to better calculate this ratio // See cb_perFrame.fRangeThreshold in their framework. This code might be something we want to port over. - // https://jira.agscollab.com/browse/ATOM-5554 + // ATOM-5554 float ratio = tileZ / 1.0f; float logMaxBins = clamp(log2(ratio), 0.0, LOG_MAX_BINS); uint ulogMaxBins = uint(logMaxBins + 0.5); diff --git a/Gems/Atom/Feature/Common/Assets/Shaders/PostProcessing/DepthOfFieldBlurBokeh.azsl b/Gems/Atom/Feature/Common/Assets/Shaders/PostProcessing/DepthOfFieldBlurBokeh.azsl index b014f4e3cb..60951ebeb5 100644 --- a/Gems/Atom/Feature/Common/Assets/Shaders/PostProcessing/DepthOfFieldBlurBokeh.azsl +++ b/Gems/Atom/Feature/Common/Assets/Shaders/PostProcessing/DepthOfFieldBlurBokeh.azsl @@ -41,7 +41,6 @@ ShaderResourceGroup PassSrg : SRG_PerDraw // The number of points to sample. // Sample 6 points around center pixel. // Similarly, sample around it as 12,18,24 points. -// Please refer to “https://wiki.agscollab.com/display/ATOM/Pencil+Map” for details. option enum class SampleNumber { Sample6, // 6 @@ -52,7 +51,6 @@ option enum class SampleNumber o_sampleNumber = SampleNumber::Sample6; // Get CocRadius from dofFactor. -// Please refer to https://wiki.agscollab.com/display/ATOM/Pencil+Map for CocRadius. inline float GetCocRadius(float dofFactor) { float cocRadius = dofFactor * ViewSrg::m_dof.m_cocToScreenRatio * 0.5f; @@ -61,14 +59,12 @@ inline float GetCocRadius(float dofFactor) } // Calculate the texcoord U of the pencil map from cocRadius. -// Please refer to https://wiki.agscollab.com/display/ATOM/Pencil+Map for the pencil map. inline float GetPencilMapTexcoordU(float cocRadius) { return cocRadius * ViewSrg::m_dof.m_pencilMapTexcoordToCocRadius + ViewSrg::m_dof.m_pencilMapFocusPointTexcoordU; } // Get the color from the coordinate array. -// Please refer to https://wiki.agscollab.com/display/ATOM/Pencil+Map for details of coordinates. inline float4 SampleColorAndDofFactor(float2 centerTexCoord, float cocRadius, int sampleIndex) { float2 sampleTexcoordOffset = PassSrg::m_sampleTexcoordsRadius[sampleIndex].xy * cocRadius; @@ -78,7 +74,6 @@ inline float4 SampleColorAndDofFactor(float2 centerTexCoord, float cocRadius, in } // Load the pencil map. Since the colors are square rooted, they are decoded (linearized). This is for accuracy. -// Please refer to https://wiki.agscollab.com/display/ATOM/Pencil+Map for the pencil map. inline float4 SamplePencilMap(float lensCoordX, float radius) { float2 bokehTexcoord = float2(lensCoordX, radius); diff --git a/Gems/Atom/Feature/Common/Assets/Shaders/PostProcessing/DepthOfFieldComposite.azsl b/Gems/Atom/Feature/Common/Assets/Shaders/PostProcessing/DepthOfFieldComposite.azsl index 5c1973d3b1..0fd89e475e 100644 --- a/Gems/Atom/Feature/Common/Assets/Shaders/PostProcessing/DepthOfFieldComposite.azsl +++ b/Gems/Atom/Feature/Common/Assets/Shaders/PostProcessing/DepthOfFieldComposite.azsl @@ -77,7 +77,6 @@ PSOutput MainPS(VSOutput IN) float3 colorSum = (float3)0; // Combine from the back buffer to the front. - // Please refer to https://wiki.agscollab.com/pages/viewpage.action?spaceKey=ATOM&title=Dof+factor+and+Buffer+composition for details //////////////////////////////////////////////////////////////////////// // Background diff --git a/Gems/Atom/Feature/Common/Code/Include/Atom/Feature/CoreLights/PointLightFeatureProcessorInterface.h b/Gems/Atom/Feature/Common/Code/Include/Atom/Feature/CoreLights/PointLightFeatureProcessorInterface.h index 68e1a01e56..30d88cb839 100644 --- a/Gems/Atom/Feature/Common/Code/Include/Atom/Feature/CoreLights/PointLightFeatureProcessorInterface.h +++ b/Gems/Atom/Feature/Common/Code/Include/Atom/Feature/CoreLights/PointLightFeatureProcessorInterface.h @@ -1,19 +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. -* -*/ + * All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or + * its licensors. + * + * For complete copyright and license terms please see the LICENSE at the root of this + * distribution (the "License"). All use of this software is governed by the License, + * or, if provided, by the license below or the license accompanying this file. Do not + * remove or 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 AZ { @@ -22,9 +23,25 @@ namespace AZ namespace Render { + struct PointLightData + { + AZStd::array m_position = {{0.0f, 0.0f, 0.0f}}; + + // Inverse of the distance at which this light no longer has an effect, squared. Also used for falloff calculations. + float m_invAttenuationRadiusSquared = 0.0f; + + AZStd::array m_rgbIntensity = {{0.0f, 0.0f, 0.0f}}; + + // Radius of spherical light in meters. + float m_bulbRadius = 0.0f; + + static const int NumShadowFaces = 6; + AZStd::array m_shadowIndices = {{0xFFFF, 0xFFFF, 0xFFFF, 0xFFFF, 0xFFFF, 0xFFFF}}; + uint32_t m_padding; + }; + //! PointLightFeatureProcessorInterface provides an interface to acquire, release, and update a point light. - class PointLightFeatureProcessorInterface - : public RPI::FeatureProcessor + class PointLightFeatureProcessorInterface : public RPI::FeatureProcessor { public: AZ_RTTI(AZ::Render::PointLightFeatureProcessorInterface, "{D3E0B016-F3C6-4C7A-A29E-0B3A4FA87806}", AZ::RPI::FeatureProcessor); @@ -33,7 +50,8 @@ namespace AZ using LightHandle = RHI::Handle; static constexpr PhotometricUnit PhotometricUnitType = PhotometricUnit::Candela; - //! Creates a new point light which can be referenced by the returned LightHandle. Must be released via ReleaseLight() when no longer needed. + //! Creates a new point light which can be referenced by the returned LightHandle. Must be released via ReleaseLight() when no + //! longer needed. virtual LightHandle AcquireLight() = 0; //! Releases a LightHandle which removes the point light. virtual bool ReleaseLight(LightHandle& handle) = 0; @@ -48,6 +66,24 @@ namespace AZ virtual void SetAttenuationRadius(LightHandle handle, float attenuationRadius) = 0; //! Sets the bulb radius for the provided LightHandle. Values greater than zero effectively make it a spherical light. virtual void SetBulbRadius(LightHandle handle, float bulbRadius) = 0; + //! Sets if shadows are enabled + virtual void SetShadowsEnabled(LightHandle handle, bool enabled) = 0; + //! Sets the shadowmap size (width and height) of the light. + virtual void SetShadowmapMaxResolution(LightHandle handle, ShadowmapSize shadowmapSize) = 0; + //! Specifies filter method of shadows. + virtual void SetShadowFilterMethod(LightHandle handle, ShadowFilterMethod method) = 0; + //! Specifies the width of boundary between shadowed area and lit area in radians. The degree ofshadowed gradually changes on + //! the boundary. 0 disables softening. + virtual void SetSofteningBoundaryWidthAngle(LightHandle handle, float boundaryWidthRadians) = 0; + //! Sets sample count to predict boundary of shadow (up to 16). It will be clamped to be less than or equal to the filtering + //! sample count. + virtual void SetPredictionSampleCount(LightHandle handle, uint16_t count) = 0; + //! Sets sample count for filtering of shadow boundary (up to 64) + virtual void SetFilteringSampleCount(LightHandle handle, uint16_t count) = 0; + //! Sets the shadowmap Pcf (percentage closer filtering) method. + virtual void SetPcfMethod(LightHandle handle, PcfMethod method) = 0; + //! Sets all of the the point data for the provided LightHandle. + virtual void SetPointData(LightHandle handle, const PointLightData& data) = 0; }; } // namespace Render } // namespace AZ diff --git a/Gems/Atom/Feature/Common/Code/Source/CoreLights/DirectionalLightFeatureProcessor.cpp b/Gems/Atom/Feature/Common/Code/Source/CoreLights/DirectionalLightFeatureProcessor.cpp index 60bf487de3..ade4b5b592 100644 --- a/Gems/Atom/Feature/Common/Code/Source/CoreLights/DirectionalLightFeatureProcessor.cpp +++ b/Gems/Atom/Feature/Common/Code/Source/CoreLights/DirectionalLightFeatureProcessor.cpp @@ -306,7 +306,7 @@ namespace AZ for (const RPI::ViewPtr& view : packet.m_views) { if (m_renderPipelineIdsForPersistentView.find(view.get()) != m_renderPipelineIdsForPersistentView.end() && - (view->GetUsageFlags() & RPI::View::UsageCamera)) + (RHI::CheckBitsAny(view->GetUsageFlags(), RPI::View::UsageCamera | RPI::View::UsageReflectiveCubeMap))) { RPI::ShaderResourceGroup* viewSrg = view->GetShaderResourceGroup().get(); @@ -1487,7 +1487,6 @@ namespace AZ float depthNear, float depthFar) const { - // For calculation, refer https://wiki.agscollab.com/display/ATOM/Cascaded+Shadowmaps // This calculates the center of bounding sphere for a camera view frustum. // By this, on the camera view (2D), the bounding sphere's center // shifts to the remarkable point. diff --git a/Gems/Atom/Feature/Common/Code/Source/CoreLights/DiskLightFeatureProcessor.cpp b/Gems/Atom/Feature/Common/Code/Source/CoreLights/DiskLightFeatureProcessor.cpp index 58bbed699a..d0fb702d5a 100644 --- a/Gems/Atom/Feature/Common/Code/Source/CoreLights/DiskLightFeatureProcessor.cpp +++ b/Gems/Atom/Feature/Common/Code/Source/CoreLights/DiskLightFeatureProcessor.cpp @@ -380,7 +380,7 @@ namespace AZ const float invRadiusSquared = diskLight.m_invAttenuationRadiusSquared; if (invRadiusSquared <= 0.f) { - AZ_Assert(false, "Attenuation radius have to be set before use the light."); + AZ_Assert(false, "Attenuation radius must be set before using the light."); return; } const float attenuationRadius = sqrtf(1.f / invRadiusSquared); diff --git a/Gems/Atom/Feature/Common/Code/Source/CoreLights/DiskLightFeatureProcessor.h b/Gems/Atom/Feature/Common/Code/Source/CoreLights/DiskLightFeatureProcessor.h index 446b008921..8391506f63 100644 --- a/Gems/Atom/Feature/Common/Code/Source/CoreLights/DiskLightFeatureProcessor.h +++ b/Gems/Atom/Feature/Common/Code/Source/CoreLights/DiskLightFeatureProcessor.h @@ -59,7 +59,7 @@ namespace AZ void SetSofteningBoundaryWidthAngle(LightHandle handle, float boundaryWidthRadians) override; void SetPredictionSampleCount(LightHandle handle, uint16_t count) override; void SetFilteringSampleCount(LightHandle handle, uint16_t count) override; - void SetPcfMethod(LightHandle handle, PcfMethod method); + void SetPcfMethod(LightHandle handle, PcfMethod method) override; void SetDiskData(LightHandle handle, const DiskLightData& data) override; @@ -84,7 +84,7 @@ namespace AZ template void SetShadowSetting(LightHandle handle, Functor&&, ParamType&& param); - ProjectedShadowFeatureProcessor* m_shadowFeatureProcessor; + ProjectedShadowFeatureProcessor* m_shadowFeatureProcessor = nullptr; IndexedDataVector m_diskLightData; GpuBufferHandler m_lightBufferHandler; diff --git a/Gems/Atom/Feature/Common/Code/Source/CoreLights/LightCullingRemap.cpp b/Gems/Atom/Feature/Common/Code/Source/CoreLights/LightCullingRemap.cpp index eb3e87dcd1..42882cec6e 100644 --- a/Gems/Atom/Feature/Common/Code/Source/CoreLights/LightCullingRemap.cpp +++ b/Gems/Atom/Feature/Common/Code/Source/CoreLights/LightCullingRemap.cpp @@ -34,7 +34,7 @@ namespace AZ const size_t NumBins = 8; const size_t MaxLightsPerTile = 256; // TODO convert this to R16_UINT. It just needs RHI support - // https://jira.agscollab.com/browse/ATOM-3975 + // ATOM-3975 const RHI::Format LightListRemappedFormat = RHI::Format::R32_UINT; RPI::Ptr LightCullingRemap::Create(const RPI::PassDescriptor& descriptor) diff --git a/Gems/Atom/Feature/Common/Code/Source/CoreLights/PointLightFeatureProcessor.cpp b/Gems/Atom/Feature/Common/Code/Source/CoreLights/PointLightFeatureProcessor.cpp index 661a7d4bf4..bb81c52b15 100644 --- a/Gems/Atom/Feature/Common/Code/Source/CoreLights/PointLightFeatureProcessor.cpp +++ b/Gems/Atom/Feature/Common/Code/Source/CoreLights/PointLightFeatureProcessor.cpp @@ -44,6 +44,13 @@ namespace AZ PointLightFeatureProcessor::PointLightFeatureProcessor() : PointLightFeatureProcessorInterface() { + // Note must match PointShadowDirections in PointLight.azsli + m_pointShadowTransforms[0] = AZ::Transform::CreateLookAt(AZ::Vector3::CreateZero(), -AZ::Vector3::CreateAxisX()); + m_pointShadowTransforms[1] = AZ::Transform::CreateLookAt(AZ::Vector3::CreateZero(), AZ::Vector3::CreateAxisX()); + m_pointShadowTransforms[2] = AZ::Transform::CreateLookAt(AZ::Vector3::CreateZero(), -AZ::Vector3::CreateAxisY()); + m_pointShadowTransforms[3] = AZ::Transform::CreateLookAt(AZ::Vector3::CreateZero(), AZ::Vector3::CreateAxisY()); + m_pointShadowTransforms[4] = AZ::Transform::CreateLookAt(AZ::Vector3::CreateZero(), -AZ::Vector3::CreateAxisZ()); + m_pointShadowTransforms[5] = AZ::Transform::CreateLookAt(AZ::Vector3::CreateZero(), AZ::Vector3::CreateAxisZ()); } void PointLightFeatureProcessor::Activate() @@ -54,6 +61,7 @@ namespace AZ desc.m_elementCountSrgName = "m_pointLightCount"; desc.m_elementSize = sizeof(PointLightData); desc.m_srgLayout = RPI::RPISystemInterface::Get()->GetViewSrgAsset()->GetLayout(); + m_shadowFeatureProcessor = GetParentScene()->GetFeatureProcessor(); m_lightBufferHandler = GpuBufferHandler(desc); } @@ -83,6 +91,15 @@ namespace AZ { if (handle.IsValid()) { + for (int i = 0; i < PointLightData::NumShadowFaces; ++i) + { + ShadowId shadowId = ShadowId(m_pointLightData.GetData(handle.GetIndex()).m_shadowIndices[i]); + if (shadowId.IsValid()) + { + m_shadowFeatureProcessor->ReleaseShadow(shadowId); + } + } + m_pointLightData.RemoveIndex(handle.GetIndex()); m_deviceBufferNeedsUpdate = true; handle.Reset(); @@ -148,6 +165,7 @@ namespace AZ lightPosition.StoreToFloat3(position.data()); m_deviceBufferNeedsUpdate = true; + UpdateShadow(handle); } void PointLightFeatureProcessor::SetAttenuationRadius(LightHandle handle, float attenuationRadius) @@ -177,5 +195,122 @@ namespace AZ return m_lightBufferHandler.GetElementCount(); } + void PointLightFeatureProcessor::SetShadowsEnabled(LightHandle handle, bool enabled) + { + auto& light = m_pointLightData.GetData(handle.GetIndex()); + for (int i = 0; i < PointLightData::NumShadowFaces; ++i) + { + ShadowId shadowId = ShadowId(light.m_shadowIndices[i]); + if (shadowId.IsValid() && !enabled) + { + // Disable shadows + m_shadowFeatureProcessor->ReleaseShadow(shadowId); + shadowId.Reset(); + light.m_shadowIndices[i] = shadowId.GetIndex(); + m_deviceBufferNeedsUpdate = true; + } + else if (shadowId.IsNull() && enabled) + { + // Enable shadows + light.m_shadowIndices[i] = m_shadowFeatureProcessor->AcquireShadow().GetIndex(); + + UpdateShadow(handle); + m_deviceBufferNeedsUpdate = true; + } + } + } + + void PointLightFeatureProcessor::SetPointData(LightHandle handle, const PointLightData& data) + { + AZ_Assert(handle.IsValid(), "Invalid LightHandle passed to PointLightFeatureProcessor::SetPointData()."); + + m_pointLightData.GetData(handle.GetIndex()) = data; + m_deviceBufferNeedsUpdate = true; + UpdateShadow(handle); + } + + void PointLightFeatureProcessor::UpdateShadow(LightHandle handle) + { + constexpr float SqrtHalf = 0.707106781187f; // sqrt(0.5); + + const auto& pointLight = m_pointLightData.GetData(handle.GetIndex()); + for (int i = 0; i < PointLightData::NumShadowFaces; ++i) + { + ShadowId shadowId = ShadowId(pointLight.m_shadowIndices[i]); + if (shadowId.IsNull()) + { + // Early out if shadows are disabled. + return; + } + + ProjectedShadowFeatureProcessorInterface::ProjectedShadowDescriptor desc = m_shadowFeatureProcessor->GetShadowProperties(shadowId); + // Make it slightly larger than 90 degrees to avoid artifacts on the boundary between 2 cubemap faces + desc.m_fieldOfViewYRadians = DegToRad(91.0f); + desc.m_transform = m_pointShadowTransforms[i]; + desc.m_transform.SetTranslation(pointLight.m_position[0], pointLight.m_position[1], pointLight.m_position[2]); + desc.m_aspectRatio = 1.0f; + desc.m_nearPlaneDistance = SqrtHalf * pointLight.m_bulbRadius; + + const float invRadiusSquared = pointLight.m_invAttenuationRadiusSquared; + if (invRadiusSquared <= 0.f) + { + AZ_Assert(false, "Attenuation radius must be set before using the light."); + return; + } + const float attenuationRadius = sqrtf(1.f / invRadiusSquared); + desc.m_farPlaneDistance = attenuationRadius + pointLight.m_bulbRadius; + + m_shadowFeatureProcessor->SetShadowProperties(shadowId, desc); + } + } + + template + void PointLightFeatureProcessor::SetShadowSetting(LightHandle handle, Functor&& functor, ParamType&& param) + { + AZ_Assert(handle.IsValid(), "Invalid LightHandle passed to PointLightFeatureProcessor::SetShadowSetting()."); + + auto& light = m_pointLightData.GetData(handle.GetIndex()); + for (int lightIndex = 0; lightIndex < PointLightData::NumShadowFaces; ++lightIndex) + { + ShadowId shadowId = ShadowId(light.m_shadowIndices[lightIndex]); + + AZ_Assert(shadowId.IsValid(), "Attempting to set a shadow property when shadows are not enabled."); + if (shadowId.IsValid()) + { + AZStd::invoke(AZStd::forward(functor), m_shadowFeatureProcessor, shadowId, AZStd::forward(param)); + } + } + } + + void PointLightFeatureProcessor::SetShadowmapMaxResolution(LightHandle handle, ShadowmapSize shadowmapSize) + { + SetShadowSetting(handle, &ProjectedShadowFeatureProcessor::SetShadowmapMaxResolution, shadowmapSize); + } + + void PointLightFeatureProcessor::SetShadowFilterMethod(LightHandle handle, ShadowFilterMethod method) + { + SetShadowSetting(handle, &ProjectedShadowFeatureProcessor::SetShadowFilterMethod, method); + } + + void PointLightFeatureProcessor::SetSofteningBoundaryWidthAngle(LightHandle handle, float boundaryWidthRadians) + { + SetShadowSetting(handle, &ProjectedShadowFeatureProcessor::SetSofteningBoundaryWidthAngle, boundaryWidthRadians); + } + + void PointLightFeatureProcessor::SetPredictionSampleCount(LightHandle handle, uint16_t count) + { + SetShadowSetting(handle, &ProjectedShadowFeatureProcessor::SetPredictionSampleCount, count); + } + + void PointLightFeatureProcessor::SetFilteringSampleCount(LightHandle handle, uint16_t count) + { + SetShadowSetting(handle, &ProjectedShadowFeatureProcessor::SetFilteringSampleCount, count); + } + + void PointLightFeatureProcessor::SetPcfMethod(LightHandle handle, PcfMethod method) + { + SetShadowSetting(handle, &ProjectedShadowFeatureProcessor::SetPcfMethod, method); + } + } // namespace Render } // namespace AZ diff --git a/Gems/Atom/Feature/Common/Code/Source/CoreLights/PointLightFeatureProcessor.h b/Gems/Atom/Feature/Common/Code/Source/CoreLights/PointLightFeatureProcessor.h index 25b9bfa2cd..c0c377e960 100644 --- a/Gems/Atom/Feature/Common/Code/Source/CoreLights/PointLightFeatureProcessor.h +++ b/Gems/Atom/Feature/Common/Code/Source/CoreLights/PointLightFeatureProcessor.h @@ -16,6 +16,7 @@ #include #include #include +#include namespace AZ { @@ -24,15 +25,6 @@ namespace AZ namespace Render { - - struct PointLightData - { - AZStd::array m_position = { { 0.0f, 0.0f, 0.0f } }; - float m_invAttenuationRadiusSquared = 0.0f; // Inverse of the distance at which this light no longer has an effect, squared. Also used for falloff calculations. - AZStd::array m_rgbIntensity = { { 0.0f, 0.0f, 0.0f } }; - float m_bulbRadius = 0.0f; // Radius of spherical light in meters. - }; - class PointLightFeatureProcessor final : public PointLightFeatureProcessorInterface { @@ -58,18 +50,34 @@ namespace AZ void SetPosition(LightHandle handle, const AZ::Vector3& lightPosition) override; void SetAttenuationRadius(LightHandle handle, float attenuationRadius) override; void SetBulbRadius(LightHandle handle, float bulbRadius) override; + void SetShadowsEnabled(LightHandle handle, bool enabled) override; + void SetShadowmapMaxResolution(LightHandle handle, ShadowmapSize shadowmapSize) override; + void SetShadowFilterMethod(LightHandle handle, ShadowFilterMethod method) override; + void SetSofteningBoundaryWidthAngle(LightHandle handle, float boundaryWidthRadians) override; + void SetPredictionSampleCount(LightHandle handle, uint16_t count) override; + void SetFilteringSampleCount(LightHandle handle, uint16_t count) override; + void SetPcfMethod(LightHandle handle, PcfMethod method) override; + void SetPointData(LightHandle handle, const PointLightData& data) override; const Data::Instance GetLightBuffer() const; uint32_t GetLightCount()const; private: PointLightFeatureProcessor(const PointLightFeatureProcessor&) = delete; + using ShadowId = ProjectedShadowFeatureProcessor::ShadowId; static constexpr const char* FeatureProcessorName = "PointLightFeatureProcessor"; + void UpdateShadow(LightHandle handle); + // Convenience function for forwarding requests to the ProjectedShadowFeatureProcessor + template + void SetShadowSetting(LightHandle handle, Functor&&, ParamType&& param); + ProjectedShadowFeatureProcessor* m_shadowFeatureProcessor = nullptr; IndexedDataVector m_pointLightData; GpuBufferHandler m_lightBufferHandler; bool m_deviceBufferNeedsUpdate = false; + + AZStd::array m_pointShadowTransforms; }; } // namespace Render } // namespace AZ diff --git a/Gems/Atom/Feature/Common/Code/Source/PostProcess/DepthOfField/DepthOfFieldSettings.cpp b/Gems/Atom/Feature/Common/Code/Source/PostProcess/DepthOfField/DepthOfFieldSettings.cpp index bad6afbc16..1baa3d072b 100644 --- a/Gems/Atom/Feature/Common/Code/Source/PostProcess/DepthOfField/DepthOfFieldSettings.cpp +++ b/Gems/Atom/Feature/Common/Code/Source/PostProcess/DepthOfField/DepthOfFieldSettings.cpp @@ -50,7 +50,7 @@ namespace AZ static constexpr Quality QualitySet[DepthOfField::QualityLevelMax] = { - // It is the radial division count of blur kernel. See "https://wiki.agscollab.com/display/ATOM/Pencil+Map" for details. + // It is the radial division count of blur kernel. {2, 3, 4}, {4, 4, 4} }; @@ -205,7 +205,6 @@ namespace AZ float scaledDiameter = ScreenApertureDiameter * 0.25f; // This is the conversion factor for calculating the blend ratio from DofFactor. - // Please refer to "https://wiki.agscollab.com/display/ATOM/Dof+factor+and+Buffer+composition" for blending of DofFactor and buffer. // coc0 : Confusion circle diameter screen ratio // coc1 : Confusion circle diameter screen ratio of one lower blur level; diff --git a/Gems/Atom/Feature/Common/Code/Source/PostProcess/DepthOfField/DepthOfFieldSettings.h b/Gems/Atom/Feature/Common/Code/Source/PostProcess/DepthOfField/DepthOfFieldSettings.h index eeb1726cfb..6e59b6aa33 100644 --- a/Gems/Atom/Feature/Common/Code/Source/PostProcess/DepthOfField/DepthOfFieldSettings.h +++ b/Gems/Atom/Feature/Common/Code/Source/PostProcess/DepthOfField/DepthOfFieldSettings.h @@ -139,7 +139,6 @@ namespace AZ float m_minBokehRadiusDivision8 = 0.0f; // Radial division count of bokeh blur kernel. - // See "https://wiki.agscollab.com/display/ATOM/Pencil+Map" for details. uint32_t m_sampleRadialDivision2 = 0; uint32_t m_sampleRadialDivision4 = 0; uint32_t m_sampleRadialDivision8 = 0; diff --git a/Gems/Atom/Feature/Common/Code/Source/PostProcessing/DepthOfFieldBokehBlurPass.cpp b/Gems/Atom/Feature/Common/Code/Source/PostProcessing/DepthOfFieldBokehBlurPass.cpp index e51bca5fde..4a4a8a8b76 100644 --- a/Gems/Atom/Feature/Common/Code/Source/PostProcessing/DepthOfFieldBokehBlurPass.cpp +++ b/Gems/Atom/Feature/Common/Code/Source/PostProcessing/DepthOfFieldBokehBlurPass.cpp @@ -194,7 +194,6 @@ namespace AZ // calculate sampling texcoords. // sample 6 points around center pixel. // Similarly, sample around it as 12,18,24 points. - // Please refer to "https://wiki.agscollab.com/display/ATOM/Pencil+Map" for details. AZ_Assert(radialDivisionCount >= 1 && radialDivisionCount <= 4, "DepthOfFieldBokehBlurPass : radialDivisionCount is illegal value."); diff --git a/Gems/Atom/Feature/Common/Code/Source/PostProcessing/DepthOfFieldPencilMap.h b/Gems/Atom/Feature/Common/Code/Source/PostProcessing/DepthOfFieldPencilMap.h index 585df1d4da..23a8cf9f51 100644 --- a/Gems/Atom/Feature/Common/Code/Source/PostProcessing/DepthOfFieldPencilMap.h +++ b/Gems/Atom/Feature/Common/Code/Source/PostProcessing/DepthOfFieldPencilMap.h @@ -18,8 +18,6 @@ namespace AZ { namespace PencilMap { - // Please refer to "https://wiki.agscollab.com/display/ATOM/Pencil+Map" for details. - // PencilMap 35mm Film static constexpr unsigned int TextureWidth = 128; static constexpr unsigned int TextureHeight = 64; diff --git a/Gems/Atom/Feature/Common/Code/Source/ReflectionProbe/ReflectionProbe.cpp b/Gems/Atom/Feature/Common/Code/Source/ReflectionProbe/ReflectionProbe.cpp index e0b79e23aa..3497855c07 100644 --- a/Gems/Atom/Feature/Common/Code/Source/ReflectionProbe/ReflectionProbe.cpp +++ b/Gems/Atom/Feature/Common/Code/Source/ReflectionProbe/ReflectionProbe.cpp @@ -120,13 +120,13 @@ namespace AZ { // stencil Srg // Note: the stencil pass uses a slightly reduced inner AABB to avoid seams - Vector3 innerExtentsReduced = m_innerExtents * m_transform.GetScale() - Vector3(0.1f, 0.1f, 0.1f); + Vector3 innerExtentsReduced = m_innerExtents - Vector3(0.1f, 0.1f, 0.1f); Matrix3x4 modelToWorldStencil = Matrix3x4::CreateFromMatrix3x3AndTranslation(Matrix3x3::CreateIdentity(), m_transform.GetTranslation()) * Matrix3x4::CreateScale(innerExtentsReduced); m_stencilSrg->SetConstant(m_reflectionRenderData->m_modelToWorldStencilConstantIndex, modelToWorldStencil); m_stencilSrg->Compile(); // blend weight Srg - Matrix3x4 modelToWorldOuter = Matrix3x4::CreateFromMatrix3x3AndTranslation(Matrix3x3::CreateIdentity(), m_transform.GetTranslation()) * Matrix3x4::CreateScale(m_outerExtents * m_transform.GetScale()); + Matrix3x4 modelToWorldOuter = Matrix3x4::CreateFromMatrix3x3AndTranslation(Matrix3x3::CreateIdentity(), m_transform.GetTranslation()) * Matrix3x4::CreateScale(m_outerExtents); m_blendWeightSrg->SetConstant(m_reflectionRenderData->m_modelToWorldRenderConstantIndex, modelToWorldOuter); m_blendWeightSrg->SetConstant(m_reflectionRenderData->m_aabbPosRenderConstantIndex, m_outerAabbWs.GetCenter()); m_blendWeightSrg->SetConstant(m_reflectionRenderData->m_outerAabbMinRenderConstantIndex, m_outerAabbWs.GetMin()); @@ -149,7 +149,7 @@ namespace AZ m_renderOuterSrg->Compile(); // render inner Srg - Matrix3x4 modelToWorldInner = Matrix3x4::CreateFromMatrix3x3AndTranslation(Matrix3x3::CreateIdentity(), m_transform.GetTranslation()) * Matrix3x4::CreateScale(m_innerExtents * m_transform.GetScale()); + Matrix3x4 modelToWorldInner = Matrix3x4::CreateFromMatrix3x3AndTranslation(Matrix3x3::CreateIdentity(), m_transform.GetTranslation()) * Matrix3x4::CreateScale(m_innerExtents); m_renderInnerSrg->SetConstant(m_reflectionRenderData->m_modelToWorldRenderConstantIndex, modelToWorldInner); m_renderInnerSrg->SetConstant(m_reflectionRenderData->m_aabbPosRenderConstantIndex, m_outerAabbWs.GetCenter()); m_renderInnerSrg->SetConstant(m_reflectionRenderData->m_outerAabbMinRenderConstantIndex, m_outerAabbWs.GetMin()); @@ -208,6 +208,12 @@ namespace AZ void ReflectionProbe::SetTransform(const AZ::Transform& transform) { + // retrieve previous scale and revert the scale on the inner/outer extents + AZ::Vector3 previousScale = m_transform.GetScale(); + m_outerExtents /= previousScale; + m_innerExtents /= previousScale; + + // store new transform m_transform = transform; // avoid scaling the visualization sphere @@ -215,22 +221,26 @@ namespace AZ visualizationTransform.ExtractScale(); m_meshFeatureProcessor->SetTransform(m_visualizationMeshHandle, visualizationTransform); - m_outerAabbWs = Aabb::CreateCenterHalfExtents(m_transform.GetTranslation(), m_outerExtents * m_transform.GetScale() / 2.0f); - m_innerAabbWs = Aabb::CreateCenterHalfExtents(m_transform.GetTranslation(), m_innerExtents * m_transform.GetScale() / 2.0f); + // update the inner/outer extents with the new scale + m_outerExtents *= m_transform.GetScale(); + m_innerExtents *= m_transform.GetScale(); + + m_outerAabbWs = Aabb::CreateCenterHalfExtents(m_transform.GetTranslation(), m_outerExtents / 2.0f); + m_innerAabbWs = Aabb::CreateCenterHalfExtents(m_transform.GetTranslation(), m_innerExtents / 2.0f); m_updateSrg = true; } void ReflectionProbe::SetOuterExtents(const AZ::Vector3& outerExtents) { - m_outerExtents = outerExtents; - m_outerAabbWs = Aabb::CreateCenterHalfExtents(m_transform.GetTranslation(), m_outerExtents * m_transform.GetScale() / 2.0f); + m_outerExtents = outerExtents * m_transform.GetScale(); + m_outerAabbWs = Aabb::CreateCenterHalfExtents(m_transform.GetTranslation(), m_outerExtents / 2.0f); m_updateSrg = true; } void ReflectionProbe::SetInnerExtents(const AZ::Vector3& innerExtents) { - m_innerExtents = innerExtents; - m_innerAabbWs = Aabb::CreateCenterHalfExtents(m_transform.GetTranslation(), m_innerExtents * m_transform.GetScale() / 2.0f); + m_innerExtents = innerExtents * m_transform.GetScale(); + m_innerAabbWs = Aabb::CreateCenterHalfExtents(m_transform.GetTranslation(), m_innerExtents / 2.0f); m_updateSrg = true; } diff --git a/Gems/Atom/Feature/Common/Code/Source/ReflectionProbe/ReflectionProbe.h b/Gems/Atom/Feature/Common/Code/Source/ReflectionProbe/ReflectionProbe.h index ab0e7a81d3..f062e0a42f 100644 --- a/Gems/Atom/Feature/Common/Code/Source/ReflectionProbe/ReflectionProbe.h +++ b/Gems/Atom/Feature/Common/Code/Source/ReflectionProbe/ReflectionProbe.h @@ -78,10 +78,10 @@ namespace AZ const Vector3& GetPosition() const { return m_transform.GetTranslation(); } void SetTransform(const AZ::Transform& transform); - AZ::Vector3 GetOuterExtents() const { return m_outerExtents * m_transform.GetScale(); } + const AZ::Vector3& GetOuterExtents() const { return m_outerExtents; } void SetOuterExtents(const AZ::Vector3& outerExtents); - AZ::Vector3 GetInnerExtents() const { return m_innerExtents * m_transform.GetScale(); } + const AZ::Vector3& GetInnerExtents() const { return m_innerExtents; } void SetInnerExtents(const AZ::Vector3& innerExtents); const Aabb& GetOuterAabbWs() const { return m_outerAabbWs; } 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/Code/Include/Atom/RHI/CpuProfilerImpl.h b/Gems/Atom/RHI/Code/Include/Atom/RHI/CpuProfilerImpl.h index 777a20ada9..30523194b6 100644 --- a/Gems/Atom/RHI/Code/Include/Atom/RHI/CpuProfilerImpl.h +++ b/Gems/Atom/RHI/Code/Include/Atom/RHI/CpuProfilerImpl.h @@ -124,6 +124,8 @@ namespace AZ // This lock will only be contested when the CpuProfiler's Shutdown() method has been called AZStd::shared_mutex m_shutdownMutex; + + bool m_initialized = false; }; }; // namespace RPI diff --git a/Gems/Atom/RHI/Code/Source/RHI/CpuProfilerImpl.cpp b/Gems/Atom/RHI/Code/Source/RHI/CpuProfilerImpl.cpp index 28c3ef6a7b..8242c89886 100644 --- a/Gems/Atom/RHI/Code/Source/RHI/CpuProfilerImpl.cpp +++ b/Gems/Atom/RHI/Code/Source/RHI/CpuProfilerImpl.cpp @@ -82,10 +82,15 @@ namespace AZ void CpuProfilerImpl::Init() { Interface::Register(this); + m_initialized = true; } void CpuProfilerImpl::Shutdown() { + if (!m_initialized) + { + return; + } // When this call is made, no more thread profiling calls can be performed anymore Interface::Unregister(this); @@ -97,6 +102,7 @@ namespace AZ // Cleanup all TLS m_registeredThreads.clear(); m_timeRegionMap.clear(); + m_initialized = false; } void CpuProfilerImpl::BeginTimeRegion(TimeRegion& timeRegion) diff --git a/Gems/Atom/RHI/Code/Source/RHI/RHISystem.cpp b/Gems/Atom/RHI/Code/Source/RHI/RHISystem.cpp index f92d2621b1..95e0a33981 100644 --- a/Gems/Atom/RHI/Code/Source/RHI/RHISystem.cpp +++ b/Gems/Atom/RHI/Code/Source/RHI/RHISystem.cpp @@ -200,9 +200,12 @@ namespace AZ m_platformLimitsDescriptor = nullptr; m_pipelineStateCache = nullptr; - m_device->PreShutdown(); - AZ_Assert(m_device->use_count()==1, "The ref count for Device is %i but it should be 1 here to ensure all the resources are released", m_device->use_count()); - m_device = nullptr; + if (m_device) + { + m_device->PreShutdown(); + AZ_Assert(m_device->use_count()==1, "The ref count for Device is %i but it should be 1 here to ensure all the resources are released", m_device->use_count()); + m_device = nullptr; + } m_cpuProfiler.Shutdown(); } diff --git a/Gems/Atom/RHI/DX12/Code/Source/RHI/AsyncUploadQueue.cpp b/Gems/Atom/RHI/DX12/Code/Source/RHI/AsyncUploadQueue.cpp index f816a7ae04..22849f7236 100644 --- a/Gems/Atom/RHI/DX12/Code/Source/RHI/AsyncUploadQueue.cpp +++ b/Gems/Atom/RHI/DX12/Code/Source/RHI/AsyncUploadQueue.cpp @@ -90,12 +90,16 @@ namespace AZ void AsyncUploadQueue::Shutdown() { - m_copyQueue->Shutdown(); + if (m_copyQueue) + { + m_copyQueue->Shutdown(); + m_copyQueue = nullptr; + } m_commandList = nullptr; - for (size_t i = 0; i < m_descriptor.m_frameCount; ++i) + for (auto& framePacket : m_framePackets) { - m_framePackets[i].m_fence.Shutdown(); + framePacket.m_fence.Shutdown(); } m_framePackets.clear(); m_uploadFence.Shutdown(); diff --git a/Gems/Atom/RHI/DX12/Code/Source/RHI/CommandQueueContext.cpp b/Gems/Atom/RHI/DX12/Code/Source/RHI/CommandQueueContext.cpp index 4c133084ac..a31e105b19 100644 --- a/Gems/Atom/RHI/DX12/Code/Source/RHI/CommandQueueContext.cpp +++ b/Gems/Atom/RHI/DX12/Code/Source/RHI/CommandQueueContext.cpp @@ -109,7 +109,10 @@ namespace AZ AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzRender); for (uint32_t hardwareQueueIdx = 0; hardwareQueueIdx < RHI::HardwareQueueClassCount; ++hardwareQueueIdx) { - m_commandQueues[hardwareQueueIdx]->WaitForIdle(); + if (m_commandQueues[hardwareQueueIdx]) + { + m_commandQueues[hardwareQueueIdx]->WaitForIdle(); + } } } 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/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/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; 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/Buffer/BufferSystem.h b/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/Buffer/BufferSystem.h index 91d60bcb36..c4b6aa74b4 100644 --- a/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/Buffer/BufferSystem.h +++ b/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/Buffer/BufferSystem.h @@ -45,6 +45,8 @@ namespace AZ private: RHI::Ptr m_commonPools[static_cast(CommonBufferPoolType::Count)]; + + bool m_initialized = false; }; } // namespace RPI } // namespace AZ diff --git a/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/Image/ImageSystem.h b/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/Image/ImageSystem.h index 67f33758dc..b8f52a532e 100644 --- a/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/Image/ImageSystem.h +++ b/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/Image/ImageSystem.h @@ -80,6 +80,8 @@ namespace AZ Data::Asset m_defaultStreamingImageControllerAsset; AZStd::fixed_vector, static_cast(SystemImage::Count)> m_systemImages; + + bool m_initialized = false; }; } } diff --git a/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/Pass/PassLibrary.h b/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/Pass/PassLibrary.h index e61b90d55a..283cea7c0a 100644 --- a/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/Pass/PassLibrary.h +++ b/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/Pass/PassLibrary.h @@ -82,7 +82,7 @@ namespace AZ void RemovePassFromLibrary(Pass* pass); //! Load pass templates which are list in an AssetAliases - void LoadPassTemplateMappings(const AZStd::string& templateMappingPath); + bool LoadPassTemplateMappings(const AZStd::string& templateMappingPath); bool LoadPassTemplateMappings(Data::Asset mappingAsset); //! Returns a list of passes found in the pass name mapping using the provided pass filter diff --git a/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/Pass/PassSystem.h b/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/Pass/PassSystem.h index acbb914dfa..d37868025c 100644 --- a/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/Pass/PassSystem.h +++ b/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/Pass/PassSystem.h @@ -66,7 +66,7 @@ namespace AZ // PassSystemInterface functions... void ProcessQueuedChanges() override; - void LoadPassTemplateMappings(const AZStd::string& templateMappingPath) override; + bool LoadPassTemplateMappings(const AZStd::string& templateMappingPath) override; void WriteTemplateToFile(const PassTemplate& passTemplate, AZStd::string_view assetFilePath) override; void DebugPrintPassHierarchy() override; bool IsBuilding() const override; diff --git a/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/Pass/PassSystemInterface.h b/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/Pass/PassSystemInterface.h index 93754c2229..82d52ab5a2 100644 --- a/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/Pass/PassSystemInterface.h +++ b/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/Pass/PassSystemInterface.h @@ -65,7 +65,7 @@ namespace AZ virtual void ProcessQueuedChanges() = 0; //! Load pass templates listed in a name-assetid mapping asset - virtual void LoadPassTemplateMappings(const AZStd::string& templateMappingPath) = 0; + virtual bool LoadPassTemplateMappings(const AZStd::string& templateMappingPath) = 0; //! Writes a pass template to a .pass file which can then be used as a pass asset. Useful for //! quickly authoring a pass template in code and then outputting it as a pass asset using JSON diff --git a/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/RPISystem.h b/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/RPISystem.h index 80b9022f0d..ff3c784a51 100644 --- a/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/RPISystem.h +++ b/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/RPISystem.h @@ -70,6 +70,7 @@ namespace AZ void Shutdown(); // RPISystemInterface overrides... + bool IsInitialized() const override; void InitializeSystemAssets() override; void RegisterScene(ScenePtr scene) override; void UnregisterScene(ScenePtr scene) override; diff --git a/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/RPISystemInterface.h b/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/RPISystemInterface.h index 27b381257d..c2ceca73a9 100644 --- a/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/RPISystemInterface.h +++ b/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/RPISystemInterface.h @@ -40,6 +40,9 @@ namespace AZ //! Note: can't rely on the AzFramework::AssetCatalogEventBus's OnCatalogLoaded since the order of calling handlers is undefined. virtual void InitializeSystemAssets() = 0; + //! Was the RPI system initialized properly + virtual bool IsInitialized() const = 0; + //! Register a created scene to RPISystem. Registered scene will be simulated and rendered in RPISystem ticks virtual void RegisterScene(ScenePtr scene) = 0; 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/Include/Atom/RPI.Reflect/Asset/AssetUtils.h b/Gems/Atom/RPI/Code/Include/Atom/RPI.Reflect/Asset/AssetUtils.h index 527bae7e1f..5a169a9e61 100644 --- a/Gems/Atom/RPI/Code/Include/Atom/RPI.Reflect/Asset/AssetUtils.h +++ b/Gems/Atom/RPI/Code/Include/Atom/RPI.Reflect/Asset/AssetUtils.h @@ -15,6 +15,8 @@ #include #include +#include + namespace AZ { namespace RPI @@ -48,6 +50,12 @@ namespace AZ //! @return a null asset if the asset could not be found or loaded. template Data::Asset LoadAssetById(Data::AssetId assetId, TraceLevel reporting = TraceLevel::Warning); + + //! Loads a critial asset using a file path (both source and product path should be same), on the current thread. + //! If the asset wasn't compiled, wait until the asset is compiled. + //! @return a null asset if the asset could not be compiled or loaded. + template + Data::Asset LoadCriticalAsset(const AZStd::string& assetFilePath, TraceLevel reporting = TraceLevel::Error); template bool LoadBlocking(AZ::Data::Asset& asset, TraceLevel reporting = TraceLevel::Warning); @@ -89,7 +97,7 @@ namespace AZ assetId, AZ::Data::AssetLoadBehavior::PreLoad); asset.BlockUntilLoadComplete(); - if (!asset.Get()) + if (!asset.IsReady()) { AssetUtilsInternal::ReportIssue(reporting, AZStd::string::format("Could not load '%s'", productPath).c_str()); return {}; @@ -117,7 +125,7 @@ namespace AZ ); asset.BlockUntilLoadComplete(); - if (!asset.Get()) + if (!asset.IsReady()) { AssetUtilsInternal::ReportIssue(reporting, AZStd::string::format("Could not load '%s'", assetId.ToString().c_str()).c_str()); return {}; @@ -126,6 +134,21 @@ namespace AZ return asset; } + template + Data::Asset LoadCriticalAsset(const AZStd::string& assetFilePath, TraceLevel reporting) + { + AzFramework::AssetSystem::AssetStatus status = AzFramework::AssetSystem::AssetStatus_Unknown; + AzFramework::AssetSystemRequestBus::BroadcastResult(status, &AzFramework::AssetSystemRequestBus::Events::CompileAssetSync, assetFilePath); + + if (status != AzFramework::AssetSystem::AssetStatus_Compiled) + { + AssetUtilsInternal::ReportIssue(reporting, AZStd::string::format("Could not compile asset '%s'", assetFilePath.c_str()).c_str()); + return {}; + } + + return LoadAssetByProductPath(assetFilePath.c_str(), reporting); + } + template bool LoadBlocking(AZ::Data::Asset& asset, TraceLevel reporting) { diff --git a/Gems/Atom/RPI/Code/Source/RPI.Public/Buffer/BufferSystem.cpp b/Gems/Atom/RPI/Code/Source/RPI.Public/Buffer/BufferSystem.cpp index 491f57deec..9a9254b0d6 100644 --- a/Gems/Atom/RPI/Code/Source/RPI.Public/Buffer/BufferSystem.cpp +++ b/Gems/Atom/RPI/Code/Source/RPI.Public/Buffer/BufferSystem.cpp @@ -61,10 +61,16 @@ namespace AZ Data::InstanceDatabase::Create(azrtti_typeid(), handler); } Interface::Register(this); + + m_initialized = true; } void BufferSystem::Shutdown() { + if (!m_initialized) + { + return; + } for (uint8_t index = 0; index < static_cast(CommonBufferPoolType::Count); index++) { m_commonPools[index] = nullptr; @@ -72,6 +78,7 @@ namespace AZ Interface::Unregister(this); Data::InstanceDatabase::Destroy(); Data::InstanceDatabase::Destroy(); + m_initialized = false; } RHI::Ptr BufferSystem::GetCommonBufferPool(CommonBufferPoolType poolType) @@ -87,6 +94,10 @@ namespace AZ bool BufferSystem::CreateCommonBufferPool(CommonBufferPoolType poolType) { + if (!m_initialized) + { + return false; + } auto* device = RHI::RHISystemInterface::Get()->GetDevice(); RHI::Ptr bufferPool = RHI::Factory::Get().CreateBufferPool(); diff --git a/Gems/Atom/RPI/Code/Source/RPI.Public/Image/ImageSystem.cpp b/Gems/Atom/RPI/Code/Source/RPI.Public/Image/ImageSystem.cpp index ac7ba1e3cc..f7cdc2ff71 100644 --- a/Gems/Atom/RPI/Code/Source/RPI.Public/Image/ImageSystem.cpp +++ b/Gems/Atom/RPI/Code/Source/RPI.Public/Image/ImageSystem.cpp @@ -148,10 +148,16 @@ namespace AZ CreateDefaultResources(desc); Interface::Register(this); + + m_initialized = true; } void ImageSystem::Shutdown() { + if (!m_initialized) + { + return; + } Interface::Unregister(this); m_defaultStreamingImageControllerAsset.Release(); @@ -167,6 +173,7 @@ namespace AZ Data::InstanceDatabase::Destroy(); m_activeStreamingPools.clear(); + m_initialized = false; } void ImageSystem::Update() diff --git a/Gems/Atom/RPI/Code/Source/RPI.Public/Pass/PassLibrary.cpp b/Gems/Atom/RPI/Code/Source/RPI.Public/Pass/PassLibrary.cpp index d8f6416abc..6c1f96e414 100644 --- a/Gems/Atom/RPI/Code/Source/RPI.Public/Pass/PassLibrary.cpp +++ b/Gems/Atom/RPI/Code/Source/RPI.Public/Pass/PassLibrary.cpp @@ -327,14 +327,15 @@ namespace AZ } } - void PassLibrary::LoadPassTemplateMappings(const AZStd::string& templateMappingPath) + bool PassLibrary::LoadPassTemplateMappings(const AZStd::string& templateMappingPath) { - Data::Asset mappingAsset = AssetUtils::LoadAssetByProductPath(templateMappingPath.c_str(), AssetUtils::TraceLevel::Error); + Data::Asset mappingAsset = AssetUtils::LoadCriticalAsset(templateMappingPath.c_str(), AssetUtils::TraceLevel::Error); bool success = LoadPassTemplateMappings(mappingAsset); if (success) { Data::AssetBus::MultiHandler::BusConnect(mappingAsset->GetId()); } + return success; } bool PassLibrary::LoadPassTemplateMappings(Data::Asset mappingAsset) diff --git a/Gems/Atom/RPI/Code/Source/RPI.Public/Pass/PassSystem.cpp b/Gems/Atom/RPI/Code/Source/RPI.Public/Pass/PassSystem.cpp index 55b71c6962..706d759231 100644 --- a/Gems/Atom/RPI/Code/Source/RPI.Public/Pass/PassSystem.cpp +++ b/Gems/Atom/RPI/Code/Source/RPI.Public/Pass/PassSystem.cpp @@ -100,9 +100,9 @@ namespace AZ m_rootPass->m_flags.m_partOfHierarchy = true; } - void PassSystem::LoadPassTemplateMappings(const AZStd::string& templateMappingPath) + bool PassSystem::LoadPassTemplateMappings(const AZStd::string& templateMappingPath) { - m_passLibrary.LoadPassTemplateMappings(templateMappingPath); + return m_passLibrary.LoadPassTemplateMappings(templateMappingPath); } void PassSystem::WriteTemplateToFile(const PassTemplate& passTemplate, AZStd::string_view assetFilePath) diff --git a/Gems/Atom/RPI/Code/Source/RPI.Public/RPISystem.cpp b/Gems/Atom/RPI/Code/Source/RPI.Public/RPISystem.cpp index 52c39d2204..5cd6f93715 100644 --- a/Gems/Atom/RPI/Code/Source/RPI.Public/RPISystem.cpp +++ b/Gems/Atom/RPI/Code/Source/RPI.Public/RPISystem.cpp @@ -334,7 +334,6 @@ namespace AZ void RPISystem::InitializeSystemAssets() { - AzFramework::AssetSystem::AssetStatus status = AzFramework::AssetSystem::AssetStatus_Unknown; if (m_systemAssetsInitialized) { AZ_Warning("RPISystem", false , "InitializeSystemAssets should only be called once'"); @@ -344,36 +343,47 @@ namespace AZ //[GFX TODO][ATOM-5867] - Move file loading code within RHI to reduce coupling with RPI AZStd::string platformLimitsFilePath = AZStd::string::format("config/platform/%s/%s/platformlimits.azasset", AZ_TRAIT_OS_PLATFORM_NAME, GetRenderApiName().GetCStr()); AZStd::to_lower(platformLimitsFilePath.begin(), platformLimitsFilePath.end()); - // Wait for the platformlimits asset to be compiled (if it exists) - AzFramework::AssetSystemRequestBus::BroadcastResult( - status, &AzFramework::AssetSystemRequestBus::Events::CompileAssetSync, platformLimitsFilePath); - Data::Asset platformLimitsAsset = RPI::AssetUtils::LoadAssetByProductPath(platformLimitsFilePath.c_str(), RPI::AssetUtils::TraceLevel::Error); - m_descriptor.m_rhiSystemDescriptor.m_platformLimits = RPI::GetDataFromAnyAsset(platformLimitsAsset); + + Data::Asset platformLimitsAsset; + platformLimitsAsset = RPI::AssetUtils::LoadCriticalAsset(platformLimitsFilePath.c_str(), RPI::AssetUtils::TraceLevel::None); + // Only read the m_platformLimits if the platformLimitsAsset is ready. + // The platformLimitsAsset may not exist for null renderer which is allowed + if (platformLimitsAsset.IsReady()) + { + m_descriptor.m_rhiSystemDescriptor.m_platformLimits = RPI::GetDataFromAnyAsset(platformLimitsAsset); + } + + m_viewSrgAsset = AssetUtils::LoadCriticalAsset( m_descriptor.m_viewSrgAssetPath.c_str()); + if (!m_viewSrgAsset.IsReady()) + { + return; + } + m_sceneSrgAsset = AssetUtils::LoadCriticalAsset(m_descriptor.m_sceneSrgAssetPath.c_str()); + if (!m_sceneSrgAsset.IsReady()) + { + return; + } m_rhiSystem.Init(m_descriptor.m_rhiSystemDescriptor); m_imageSystem.Init(m_descriptor.m_imageSystemDescriptor); m_bufferSystem.Init(); m_dynamicDraw.Init(m_descriptor.m_dynamicDrawSystemDescriptor); - // Wait for the assets be compiled - AzFramework::AssetSystemRequestBus::BroadcastResult( - status, &AzFramework::AssetSystemRequestBus::Events::CompileAssetSync, m_descriptor.m_viewSrgAssetPath); - AZ_Error("RPISystem", status == AzFramework::AssetSystem::AssetStatus_Compiled, "Could not compile view SRG at '%s'", m_descriptor.m_viewSrgAssetPath.c_str()); - AzFramework::AssetSystemRequestBus::BroadcastResult( - status, &AzFramework::AssetSystemRequestBus::Events::CompileAssetSync, m_descriptor.m_sceneSrgAssetPath); - AZ_Error("RPISystem", status == AzFramework::AssetSystem::AssetStatus_Compiled, "Could not compile scene SRG at '%s'", m_descriptor.m_sceneSrgAssetPath.c_str()); - AzFramework::AssetSystemRequestBus::BroadcastResult( - status, &AzFramework::AssetSystemRequestBus::Events::CompileAssetSync, m_descriptor.m_passTemplatesMappingPath); - AZ_Error("RPISystem", status == AzFramework::AssetSystem::AssetStatus_Compiled, "Could not compile pass template mapping at '%s'", m_descriptor.m_passTemplatesMappingPath.c_str()); - - m_viewSrgAsset = AssetUtils::LoadAssetByProductPath(m_descriptor.m_viewSrgAssetPath.c_str(), AssetUtils::TraceLevel::Error); - m_sceneSrgAsset = AssetUtils::LoadAssetByProductPath(m_descriptor.m_sceneSrgAssetPath.c_str(), AssetUtils::TraceLevel::Error); - // Have pass system load default pass template mapping - m_passSystem.LoadPassTemplateMappings(m_descriptor.m_passTemplatesMappingPath); + bool passSystemReady = m_passSystem.LoadPassTemplateMappings(m_descriptor.m_passTemplatesMappingPath); + if (!passSystemReady) + { + return; + } + m_systemAssetsInitialized = true; } + bool RPISystem::IsInitialized() const + { + return m_systemAssetsInitialized; + } + void RPISystem::InitializeSystemAssetsForTests() { if (m_systemAssetsInitialized) 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; diff --git a/Gems/Atom/RPI/Code/Source/RPI.Public/ViewportContext.cpp b/Gems/Atom/RPI/Code/Source/RPI.Public/ViewportContext.cpp index b2f9acb855..22287238e9 100644 --- a/Gems/Atom/RPI/Code/Source/RPI.Public/ViewportContext.cpp +++ b/Gems/Atom/RPI/Code/Source/RPI.Public/ViewportContext.cpp @@ -26,6 +26,7 @@ namespace AZ , m_windowContext(AZStd::make_shared()) , m_manager(manager) , m_name(name) + , m_viewportSize(1, 1) { m_windowContext->Initialize(device, nativeWindow); AzFramework::WindowRequestBus::EventResult( @@ -39,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); @@ -199,6 +201,7 @@ namespace AZ { const auto view = GetDefaultView(); view->SetCameraTransform(AZ::Matrix3x4::CreateFromTransform(transform.GetOrthogonalized())); + m_viewMatrixChangedEvent.Signal(view->GetWorldToViewMatrix()); } void ViewportContext::SetDefaultView(ViewPtr view) diff --git a/Gems/Atom/RPI/Code/Source/RPI.Reflect/Shader/ShaderResourceGroupAsset.cpp b/Gems/Atom/RPI/Code/Source/RPI.Reflect/Shader/ShaderResourceGroupAsset.cpp index d372e1442d..d8f8c7d1ce 100644 --- a/Gems/Atom/RPI/Code/Source/RPI.Reflect/Shader/ShaderResourceGroupAsset.cpp +++ b/Gems/Atom/RPI/Code/Source/RPI.Reflect/Shader/ShaderResourceGroupAsset.cpp @@ -41,7 +41,11 @@ namespace AZ const RHI::ShaderResourceGroupLayout* ShaderResourceGroupAsset::GetLayout() const { - AZ_Assert(m_currentAPITypeIndex < m_perAPILayout.size(), "Invalid API Type index"); + AZ_Error("RHI::ShaderResourceGroupLayout", m_currentAPITypeIndex < m_perAPILayout.size(), "Invalid API Type index"); + if (m_currentAPITypeIndex >= m_perAPILayout.size()) + { + return nullptr; + } return m_perAPILayout[m_currentAPITypeIndex].second.get(); } diff --git a/Gems/Atom/RPI/Code/Tests.Builders/BuilderTestFixture.cpp b/Gems/Atom/RPI/Code/Tests.Builders/BuilderTestFixture.cpp index 657657d07d..36598fb29f 100644 --- a/Gems/Atom/RPI/Code/Tests.Builders/BuilderTestFixture.cpp +++ b/Gems/Atom/RPI/Code/Tests.Builders/BuilderTestFixture.cpp @@ -75,6 +75,7 @@ namespace UnitTest // Adding this handler to allow utility functions access the serialize context ComponentApplicationBus::Handler::BusConnect(); + AZ::Interface::Register(this); // Startup default local FileIO (hits OSAllocator) if not already setup. if (IO::FileIOBase::GetInstance() == nullptr) @@ -113,6 +114,7 @@ namespace UnitTest delete IO::FileIOBase::GetInstance(); IO::FileIOBase::SetInstance(nullptr); + AZ::Interface::Unregister(this); ComponentApplicationBus::Handler::BusDisconnect(); m_jsonRegistrationContext->EnableRemoveReflection(); diff --git a/Gems/Atom/RPI/Code/Tests.Builders/BuilderTestFixture.h b/Gems/Atom/RPI/Code/Tests.Builders/BuilderTestFixture.h index 51282642aa..81d9ddb87a 100644 --- a/Gems/Atom/RPI/Code/Tests.Builders/BuilderTestFixture.h +++ b/Gems/Atom/RPI/Code/Tests.Builders/BuilderTestFixture.h @@ -41,6 +41,10 @@ namespace UnitTest void UnregisterComponentDescriptor(const AZ::ComponentDescriptor*) override { } void RegisterEntityAddedEventHandler(AZ::EntityAddedEvent::Handler&) override { } void RegisterEntityRemovedEventHandler(AZ::EntityRemovedEvent::Handler&) override { } + void RegisterEntityActivatedEventHandler(AZ::EntityActivatedEvent::Handler&) override { } + void RegisterEntityDeactivatedEventHandler(AZ::EntityDeactivatedEvent::Handler&) override { } + void SignalEntityActivated(AZ::Entity*) override { } + void SignalEntityDeactivated(AZ::Entity*) override { } bool AddEntity(AZ::Entity*) override { return false; } bool RemoveEntity(AZ::Entity*) override { return false; } bool DeleteEntity(const AZ::EntityId&) override { return false; } diff --git a/Gems/Atom/RPI/Code/Tests/Common/AssetManagerTestFixture.h b/Gems/Atom/RPI/Code/Tests/Common/AssetManagerTestFixture.h index f400a171c5..9ab6aea51a 100644 --- a/Gems/Atom/RPI/Code/Tests/Common/AssetManagerTestFixture.h +++ b/Gems/Atom/RPI/Code/Tests/Common/AssetManagerTestFixture.h @@ -38,6 +38,10 @@ namespace UnitTest void UnregisterComponentDescriptor(const AZ::ComponentDescriptor*) override { } void RegisterEntityAddedEventHandler(AZ::EntityAddedEvent::Handler&) override { } void RegisterEntityRemovedEventHandler(AZ::EntityRemovedEvent::Handler&) override { } + void RegisterEntityActivatedEventHandler(AZ::EntityActivatedEvent::Handler&) override { } + void RegisterEntityDeactivatedEventHandler(AZ::EntityDeactivatedEvent::Handler&) override { } + void SignalEntityActivated(AZ::Entity*) override { } + void SignalEntityDeactivated(AZ::Entity*) override { } bool AddEntity(AZ::Entity*) override { return false; } bool RemoveEntity(AZ::Entity*) override { return false; } bool DeleteEntity(const AZ::EntityId&) override { return false; } 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/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/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/Include/AtomToolsFramework/Viewport/RenderViewportWidget.h b/Gems/Atom/Tools/AtomToolsFramework/Code/Include/AtomToolsFramework/Viewport/RenderViewportWidget.h index ff2a9cdf98..a41c8221f0 100644 --- a/Gems/Atom/Tools/AtomToolsFramework/Code/Include/AtomToolsFramework/Viewport/RenderViewportWidget.h +++ b/Gems/Atom/Tools/AtomToolsFramework/Code/Include/AtomToolsFramework/Viewport/RenderViewportWidget.h @@ -100,7 +100,7 @@ namespace AtomToolsFramework const AzFramework::ScreenPoint& screenPosition) override; //! Set interface for providing viewport specific settings (e.g. snapping properties). - void SetViewportSettings(AzToolsFramework::ViewportInteraction::ViewportSettings* viewportSettings); + void SetViewportSettings(const AzToolsFramework::ViewportInteraction::ViewportSettings* viewportSettings); // AzToolsFramework::ViewportInteraction::ViewportMouseCursorRequestBus::Handler ... void BeginCursorCapture() override; 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/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/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::ExpandGroup(const AZStd::string& groupNameId) + { + auto groupItr = m_groups.find(groupNameId); + if (groupItr != m_groups.end()) + { + groupItr->second.first->SetExpanded(true); + groupItr->second.second->setVisible(true); + } + } + + void InspectorWidget::CollapseGroup(const AZStd::string& groupNameId) + { + auto groupItr = m_groups.find(groupNameId); + if (groupItr != m_groups.end()) + { + groupItr->second.first->SetExpanded(false); + groupItr->second.second->setVisible(false); + } + } + + 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(true); - } - for (auto groupWidget : m_groups) - { - groupWidget->setVisible(true); + groupPair.second.first->SetExpanded(true); + groupPair.second.second->setVisible(true); } } void InspectorWidget::CollapseAll() { - for (auto headerWidget : m_headers) + for (auto& groupPair : m_groups) { - headerWidget->SetExpanded(false); - } - for (auto groupWidget : 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/AtomToolsFramework/Code/Source/Viewport/RenderViewportWidget.cpp b/Gems/Atom/Tools/AtomToolsFramework/Code/Source/Viewport/RenderViewportWidget.cpp index 961de670e8..cee178c724 100644 --- a/Gems/Atom/Tools/AtomToolsFramework/Code/Source/Viewport/RenderViewportWidget.cpp +++ b/Gems/Atom/Tools/AtomToolsFramework/Code/Source/Viewport/RenderViewportWidget.cpp @@ -407,7 +407,7 @@ namespace AtomToolsFramework return m_viewportSettings ? m_viewportSettings->AngleStep() : 0.0f; } - void RenderViewportWidget::SetViewportSettings(AzToolsFramework::ViewportInteraction::ViewportSettings* viewportSettings) + void RenderViewportWidget::SetViewportSettings(const AzToolsFramework::ViewportInteraction::ViewportSettings* viewportSettings) { m_viewportSettings = viewportSettings; } diff --git a/Gems/ImageProcessing/Code/Source/BuilderSettings/BuilderSettings.h b/Gems/Atom/Tools/MaterialEditor/Code/Include/Atom/Document/MaterialDocumentSettings.h similarity index 50% rename from Gems/ImageProcessing/Code/Source/BuilderSettings/BuilderSettings.h rename to Gems/Atom/Tools/MaterialEditor/Code/Include/Atom/Document/MaterialDocumentSettings.h index 500b69f472..86c913d271 100644 --- a/Gems/ImageProcessing/Code/Source/BuilderSettings/BuilderSettings.h +++ b/Gems/Atom/Tools/MaterialEditor/Code/Include/Atom/Document/MaterialDocumentSettings.h @@ -12,22 +12,24 @@ #pragma once -#include +#if !defined(Q_MOC_RUN) +#include +#include +#include +#include +#endif -namespace ImageProcessing +namespace MaterialEditor { - //builder setting for a platform - struct BuilderSettings + struct MaterialDocumentSettings + : public AZ::UserSettings { - AZ_TYPE_INFO(BuilderSettings, "{4085AB56-934C-43A6-AF25-4443E1EEB71D}"); - AZ_CLASS_ALLOCATOR(BuilderSettings, AZ::SystemAllocator, 0); + AZ_RTTI(MaterialDocumentSettings, "{FA4F4BF3-BF39-4753-AAF7-AF383B868881}", AZ::UserSettings); + AZ_CLASS_ALLOCATOR(MaterialDocumentSettings, AZ::SystemAllocator, 0); + static void Reflect(AZ::ReflectContext* context); - //global settings - float m_brdfGlossScale = 16.0f; - float m_brdfGlossBias = 0.0f; - bool m_enableStreaming = true; - bool m_enablePlatform = true; - AZStd::map m_presets; + bool m_showReloadDocumentPrompt = true; + AZStd::string m_defaultMaterialTypeName = "StandardPBR"; }; -} // namespace ImageProcessing +} // 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..9ff03038f7 --- /dev/null +++ b/Gems/Atom/Tools/MaterialEditor/Code/Include/Atom/Window/MaterialEditorWindowSettings.h @@ -0,0 +1,35 @@ +/* +* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or +* its licensors. +* +* For complete copyright and license terms please see the LICENSE at the root of this +* distribution (the "License"). All use of this software is governed by the License, +* or, if provided, by the license below or the license accompanying this file. Do not +* remove or 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); + + AZStd::vector m_mainWindowState; + AZStd::unordered_set m_inspectorCollapsedGroups; + }; +} // 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..0dab7ea9f6 --- /dev/null +++ b/Gems/Atom/Tools/MaterialEditor/Code/Source/Document/MaterialDocumentSettings.cpp @@ -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. +* +*/ + +#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) + ->Field("defaultMaterialTypeName", &MaterialDocumentSettings::m_defaultMaterialTypeName) + ; + + 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", "") + ->DataElement(AZ::Edit::UIHandlers::Default, &MaterialDocumentSettings::m_defaultMaterialTypeName, "Default Material Type Name", "") + ; + } + } + + 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)) + ->Property("defaultMaterialTypeName", BehaviorValueProperty(&MaterialDocumentSettings::m_defaultMaterialTypeName)) + ; + } + } +} // 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..c7265e0039 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,13 +233,23 @@ 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); + + 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(); 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/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/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/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..64b6e01b61 100644 --- a/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/MaterialEditorWindow.cpp +++ b/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/MaterialEditorWindow.cpp @@ -10,45 +10,51 @@ * */ -#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 +#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 @@ -56,9 +62,18 @@ 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")); + QApplication::setWindowIcon(QIcon(":/Icons/materialeditor.svg")); AZ::Name apiName = AZ::RHI::Factory::Get().GetName(); if (!apiName.IsEmpty()) @@ -74,6 +89,7 @@ namespace MaterialEditor m_advancedDockManager = new AzQtComponents::FancyDocking(this); + setObjectName("MaterialEditorWindow"); setDockNestingEnabled(true); setCorner(Qt::TopLeftCorner, Qt::LeftDockWidgetArea); setCorner(Qt::BottomLeftCorner, Qt::LeftDockWidgetArea); @@ -81,17 +97,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); @@ -103,7 +123,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(); @@ -118,6 +139,19 @@ namespace MaterialEditor SetDockWidgetVisible("Performance Monitor", false); SetDockWidgetVisible("Python Terminal", false); + // 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); + + if (!windowSettings->m_mainWindowState.empty()) + { + QByteArray windowState(windowSettings->m_mainWindowState.data(), windowSettings->m_mainWindowState.size()); + m_advancedDockManager->restoreState(windowState); + } + MaterialEditorWindowRequestBus::Handler::BusConnect(); MaterialDocumentNotificationBus::Handler::BusConnect(); OnDocumentOpened(AZ::Uuid::CreateNull()); @@ -144,8 +178,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); @@ -203,15 +238,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()); } @@ -235,6 +271,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); } @@ -272,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); @@ -465,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"); @@ -512,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/MaterialEditorWindowComponent.cpp b/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/MaterialEditorWindowComponent.cpp index 820cee30f9..b0e8533ba4 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)) { @@ -102,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 new file mode 100644 index 0000000000..da04e2ea20 --- /dev/null +++ b/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/MaterialEditorWindowSettings.cpp @@ -0,0 +1,50 @@ +/* +* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or +* its licensors. +* +* For complete copyright and license terms please see the LICENSE at the root of this +* distribution (the "License"). All use of this software is governed by the License, +* or, if provided, by the license below or the license accompanying this file. Do not +* remove or 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("mainWindowState", &MaterialEditorWindowSettings::m_mainWindowState) + ->Field("inspectorCollapsedGroups", &MaterialEditorWindowSettings::m_inspectorCollapsedGroups) + ; + + if (auto editContext = serializeContext->GetEditContext()) + { + editContext->Class( + "MaterialEditorWindowSettings", "") + ->ClassElement(AZ::Edit::ClassElements::EditorData, "") + ->Attribute(AZ::Edit::Attributes::AutoExpand, true) + ; + } + } + + 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() + ; + } + } +} // namespace MaterialEditor 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..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,13 +21,16 @@ #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(); } @@ -39,6 +42,7 @@ namespace MaterialEditor void MaterialInspector::Reset() { + m_documentPath.clear(); m_documentId = AZ::Uuid::CreateNull(); m_groups = {}; @@ -46,6 +50,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(); @@ -55,6 +75,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 @@ -70,10 +92,24 @@ 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; - 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"; @@ -81,20 +117,19 @@ 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 - auto propertyGroupWidget = new AtomToolsFramework::InspectorPropertyGroupWidget(&group, &group, group.TYPEINFO_Uuid(), this, this, - [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); - }); + auto propertyGroupWidget = new AtomToolsFramework::InspectorPropertyGroupWidget( + &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); } @@ -114,32 +149,33 @@ 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); } // 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, - [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); - }); + auto propertyGroupWidget = new AtomToolsFramework::InspectorPropertyGroupWidget( + &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); } 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; @@ -150,18 +186,17 @@ 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); } } // 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, - [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); - }); + auto propertyGroupWidget = new AtomToolsFramework::InspectorPropertyGroupWidget( + &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); } } @@ -177,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; } @@ -185,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) { @@ -197,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; } @@ -214,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) { @@ -233,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; @@ -258,4 +299,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 efe979e5ea..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 @@ -41,7 +42,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(); @@ -64,6 +74,8 @@ namespace MaterialEditor const AtomToolsFramework::DynamicProperty* m_activeProperty = nullptr; 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/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/Code/CryEngine/CryCommon/EngineSettingsBackend.cpp b/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/SettingsDialog/SettingsDialog.h similarity index 59% rename from Code/CryEngine/CryCommon/EngineSettingsBackend.cpp rename to Gems/Atom/Tools/MaterialEditor/Code/Source/Window/SettingsDialog/SettingsDialog.h index caf7e03f31..a5ad35c4a3 100644 --- a/Code/CryEngine/CryCommon/EngineSettingsBackend.cpp +++ b/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/SettingsDialog/SettingsDialog.h @@ -10,25 +10,18 @@ * */ +#pragma once -#include "EngineSettingsBackend.h" +#include -#ifdef CRY_ENABLE_RC_HELPER - -CEngineSettingsBackend::CEngineSettingsBackend(CEngineSettingsManager* parent, const wchar_t* moduleName) - : m_parent(parent) - , m_moduleName() +namespace MaterialEditor { - if (moduleName != nullptr) + class SettingsDialog + : public QDialog { - m_moduleName = moduleName; - } -} - -CEngineSettingsBackend::~CEngineSettingsBackend() -{ - -} - -#endif // CRY_ENABLE_RC_HELPER - + 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/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..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,86 +1,40 @@ /* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or 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 { - 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); + + m_windowSettings = AZ::UserSettings::CreateFind( + AZ::Crc32("MaterialEditorWindowSettings"), AZ::UserSettings::CT_GLOBAL); + MaterialViewportNotificationBus::Handler::BusConnect(); } @@ -92,7 +46,7 @@ namespace MaterialEditor AtomToolsFramework::InspectorRequestBus::Handler::BusDisconnect(); } - void ViewportSettingsInspector::Popuate() + void ViewportSettingsInspector::Populate() { AddGroupsBegin(); AddGeneralGroup(); @@ -103,20 +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"; 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, 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); @@ -142,7 +97,7 @@ namespace MaterialEditor if (m_modelPreset) { 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, GetGroupSaveStateKey(groupNameId)); groupWidget->layout()->addWidget(inspectorWidget); } @@ -201,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); @@ -229,7 +184,8 @@ namespace MaterialEditor if (m_lightingPreset) { 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, + GetGroupSaveStateKey(groupNameId)); groupWidget->layout()->addWidget(inspectorWidget); } @@ -247,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); } } @@ -272,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()) { @@ -300,13 +256,15 @@ 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(); @@ -316,7 +274,7 @@ namespace MaterialEditor { if (m_lightingPreset != preset) { - Popuate(); + Populate(); } } @@ -324,37 +282,37 @@ namespace MaterialEditor { if (m_modelPreset != preset) { - Popuate(); + Populate(); } } 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 +337,14 @@ 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 @@ -398,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 c61acb2e4c..23bad988f0 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,17 @@ #if !defined(Q_MOC_RUN) #include -#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 @@ -51,7 +40,7 @@ namespace MaterialEditor ~ViewportSettingsInspector() override; private: - void Popuate(); + void Populate(); void AddGeneralGroup(); void AddModelGroup(); @@ -90,8 +79,14 @@ namespace MaterialEditor AZStd::string GetDefaultUniqueSaveFilePath(const AZStd::string& baseName) const; - GeneralViewportSettings m_generalSettings; + 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 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..7a1aa8c735 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 @@ -26,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 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 diff --git a/Gems/AtomLyIntegration/AtomBridge/Code/CMakeLists.txt b/Gems/AtomLyIntegration/AtomBridge/Code/CMakeLists.txt index 885f0d1a25..c431746b40 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 @@ -29,8 +31,6 @@ ly_add_target( Gem::Atom_RPI.Public Gem::Atom_Bootstrap.Headers Legacy::CryCommon - RUNTIME_DEPENDENCIES - Gem::AtomViewportDisplayInfo ) ly_add_target( @@ -43,12 +43,27 @@ 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_RHI_Null.Private + Gem::Atom_Feature_Common + Gem::Atom_Bootstrap + Gem::Atom_Component_DebugCamera + Gem::AtomImGuiTools + Gem::AtomLyIntegration_CommonFeatures + Gem::EMotionFX_Atom + Gem::ImguiAtom + Gem::AtomFont + Gem::AtomViewportDisplayInfo ) if(PAL_TRAIT_BUILD_HOST_TOOLS) @@ -62,6 +77,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 @@ -71,6 +88,23 @@ if(PAL_TRAIT_BUILD_HOST_TOOLS) Gem::Atom_Utils.Static Gem::Atom_AtomBridge.Static RUNTIME_DEPENDENCIES + 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 + 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 Gem::AtomViewportDisplayInfo ) endif() diff --git a/Gems/AtomLyIntegration/AtomBridge/Code/Source/AtomDebugDisplayViewportInterface.cpp b/Gems/AtomLyIntegration/AtomBridge/Code/Source/AtomDebugDisplayViewportInterface.cpp index 8a063cd7a7..482bd21972 100644 --- a/Gems/AtomLyIntegration/AtomBridge/Code/Source/AtomDebugDisplayViewportInterface.cpp +++ b/Gems/AtomLyIntegration/AtomBridge/Code/Source/AtomDebugDisplayViewportInterface.cpp @@ -506,9 +506,10 @@ namespace AZ::AtomBridge { if (m_auxGeomPtr) { + AZStd::vector transformedVertices = ToWorldSpacePosition(vertices); AZ::RPI::AuxGeomDraw::AuxGeomDynamicDrawArguments drawArgs; - drawArgs.m_verts = vertices.data(); - drawArgs.m_vertCount = aznumeric_cast(vertices.size()); + drawArgs.m_verts = transformedVertices.data(); + drawArgs.m_vertCount = aznumeric_cast(transformedVertices.size()); drawArgs.m_colors = &color; drawArgs.m_colorCount = 1; drawArgs.m_opacityType = m_rendState.m_opacityType; @@ -526,9 +527,10 @@ namespace AZ::AtomBridge { if (m_auxGeomPtr) { + AZStd::vector transformedVertices = ToWorldSpacePosition(vertices); AZ::RPI::AuxGeomDraw::AuxGeomDynamicIndexedDrawArguments drawArgs; - drawArgs.m_verts = vertices.data(); - drawArgs.m_vertCount = aznumeric_cast(vertices.size()); + drawArgs.m_verts = transformedVertices.data(); + drawArgs.m_vertCount = aznumeric_cast(transformedVertices.size()); drawArgs.m_indices = indices.data(); drawArgs.m_indexCount = aznumeric_cast(indices.size()); drawArgs.m_colors = &color; @@ -659,9 +661,10 @@ namespace AZ::AtomBridge { if (m_auxGeomPtr) { + AZStd::vector transformedLines = ToWorldSpacePosition(lines); AZ::RPI::AuxGeomDraw::AuxGeomDynamicDrawArguments drawArgs; - drawArgs.m_verts = lines.data(); - drawArgs.m_vertCount = aznumeric_cast(lines.size()); + drawArgs.m_verts = transformedLines.data(); + drawArgs.m_vertCount = aznumeric_cast(transformedLines.size()); drawArgs.m_colors = &color; drawArgs.m_colorCount = 1; drawArgs.m_size = m_rendState.m_lineWidth; @@ -928,13 +931,14 @@ namespace AZ::AtomBridge { if (m_auxGeomPtr) { + const float scale = GetCurrentTransform().RetrieveScale().GetMaxElement(); const AZ::Vector3 worldCenter = ToWorldSpacePosition(center); const AZ::Vector3 worldAxis = ToWorldSpaceVector(axis); m_auxGeomPtr->DrawCylinder( worldCenter, worldAxis, - radius, - height, + scale * radius, + scale * height, m_rendState.m_color, AZ::RPI::AuxGeomDraw::DrawStyle::Line, m_rendState.m_depthTest, @@ -954,13 +958,14 @@ namespace AZ::AtomBridge { if (m_auxGeomPtr) { + const float scale = GetCurrentTransform().RetrieveScale().GetMaxElement(); const AZ::Vector3 worldCenter = ToWorldSpacePosition(center); const AZ::Vector3 worldAxis = ToWorldSpaceVector(axis); m_auxGeomPtr->DrawCylinder( worldCenter, worldAxis, - radius, - height, + scale * radius, + scale * height, m_rendState.m_color, drawShaded ? AZ::RPI::AuxGeomDraw::DrawStyle::Shaded : AZ::RPI::AuxGeomDraw::DrawStyle::Solid, m_rendState.m_depthTest, @@ -1064,10 +1069,10 @@ namespace AZ::AtomBridge { if (m_auxGeomPtr) { - + const float scale = GetCurrentTransform().RetrieveScale().GetMaxElement(); m_auxGeomPtr->DrawSphere( ToWorldSpacePosition(pos), - radius, + scale * radius, m_rendState.m_color, AZ::RPI::AuxGeomDraw::DrawStyle::Line, m_rendState.m_depthTest, @@ -1158,12 +1163,13 @@ namespace AZ::AtomBridge { if (m_auxGeomPtr) { + const float scale = GetCurrentTransform().RetrieveScale().GetMaxElement(); const AZ::Vector3 worldPos = ToWorldSpacePosition(pos); const AZ::Vector3 worldDir = ToWorldSpaceVector(dir); m_auxGeomPtr->DrawDisk( worldPos, worldDir, - radius, + scale * radius, m_rendState.m_color, AZ::RPI::AuxGeomDraw::DrawStyle::Shaded, m_rendState.m_depthTest, @@ -1513,6 +1519,26 @@ namespace AZ::AtomBridge return m_rendState.m_transformStack[m_rendState.m_currentTransform]; } + AZStd::vector AtomDebugDisplayViewportInterface::ToWorldSpacePosition(const AZStd::vector& positions) const + { + AZStd::vector transformedPositions; + transformedPositions.resize_no_construct(positions.size()); + AZStd::transform(positions.begin(), positions.end(), transformedPositions.begin(), [this](const AZ::Vector3& position) { + return ToWorldSpacePosition(position); + }); + return transformedPositions; + } + + AZStd::vector AtomDebugDisplayViewportInterface::ToWorldSpaceVector(const AZStd::vector& vectors) const + { + AZStd::vector transformedVectors; + transformedVectors.resize_no_construct(vectors.size()); + AZStd::transform(vectors.begin(), vectors.end(), transformedVectors.begin(), [this](const AZ::Vector3& vector) { + return ToWorldSpaceVector(vector); + }); + return transformedVectors; + } + AZ::RPI::ViewportContextPtr AtomDebugDisplayViewportInterface::GetViewportContext() const { auto viewContextManager = AZ::Interface::Get(); diff --git a/Gems/AtomLyIntegration/AtomBridge/Code/Source/AtomDebugDisplayViewportInterface.h b/Gems/AtomLyIntegration/AtomBridge/Code/Source/AtomDebugDisplayViewportInterface.h index c872e2b81e..18d280ef88 100644 --- a/Gems/AtomLyIntegration/AtomBridge/Code/Source/AtomDebugDisplayViewportInterface.h +++ b/Gems/AtomLyIntegration/AtomBridge/Code/Source/AtomDebugDisplayViewportInterface.h @@ -249,6 +249,12 @@ namespace AZ::AtomBridge //! Convert direction to world space (translation is not considered) AZ::Vector3 ToWorldSpaceVector(const AZ::Vector3& v) const { return m_rendState.m_transformStack[m_rendState.m_currentTransform].Multiply3x3(v); } + //! Convert positions to world space. + AZStd::vector ToWorldSpacePosition(const AZStd::vector& positions) const; + + //! Convert directions to world space (translation is not considered) + AZStd::vector ToWorldSpaceVector(const AZStd::vector& vectors) const; + void CalcBasisVectors(const AZ::Vector3& n, AZ::Vector3& b1, AZ::Vector3& b2) const; const AZ::Matrix3x4& GetCurrentTransform() const; diff --git a/Gems/AtomLyIntegration/AtomBridge/Code/Source/Platform/Android/additional_android_runtime_deps.cmake b/Gems/AtomLyIntegration/AtomBridge/Code/Source/Platform/Android/additional_android_runtime_deps.cmake new file mode 100644 index 0000000000..31c0cab74b --- /dev/null +++ b/Gems/AtomLyIntegration/AtomBridge/Code/Source/Platform/Android/additional_android_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/ImageProcessing/CMakeLists.txt b/Gems/AtomLyIntegration/AtomBridge/Code/Source/Platform/Android/additional_android_tool_deps.cmake similarity index 94% rename from Gems/ImageProcessing/CMakeLists.txt rename to Gems/AtomLyIntegration/AtomBridge/Code/Source/Platform/Android/additional_android_tool_deps.cmake index 20a680bce9..99eec9a733 100644 --- a/Gems/ImageProcessing/CMakeLists.txt +++ b/Gems/AtomLyIntegration/AtomBridge/Code/Source/Platform/Android/additional_android_tool_deps.cmake @@ -9,4 +9,5 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # -add_subdirectory(Code) +set(LY_RUNTIME_DEPENDENCIES +) diff --git a/Gems/AtomLyIntegration/AtomBridge/Code/Source/Platform/Linux/additional_linux_runtime_deps.cmake b/Gems/AtomLyIntegration/AtomBridge/Code/Source/Platform/Linux/additional_linux_runtime_deps.cmake new file mode 100644 index 0000000000..31c0cab74b --- /dev/null +++ b/Gems/AtomLyIntegration/AtomBridge/Code/Source/Platform/Linux/additional_linux_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/Code/CryEngine/CryCommon/Platform/Mac/crycommon_enginesettings_mac_files.cmake b/Gems/AtomLyIntegration/AtomBridge/Code/Source/Platform/Linux/additional_linux_tool_deps.cmake similarity index 80% rename from Code/CryEngine/CryCommon/Platform/Mac/crycommon_enginesettings_mac_files.cmake rename to Gems/AtomLyIntegration/AtomBridge/Code/Source/Platform/Linux/additional_linux_tool_deps.cmake index f862be24f6..908417b1f8 100644 --- a/Code/CryEngine/CryCommon/Platform/Mac/crycommon_enginesettings_mac_files.cmake +++ b/Gems/AtomLyIntegration/AtomBridge/Code/Source/Platform/Linux/additional_linux_tool_deps.cmake @@ -9,7 +9,8 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # -set(FILES - ../../EngineSettingsBackendApple.cpp - ../../EngineSettingsBackendApple.h +set(LY_RUNTIME_DEPENDENCIES + 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_runtime_deps.cmake b/Gems/AtomLyIntegration/AtomBridge/Code/Source/Platform/Mac/additional_mac_runtime_deps.cmake new file mode 100644 index 0000000000..a0aa67c703 --- /dev/null +++ b/Gems/AtomLyIntegration/AtomBridge/Code/Source/Platform/Mac/additional_mac_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_mac_tool_deps.cmake b/Gems/AtomLyIntegration/AtomBridge/Code/Source/Platform/Mac/additional_mac_tool_deps.cmake new file mode 100644 index 0000000000..445a416a68 --- /dev/null +++ b/Gems/AtomLyIntegration/AtomBridge/Code/Source/Platform/Mac/additional_mac_tool_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_Metal.Builders + Gem::Atom_RHI_Vulkan.Builders + Gem::Atom_RHI_DX12.Builders +) diff --git a/Code/CryEngine/CryCommon/Platform/Windows/crycommon_enginesettings_windows_files.cmake b/Gems/AtomLyIntegration/AtomBridge/Code/Source/Platform/Windows/additional_windows_runtime_deps.cmake similarity index 81% rename from Code/CryEngine/CryCommon/Platform/Windows/crycommon_enginesettings_windows_files.cmake rename to Gems/AtomLyIntegration/AtomBridge/Code/Source/Platform/Windows/additional_windows_runtime_deps.cmake index db9fd5b464..dfd0319c05 100644 --- a/Code/CryEngine/CryCommon/Platform/Windows/crycommon_enginesettings_windows_files.cmake +++ b/Gems/AtomLyIntegration/AtomBridge/Code/Source/Platform/Windows/additional_windows_runtime_deps.cmake @@ -9,7 +9,8 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # -set(FILES - ../../EngineSettingsBackendWin32.cpp - ../../EngineSettingsBackendWin32.h +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..908417b1f8 --- /dev/null +++ b/Gems/AtomLyIntegration/AtomBridge/Code/Source/Platform/Windows/additional_windows_tool_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.Builders + Gem::Atom_RHI_DX12.Builders + Gem::Atom_RHI_Metal.Builders +) diff --git a/Gems/AtomLyIntegration/AtomBridge/Code/Source/Platform/iOS/additional_ios_runtime_deps.cmake b/Gems/AtomLyIntegration/AtomBridge/Code/Source/Platform/iOS/additional_ios_runtime_deps.cmake new file mode 100644 index 0000000000..a0aa67c703 --- /dev/null +++ b/Gems/AtomLyIntegration/AtomBridge/Code/Source/Platform/iOS/additional_ios_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/ImageProcessing/Code/Source/Platform/Mac/platform_mac.cmake b/Gems/AtomLyIntegration/AtomBridge/Code/Source/Platform/iOS/additional_ios_tool_deps.cmake similarity index 94% rename from Gems/ImageProcessing/Code/Source/Platform/Mac/platform_mac.cmake rename to Gems/AtomLyIntegration/AtomBridge/Code/Source/Platform/iOS/additional_ios_tool_deps.cmake index 4d5680a30d..99eec9a733 100644 --- a/Gems/ImageProcessing/Code/Source/Platform/Mac/platform_mac.cmake +++ b/Gems/AtomLyIntegration/AtomBridge/Code/Source/Platform/iOS/additional_ios_tool_deps.cmake @@ -8,3 +8,6 @@ # remove or 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/AtomFont/Code/Include/AtomLyIntegration/AtomFont/AtomFont.h b/Gems/AtomLyIntegration/AtomFont/Code/Include/AtomLyIntegration/AtomFont/AtomFont.h index fbefc84aad..d5463fc15c 100644 --- a/Gems/AtomLyIntegration/AtomFont/Code/Include/AtomLyIntegration/AtomFont/AtomFont.h +++ b/Gems/AtomLyIntegration/AtomFont/Code/Include/AtomLyIntegration/AtomFont/AtomFont.h @@ -79,7 +79,6 @@ namespace AZ FontFamilyPtr LoadFontFamily(const char* fontFamilyName) override; FontFamilyPtr GetFontFamily(const char* fontFamilyName) override; void AddCharsToFontTextures(FontFamilyPtr fontFamily, const char* chars, int glyphSizeX = ICryFont::defaultGlyphSizeX, int glyphSizeY = ICryFont::defaultGlyphSizeY) override; - void SetRendererProperties([[maybe_unused]] IRenderer* renderer) override {} void GetMemoryUsage([[maybe_unused]] ICrySizer* sizer) const override {} string GetLoadedFontNames() const; void OnLanguageChanged() override; diff --git a/Gems/AtomLyIntegration/AtomFont/Code/Include/AtomLyIntegration/AtomFont/AtomNullFont.h b/Gems/AtomLyIntegration/AtomFont/Code/Include/AtomLyIntegration/AtomFont/AtomNullFont.h index 11efc35109..4951f909e8 100644 --- a/Gems/AtomLyIntegration/AtomFont/Code/Include/AtomLyIntegration/AtomFont/AtomNullFont.h +++ b/Gems/AtomLyIntegration/AtomFont/Code/Include/AtomLyIntegration/AtomFont/AtomNullFont.h @@ -79,7 +79,6 @@ namespace AZ virtual FontFamilyPtr LoadFontFamily([[maybe_unused]] const char* fontFamilyName) override { CRY_ASSERT(false); return nullptr; } virtual FontFamilyPtr GetFontFamily([[maybe_unused]] const char* fontFamilyName) override { CRY_ASSERT(false); return nullptr; } virtual void AddCharsToFontTextures([[maybe_unused]] FontFamilyPtr fontFamily, [[maybe_unused]] const char* chars, [[maybe_unused]] int glyphSizeX, [[maybe_unused]] int glyphSizeY) override {}; - virtual void SetRendererProperties([[maybe_unused]] IRenderer* pRenderer) override {} virtual void GetMemoryUsage([[maybe_unused]] ICrySizer* sizer) const override {} virtual string GetLoadedFontNames() const override { return ""; } virtual void OnLanguageChanged() override { } diff --git a/Gems/AtomLyIntegration/AtomFont/Code/Source/FFont.cpp b/Gems/AtomLyIntegration/AtomFont/Code/Source/FFont.cpp index faeed52fb0..be0f87100a 100644 --- a/Gems/AtomLyIntegration/AtomFont/Code/Source/FFont.cpp +++ b/Gems/AtomLyIntegration/AtomFont/Code/Source/FFont.cpp @@ -1233,7 +1233,8 @@ void AZ::FFont::WrapText(string& result, float maxWidth, const char* str, const if (ctx.m_sizeIn800x600) { - maxWidth = gEnv->pRenderer->ScaleCoordX(maxWidth); + // ToDo: Update to work with Atom? LYN-3676 + // maxWidth = ???->ScaleCoordX(maxWidth); } Vec2 strSize = GetTextSize(result.c_str(), true, ctx); diff --git a/Gems/AtomLyIntegration/AtomFont/gem.json b/Gems/AtomLyIntegration/AtomFont/gem.json index 2a422eaf53..d5ca7834fd 100644 --- a/Gems/AtomLyIntegration/AtomFont/gem.json +++ b/Gems/AtomLyIntegration/AtomFont/gem.json @@ -1,5 +1,5 @@ { - "gem_name": "AtomLyIntegration_AtomFont", + "gem_name": "AtomFont", "Dependencies": [ ], "GemFormatVersion": 4, diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/CoreLights/AreaLightComponentConfig.cpp b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/CoreLights/AreaLightComponentConfig.cpp index 2dc439b846..8f10204ae9 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/CoreLights/AreaLightComponentConfig.cpp +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/CoreLights/AreaLightComponentConfig.cpp @@ -112,7 +112,7 @@ namespace AZ bool AreaLightComponentConfig::SupportsShadows() const { - return m_shapeType == AZ_CRC_CE("DiskShape"); + return m_lightType == LightType::SpotDisk || m_lightType == LightType::Sphere; } bool AreaLightComponentConfig::ShadowsDisabled() const 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); + } } } diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/CoreLights/SphereLightDelegate.cpp b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/CoreLights/SphereLightDelegate.cpp index de733e255b..e3cf1fac78 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/CoreLights/SphereLightDelegate.cpp +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/CoreLights/SphereLightDelegate.cpp @@ -63,5 +63,64 @@ namespace AZ debugDisplay.DrawWireSphere(transform.GetTranslation(), CalculateAttenuationRadius(AreaLightComponentConfig::CutoffIntensity)); } } + + void SphereLightDelegate::SetEnableShadow(bool enabled) + { + Base::SetEnableShadow(enabled); + + if (GetLightHandle().IsValid()) + { + GetFeatureProcessor()->SetShadowsEnabled(GetLightHandle(), enabled); + } + } + + void SphereLightDelegate::SetShadowmapMaxSize(ShadowmapSize size) + { + if (GetShadowsEnabled() && GetLightHandle().IsValid()) + { + GetFeatureProcessor()->SetShadowmapMaxResolution(GetLightHandle(), size); + } + } + + void SphereLightDelegate::SetShadowFilterMethod(ShadowFilterMethod method) + { + if (GetShadowsEnabled() && GetLightHandle().IsValid()) + { + GetFeatureProcessor()->SetShadowFilterMethod(GetLightHandle(), method); + } + } + + void SphereLightDelegate::SetSofteningBoundaryWidthAngle(float widthInDegrees) + { + if (GetShadowsEnabled() && GetLightHandle().IsValid()) + { + GetFeatureProcessor()->SetSofteningBoundaryWidthAngle(GetLightHandle(), DegToRad(widthInDegrees)); + } + } + + void SphereLightDelegate::SetPredictionSampleCount(uint32_t count) + { + if (GetShadowsEnabled() && GetLightHandle().IsValid()) + { + GetFeatureProcessor()->SetPredictionSampleCount(GetLightHandle(), count); + } + } + + void SphereLightDelegate::SetFilteringSampleCount(uint32_t count) + { + if (GetShadowsEnabled() && GetLightHandle().IsValid()) + { + GetFeatureProcessor()->SetFilteringSampleCount(GetLightHandle(), count); + } + } + + void SphereLightDelegate::SetPcfMethod(PcfMethod method) + { + if (GetShadowsEnabled() && GetLightHandle().IsValid()) + { + GetFeatureProcessor()->SetPcfMethod(GetLightHandle(), method); + } + } + } // namespace Render } // namespace AZ diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/CoreLights/SphereLightDelegate.h b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/CoreLights/SphereLightDelegate.h index 7d790f2d6c..178540fd01 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/CoreLights/SphereLightDelegate.h +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/CoreLights/SphereLightDelegate.h @@ -24,6 +24,8 @@ namespace AZ class SphereLightDelegate final : public LightDelegateBase { + using Base = LightDelegateBase; + public: SphereLightDelegate(LmbrCentral::SphereShapeComponentRequests* shapeBus, EntityId entityId, bool isVisible); @@ -32,6 +34,13 @@ namespace AZ void DrawDebugDisplay(const Transform& transform, const Color& color, AzFramework::DebugDisplayRequests& debugDisplay, bool isSelected) const override; float GetSurfaceArea() const override; float GetEffectiveSolidAngle() const override { return PhotometricValue::OmnidirectionalSteradians; } + void SetEnableShadow(bool enabled) override; + void SetShadowmapMaxSize(ShadowmapSize size) override; + void SetShadowFilterMethod(ShadowFilterMethod method) override; + void SetSofteningBoundaryWidthAngle(float widthInDegrees) override; + void SetPredictionSampleCount(uint32_t count) override; + void SetFilteringSampleCount(uint32_t count) override; + void SetPcfMethod(PcfMethod method) override; private: diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Material/EditorMaterialComponentInspector.cpp b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Material/EditorMaterialComponentInspector.cpp index 03533e142f..7f54e386fc 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(), + 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) { 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(), + 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) { AZ_UNUSED(source); const AtomToolsFramework::DynamicProperty* property = AtomToolsFramework::FindDynamicPropertyForInstanceDataNode(target); diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Mesh/MeshComponentController.cpp b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Mesh/MeshComponentController.cpp index 70627fd2f1..a4a91cf708 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Mesh/MeshComponentController.cpp +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Mesh/MeshComponentController.cpp @@ -296,8 +296,7 @@ namespace AZ m_configuration.m_modelAsset = modelAsset; MeshComponentNotificationBus::Event(m_entityId, &MeshComponentNotificationBus::Events::OnModelReady, m_configuration.m_modelAsset, model); MaterialReceiverNotificationBus::Event(m_entityId, &MaterialReceiverNotificationBus::Events::OnMaterialAssignmentsChanged); - AzFramework::EntityBoundsUnionRequestBus::Broadcast( - &AzFramework::EntityBoundsUnionRequestBus::Events::RefreshEntityLocalBoundsUnion, m_entityId); + AZ::Interface::Get()->RefreshEntityLocalBoundsUnion(m_entityId); } } diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/ReflectionProbe/ReflectionProbeComponentController.cpp b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/ReflectionProbe/ReflectionProbeComponentController.cpp index 772a995584..91040885f1 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/ReflectionProbe/ReflectionProbeComponentController.cpp +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/ReflectionProbe/ReflectionProbeComponentController.cpp @@ -253,8 +253,7 @@ namespace AZ m_configuration.m_outerLength = dimensions.GetY(); m_configuration.m_outerHeight = dimensions.GetZ(); - AzFramework::EntityBoundsUnionRequestBus::Broadcast( - &AzFramework::EntityBoundsUnionRequestBus::Events::RefreshEntityLocalBoundsUnion, m_entityId); + AZ::Interface::Get()->RefreshEntityLocalBoundsUnion(m_entityId); // clamp the inner extents to the outer extents m_configuration.m_innerWidth = AZStd::min(m_configuration.m_innerWidth, m_configuration.m_outerWidth); diff --git a/Gems/AtomLyIntegration/EMotionFXAtom/Code/Source/AtomActorInstance.cpp b/Gems/AtomLyIntegration/EMotionFXAtom/Code/Source/AtomActorInstance.cpp index f8b638efaf..d0116452b7 100644 --- a/Gems/AtomLyIntegration/EMotionFXAtom/Code/Source/AtomActorInstance.cpp +++ b/Gems/AtomLyIntegration/EMotionFXAtom/Code/Source/AtomActorInstance.cpp @@ -82,8 +82,7 @@ namespace AZ // Update RenderActorInstance local bounding box m_localAABB = AZ::Aabb::CreateFromMinMax(m_actorInstance->GetStaticBasedAABB().GetMin(), m_actorInstance->GetStaticBasedAABB().GetMax()); - AzFramework::EntityBoundsUnionRequestBus::Broadcast( - &AzFramework::EntityBoundsUnionRequestBus::Events::RefreshEntityLocalBoundsUnion, m_entityId); + AZ::Interface::Get()->RefreshEntityLocalBoundsUnion(m_entityId); } AZ::Aabb AtomActorInstance:: GetWorldBounds() diff --git a/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/Editor/Scripts/bootstrap.py b/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/Editor/Scripts/bootstrap.py index d1c1921ee5..6fd8b03e9e 100755 --- a/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/Editor/Scripts/bootstrap.py +++ b/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/Editor/Scripts/bootstrap.py @@ -16,7 +16,7 @@ with Lumberyard. Note: this boostrap is only designed fo be py3 compatible. If you need DCCsi access in py27 (Autodesk Maya for instance) you may need to implement your own boostrapper module. Currently this is boostrapped from add_dccsi.py, as a temporty measure related to this Jira: -https://jira.agscollab.com/browse/SPEC-2581""" +SPEC-2581""" # standard imports import sys import os diff --git a/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/SDK/Maya/Scripts/userSetup.py b/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/SDK/Maya/Scripts/userSetup.py index c615311f3c..0a206245c0 100755 --- a/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/SDK/Maya/Scripts/userSetup.py +++ b/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/SDK/Maya/Scripts/userSetup.py @@ -25,7 +25,7 @@ the provided env and launcher bat files. If you are developing for the DCCsi you can use this launcher to start Maya: DccScriptingInterface\Launchers\Windows\Launch_Maya_2020.bat" -To Do: https://jira.agscollab.com/browse/ATOM-5861 +To Do: ATOM-5861 """ __project__ = 'DccScriptingInterface' diff --git a/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/dev/ide/wing/readme.txt b/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/dev/ide/wing/readme.txt index 80c950d10b..2d32541c40 100644 --- a/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/dev/ide/wing/readme.txt +++ b/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/dev/ide/wing/readme.txt @@ -43,7 +43,7 @@ Note: to get this to work unfortunatley each user must configure the wingide pre (there is no shared project / data-driven way that I know of to set this up otherwise) Note: lumberyard is not currently generating __init__.pyi files in that package structure: -https://jira.agscollab.com/browse/SPEC-3315 +SPEC-3315 The workaround is to create them yourself (they can be empty) and needs to be in the root of each package folder, like this: dev\Cache\AtomTechArt\pc\user\python_symbols\azlmbr\__init__.pyi @@ -63,4 +63,4 @@ You might need to reboot wing. Then you should have auto-complete for the lumbe Note: the entirety of azlmbr api does not generate .pyi files currently, all of the "Behaviour Context" based classes do non-BC modules such as azlmbr.paths currently do not -https://jira.agscollab.com/browse/SPEC-3316 +SPEC-3316 diff --git a/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/common/core_utils.py b/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/common/core_utils.py index 6404f3ee07..958d3f688d 100755 --- a/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/common/core_utils.py +++ b/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/common/core_utils.py @@ -40,7 +40,7 @@ Module Documentation: To Do: - https://jira.agscollab.com/browse/ATOM-5859 + ATOM-5859 ''' # ------------------------------------------------------------------------- diff --git a/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/common/envar_utils.py b/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/common/envar_utils.py index 4e59f86063..acc24f3f79 100755 --- a/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/common/envar_utils.py +++ b/Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/common/envar_utils.py @@ -22,7 +22,7 @@ Module: \azpy\shared\common\config_utils.py To Do: - https://jira.agscollab.com/browse/ATOM-5859 + ATOM-5859 ''' # ------------------------------------------------------------------------- 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/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/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/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/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/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/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/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/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/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/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/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..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; @@ -1757,16 +1763,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..25e6a22d84 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)) @@ -105,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/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/AudioSystem/Code/Source/Engine/ATL.cpp b/Gems/AudioSystem/Code/Source/Engine/ATL.cpp index 2398836e48..dc6742d460 100644 --- a/Gems/AudioSystem/Code/Source/Engine/ATL.cpp +++ b/Gems/AudioSystem/Code/Source/Engine/ATL.cpp @@ -2018,7 +2018,8 @@ namespace Audio { AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::Audio); - if (IRenderAuxGeom* pAuxGeom = (g_audioCVars.m_nDrawAudioDebug > 0 && gEnv->pRenderer) ? gEnv->pRenderer->GetIRenderAuxGeom() : nullptr) + // ToDo: Update to work with Atom? LYN-3677 + /*if (g_audioCVars.m_nDrawAudioDebug > 0) { DrawAudioObjectDebugInfo(*pAuxGeom); // needs to be called first so that the rest of the labels are printed // on top (Draw2dLabel doesn't provide a way set which labels are printed on top) @@ -2108,7 +2109,7 @@ namespace Audio DrawATLComponentDebugInfo(*pAuxGeom, fPosX, fPosY); pAuxGeom->Commit(7); - } + }*/ } /////////////////////////////////////////////////////////////////////////////////////////////////// diff --git a/Gems/AudioSystem/Code/Source/Engine/ATLAudioObject.cpp b/Gems/AudioSystem/Code/Source/Engine/ATLAudioObject.cpp index 7f3735dacf..3b820eb51d 100644 --- a/Gems/AudioSystem/Code/Source/Engine/ATLAudioObject.cpp +++ b/Gems/AudioSystem/Code/Source/Engine/ATLAudioObject.cpp @@ -839,16 +839,16 @@ namespace Audio const AZ::Vector3 vPos(m_oPosition.GetPositionVec()); AZ::Vector3 vScreenPos(0.f); - if (IRenderer* pRenderer = gEnv->pRenderer) - { + // ToDo: Update to work with Atom? LYN-3677 + /*{ float screenProj[3]; - pRenderer->ProjectToScreen(vPos.GetX(), vPos.GetY(), vPos.GetZ(), &screenProj[0], &screenProj[1], &screenProj[2]); + ???->ProjectToScreen(vPos.GetX(), vPos.GetY(), vPos.GetZ(), &screenProj[0], &screenProj[1], &screenProj[2]); - screenProj[0] *= 0.01f * static_cast(pRenderer->GetWidth()); - screenProj[1] *= 0.01f * static_cast(pRenderer->GetHeight()); + screenProj[0] *= 0.01f * static_cast(???->GetWidth()); + screenProj[1] *= 0.01f * static_cast(???->GetHeight()); vScreenPos.Set(screenProj); } - else + else*/ { vScreenPos.SetZ(-1.0f); } @@ -1081,8 +1081,8 @@ namespace Audio ); } - IRenderer* renderer = gEnv->pRenderer; - if (drawLabels && renderer) + // ToDo: Update to work with Atom? LYN-3677 + /*if (drawLabels) { float screenProj[3]; renderer->ProjectToScreen(rayEnd.GetX(), rayEnd.GetY(), rayEnd.GetZ(), @@ -1108,7 +1108,7 @@ namespace Audio rayInfo.GetDistanceScaledContribution() ); } - } + }*/ } auxGeom.SetRenderFlags(previousRenderFlags); diff --git a/Gems/CMakeLists.txt b/Gems/CMakeLists.txt deleted file mode 100644 index 8a9a140008..0000000000 --- a/Gems/CMakeLists.txt +++ /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. -# - -add_subdirectory(TextureAtlas) -add_subdirectory(LmbrCentral) -add_subdirectory(LyShine) -add_subdirectory(Maestro) -add_subdirectory(SceneProcessing) -add_subdirectory(SurfaceData) -add_subdirectory(EMotionFX) -add_subdirectory(Achievements) -add_subdirectory(CameraFramework) -add_subdirectory(HttpRequestor) -add_subdirectory(Gestures) -add_subdirectory(FastNoise) -add_subdirectory(GradientSignal) -add_subdirectory(AudioSystem) -add_subdirectory(AudioEngineWwise) -add_subdirectory(GraphCanvas) -add_subdirectory(DebugDraw) -add_subdirectory(ImGui) -add_subdirectory(InAppPurchases) -add_subdirectory(LocalUser) -add_subdirectory(LyShineExamples) -add_subdirectory(ExpressionEvaluation) -add_subdirectory(MessagePopup) -add_subdirectory(PhysX) -add_subdirectory(PhysXDebug) -add_subdirectory(ScriptEvents) -add_subdirectory(AssetValidation) -add_subdirectory(VirtualGamepad) -add_subdirectory(SaveData) -add_subdirectory(Camera) -add_subdirectory(GameState) -add_subdirectory(Vegetation) -add_subdirectory(GameStateSamples) -add_subdirectory(SliceFavorites) -add_subdirectory(Metastream) -add_subdirectory(ScriptCanvas) -add_subdirectory(ScriptedEntityTweener) -add_subdirectory(StartingPointMovement) -add_subdirectory(StartingPointInput) -add_subdirectory(ScriptCanvasPhysics) -add_subdirectory(StartingPointCamera) -add_subdirectory(Presence) -add_subdirectory(ScriptCanvasTesting) -add_subdirectory(TestAssetBuilder) -add_subdirectory(ScriptCanvasDeveloper) -add_subdirectory(CustomAssetExample) -add_subdirectory(AutomatedLauncherTesting) -add_subdirectory(NvCloth) -add_subdirectory(AssetMemoryAnalyzer) -add_subdirectory(CertificateManager) -add_subdirectory(TickBusOrderViewer) -add_subdirectory(MultiplayerCompression) -add_subdirectory(Multiplayer) -add_subdirectory(SceneLoggingExample) -add_subdirectory(VideoPlaybackFramework) -add_subdirectory(CrashReporting) -add_subdirectory(Twitch) -add_subdirectory(EditorPythonBindings) -add_subdirectory(QtForPython) -add_subdirectory(Microphone) -add_subdirectory(Atom) -add_subdirectory(AtomLyIntegration) -add_subdirectory(RADTelemetry) -add_subdirectory(GraphModel) -add_subdirectory(LandscapeCanvas) -add_subdirectory(WhiteBox) -add_subdirectory(Blast) -add_subdirectory(PythonAssetBuilder) -add_subdirectory(Prefab) -add_subdirectory(AWSClientAuth) -add_subdirectory(AWSCore) -add_subdirectory(AWSMetrics) diff --git a/Gems/EMotionFX/Code/Source/Integration/Components/ActorComponent.cpp b/Gems/EMotionFX/Code/Source/Integration/Components/ActorComponent.cpp index 8ef87af9a7..982b62fbcf 100644 --- a/Gems/EMotionFX/Code/Source/Integration/Components/ActorComponent.cpp +++ b/Gems/EMotionFX/Code/Source/Integration/Components/ActorComponent.cpp @@ -504,8 +504,7 @@ namespace EMotionFX { m_renderActorInstance->OnTick(deltaTime); m_renderActorInstance->UpdateBounds(); - AzFramework::EntityBoundsUnionRequestBus::Broadcast( - &AzFramework::EntityBoundsUnionRequestBus::Events::RefreshEntityLocalBoundsUnion, GetEntityId()); + AZ::Interface::Get()->RefreshEntityLocalBoundsUnion(GetEntityId()); // Optimization: Set the actor instance invisible when character is out of camera view. This will stop the joint transforms update, except the root joint. // Calling it after the bounds on the render actor updated. 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/Tests/MorphSkinAttachmentTests.cpp b/Gems/EMotionFX/Code/Tests/MorphSkinAttachmentTests.cpp index 42c2cc2110..d69aa02fc6 100644 --- a/Gems/EMotionFX/Code/Tests/MorphSkinAttachmentTests.cpp +++ b/Gems/EMotionFX/Code/Tests/MorphSkinAttachmentTests.cpp @@ -168,8 +168,8 @@ namespace EMotionFX // The skin attachment should now receive morph values from the main actor. const Pose& attachPose = *m_attachmentActorInstance->GetTransformData()->GetCurrentPose(); ASSERT_EQ(attachPose.GetNumMorphWeights(), 4); - EXPECT_FLOAT_EQ(attachPose.GetMorphWeight(0), 0.0f); // Once we auto register missing morphs this should be 0.5. See https://jira.agscollab.com/browse/LY-100212 - EXPECT_FLOAT_EQ(attachPose.GetMorphWeight(1), 0.0f); // Once we auto register missing morphs this should be 0.6. See https://jira.agscollab.com/browse/LY-100212 + EXPECT_FLOAT_EQ(attachPose.GetMorphWeight(0), 0.0f); // Once we auto register missing morphs this should be 0.5. See LY-100212 + EXPECT_FLOAT_EQ(attachPose.GetMorphWeight(1), 0.0f); // Once we auto register missing morphs this should be 0.6. See LY-100212 EXPECT_FLOAT_EQ(attachPose.GetMorphWeight(2), 0.1f); EXPECT_FLOAT_EQ(attachPose.GetMorphWeight(3), 0.2f); }; diff --git a/Gems/EMotionFX/Code/Tests/UI/LODSkinnedMeshTests.cpp b/Gems/EMotionFX/Code/Tests/UI/LODSkinnedMeshTests.cpp index b9b512da36..9fa3e17263 100644 --- a/Gems/EMotionFX/Code/Tests/UI/LODSkinnedMeshTests.cpp +++ b/Gems/EMotionFX/Code/Tests/UI/LODSkinnedMeshTests.cpp @@ -77,7 +77,6 @@ namespace EMotionFX m_app.RegisterComponentDescriptor(AzFramework::TransformComponent::CreateDescriptor()); m_envPrev = gEnv; - m_env.pRenderer = &m_data.m_renderer; m_env.pSystem = &m_data.m_system; gEnv = &m_env; } 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/EMotionFX/gem.json b/Gems/EMotionFX/gem.json index 022f3b3077..f116a6a2c0 100644 --- a/Gems/EMotionFX/gem.json +++ b/Gems/EMotionFX/gem.json @@ -1,5 +1,5 @@ { - "gem_name": "EmotionFX", + "gem_name": "EMotionFX", "Dependencies": [ { "Uuid": "ff06785f7145416b9d46fde39098cb0c", 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/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/ImGui/Code/CMakeLists.txt b/Gems/ImGui/Code/CMakeLists.txt index 9b594d86f9..2f7d6c6ce7 100644 --- a/Gems/ImGui/Code/CMakeLists.txt +++ b/Gems/ImGui/Code/CMakeLists.txt @@ -95,8 +95,6 @@ if(PAL_TRAIT_BUILD_HOST_TOOLS) NAME ImGui.Editor GEM_MODULE NAMESPACE Gem - AUTOMOC - AUTOUIC FILES_CMAKE imgui_editor_files.cmake COMPILE_DEFINITIONS @@ -112,9 +110,6 @@ if(PAL_TRAIT_BUILD_HOST_TOOLS) BUILD_DEPENDENCIES PRIVATE Gem::ImGui.Static - 3rdParty::Qt::Widgets - AZ::AzToolsFramework - Legacy::Editor.Headers RUNTIME_DEPENDENCIES Gem::LmbrCentral.Editor ) diff --git a/Gems/ImGui/Code/Editor/ImGuiEditorWindowBus.h b/Gems/ImGui/Code/Editor/ImGuiEditorWindowBus.h deleted file mode 100644 index 1ee987a74d..0000000000 --- a/Gems/ImGui/Code/Editor/ImGuiEditorWindowBus.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. -* -*/ - -#pragma once - -#include - -namespace ImGui -{ - class ImGuiEditorWindowRequests - : public AZ::EBusTraits - { - public: - ////////////////////////////////////////////////////////////////////////// - // EBusTraits overrides - static const AZ::EBusHandlerPolicy HandlerPolicy = AZ::EBusHandlerPolicy::Single; - static const AZ::EBusAddressPolicy AddressPolicy = AZ::EBusAddressPolicy::Single; - ////////////////////////////////////////////////////////////////////////// - - // Put your public methods here - }; - using ImGuiEditorWindowRequestBus = AZ::EBus; -} // namespace ImGuiEditorWindow diff --git a/Gems/ImGui/Code/Editor/ImGuiEditorWindowModule.cpp b/Gems/ImGui/Code/Editor/ImGuiEditorWindowModule.cpp index f44d5cb61e..b02f470ad9 100644 --- a/Gems/ImGui/Code/Editor/ImGuiEditorWindowModule.cpp +++ b/Gems/ImGui/Code/Editor/ImGuiEditorWindowModule.cpp @@ -13,7 +13,6 @@ #include "ImGui_precompiled.h" #include "ImGuiGem.h" -#include "ImGuiEditorWindowSystemComponent.h" namespace ImGui { @@ -26,22 +25,6 @@ namespace ImGui ImGuiEditorWindowModule() : ImGuiModule() { - // Push results of [MyComponent]::CreateDescriptor() into m_descriptors here. - m_descriptors.insert(m_descriptors.end(), { - ImGuiEditorWindowSystemComponent::CreateDescriptor(), - }); - } - - /** - * Add required SystemComponents to the SystemEntity. - */ - AZ::ComponentTypeList GetRequiredSystemComponents() const override - { - AZ::ComponentTypeList requiredComponents = ImGuiModule::GetRequiredSystemComponents(); - - requiredComponents.push_back(azrtti_typeid()); - - return requiredComponents; } }; } diff --git a/Gems/ImGui/Code/Editor/ImGuiEditorWindowSystemComponent.cpp b/Gems/ImGui/Code/Editor/ImGuiEditorWindowSystemComponent.cpp deleted file mode 100644 index 07ab3b0a42..0000000000 --- a/Gems/ImGui/Code/Editor/ImGuiEditorWindowSystemComponent.cpp +++ /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. -* -*/ - -#include "ImGui_precompiled.h" - -#include -#include -#include -#include "ImGuiEditorWindowSystemComponent.h" -#include "ImGuiMainWindow.h" -#include - -static const char* s_ImGuiQtViewPaneName = "ImGui Editor"; - -namespace ImGui -{ - void ImGuiEditorWindowSystemComponent::Reflect(AZ::ReflectContext* context) - { - if (AZ::SerializeContext* serialize = azrtti_cast(context)) - { - serialize->Class() - ->Version(0) - ; - } - } - - void ImGuiEditorWindowSystemComponent::Activate() - { - AzToolsFramework::EditorEvents::Bus::Handler::BusConnect(); - ImGuiEditorWindowRequestBus::Handler::BusConnect(); - ImGuiUpdateListenerBus::Handler::BusConnect(); - } - - void ImGuiEditorWindowSystemComponent::Deactivate() - { - ImGuiUpdateListenerBus::Handler::BusDisconnect(); - ImGuiEditorWindowRequestBus::Handler::BusDisconnect(); - AzToolsFramework::EditorEvents::Bus::Handler::BusDisconnect(); - } - - ImGuiEditorWindowSystemComponent::~ImGuiEditorWindowSystemComponent() - { - EBUS_EVENT(AzToolsFramework::EditorRequests::Bus, UnregisterViewPane, s_ImGuiQtViewPaneName); - } - - void ImGuiEditorWindowSystemComponent::OnOpenEditorWindow() - { - EBUS_EVENT(AzToolsFramework::EditorRequests::Bus, OpenViewPane, s_ImGuiQtViewPaneName); - } - - void ImGuiEditorWindowSystemComponent::NotifyRegisterViews() - { - } -} diff --git a/Gems/ImGui/Code/Editor/ImGuiEditorWindowSystemComponent.h b/Gems/ImGui/Code/Editor/ImGuiEditorWindowSystemComponent.h deleted file mode 100644 index 1f9d3cdc52..0000000000 --- a/Gems/ImGui/Code/Editor/ImGuiEditorWindowSystemComponent.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. -* -*/ - -#pragma once - -#include - -#include -#include -#include "ImGuiManager.h" -#include "ImGuiBus.h" - -namespace ImGui -{ - class ImGuiEditorWindowSystemComponent - : public AZ::Component - , protected ImGuiEditorWindowRequestBus::Handler - , public ImGuiUpdateListenerBus::Handler - , protected AzToolsFramework::EditorEvents::Bus::Handler - { - public: - AZ_COMPONENT(ImGuiEditorWindowSystemComponent, "{91021F3E-B5F0-4E26-A7C9-6ED0F6CB6C5A}"); - - virtual ~ImGuiEditorWindowSystemComponent(); - - static void Reflect(AZ::ReflectContext* context); - - protected: - //////////////////////////////////////////////////////////////////////// - // ImGuiEditorWindowRequestBus interface implementation - - //////////////////////////////////////////////////////////////////////// - - //////////////////////////////////////////////////////////////////////// - // AZ::Component interface implementation - void Activate() override; - void Deactivate() override; - //////////////////////////////////////////////////////////////////////// - - //////////////////////////////////////////////////////////////////////// - // ImGuiUpdateListenerBus interface implementation - void OnOpenEditorWindow() override; - //////////////////////////////////////////////////////////////////////// - - //////////////////////////////////////////////////////////////////////// - // EditorEvents - void NotifyRegisterViews() override; - //////////////////////////////////////////////////////////////////////// - }; -} diff --git a/Gems/ImGui/Code/Editor/ImGuiMainWindow.cpp b/Gems/ImGui/Code/Editor/ImGuiMainWindow.cpp deleted file mode 100644 index b4774d1334..0000000000 --- a/Gems/ImGui/Code/Editor/ImGuiMainWindow.cpp +++ /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. -* -*/ -#include "ImGui_precompiled.h" -#include "ImGuiMainWindow.h" -#include "QtViewPaneManager.h" -#include "ImGuiViewport.h" -#include - -using namespace ImGui; - -ImGuiMainWindow::ImGuiMainWindow(QWidget* parent) - : QMainWindow(parent) - , m_ui(new Ui::ImGuiMainWindow) - , m_viewport(new ImGuiViewportWidget(this)) -{ - m_ui->setupUi(this); - - //@rky: Add the ImGuiViewport to this window - m_viewport->setFocusPolicy(Qt::StrongFocus); - m_ui->gridLayout->addWidget(m_viewport, 0, 0, 1, 1); -} - -#include diff --git a/Gems/ImGui/Code/Editor/ImGuiMainWindow.h b/Gems/ImGui/Code/Editor/ImGuiMainWindow.h deleted file mode 100644 index 659ec7b4c1..0000000000 --- a/Gems/ImGui/Code/Editor/ImGuiMainWindow.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. -* -*/ -#ifndef __IMGUI_MAINWINDOW_H__ -#define __IMGUI_MAINWINDOW_H__ - -#pragma once - -#if !defined(Q_MOC_RUN) -#include -#include "IEditor.h" -#include -#endif - -namespace Ui -{ - class ImGuiMainWindow; -} - -namespace ImGui -{ - class ImGuiViewportWidget; - - class ImGuiMainWindow : public QMainWindow - { - Q_OBJECT - public: - - static const GUID& GetClassID() - { - // {ECA9F41C-716E-4395-A096-5A519227F9A4} - static const GUID guid = - { 0xeca9f41c, 0x716e, 0x4395, { 0xa0, 0x96, 0x5a, 0x51, 0x92, 0x27, 0xf9, 0xa4 } }; - - return guid; - } - - explicit ImGuiMainWindow(QWidget* parent = nullptr); - - private: - QScopedPointer m_ui; - - ImGuiViewportWidget* m_viewport; - }; -} - -#endif //__IMGUI_MAINWINDOW_H__ diff --git a/Gems/ImGui/Code/Editor/ImGuiMainwindow.ui b/Gems/ImGui/Code/Editor/ImGuiMainwindow.ui deleted file mode 100644 index 7124e22c7a..0000000000 --- a/Gems/ImGui/Code/Editor/ImGuiMainwindow.ui +++ /dev/null @@ -1,33 +0,0 @@ - - - ImGuiMainWindow - - - - 0 - 0 - 1263 - 740 - - - - MainWindow - - - - - - - - 0 - 0 - 1263 - 21 - - - - - - - - diff --git a/Gems/ImGui/Code/Editor/ImGuiViewport.cpp b/Gems/ImGui/Code/Editor/ImGuiViewport.cpp deleted file mode 100644 index 7c467d7f08..0000000000 --- a/Gems/ImGui/Code/Editor/ImGuiViewport.cpp +++ /dev/null @@ -1,339 +0,0 @@ -/* - * All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or - * its licensors. - * - * For complete copyright and license terms please see the LICENSE at the root of this - * distribution (the "License"). All use of this software is governed by the License, - * or, if provided, by the license below or the license accompanying this file. Do not - * remove or 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 "ImGui_precompiled.h" - -#include "ImGuiViewport.h" -#include -#include -#include -#include -#include "ImGuiBus.h" -#include "ImGuiManager.h" -#include - -using namespace ImGui; - -ImGuiViewportWidget::ImGuiViewportWidget(QWidget* parent) - : QWidget(parent) - , m_width(0) - , m_height(0) - , m_renderContextCreated(false) - , m_creatingRenderContext(false) - , m_lastTime(0) - , m_lastFrameTime(0.f) - , m_averageFrameTime(0.f) -{ - // Setup a timer for the maximum refresh rate we want. - // Refresh is actually triggered by interaction events and by the IdleUpdate. This avoids the UI - // Editor slowing down the main editor when no UI interaction is occurring. - QObject::connect(&m_updateTimer, SIGNAL(timeout()), this, SLOT(RefreshTick())); - const int kUpdateIntervalInMillseconds = 1000 / 60; // 60 Hz - m_updateTimer.start(kUpdateIntervalInMillseconds); - - CreateRenderContext(); -} - -ImGuiViewportWidget::~ImGuiViewportWidget() -{ - DestroyRenderContext(); - ImGuiManagerBus::Broadcast(&IImGuiManager::SetEditorWindowState, - DisplayState::Hidden); -} - -bool ImGuiViewportWidget::CreateRenderContext() -{ - if (m_creatingRenderContext) - { - return false; - } - m_creatingRenderContext = true; - DestroyRenderContext(); - HWND window = (HWND)QWidget::winId(); - IEditor* editor = nullptr; - EBUS_EVENT_RESULT(editor, AzToolsFramework::EditorRequests::Bus, GetEditor); - if (window && editor->GetEnv()->pRenderer && !m_renderContextCreated) - { - m_renderContextCreated = true; - - StorePreviousContext(); - editor->GetEnv()->pRenderer->CreateContext(window); - RestorePreviousContext(); - - ImGuiManagerBus::Broadcast(&IImGuiManager::SetEditorWindowState, - DisplayState::Visible); - - m_creatingRenderContext = false; - return true; - } - m_creatingRenderContext = false; - return false; -} - -void ImGuiViewportWidget::DestroyRenderContext() -{ - IEditor* editor = nullptr; - EBUS_EVENT_RESULT(editor, AzToolsFramework::EditorRequests::Bus, GetEditor); - if (editor->GetEnv()->pRenderer && m_renderContextCreated) - { - HWND window = (HWND)QWidget::winId(); - if (window != editor->GetEnv()->pRenderer->GetHWND()) - { - editor = nullptr; - EBUS_EVENT_RESULT(editor, AzToolsFramework::EditorRequests::Bus, GetEditor); - editor->GetEnv()->pRenderer->DeleteContext(window); - } - m_renderContextCreated = false; - } -} - -void ImGuiViewportWidget::StorePreviousContext() -{ - SPreviousContext previous; - IEditor* editor = nullptr; - EBUS_EVENT_RESULT(editor, AzToolsFramework::EditorRequests::Bus, GetEditor); - previous.width = editor->GetEnv()->pRenderer->GetWidth(); - previous.height = editor->GetEnv()->pRenderer->GetHeight(); - previous.window = (HWND)editor->GetEnv()->pRenderer->GetCurrentContextHWND(); - previous.renderCamera = editor->GetEnv()->pRenderer->GetCamera(); - previous.systemCamera = gEnv->pSystem->GetViewCamera(); - previous.isMainViewport = editor->GetEnv()->pRenderer->IsCurrentContextMainVP(); - m_previousContexts.push(previous); -} - -void ImGuiViewportWidget::SetCurrentContext() -{ - StorePreviousContext(); - - IEditor* editor = nullptr; - EBUS_EVENT_RESULT(editor, AzToolsFramework::EditorRequests::Bus, GetEditor); - - HWND window = (HWND)QWidget::winId(); - editor->GetEnv()->pRenderer->SetCurrentContext(window); - editor->GetEnv()->pRenderer->ChangeViewport(0, 0, m_width, m_height); -} - -void ImGuiViewportWidget::RestorePreviousContext() -{ - if (m_previousContexts.empty()) - { - return; - } - - SPreviousContext x = m_previousContexts.top(); - m_previousContexts.pop(); - IEditor* editor = nullptr; - EBUS_EVENT_RESULT(editor, AzToolsFramework::EditorRequests::Bus, GetEditor); - editor->GetEnv()->pRenderer->SetCurrentContext(x.window); - editor->GetEnv()->pRenderer->ChangeViewport(0, 0, x.width, x.height, x.isMainViewport); - - editor->GetEnv()->pRenderer->SetCamera(x.renderCamera); - gEnv->pSystem->SetViewCamera(x.systemCamera); -} - -void ImGuiViewportWidget::Render() -{ - SetCurrentContext(); - - IEditor* editor = nullptr; - EBUS_EVENT_RESULT(editor, AzToolsFramework::EditorRequests::Bus, GetEditor); - - IRenderer* renderer = editor->GetEnv()->pRenderer; - - ColorF viewportBackgroundColor(Col_Gray); - ColorF stateMessageColor(Col_Gray); - AZStd::string stateMessage = "No State"; - DisplayState visibilityState = DisplayState::Hidden; - ImGuiManagerBus::BroadcastResult(visibilityState, - &IImGuiManager::GetEditorWindowState); - switch (visibilityState) - { - case ImGui::DisplayState::Hidden: - stateMessage = "Invisible"; - break; - case ImGui::DisplayState::Visible: - stateMessage = "ImGui Window"; - stateMessageColor = Col_SteelBlue; - viewportBackgroundColor = Col_SkyBlue; - break; - case ImGui::DisplayState::VisibleNoMouse: - stateMessage = "Game Focus"; - stateMessageColor = Col_Gray; - viewportBackgroundColor = Col_LightGray; - break; - } - - renderer->ClearTargetsImmediately(FRT_CLEAR | FRT_CLEAR_IMMEDIATE, viewportBackgroundColor); - renderer->ResetToDefault(); - - renderer->Draw2dLabel( - 12.0f, m_height - 50.f, 1.25f, Col_White, false, "FPS: %.2f", 1.0f / m_averageFrameTime); - renderer->Draw2dLabel( - 12.0f, m_height - 30.f, 2.f, stateMessageColor, false, "State: %s", stateMessage.c_str()); - - if (ImDrawData* drawData = ImGui::GetDrawData()) - { - // Configure renderer for 2d imgui rendering - renderer->SetCullMode(R_CULL_DISABLE); - TransformationMatrices backupSceneMatrices; - renderer->Set2DMode(renderer->GetWidth(), renderer->GetHeight(), backupSceneMatrices); - renderer->SetColorOp(eCO_REPLACE, eCO_MODULATE, eCA_Diffuse, DEF_TEXARG0); - renderer->SetSrgbWrite(false); - renderer->SetState(GS_BLSRC_SRCALPHA | GS_BLDST_ONEMINUSSRCALPHA | GS_NODEPTHTEST); - - // Expand vertex buffer if necessary - m_vertBuffer.reserve(drawData->TotalVtxCount); - if (m_vertBuffer.size() < drawData->TotalVtxCount) - { - m_vertBuffer.insert(m_vertBuffer.end(), - drawData->TotalVtxCount - m_vertBuffer.size(), - SVF_P3F_C4B_T2F()); - } - - // Expand index buffer if necessary - m_idxBuffer.reserve(drawData->TotalIdxCount); - if (m_idxBuffer.size() < drawData->TotalIdxCount) - { - m_idxBuffer.insert(m_idxBuffer.end(), drawData->TotalIdxCount - m_idxBuffer.size(), 0); - } - - // Process each draw command list individually - for (int n = 0; n < drawData->CmdListsCount; n++) - { - const ImDrawList* cmd_list = drawData->CmdLists[n]; - - // Cache max vert count for easy access - int numVerts = cmd_list->VtxBuffer.Size; - - // Copy command list verts into buffer - for (int i = 0; i < numVerts; ++i) - { - const ImDrawVert& imguiVert = cmd_list->VtxBuffer[i]; - SVF_P3F_C4B_T2F& vert = m_vertBuffer[i]; - - vert.xyz = Vec3(imguiVert.pos.x, imguiVert.pos.y, 0.0f); - // Convert color from RGBA to ARGB - vert.color.dcolor = (imguiVert.col & 0xFF00FF00) - | ((imguiVert.col & 0xFF0000) >> 16) - | ((imguiVert.col & 0xFF) << 16); - vert.st = Vec2(imguiVert.uv.x, imguiVert.uv.y); - } - - // Copy command list indices into buffer - for (int i = 0; i < cmd_list->IdxBuffer.Size; ++i) - { - m_idxBuffer[i] = uint16(cmd_list->IdxBuffer[i]); - } - - // Use offset pointer to step along rendering operation - uint16* idxBufferDataOffset = m_idxBuffer.data(); - - // Process each draw command individually - for (int cmd_i = 0; cmd_i < cmd_list->CmdBuffer.size(); cmd_i++) - { - const ImDrawCmd* pcmd = &cmd_list->CmdBuffer[cmd_i]; - - // Defer to user rendering callback, if appropriate - if (pcmd->UserCallback) - { - pcmd->UserCallback(cmd_list, pcmd); - } - // Otherwise render our buffers - else - { - int textureId = ((ITexture*)pcmd->TextureId)->GetTextureID(); - renderer->SetTexture(textureId); - renderer->SetScissor((int)pcmd->ClipRect.x, - (int)(pcmd->ClipRect.y), - (int)(pcmd->ClipRect.z - pcmd->ClipRect.x), - (int)(pcmd->ClipRect.w - pcmd->ClipRect.y)); - renderer->DrawDynVB(m_vertBuffer.data(), - idxBufferDataOffset, - numVerts, - pcmd->ElemCount, - prtTriangleList); - } - - // Update offset pointer into command list's index buffer - idxBufferDataOffset += pcmd->ElemCount; - } - } - - // Reset scissor usage on renderer - renderer->SetScissor(); - - // Clean up renderer settings - renderer->Unset2DMode(backupSceneMatrices); - } - - RestorePreviousContext(); -} - -void ImGuiViewportWidget::resizeEvent(QResizeEvent* ev) -{ - QWidget::resizeEvent(ev); - - int cx = ev->size().width(); - int cy = ev->size().height(); - if (cx == 0 || cy == 0) - { - return; - } - - m_width = cx; - m_height = cy; - - IEditor* editor = nullptr; - EBUS_EVENT_RESULT(editor, AzToolsFramework::EditorRequests::Bus, GetEditor); - editor->GetEnv()->pSystem->GetISystemEventDispatcher()->OnSystemEvent( - ESYSTEM_EVENT_RESIZE, cx, cy); - - RefreshTick(); -} - -void ImGuiViewportWidget::RefreshTick() -{ - IEditor* editor = nullptr; - EBUS_EVENT_RESULT(editor, AzToolsFramework::EditorRequests::Bus, GetEditor); - int64 time = editor->GetEnv()->pSystem->GetITimer()->GetAsyncTime().GetMilliSecondsAsInt64(); - 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; - } - - Render(); - - m_updateTimer.start(); -} - -bool ImGuiViewportWidget::event(QEvent* ev) -{ - bool result = QWidget::event(ev); - - if (ev->type() == QEvent::WinIdChange) - { - CreateRenderContext(); - } - - return result; -} - -#include diff --git a/Gems/ImGui/Code/Editor/ImGuiViewport.h b/Gems/ImGui/Code/Editor/ImGuiViewport.h deleted file mode 100644 index 2f7c475395..0000000000 --- a/Gems/ImGui/Code/Editor/ImGuiViewport.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. - * - */ - -#pragma once -#if !defined(Q_MOC_RUN) -#include -#include -#include -#include -#include -#include -#include -#endif - -namespace ImGui -{ - class ImGuiViewportWidget : public QWidget - { - Q_OBJECT - public: - ImGuiViewportWidget(QWidget* parent); - ~ImGuiViewportWidget(); - - void Render(); - - private slots: - void RefreshTick(); - - private: - struct SPreviousContext - { - int width; - int height; - HWND window; - CCamera renderCamera; - CCamera systemCamera; - bool isMainViewport; - }; - - bool CreateRenderContext(); - void DestroyRenderContext(); - void StorePreviousContext(); - void SetCurrentContext(); - void RestorePreviousContext(); - - void resizeEvent(QResizeEvent* ev) override; - bool event(QEvent* ev) override; - - AZStd::stack m_previousContexts; - unsigned int m_width; - unsigned int m_height; - bool m_renderContextCreated; - bool m_creatingRenderContext; - int64 m_lastTime; - float m_lastFrameTime; - float m_averageFrameTime; - AZStd::vector m_vertBuffer; - AZStd::vector m_idxBuffer; - QTimer m_updateTimer; - }; -} diff --git a/Gems/ImGui/Code/imgui_editor_files.cmake b/Gems/ImGui/Code/imgui_editor_files.cmake index 75a98524ae..842fde7965 100644 --- a/Gems/ImGui/Code/imgui_editor_files.cmake +++ b/Gems/ImGui/Code/imgui_editor_files.cmake @@ -10,15 +10,7 @@ # set(FILES - Editor/ImGuiEditorWindowBus.h Editor/ImGuiEditorWindowModule.cpp - Editor/ImGuiEditorWindowSystemComponent.cpp - Editor/ImGuiEditorWindowSystemComponent.h - Editor/ImGuiMainWindow.h - Editor/ImGuiMainWindow.cpp - Editor/ImGuiMainwindow.ui - Editor/ImGuiViewport.h - Editor/ImGuiViewport.cpp Source/ImGuiGem.h Source/ImGuiGem.cpp ) diff --git a/Gems/ImGui/External/ImGui/v1.82/imgui/imgui.cpp b/Gems/ImGui/External/ImGui/v1.82/imgui/imgui.cpp index 2555d1a6af..c2db0da54a 100644 --- a/Gems/ImGui/External/ImGui/v1.82/imgui/imgui.cpp +++ b/Gems/ImGui/External/ImGui/v1.82/imgui/imgui.cpp @@ -7118,7 +7118,9 @@ static void ImGui::ErrorCheckEndFrameSanityChecks() // We silently accommodate for this case by ignoring/ the case where all io.KeyXXX modifiers were released (aka key_mod_flags == 0), // while still correctly asserting on mid-frame key press events. const ImGuiKeyModFlags key_mod_flags = GetMergedKeyModFlags(); - IM_ASSERT((key_mod_flags == 0 || g.IO.KeyMods == key_mod_flags) && "Mismatching io.KeyCtrl/io.KeyShift/io.KeyAlt/io.KeySuper vs io.KeyMods"); + + // [GFX TODO] Commented this line until Atom ImGuiPass is refactored (ATOM-15495). + // IM_ASSERT((key_mod_flags == 0 || g.IO.KeyMods == key_mod_flags) && "Mismatching io.KeyCtrl/io.KeyShift/io.KeyAlt/io.KeySuper vs io.KeyMods"); IM_UNUSED(key_mod_flags); // Recover from errors diff --git a/Gems/ImageProcessing/AssetProcessorGemConfig.setreg b/Gems/ImageProcessing/AssetProcessorGemConfig.setreg deleted file mode 100644 index 17d9887fe8..0000000000 --- a/Gems/ImageProcessing/AssetProcessorGemConfig.setreg +++ /dev/null @@ -1,7 +0,0 @@ -{ - "Amazon": { - "AssetProcessor": { - "Settings": {} - } - } -} diff --git a/Gems/ImageProcessing/Assets/Editor/Backward.png b/Gems/ImageProcessing/Assets/Editor/Backward.png deleted file mode 100644 index 82b3eafbd9..0000000000 --- a/Gems/ImageProcessing/Assets/Editor/Backward.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:1a1623477f4e2e5ef0440ecfc0c08e775d9b5f12d8ebc6b434e8212bf3445bcd -size 224 diff --git a/Gems/ImageProcessing/Assets/Editor/Forward.png b/Gems/ImageProcessing/Assets/Editor/Forward.png deleted file mode 100644 index a7a29a4c25..0000000000 --- a/Gems/ImageProcessing/Assets/Editor/Forward.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:31b247223c1116d4fc014189a9d8d86d4458b792c1120442673631136fd89520 -size 222 diff --git a/Gems/ImageProcessing/Assets/Editor/Resources.qrc b/Gems/ImageProcessing/Assets/Editor/Resources.qrc deleted file mode 100644 index c309d19053..0000000000 --- a/Gems/ImageProcessing/Assets/Editor/Resources.qrc +++ /dev/null @@ -1,11 +0,0 @@ - - - refresh-active.png - warning.png - refresh.png - info.png - Backward.png - Forward.png - reset.png - - diff --git a/Gems/ImageProcessing/Assets/Editor/info.png b/Gems/ImageProcessing/Assets/Editor/info.png deleted file mode 100644 index 002cf9c775..0000000000 --- a/Gems/ImageProcessing/Assets/Editor/info.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:3fec3caae92b9c9290c4157b3aeca29dcb366edd12719355e1d93dfb9d80cfed -size 825 diff --git a/Gems/ImageProcessing/Assets/Editor/refresh-active.png b/Gems/ImageProcessing/Assets/Editor/refresh-active.png deleted file mode 100644 index 33bc1c592a..0000000000 --- a/Gems/ImageProcessing/Assets/Editor/refresh-active.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:d29af2b69b74815c88352f85a7131384482e4f2d26ecf36581b46dede542fccb -size 2973 diff --git a/Gems/ImageProcessing/Assets/Editor/refresh.png b/Gems/ImageProcessing/Assets/Editor/refresh.png deleted file mode 100644 index fc9ef09987..0000000000 --- a/Gems/ImageProcessing/Assets/Editor/refresh.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:36591b457ee3519b16405d281674fcdd18645e3570bfc960a22b8f142ee99a14 -size 436 diff --git a/Gems/ImageProcessing/Assets/Editor/reset.png b/Gems/ImageProcessing/Assets/Editor/reset.png deleted file mode 100644 index ed9c2f016d..0000000000 --- a/Gems/ImageProcessing/Assets/Editor/reset.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:0362da38d3804e2911130d138be4fd73040d66c8ac7d1b5f9f60c70037e8ca93 -size 1292 diff --git a/Gems/ImageProcessing/Assets/Editor/warning.png b/Gems/ImageProcessing/Assets/Editor/warning.png deleted file mode 100644 index 6020245f86..0000000000 --- a/Gems/ImageProcessing/Assets/Editor/warning.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:cf5e987ea92164dcaa6deb88989aaac962bc092f5745274017f71224f48dbf7a -size 651 diff --git a/Gems/ImageProcessing/Code/CMakeLists.txt b/Gems/ImageProcessing/Code/CMakeLists.txt deleted file mode 100644 index a5cb6f6cb9..0000000000 --- a/Gems/ImageProcessing/Code/CMakeLists.txt +++ /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. -# - -ly_add_target( - NAME ImageProcessing.Headers HEADERONLY - NAMESPACE Gem - FILES_CMAKE - imageprocessing_headers_files.cmake - INCLUDE_DIRECTORIES - INTERFACE - Include -) - -if (NOT PAL_TRAIT_BUILD_HOST_TOOLS) - return() -endif() - -ly_get_list_relative_pal_filename(pal_dir ${CMAKE_CURRENT_LIST_DIR}/Source/Platform/${PAL_PLATFORM_NAME}) - -set(platform_tools_files) -set(pal_tools_include_files) -set(pal_tools_dirs) -foreach(enabled_platform ${LY_PAL_TOOLS_ENABLED}) - string(TOLOWER ${enabled_platform} enabled_platform_lowercase) - ly_get_list_relative_pal_filename(pal_tools_dir ${CMAKE_CURRENT_LIST_DIR}/Source/Platform/${enabled_platform}) - list(APPEND platform_tools_files ${pal_tools_dir}/pal_tools_${enabled_platform_lowercase}.cmake) - list(APPEND pal_tools_include_files ${pal_tools_dir}/pal_tools_${enabled_platform_lowercase}_files.cmake) - list(APPEND pal_tools_dirs ${pal_tools_dir}) -endforeach() - -ly_add_target( - NAME ImageProcessing.Static STATIC - NAMESPACE Gem - AUTOMOC - AUTOUIC - FILES_CMAKE - imageprocessing_static_files.cmake - ${pal_tools_include_files} - ${pal_dir}/platform_${PAL_PLATFORM_NAME_LOWERCASE}_files.cmake - PLATFORM_INCLUDE_FILES - ${pal_dir}/platform_${PAL_PLATFORM_NAME_LOWERCASE}.cmake - ${platform_tools_files} - INCLUDE_DIRECTORIES - PRIVATE - . - Source - ../External - ${pal_dir} - ${pal_tools_dirs} - PUBLIC - Include - BUILD_DEPENDENCIES - PRIVATE - 3rdParty::Qt::Core - 3rdParty::Qt::Widgets - 3rdParty::etc2comp - 3rdParty::PVRTexTool - 3rdParty::squish-ccr - 3rdParty::zlib - 3rdParty::tiff - Legacy::CryCommon - AZ::AzCore - AZ::AssetBuilderSDK - Gem::TextureAtlas -) -ly_add_source_properties( - SOURCES - Source/BuilderSettings/BuilderSettingManager.cpp - Source/Processing/ImageConvert.cpp - PROPERTY COMPILE_DEFINITIONS - VALUES ${LY_PAL_TOOLS_DEFINES} -) - -ly_add_target( - NAME ImageProcessing.Editor GEM_MODULE - - NAMESPACE Gem - AUTOMOC - AUTORCC - FILES_CMAKE - imageprocessing_files.cmake - PLATFORM_INCLUDE_FILES - ${platform_tools_files} - INCLUDE_DIRECTORIES - PRIVATE - . - Source - ${pal_dir} - PUBLIC - Include - BUILD_DEPENDENCIES - PRIVATE - 3rdParty::Qt::Widgets - 3rdParty::PVRTexTool - 3rdParty::squish-ccr - Legacy::CryCommon - AZ::AzCore - AZ::AzToolsFramework - AZ::AssetBuilderSDK - Gem::ImageProcessing.Static - Gem::TextureAtlas - RUNTIME_DEPENDENCIES - 3rdParty::ASTCEncoder - Gem::TextureAtlas -) - -if(PAL_TRAIT_BUILD_TESTS_SUPPORTED) - ly_add_target( - NAME ImageProcessing.Tests ${PAL_TRAIT_TEST_TARGET_TYPE} - NAMESPACE Gem - FILES_CMAKE - imageprocessing_tests_files.cmake - INCLUDE_DIRECTORIES - PRIVATE - Tests - . - Source - ${pal_dir} - BUILD_DEPENDENCIES - PRIVATE - AZ::AzTest - 3rdParty::Qt::Widgets - Legacy::CryCommon - AZ::AssetBuilderSDK - Gem::ImageProcessing.Static - Gem::ImageProcessing.Editor - Gem::TextureAtlas - ) - ly_add_googletest( - NAME Gem::ImageProcessing.Tests - ) - - ly_add_source_properties( - SOURCES Tests/ImageProcessing_Test.cpp - PROPERTY COMPILE_DEFINITIONS - VALUES ${LY_PAL_TOOLS_DEFINES} - ) - -endif() diff --git a/Gems/ImageProcessing/Code/Include/ImageProcessing/ImageObject.h b/Gems/ImageProcessing/Code/Include/ImageProcessing/ImageObject.h deleted file mode 100644 index baa6613daf..0000000000 --- a/Gems/ImageProcessing/Code/Include/ImageProcessing/ImageObject.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. -* -*/ - -#pragma once - -#include -#include -#include -#include -#include -#include - -namespace AZ -{ - namespace IO - { - class SystemFileStream; - } -} - -namespace ImageProcessing -{ - class IImageObject; - class TextureSettings; - typedef AZStd::shared_ptr IImageObjectPtr; - - enum class EAlphaContent - { - eAlphaContent_Indeterminate, // the format may have alpha, but can't be calculated - eAlphaContent_Absent, // the format has no alpha - eAlphaContent_OnlyWhite, // alpha contains just white - eAlphaContent_OnlyBlack, // alpha contains just black - eAlphaContent_OnlyBlackAndWhite, // alpha contains just black and white - eAlphaContent_Greyscale // alpha contains grey tones - }; - - //interface for image object. The image object may have mipmaps. - class IImageObject - { - public: - //static functions - static IImageObject* CreateImage(AZ::u32 width, AZ::u32 height, AZ::u32 maxMipCount, EPixelFormat pixelFormat); - - virtual ~IImageObject() {}; - public: - //creating new image object outof this image object - virtual IImageObject* Clone() const = 0; - // allocate an empty image object with requested format and same properties with current image - virtual IImageObject* AllocateImage(EPixelFormat pixelFormat) const = 0; - virtual IImageObject* AllocateImage() const = 0; - - //get pixel format - virtual EPixelFormat GetPixelFormat() const = 0; - - virtual AZ::u32 GetPixelCount(AZ::u32 mip) const = 0; - virtual AZ::u32 GetWidth(AZ::u32 mip) const = 0; - virtual AZ::u32 GetHeight(AZ::u32 mip) const = 0; - virtual bool IsCubemap() const = 0; - virtual AZ::u32 GetMipCount() const = 0; - - //get pixel data buffer - virtual void GetImagePointer(AZ::u32 mip, AZ::u8*& pMem, AZ::u32& pitch) const = 0; - virtual AZ::u32 GetMipBufSize(AZ::u32 mip) const = 0; - virtual void SetMipData(AZ::u32 mip, AZ::u8* mipBuf, AZ::u32 bufSize, AZ::u32 pitch) = 0; - - //get/set image flags - virtual AZ::u32 GetImageFlags() const = 0; - virtual void SetImageFlags(AZ::u32 imageFlags) = 0; - virtual void AddImageFlags(AZ::u32 imageFlags) = 0; - virtual void RemoveImageFlags(AZ::u32 imageFlags) = 0; - virtual bool HasImageFlags(AZ::u32 imageFlags) const = 0; - - // image data operations and calculation - // Calculates "(pixel.rgba * scale) + bias" - virtual void ScaleAndBiasChannels(AZ::u32 firstMip, AZ::u32 maxMipCount, const AZ::Vector4& scale, const AZ::Vector4& bias) = 0; - // Calculates "clamp(pixel.rgba, min, max)" - virtual void ClampChannels(AZ::u32 firstMip, AZ::u32 maxMipCount, const AZ::Vector4& min, const AZ::Vector4& max) = 0; - - //transfer alpha coverage from source image - virtual void TransferAlphaCoverage(const TextureSettings* textureSetting, const IImageObjectPtr srcImg) = 0; - // Routines to measure and manipulate alpha coverage - virtual float ComputeAlphaCoverageScaleFactor(AZ::u32 mip, float fDesiredCoverage, float fAlphaRef) const = 0; - virtual float ComputeAlphaCoverage(AZ::u32 mip, float fAlphaRef) const = 0; - - //helper functions - //compare whether two images are same. return true if they are same. - virtual bool CompareImage(const IImageObjectPtr otherImage) const = 0; - - // Writes this image to file used for runtime, overwrites any existing file. - // It may write alpha image as attached image into the same file - // outFilePaths will save filenames finally saved to since the image might be split and saved to multiple files - virtual bool SaveImage(const char* filename, IImageObjectPtr alphaImage, AZStd::vector& outFilePaths) const = 0; - virtual bool SaveImage(AZ::IO::SystemFileStream& out) const = 0; - virtual bool SaveMipToFile(AZ::u32 mip, const AZStd::string& filename) const = 0; - - //get total image data size in memory of all mipmaps. Not includs header and flags. - virtual AZ::u32 GetTextureMemory() const = 0; - - //identify content of the alpha channel - virtual EAlphaContent GetAlphaContent() const = 0; - - //normalize rgb channel for specified mips - virtual void NormalizeVectors(AZ::u32 firstMip, AZ::u32 maxMipCount) = 0; - - // use when you convert an image to another one - virtual void CopyPropertiesFrom(const IImageObjectPtr src) = 0; - - //swizzle data for source channels to dest channels - virtual void Swizzle(const char channels[4]) = 0; - - //get/set properties of the image object - virtual void GetColorRange(AZ::Color& minColor, AZ::Color& maxColor) const = 0; - virtual void SetColorRange(const AZ::Color& minColor, const AZ::Color& maxColor) = 0; - virtual AZ::u32 GetNumPersistentMips() const = 0; - virtual void SetNumPersistentMips(AZ::u32 nMips) = 0; - virtual float GetAverageBrightness() const = 0; - virtual void SetAverageBrightness(float avgBrightness) = 0; - - // Derive new roughness from normal variance to preserve the bumpiness of normal map mips and to reduce specular aliasing. - // The derived roughness is combined with the artist authored roughness stored in the alpha channel of the normal map. - // The algorithm is based on the Frequency Domain Normal Mapping implementation presented by Neubelt and Pettineo at Siggraph 2013. - virtual void GlossFromNormals(bool hasAuthoredGloss) = 0; - - //convert gloss map from legacy distribution to new one. New World is still using legacy gloss map. - virtual void ConvertLegacyGloss() = 0; - - //clear image with color - virtual void ClearColor(float r, float g, float b, float a) = 0; - - virtual bool HasPowerOfTwoSizes() const = 0; - }; - - //loading function to load output dds file to a IImageObject - IImageObject* LoadImageFromDdsFile(const AZStd::string& filename); - IImageObject* LoadImageFromDdsFile(AZ::IO::SystemFileStream& fileLoadStream); - IImageObject* LoadAttachedImageFromDdsFile(const AZStd::string& filename, IImageObjectPtr originImage); - -} // namespace ImageProcessing diff --git a/Gems/ImageProcessing/Code/Include/ImageProcessing/ImageProcessingBus.h b/Gems/ImageProcessing/Code/Include/ImageProcessing/ImageProcessingBus.h deleted file mode 100644 index 8b127b3f6e..0000000000 --- a/Gems/ImageProcessing/Code/Include/ImageProcessing/ImageProcessingBus.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 -#include - -namespace ImageProcessing -{ - class ImageProcessingRequests - : public AZ::EBusTraits - { - public: - ////////////////////////////////////////////////////////////////////////// - // EBusTraits overrides - static const AZ::EBusHandlerPolicy HandlerPolicy = AZ::EBusHandlerPolicy::Single; - static const AZ::EBusAddressPolicy AddressPolicy = AZ::EBusAddressPolicy::Single; - ////////////////////////////////////////////////////////////////////////// - - // Loads an image from a source file path - virtual IImageObjectPtr LoadImage(const AZStd::string& filePath) = 0; - - // Loads an image from a source file path and converts it to a format suitable for previewing in tools - virtual IImageObjectPtr LoadImagePreview(const AZStd::string& filePath) = 0; - }; - using ImageProcessingRequestBus = AZ::EBus; -} // namespace ImageProcessing diff --git a/Gems/ImageProcessing/Code/Include/ImageProcessing/ImageProcessingEditorBus.h b/Gems/ImageProcessing/Code/Include/ImageProcessing/ImageProcessingEditorBus.h deleted file mode 100644 index eae1fdeb6d..0000000000 --- a/Gems/ImageProcessing/Code/Include/ImageProcessing/ImageProcessingEditorBus.h +++ /dev/null @@ -1,36 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -#pragma once - -#include - -class QString; - -namespace ImageProcessingEditor -{ - class ImageProcessingEditorRequests - : public AZ::EBusTraits - { - public: - ////////////////////////////////////////////////////////////////////////// - // EBusTraits overrides - static const AZ::EBusHandlerPolicy HandlerPolicy = AZ::EBusHandlerPolicy::Single; - static const AZ::EBusAddressPolicy AddressPolicy = AZ::EBusAddressPolicy::Single; - ///////////////////////////////////////////////////////////////////////// - - //! Open single texture file - virtual void OpenSourceTextureFile(const AZ::Uuid& textureSourceID) = 0; - }; - - using ImageProcessingEditorRequestBus = AZ::EBus; -}//namespace ImageProcessingEditor - diff --git a/Gems/ImageProcessing/Code/Include/ImageProcessing/PixelFormats.h b/Gems/ImageProcessing/Code/Include/ImageProcessing/PixelFormats.h deleted file mode 100644 index 2ceb889ac9..0000000000 --- a/Gems/ImageProcessing/Code/Include/ImageProcessing/PixelFormats.h +++ /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. -* -*/ -#pragma once - -namespace ImageProcessing -{ - enum EPixelFormat : int - { - //unsigned formats - ePixelFormat_R8G8B8A8 = 0, - ePixelFormat_R8G8B8X8, - ePixelFormat_R8G8, - ePixelFormat_R8, - ePixelFormat_A8, - ePixelFormat_R16G16B16A16, - ePixelFormat_R16G16, - ePixelFormat_R16, - - //Custom FourCC Formats - // Data in these FourCC formats is custom compressed data and only decodable by certain hardware. - //ASTC formats supported by ios devices with A8 processor. Also supported by Android Extension Pack. - ePixelFormat_ASTC_4x4, - ePixelFormat_ASTC_5x4, - ePixelFormat_ASTC_5x5, - ePixelFormat_ASTC_6x5, - ePixelFormat_ASTC_6x6, - ePixelFormat_ASTC_8x5, - ePixelFormat_ASTC_8x6, - ePixelFormat_ASTC_8x8, - ePixelFormat_ASTC_10x5, - ePixelFormat_ASTC_10x6, - ePixelFormat_ASTC_10x8, - ePixelFormat_ASTC_10x10, - ePixelFormat_ASTC_12x10, - ePixelFormat_ASTC_12x12, - //Formats supported by PowerVR GPU. Mainly for ios devices. - ePixelFormat_PVRTC2, //2bpp - ePixelFormat_PVRTC4, //4bpp - //formats for opengl and opengles 3.0 (android devices) - ePixelFormat_EAC_R11, //one channel unsigned data - ePixelFormat_EAC_RG11, //two channel unsigned data - ePixelFormat_ETC2, //Compresses RGB888 data, it taks 4x4 groups of pixel data and compresses each into a 64-bit - ePixelFormat_ETC2a, //Compresses RGBA8888 data with full alpha support - - // Standardized Compressed DXGI Formats (DX10+) - // Data in these compressed formats is hardware decodable on all DX10 chips, and manageable with the DX10-API. - ePixelFormat_BC1, // RGB without alpha, 0.5 byte/px - ePixelFormat_BC1a, // RGB with 1 bit of alpha, 0.5 byte/px. - ePixelFormat_BC3, // RGBA 1 byte/px, color maps with full alpha. - ePixelFormat_BC3t, // BC3 with alpha weighted color - ePixelFormat_BC4, // One color channel, 0.5 byte/px, unsigned - ePixelFormat_BC4s, // BC4, signed - ePixelFormat_BC5, // Two color channels, 1 byte/px, unsigned. Usually use for tangent-space normal maps - ePixelFormat_BC5s, // BC5, signed - ePixelFormat_BC6UH, // RGB, floating-point. Used for HDR images. Decompress to RGB in half floating point - ePixelFormat_BC7, // RGB or RGBA. 1 byte/px. Three color channels (4 to 7 bits per channel) with 0 to 8 bits of alpha - ePixelFormat_BC7t, // BC& with alpha weighted color - - // Float formats - // Data in a Float format is floating point data. - ePixelFormat_R9G9B9E5, - ePixelFormat_R32G32B32A32F, - ePixelFormat_R32G32F, - ePixelFormat_R32F, - ePixelFormat_R16G16B16A16F, - ePixelFormat_R16G16F, - ePixelFormat_R16F, - - //legacy format. Only used to load old converted dds files. - ePixelFormat_B8G8R8A8, //32bits rgba format - - ePixelFormat_R32, - - ePixelFormat_Count, - ePixelFormat_Unknown = ePixelFormat_Count - }; - - inline bool IsASTCFormat(EPixelFormat fmt) - { - return fmt == ePixelFormat_ASTC_4x4 || fmt == ePixelFormat_ASTC_5x4 || fmt == ePixelFormat_ASTC_5x5 || - fmt == ePixelFormat_ASTC_6x5 || fmt == ePixelFormat_ASTC_6x6 || fmt == ePixelFormat_ASTC_8x5 || - fmt == ePixelFormat_ASTC_8x6 || fmt == ePixelFormat_ASTC_8x8 || fmt == ePixelFormat_ASTC_10x5 || - fmt == ePixelFormat_ASTC_10x6 || fmt == ePixelFormat_ASTC_10x8 || fmt == ePixelFormat_ASTC_10x10 || - fmt == ePixelFormat_ASTC_12x10 || fmt == ePixelFormat_ASTC_12x12; - } - - inline bool IsETCFormat(EPixelFormat fmt) - { - return fmt == ePixelFormat_ETC2 || fmt == ePixelFormat_ETC2a || fmt == ePixelFormat_EAC_R11 || - fmt == ePixelFormat_EAC_RG11; - } - - inline bool IsPVRTCFormat(EPixelFormat fmt) - { - return fmt == ePixelFormat_PVRTC2 || fmt == ePixelFormat_PVRTC4; - } - -} // namespace ImageProcessing diff --git a/Gems/ImageProcessing/Code/Source/AtlasBuilder/AtlasBuilderComponent.cpp b/Gems/ImageProcessing/Code/Source/AtlasBuilder/AtlasBuilderComponent.cpp deleted file mode 100644 index e8d4948cc9..0000000000 --- a/Gems/ImageProcessing/Code/Source/AtlasBuilder/AtlasBuilderComponent.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. -* -*/ - -#include "ImageProcessing_precompiled.h" -#include "AtlasBuilderComponent.h" - -#include - -namespace TextureAtlasBuilder -{ - // AZ Components should only initialize their members to null and empty in constructor - // Allocation of data should occur in Init(), once we can guarantee reflection and registration of types - AtlasBuilderComponent::AtlasBuilderComponent() - { - } - - // Handle deallocation of your memory allocated in Init() - AtlasBuilderComponent::~AtlasBuilderComponent() - { - } - - // Init is where you'll actually allocate memory or create objects - // This ensures that any dependency components will have been been created and serialized - void AtlasBuilderComponent::Init() - { - } - - // Activate is where you'd perform registration with other objects and systems. - // All builder classes owned by this component should be registered here - // Any EBuses for the builder classes should also be connected at this point - void AtlasBuilderComponent::Activate() - { - AssetBuilderSDK::AssetBuilderDesc builderDescriptor; - builderDescriptor.m_name = "Atlas Worker Builder"; - builderDescriptor.m_version = 1; - builderDescriptor.m_patterns.emplace_back(AssetBuilderSDK::AssetBuilderPattern("*.texatlas", AssetBuilderSDK::AssetBuilderPattern::PatternType::Wildcard)); - builderDescriptor.m_busId = azrtti_typeid(); - builderDescriptor.m_createJobFunction = AZStd::bind(&AtlasBuilderWorker::CreateJobs, &m_atlasBuilder, AZStd::placeholders::_1, AZStd::placeholders::_2); - builderDescriptor.m_processJobFunction = AZStd::bind(&AtlasBuilderWorker::ProcessJob, &m_atlasBuilder, AZStd::placeholders::_1, AZStd::placeholders::_2); - - m_atlasBuilder.BusConnect(builderDescriptor.m_busId); - - AssetBuilderSDK::AssetBuilderBus::Broadcast(&AssetBuilderSDK::AssetBuilderBusTraits::RegisterBuilderInformation, builderDescriptor); - } - - // Disconnects from any EBuses we connected to in Activate() - // Unregisters from objects and systems we register with in Activate() - void AtlasBuilderComponent::Deactivate() - { - m_atlasBuilder.BusDisconnect(); - - // We don't need to unregister the builder - the AP will handle this for us, because it is managing the lifecycle of this component - } - - // Reflect the input and output formats for the serializer - void AtlasBuilderComponent::Reflect(AZ::ReflectContext* context) - { - // components also get Reflect called automatically - // this is your opportunity to perform static reflection or type registration of any types you want the serializer to know about - if (AZ::SerializeContext* serialize = azrtti_cast(context)) - { - serialize->Class() - ->Version(0) - ->Attribute(AZ::Edit::Attributes::SystemComponentTags, AZStd::vector({ AssetBuilderSDK::ComponentTags::AssetBuilder })) - ; - } - - AtlasBuilderInput::Reflect(context); - } - - void AtlasBuilderComponent::GetProvidedServices(AZ::ComponentDescriptor::DependencyArrayType& provided) - { - provided.push_back(AZ_CRC("Atlas Builder Plugin Service", 0x35974d0d)); - } - - void AtlasBuilderComponent::GetIncompatibleServices(AZ::ComponentDescriptor::DependencyArrayType& incompatible) - { - incompatible.push_back(AZ_CRC("Atlas Builder Plugin Service", 0x35974d0d)); - } - - void AtlasBuilderComponent::GetRequiredServices(AZ::ComponentDescriptor::DependencyArrayType& required) - { - AZ_UNUSED(required); - } - - void AtlasBuilderComponent::GetDependentServices(AZ::ComponentDescriptor::DependencyArrayType& dependent) - { - AZ_UNUSED(dependent); - } -} diff --git a/Gems/ImageProcessing/Code/Source/AtlasBuilder/AtlasBuilderComponent.h b/Gems/ImageProcessing/Code/Source/AtlasBuilder/AtlasBuilderComponent.h deleted file mode 100644 index eb8b85dfcf..0000000000 --- a/Gems/ImageProcessing/Code/Source/AtlasBuilder/AtlasBuilderComponent.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. - * - */ - -#pragma once - -#include -#include -#include "AtlasBuilderWorker.h" - -namespace TextureAtlasBuilder -{ - class AtlasBuilderComponent : public AZ::Component - { - public: - AZ_COMPONENT(AtlasBuilderComponent, "{F49987FB-3375-4417-AB83-97B44C78B335}"); - - AtlasBuilderComponent(); - ~AtlasBuilderComponent() override; - - void Init() override; - void Activate() override; - void Deactivate() override; - - //! Reflect formats for input and output - static void Reflect(AZ::ReflectContext* context); - - static void GetProvidedServices(AZ::ComponentDescriptor::DependencyArrayType& provided); - static void GetIncompatibleServices(AZ::ComponentDescriptor::DependencyArrayType& incompatible); - static void GetRequiredServices(AZ::ComponentDescriptor::DependencyArrayType& required); - static void GetDependentServices(AZ::ComponentDescriptor::DependencyArrayType& dependent); - - private: - AtlasBuilderWorker m_atlasBuilder; - }; -} // namespace TextureAtlasBuilder diff --git a/Gems/ImageProcessing/Code/Source/AtlasBuilder/AtlasBuilderWorker.cpp b/Gems/ImageProcessing/Code/Source/AtlasBuilder/AtlasBuilderWorker.cpp deleted file mode 100644 index 95cc9b851f..0000000000 --- a/Gems/ImageProcessing/Code/Source/AtlasBuilder/AtlasBuilderWorker.cpp +++ /dev/null @@ -1,1494 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or 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 "ImageProcessing_precompiled.h" -#include "AtlasBuilderWorker.h" - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include -#include -#include -#include -#include -#include - -#include -#include -#include - -#include -#include -#include -#include - -namespace TextureAtlasBuilder -{ - //! Counts leading zeros - uint32 CountLeadingZeros32(uint32 x) - { - return x == 0 ? 32 : az_clz_u32(x); - } - - //! Integer log2 - uint32 IntegerLog2(uint32 x) - { - return 31 - CountLeadingZeros32(x); - } - - bool IsFolderPath(const AZStd::string& path) - { - bool hasExtension = AzFramework::StringFunc::Path::HasExtension(path.c_str()); - return !hasExtension; - } - - bool HasTrailingSlash(const AZStd::string& path) - { - size_t pathLength = path.size(); - return (pathLength > 0 && (path.at(pathLength - 1) == '/' || path.at(pathLength - 1) == '\\')); - } - - bool ResolveRelativePath(const AZStd::string& relativePath, const AZStd::string& watchDirectory, AZStd::string& resolvedFullPathOut) - { - // Get full path by appending the relative path to the watch directory - AZ::IO::FixedMaxPath resolvedPath; - AZ::IO::FileIOBase::GetInstance()->ReplaceAlias(resolvedPath, AZ::IO::PathView{relativePath}); - - resolvedPath = (AZ::IO::FixedMaxPath{watchDirectory} / resolvedPath).LexicallyNormal(); - resolvedFullPathOut = resolvedPath.String(); - - return true; - } - - bool GetAbsoluteSourcePathFromRelativePath(const AZStd::string& relativeSourcePath, AZStd::string& absoluteSourcePathOut) - { - bool result = false; - AZ::Data::AssetInfo info; - AZStd::string watchFolder; - AzToolsFramework::AssetSystemRequestBus::BroadcastResult(result, &AzToolsFramework::AssetSystemRequestBus::Events::GetSourceInfoBySourcePath, relativeSourcePath.c_str(), info, watchFolder); - if (result) - { - absoluteSourcePathOut = AZStd::string::format("%s/%s", watchFolder.c_str(), info.m_relativePath.c_str()); - - // Normalize path - AzFramework::ApplicationRequests::Bus::Broadcast(&AzFramework::ApplicationRequests::NormalizePathKeepCase, absoluteSourcePathOut); - } - return result; - } - - const ImageProcessing::PresetSettings* GetImageProcessPresetSettings(const AZStd::string& presetName, const AZStd::string& platformIdentifier) - { - // Get the specified presetId - AZ::Uuid presetId = ImageProcessing::BuilderSettingManager::Instance()->GetPresetIdFromName(presetName); - if (presetId.IsNull()) - { - AZ_Error("Texture Editor", false, "Texture Preset %s has no associated UUID.", presetName.c_str()); - return nullptr; - } - - // Get the preset settings for the platform this job is building for - const ImageProcessing::PresetSettings* presetSettings = ImageProcessing::BuilderSettingManager::Instance()->GetPreset( - presetId, platformIdentifier); - - return presetSettings; - } - - // Reflect the input parameters - void AtlasBuilderInput::Reflect(AZ::ReflectContext* context) - { - if (AZ::SerializeContext* serialize = azrtti_cast(context)) - { - serialize->Class() - ->Version(1) - ->Field("Force Square", &AtlasBuilderInput::m_forceSquare) - ->Field("Force Power of Two", &AtlasBuilderInput::m_forcePowerOf2) - ->Field("Include White Texture", &AtlasBuilderInput::m_includeWhiteTexture) - ->Field("Maximum Dimension", &AtlasBuilderInput::m_maxDimension) - ->Field("Padding", &AtlasBuilderInput::m_padding) - ->Field("UnusedColor", &AtlasBuilderInput::m_unusedColor) - ->Field("PresetName", &AtlasBuilderInput::m_presetName) - ->Field("Textures to Add", &AtlasBuilderInput::m_filePaths); - } - } - - // Supports a custom parser format - AtlasBuilderInput AtlasBuilderInput::ReadFromFile(const AZStd::string& path, const AZStd::string& directory, bool& valid) - { - // Open the file - AZ::IO::FileIOBase* input = AZ::IO::FileIOBase::GetInstance(); - AZ::IO::HandleType handle; - input->Open(path.c_str(), AZ::IO::OpenMode::ModeRead, handle); - - // Read the file - AZ::u64 size; - input->Size(handle, size); - char* buffer = new char[size + 1]; - input->Read(handle, buffer, size); - buffer[size] = 0; - - // Close the file - input->Close(handle); - - // Prepare the output - AtlasBuilderInput data; - - // Parse the input into lines - AZStd::vector lines; - AzFramework::StringFunc::Tokenize(buffer, lines, "\n\t"); - delete[] buffer; - - // Parse the individual lines - for (auto line : lines) - { - line = AzFramework::StringFunc::TrimWhiteSpace(line, true, true); - // Check for comments and empty lines - if ((line.length() >= 2 && line[0] == '/' && line[1] == '/') || line.length() < 1) - { - continue; - } - else if (line.find('=') != -1) - { - AZStd::vector args; - AzFramework::StringFunc::Tokenize(line.c_str(), args, '=', true, true); - - if (args.size() > 2) - { - AZ_Error("AtlasBuilder", false, AZStd::string::format("Atlas Builder unable to parse line: Excessive '=' symbols were found: \"%s\"", line.c_str()).c_str()); - valid = false; - } - - // Trim whitespace - args[0] = AzFramework::StringFunc::TrimWhiteSpace(args[0], true, true); - args[1] = AzFramework::StringFunc::TrimWhiteSpace(args[1], true, true); - - // No case sensitivity for property names - AZStd::to_lower(args[0].begin(), args[0].end()); - - // Keep track of if the value is rejected - bool accepted = false; - - if (args[0] == "square") - { - accepted = AzFramework::StringFunc::LooksLikeBool(args[1].c_str()); - if (accepted) - { - data.m_forceSquare = AzFramework::StringFunc::ToBool(args[1].c_str()); - } - } - else if (args[0] == "poweroftwo") - { - accepted = AzFramework::StringFunc::LooksLikeBool(args[1].c_str()); - if (accepted) - { - data.m_forcePowerOf2 = AzFramework::StringFunc::ToBool(args[1].c_str()); - } - } - else if (args[0] == "whitetexture") - { - accepted = AzFramework::StringFunc::LooksLikeBool(args[1].c_str()); - if (accepted) - { - data.m_includeWhiteTexture = AzFramework::StringFunc::ToBool(args[1].c_str()); - } - } - else if (args[0] == "maxdimension") - { - accepted = AzFramework::StringFunc::LooksLikeInt(args[1].c_str()); - if (accepted) - { - data.m_maxDimension = AzFramework::StringFunc::ToInt(args[1].c_str()); - } - } - else if (args[0] == "padding") - { - accepted = AzFramework::StringFunc::LooksLikeInt(args[1].c_str()); - if (accepted) - { - data.m_padding = AzFramework::StringFunc::ToInt(args[1].c_str()); - } - } - else if (args[0] == "unusedcolor") - { - accepted = args[1].at(0) == '#' && args[1].length() == 9; - if (accepted) - { - AZStd::string color = AZStd::string::format("%s%s%s%s", args[1].substr(7).c_str(), args[1].substr(5, 2).c_str(), - args[1].substr(3, 2).c_str(), args[1].substr(1, 2).c_str()); - data.m_unusedColor.FromU32(AZStd::stoul(color, nullptr, 16)); - } - } - else if (args[0] == "presetname") - { - accepted = true; - data.m_presetName = args[1]; - } - else - { - // Supress accepted error because this error superceeds it - accepted = true; - valid = false; - AZ_Error("AtlasBuilder", false, AZStd::string::format("Atlas Builder unable to parse line: Unrecognized property: \"%s\"", args[0].c_str()).c_str()); - } - - // If the property is recognized but the value is rejected, fail the job - if (!accepted) - { - valid = false; - AZ_Error("AtlasBuilder", false, AZStd::string::format("Atlas Builder unable to parse line: Invalid value assigned to property: Property: \"%s\" Value: \"%s\"", args[0].c_str(), args[1].c_str()).c_str()); - } - } - else if ((line[0] == '-')) - { - // Remove image files - AZStd::string remove = line.substr(1); - remove = AzFramework::StringFunc::TrimWhiteSpace(remove, true, true); - if (remove.find('*') != -1) - { - AZStd::string resolvedAbsolutePath; - bool resolved = ResolveRelativePath(remove, directory, resolvedAbsolutePath); - if (resolved) - { - RemoveFilesUsingWildCard(data.m_filePaths, resolvedAbsolutePath); - } - else - { - valid = false; - AZ_Error("AtlasBuilder", false, AZStd::string::format("Atlas Builder unable to resolve relative path: %s", remove.c_str()).c_str()); - } - } - else if (IsFolderPath(remove)) - { - AZStd::string resolvedAbsolutePath; - bool resolved = ResolveRelativePath(remove, directory, resolvedAbsolutePath); - if (resolved) - { - RemoveFolderContents(data.m_filePaths, resolvedAbsolutePath); - } - else - { - valid = false; - AZ_Error("AtlasBuilder", false, AZStd::string::format("Atlas Builder unable to resolve relative path: %s", remove.c_str()).c_str()); - } - } - else - { - // Get the full path to the source image from the relative source path - AZStd::string fullSourceAssetPathName; - bool fullPathFound = GetAbsoluteSourcePathFromRelativePath(remove, fullSourceAssetPathName); - - if (!fullPathFound) - { - // Try to resolve relative path as it might be using "./" or "../" - fullPathFound = ResolveRelativePath(remove, directory, fullSourceAssetPathName); - } - - if (fullPathFound) - { - for (size_t i = 0; i < data.m_filePaths.size(); ++i) - { - if (data.m_filePaths[i] == fullSourceAssetPathName) - { - data.m_filePaths.erase(data.m_filePaths.begin() + i); - } - } - } - else - { - valid = false; - AZ_Error("AtlasBuilder", false, AZStd::string::format("Atlas Builder unable to get source asset path for image: %s", remove.c_str()).c_str()); - } - } - } - else - { - // Add image files - AzFramework::ApplicationRequests::Bus::Broadcast(&AzFramework::ApplicationRequests::NormalizePathKeepCase, line); - bool duplicate = false; - if (line.find('*') != -1) - { - AZStd::string resolvedAbsolutePath; - bool resolved = ResolveRelativePath(line, directory, resolvedAbsolutePath); - if (resolved) - { - AddFilesUsingWildCard(data.m_filePaths, resolvedAbsolutePath); - } - else - { - valid = false; - AZ_Error("AtlasBuilder", false, AZStd::string::format("Atlas Builder unable to resolve relative path: %s", line.c_str()).c_str()); - } - } - else if (IsFolderPath(line)) - { - AZStd::string resolvedAbsolutePath; - bool resolved = ResolveRelativePath(line, directory, resolvedAbsolutePath); - if (resolved) - { - AddFolderContents(data.m_filePaths, resolvedAbsolutePath, valid); - } - else - { - valid = false; - AZ_Error("AtlasBuilder", false, AZStd::string::format("Atlas Builder unable to resolve relative path: %s", line.c_str()).c_str()); - } - } - else - { - // Get the full path to the source image from the relative source path - AZStd::string fullSourceAssetPathName; - bool fullPathFound = GetAbsoluteSourcePathFromRelativePath(line, fullSourceAssetPathName); - - if (!fullPathFound) - { - // Try to resolve relative path as it might be using "./" or "../" - fullPathFound = ResolveRelativePath(line, directory, fullSourceAssetPathName); - } - - if (fullPathFound) - { - // Prevent duplicates - for (size_t i = 0; i < data.m_filePaths.size() && !duplicate; ++i) - { - duplicate = data.m_filePaths[i] == fullSourceAssetPathName; - } - if (!duplicate) - { - data.m_filePaths.push_back(fullSourceAssetPathName); - } - } - else - { - valid = false; - AZ_Error("AtlasBuilder", false, AZStd::string::format("Atlas Builder unable to get source asset path for image: %s", line.c_str()).c_str()); - } - } - } - } - - return data; - } - - void AtlasBuilderInput::AddFilesUsingWildCard(AZStd::vector& paths, const AZStd::string& insert) - { - AZ::IO::PathView fullPathView(insert); - - // Find first path element with a wild card in it - AZ::IO::Path staticPath; - auto wildCardPathElementIter = fullPathView.begin(); - for (; wildCardPathElementIter != fullPathView.end(); ++wildCardPathElementIter) - { - if (wildCardPathElementIter->Native().contains('*')) - { - break; - } - staticPath /= *wildCardPathElementIter; - } - - // The remaining path segments are part of the wild card path - - AZStd::vector candidates{ AZStd::move(staticPath) }; - for(; wildCardPathElementIter != fullPathView.end() && !candidates.empty(); ++wildCardPathElementIter) - { - AZStd::vector nextCandidates; - for (const AZ::IO::Path& candidate : candidates) - { - if (QDir inputFolder(QString::fromUtf8(candidate.c_str(), aznumeric_cast(candidate.Native().size()))); - inputFolder.exists()) - { - QFileInfoList entries = inputFolder.entryInfoList(QDir::Dirs | QDir::NoDotAndDotDot | QDir::Files); - for (const QFileInfo& entry : entries) - { - AZ::IO::Path filenameEntry(entry.fileName().toUtf8().data()); - if (filenameEntry.Match(wildCardPathElementIter->Native())) - { - nextCandidates.push_back(entry.filePath().toUtf8().data()); - } - } - } - } - candidates = nextCandidates; - } - - for (const AZ::IO::Path& candidate : candidates) - { - QFileInfo fileInfo(QString::fromUtf8(candidate.c_str(), aznumeric_cast(candidate.Native().size()))); - if (fileInfo.isFile()) - { - AZStd::string ext = fileInfo.suffix().toUtf8().data(); - if (ImageProcessing::IsExtensionSupported(ext.c_str()) && ext != "dds") - { - auto FindExistingPath = [&candidate](const AZStd::string& path) - { - return candidate == AZ::IO::PathView(path); - }; - if (auto foundIt = AZStd::find_if(paths.begin(), paths.end(), FindExistingPath); - foundIt == paths.end()) - { - AZStd::string normalizedPath = AZ::IO::Path(candidate.Native(), AZ::IO::PosixPathSeparator).LexicallyNormal().Native(); - paths.push_back(AZStd::move(normalizedPath)); - } - } - } - else if (fileInfo.isDir()) - { - bool waste = true; - AddFolderContents(paths, candidate.Native(), waste); - } - } - } - - void AtlasBuilderInput::RemoveFilesUsingWildCard(AZStd::vector& paths, const AZStd::string& remove) - { - auto RemoveWildCardPath = [&remove](const AZStd::string& subPath) - { - return AZ::IO::PathView(subPath).Match(remove); - }; - AZStd::erase_if(paths, RemoveWildCardPath); - } - - // Replaces all folder paths with the files they contain - void AtlasBuilderInput::AddFolderContents(AZStd::vector& paths, const AZStd::string& insert, bool& valid) - { - if (QDir inputFolder(insert.c_str()); inputFolder.exists()) - { - QFileInfoList entries = inputFolder.entryInfoList(QDir::Dirs | QDir::NoDotAndDotDot | QDir::Files); - for (const QFileInfo& entry : entries) - { - AZ::IO::Path child = entry.filePath().toUtf8().data(); - AZStd::string ext = entry.suffix().toUtf8().data(); - const bool isDir = entry.isDir(); - if (isDir) - { - AddFolderContents(paths, child.Native(), valid); - } - else if (ImageProcessing::IsExtensionSupported(ext.c_str()) && ext != "dds") - { - auto FindExistingPath = [&child](const AZStd::string& path) - { - return child == AZ::IO::PathView(path); - }; - if (auto foundIter = AZStd::find_if(paths.begin(), paths.end(), FindExistingPath); - foundIter == paths.end()) - { - // Normalize the path to have posix slashes - AZStd::string normalizedPath = AZ::IO::Path(child.Native(), AZ::IO::PosixPathSeparator).LexicallyNormal().Native(); - paths.push_back(AZStd::move(normalizedPath)); - } - } - } - } - else - { - valid = false; - AZ_Error("AtlasBuilder", false, AZStd::string::format("Atlas Builder unable to find requested directory: %s", insert.c_str()).c_str()); - } - } - - // Removes all of the contents of a folder - void AtlasBuilderInput::RemoveFolderContents(AZStd::vector& paths, const AZStd::string& remove) - { - auto RemoveSubPath = [folder = AZ::IO::PathView(remove)](const AZStd::string& subPath) - { - return AZ::IO::PathView(subPath).IsRelativeTo(folder); - }; - AZStd::erase_if(paths, RemoveSubPath); - } - - // Note - Shutdown will be called on a different thread than your process job thread - void AtlasBuilderWorker::ShutDown() { m_isShuttingDown = true; } - - void AtlasBuilderWorker::CreateJobs(const AssetBuilderSDK::CreateJobsRequest& request, - AssetBuilderSDK::CreateJobsResponse& response) - { - // Read in settings/filepaths to set dependencies - AZStd::string fullPath; - AzFramework::StringFunc::Path::Join( - request.m_watchFolder.c_str(), request.m_sourceFile.c_str(), fullPath, true, true); - // Check if input is valid - bool valid = true; - AtlasBuilderInput input = AtlasBuilderInput::ReadFromFile(fullPath, request.m_watchFolder, valid); - - // Set dependencies - for (int i = 0; i < input.m_filePaths.size(); ++i) - { - AssetBuilderSDK::SourceFileDependency dependency; - dependency.m_sourceFileDependencyPath = input.m_filePaths[i].c_str(); - response.m_sourceFileDependencyList.push_back(dependency); - } - - // We process the same file for all platforms - for (const AssetBuilderSDK::PlatformInfo& info : request.m_enabledPlatforms) - { - if (ImageProcessing::BuilderSettingManager::Instance()->DoesSupportPlatform(info.m_identifier)) - { - AssetBuilderSDK::JobDescriptor descriptor = GetJobDescriptor(request.m_sourceFile, input); - descriptor.SetPlatformIdentifier(info.m_identifier.c_str()); - response.m_createJobOutputs.push_back(descriptor); - } - } - - if (valid) - { - response.m_result = AssetBuilderSDK::CreateJobsResultCode::Success; - } - - return; - } - - AssetBuilderSDK::JobDescriptor AtlasBuilderWorker::GetJobDescriptor(const AZStd::string& sourceFile, const AtlasBuilderInput& input) - { - // Get the extension of the file - AZStd::string ext; - AzFramework::StringFunc::Path::GetExtension(sourceFile.c_str(), ext, false); - AZStd::to_upper(ext.begin(), ext.end()); - - AssetBuilderSDK::JobDescriptor descriptor; - descriptor.m_jobKey = ext + " Atlas"; - descriptor.m_critical = false; - descriptor.m_jobParameters[AZ_CRC("forceSquare")] = input.m_forceSquare ? "true" : "false"; - descriptor.m_jobParameters[AZ_CRC("forcePowerOf2")] = input.m_forcePowerOf2 ? "true" : "false"; - descriptor.m_jobParameters[AZ_CRC("includeWhiteTexture")] = input.m_includeWhiteTexture ? "true" : "false"; - descriptor.m_jobParameters[AZ_CRC("padding")] = AZStd::to_string(input.m_padding); - descriptor.m_jobParameters[AZ_CRC("maxDimension")] = AZStd::to_string(input.m_maxDimension); - descriptor.m_jobParameters[AZ_CRC("filePaths")] = AZStd::to_string(input.m_filePaths.size()); - - AZ::u32 col = input.m_unusedColor.ToU32(); - descriptor.m_jobParameters[AZ_CRC("unusedColor")] = AZStd::to_string(*reinterpret_cast(&col)); - descriptor.m_jobParameters[AZ_CRC("presetName")] = input.m_presetName; - - // The starting point for the list - const int start = static_cast(descriptor.m_jobParameters.size()) + 1; - descriptor.m_jobParameters[AZ_CRC("startPoint")] = AZStd::to_string(start); - - for (int i = 0; i < input.m_filePaths.size(); ++i) - { - descriptor.m_jobParameters[start + i] = input.m_filePaths[i]; - } - - return descriptor; - } - - void AtlasBuilderWorker::ProcessJob(const AssetBuilderSDK::ProcessJobRequest& request, - AssetBuilderSDK::ProcessJobResponse& response) - { - // Before we begin, let's make sure we are not meant to abort. - AssetBuilderSDK::JobCancelListener jobCancelListener(request.m_jobId); - - AZStd::vector productFilepaths; - - const AZStd::string path = request.m_fullPath; - - bool imageProcessingSuccessful = false; - - // read in settings/filepaths - AtlasBuilderInput input; - input.m_forceSquare = AzFramework::StringFunc::ToBool(request.m_jobDescription.m_jobParameters.find(AZ_CRC("forceSquare"))->second.c_str()); - input.m_forcePowerOf2 = AzFramework::StringFunc::ToBool(request.m_jobDescription.m_jobParameters.find(AZ_CRC("forcePowerOf2"))->second.c_str()); - input.m_includeWhiteTexture = AzFramework::StringFunc::ToBool(request.m_jobDescription.m_jobParameters.find(AZ_CRC("includeWhiteTexture"))->second.c_str()); - input.m_padding = AzFramework::StringFunc::ToInt(request.m_jobDescription.m_jobParameters.find(AZ_CRC("padding"))->second.c_str()); - input.m_maxDimension = AzFramework::StringFunc::ToInt(request.m_jobDescription.m_jobParameters.find(AZ_CRC("maxDimension"))->second.c_str()); - int startAsInt = AzFramework::StringFunc::ToInt(request.m_jobDescription.m_jobParameters.find(AZ_CRC("startPoint"))->second.c_str()); - int sizeAsInt = AzFramework::StringFunc::ToInt(request.m_jobDescription.m_jobParameters.find(AZ_CRC("filePaths"))->second.c_str()); - AZ::u32 start = static_cast(AZStd::max(0, startAsInt)); - AZ::u32 size = static_cast(AZStd::max(0, sizeAsInt)); - - int col = AzFramework::StringFunc::ToInt(request.m_jobDescription.m_jobParameters.find(AZ_CRC("unusedColor"))->second.c_str()); - input.m_unusedColor.FromU32(*reinterpret_cast(&col)); - - input.m_presetName = request.m_jobDescription.m_jobParameters.find(AZ_CRC("presetName"))->second; - - for (AZ::u32 i = 0; i < size; ++i) - { - input.m_filePaths.push_back(request.m_jobDescription.m_jobParameters.find(start + i)->second); - } - - if (input.m_filePaths.empty()) - { - AZ_Error("AtlasBuilder", false, "No image files specified. Cannot create an empty atlas."); - return; - } - - // Don't allow padding to be less than zero - if (input.m_padding < 0) - { - input.m_padding = 0; - } - - if (input.m_presetName.empty()) - { - // Default to the TextureAtlas preset which is currently set to use compression for all platforms except for iOS. - // Currently the only fully supported compression for iOS is PVRTC which requires the texture to be square and a power of 2. - // Due to this limitation, we default to using no compression for iOS until ASTC is fully supported - const AZStd::string defaultPresetName = "TextureAtlas"; - input.m_presetName = defaultPresetName; - } - - // Get a preset to use for the output image - const ImageProcessing::PresetSettings* preset = GetImageProcessPresetSettings(input.m_presetName, request.m_platformInfo.m_identifier); - if (preset) - { - // Check the preset's pixel format requirements - const ImageProcessing::PixelFormatInfo* pixelFormatInfo = ImageProcessing::CPixelFormats::GetInstance().GetPixelFormatInfo(preset->m_pixelFormat); - if (pixelFormatInfo && pixelFormatInfo->bSquarePow2) - { - // Override the user config settings to force square and power of 2. - // Otherwise the image conversion process will stretch the image to satisfy these requirements - input.m_forceSquare = true; - input.m_forcePowerOf2 = true; - } - } - else - { - AZ_Error("AtlasBuilder", false, "Could not find a preset setting for the output image."); - return; - } - - // Read in images - AZStd::vector images; - AZ::u64 totalArea = 0; - int maxArea = input.m_maxDimension * input.m_maxDimension; - bool sizeFailure = false; - for (int i = 0; i < input.m_filePaths.size() && !jobCancelListener.IsCancelled(); ++i) - { - ImageProcessing::IImageObject* inputImage = ImageProcessing::LoadImageFromFile(input.m_filePaths[i]); - // Check if we were able to load the image - if (inputImage) - { - ImageProcessing::IImageObjectPtr image = ImageProcessing::IImageObjectPtr(inputImage); - images.push_back(image); - totalArea += inputImage->GetWidth(0) * inputImage->GetHeight(0); - } - else - { - AZ_Error("AtlasBuilder", false, AZStd::string::format("Atlas Builder unable to load file: %s", input.m_filePaths[i].c_str()).c_str()); - return; - } - if (maxArea < totalArea) - { - sizeFailure = true; - } - } - // If we get cancelled, return - if (jobCancelListener.IsCancelled()) - { - return; - } - - if (sizeFailure) - { - AZ_Error("AtlasBuilder", false, AZStd::string::format("Total image area exceeds maximum alotted area. %llu > %d", totalArea, maxArea).c_str()); - return; - } - - // Convert all image paths to their output format referenced at runtime - for (auto& filePath : input.m_filePaths) - { - // Get path relative to the watch folder - bool result = false; - AZ::Data::AssetInfo info; - AZStd::string watchFolder; - AzToolsFramework::AssetSystemRequestBus::BroadcastResult(result, &AzToolsFramework::AssetSystemRequestBus::Events::GetSourceInfoBySourcePath, filePath.c_str(), info, watchFolder); - if (!result) - { - AZ_Error("AtlasBuilder", false, AZStd::string::format("Atlas Builder unable to get relative source path for image: %s", filePath.c_str()).c_str()); - return; - } - - // Remove extension - filePath = info.m_relativePath.substr(0, info.m_relativePath.find_last_of('.')); - - // Normalize path - AzFramework::ApplicationRequests::Bus::Broadcast(&AzFramework::ApplicationRequests::NormalizePathKeepCase, filePath); - } - - // Add white texture if we need to - if (input.m_includeWhiteTexture) - { - ImageProcessing::IImageObjectPtr texture(ImageProcessing::IImageObject::CreateImage( - cellSize, cellSize, 1, ImageProcessing::EPixelFormat::ePixelFormat_R8G8B8A8)); - - // Make the texture white - texture->ClearColor(1, 1, 1, 1); - images.push_back(texture); - input.m_filePaths.push_back("WhiteTexture"); - } - - // Generate algorithm inputs - ImageDimensionData data; - for (int i = 0; i < images.size(); ++i) - { - data.push_back(IndexImageDimension(i, - ImageDimension(images[i]->GetWidth(0), - images[i]->GetHeight(0)))); - } - AZStd::sort(data.begin(), data.end()); - - // Run algorithm - - // Variables that keep track of the optimal solution - int resultWidth = -1; - int resultHeight = -1; - - // Check that the max dimension is not large enough for the area to loop past the maximum integer - // This is important because we do not want the area to be calculated negative - if (input.m_maxDimension > 65535) - { - input.m_maxDimension = 65535; - } - - // Get the optimal mappings based on the input settings - AZStd::vector paddedMap; - size_t amountFit = 0; - if (!TryTightening( - input, data, GetWidest(data), GetTallest(data), aznumeric_cast(totalArea), input.m_padding, resultWidth, resultHeight, amountFit, paddedMap)) - { - AZ_Error("AtlasBuilder", false, AZStd::string::format("Cannot fit images into given maximum atlas size (%dx%d). Only %zu out of %zu images fit.", input.m_maxDimension, input.m_maxDimension, amountFit, input.m_filePaths.size()).c_str()); - // For some reason, failing the assert isn't enough to stop the Asset builder. It will still fail further - // down when it tries to assemble the atlas, but returning here is cleaner. - return; - } - - // Move coordinates from algorithm space to padded result space - TextureAtlasNamespace::AtlasCoordinateSets output; - resultWidth = 0; - resultHeight = 0; - AZStd::vector map; - for (int i = 0; i < paddedMap.size(); ++i) - { - map.push_back(AtlasCoordinates(paddedMap[i].GetLeft(), paddedMap[i].GetLeft() + images[data[i].first]->GetWidth(0), paddedMap[i].GetTop(), paddedMap[i].GetTop() + images[data[i].first]->GetHeight(0))); - resultHeight = resultHeight > map[i].GetBottom() ? resultHeight : map[i].GetBottom(); - resultWidth = resultWidth > map[i].GetRight() ? resultWidth : map[i].GetRight(); - - const AZStd::string& outputFilePath = input.m_filePaths[data[i].first]; - output.push_back(AZStd::pair(outputFilePath, map[i])); - } - if (input.m_forcePowerOf2) - { - resultWidth = aznumeric_cast(pow(2, 1 + IntegerLog2(static_cast(resultWidth - 1)))); - resultHeight = aznumeric_cast(pow(2, 1 + IntegerLog2(static_cast(resultHeight - 1)))); - } - else - { - resultWidth = (resultWidth + (cellSize - 1)) / cellSize * cellSize; - resultHeight = (resultHeight + (cellSize - 1)) / cellSize * cellSize; - } - if (input.m_forceSquare) - { - if (resultWidth > resultHeight) - { - resultHeight = resultWidth; - } - else - { - resultWidth = resultHeight; - } - } - - // Process texture sheet - ImageProcessing::IImageObjectPtr outImage(ImageProcessing::IImageObject::CreateImage( - resultWidth, resultHeight, 1, ImageProcessing::EPixelFormat::ePixelFormat_R8G8B8A8)); - - // Clear the sheet - outImage->ClearColor(input.m_unusedColor.GetR(), input.m_unusedColor.GetG(), input.m_unusedColor.GetB(), input.m_unusedColor.GetA()); - - AZ::u8* outBuffer = nullptr; - AZ::u32 outPitch; - outImage->GetImagePointer(0, outBuffer, outPitch); - - // Copy images over - for (int i = 0; i < map.size() && !jobCancelListener.IsCancelled(); ++i) - { - AZ::u8* inBuffer = nullptr; - AZ::u32 inPitch; - images[data[i].first]->GetImagePointer(0, inBuffer, inPitch); - int j = 0; - - // The padding calculated here is the amount of excess horizontal space measured in bytes that are in each - // row of the destination space AFTER the placement of the source row. - int rightPadding = (paddedMap[i].GetRight() - map[i].GetRight() - input.m_padding); - if (map[i].GetRight() + rightPadding > resultWidth) - { - rightPadding = resultWidth - map[i].GetRight(); - } - rightPadding *= bytesPerPixel; - int bottomPadding = (paddedMap[i].GetBottom() - map[i].GetBottom() - input.m_padding); - if (map[i].GetBottom() + bottomPadding > resultHeight) - { - bottomPadding = resultHeight - map[i].GetBottom(); - } - - int leftPadding = 0; - if (map[i].GetLeft() - input.m_padding >= 0) - { - leftPadding = input.m_padding * bytesPerPixel; - } - - int topPadding = 0; - if (map[i].GetTop() - input.m_padding >= 0) - { - topPadding = input.m_padding; - } - - for (j = 0; j < map[i].GetHeight(); ++j) - { - // When we multiply `map[i].GetLeft()` by 4, we are changing the measure from atlas space, to byte array - // space. The number is 4 because in this format, each pixel is 4 bytes long. - memcpy(outBuffer + (map[i].GetTop() + j) * outPitch + (map[i].GetLeft() * bytesPerPixel), - inBuffer + inPitch * j, - inPitch); - // Fill in the last bit of the row in the destination space with the same colors - SetPixels(outBuffer + (map[i].GetTop() + j) * outPitch + (map[i].GetLeft() * bytesPerPixel) + inPitch, - outBuffer + (map[i].GetTop() + j) * outPitch + (map[i].GetLeft() * bytesPerPixel) + inPitch - bytesPerPixel, - rightPadding); - // Fill in the first bit of the row in the destination space with the same colors - SetPixels(outBuffer + (map[i].GetTop() + j) * outPitch + (map[i].GetLeft() * bytesPerPixel) - leftPadding, - outBuffer + (map[i].GetTop() + j) * outPitch + (map[i].GetLeft() * bytesPerPixel), - leftPadding); - } - // Fill in the last few rows of the buffer with the same colors - for (; j < map[i].GetHeight() + bottomPadding; ++j) - { - memcpy(outBuffer + (map[i].GetTop() + j) * outPitch + (map[i].GetLeft() * bytesPerPixel) - leftPadding, - outBuffer + (map[i].GetBottom() - 1) * outPitch + (map[i].GetLeft() * bytesPerPixel) - leftPadding, - inPitch + leftPadding + rightPadding); - } - for (j = 1; j <= topPadding; ++j) - { - memcpy(outBuffer + (map[i].GetTop() - j) * outPitch + (map[i].GetLeft() * bytesPerPixel) - leftPadding, - outBuffer + map[i].GetTop() * outPitch + (map[i].GetLeft() * bytesPerPixel) - leftPadding, - inPitch + rightPadding + leftPadding); - } - } - - // If we get cancelled, return - if (jobCancelListener.IsCancelled()) - { - return; - } - - // Output Atlas Coordinates - AZStd::string fileName; - AZStd::string outputPath; - AzFramework::StringFunc::Path::GetFullFileName(request.m_sourceFile.c_str(), fileName); - fileName = fileName.append("idx"); - AzFramework::StringFunc::Path::Join( - request.m_tempDirPath.c_str(), fileName.c_str(), outputPath, true, true); - - // Output texture sheet - AZStd::string imageFileName, imageOutputPath; - AzFramework::StringFunc::Path::GetFileName(request.m_sourceFile.c_str(), imageFileName); - imageFileName += ".dds"; - AzFramework::StringFunc::Path::Join( - request.m_tempDirPath.c_str(), imageFileName.c_str(), imageOutputPath, true, true); - - // Let the ImageProcessor do the rest of the work. - ImageProcessing::TextureSettings textureSettings; - textureSettings.m_preset = preset->m_uuid; - - // Mipmaps for the texture atlas would require more work than the Image Processor does. This is because if we - // let the Image Processor make mipmaps, it might bleed the textures in the atlas together. - textureSettings.m_enableMipmap = false; - - // Check if the ImageBuilder wants to enable streaming - bool isStreaming = ImageProcessing::BuilderSettingManager::Instance() - ->GetBuilderSetting(request.m_platformInfo.m_identifier) - ->m_enableStreaming; - - bool canOverridePreset = false; - ImageProcessing::ImageConvertProcess* process = - new ImageProcessing::ImageConvertProcess(outImage, - textureSettings, - *preset, - false, - isStreaming, - canOverridePreset, - imageOutputPath, - request.m_platformInfo.m_identifier); - - if (process != nullptr) - { - // the process can be stopped if the job is cancelled or the worker is shutting down - while (!process->IsFinished() && !m_isShuttingDown && !jobCancelListener.IsCancelled()) - { - process->UpdateProcess(); - } - - // get process result - imageProcessingSuccessful = process->IsSucceed(); - process->GetAppendOutputFilePaths(productFilepaths); - - delete process; - } - else - { - imageProcessingSuccessful = false; - } - - if (imageProcessingSuccessful) - { - TextureAtlasNamespace::TextureAtlasRequestBus::Broadcast( - &TextureAtlasNamespace::TextureAtlasRequests::SaveAtlasToFile, outputPath, output, resultWidth, resultHeight); - response.m_outputProducts.push_back(AssetBuilderSDK::JobProduct(outputPath)); - response.m_outputProducts[static_cast(Product::TexatlasidxProduct)].m_productAssetType = azrtti_typeid(); - response.m_outputProducts[static_cast(Product::TexatlasidxProduct)].m_productSubID = 0; - - // The Image Processing Gem can produce multiple output files under certain - // circumstances, but the texture atlas is not expected to produce such output - if (productFilepaths.size() > 1) - { - AZ_Error("AtlasBuilder", false, "Image processing resulted in multiple output files. Texture atlas is expected to produce one output."); - response.m_outputProducts.clear(); - return; - } - - if (productFilepaths.size() > 0) - { - response.m_outputProducts.push_back(AssetBuilderSDK::JobProduct(productFilepaths[0])); - response.m_outputProducts.back().m_productAssetType = azrtti_typeid(); - response.m_outputProducts.back().m_productSubID = 1; - - // The texatlasidx file is a data file that indicates where the original parts are inside the atlas, - // and this would usually imply that it refers to its dds file in some way or needs it to function. - // The texatlasidx file should be the one that depends on the DDS because its possible to use the DDS - // without the texatlasid, but not the other way around - AZ::Data::AssetId productAssetId(request.m_sourceFileUUID, response.m_outputProducts.back().m_productSubID); - response.m_outputProducts[static_cast(Product::TexatlasidxProduct)].m_dependencies.push_back(AssetBuilderSDK::ProductDependency(productAssetId, 0)); - response.m_outputProducts[static_cast(Product::TexatlasidxProduct)].m_dependenciesHandled = true; // We've populated the dependencies immediately above so it's OK to tell the AP we've handled dependencies - } - response.m_resultCode = AssetBuilderSDK::ProcessJobResult_Success; - } - } - - bool AtlasBuilderWorker::TryPack(const ImageDimensionData& images, - int targetWidth, - int targetHeight, - int padding, - size_t& amountFit, - AZStd::vector& out) - { - // Start with one open slot and initialize a vector to store the closed products - AZStd::vector open; - AZStd::vector closed; - open.push_back(AtlasCoordinates(0, targetWidth, 0, targetHeight)); - bool slotNotFound = false; - for (size_t i = 0; i < images.size() && !slotNotFound; ++i) - { - slotNotFound = true; - // Try to place the image in every open slot - for (size_t j = 0; j < open.size(); ++j) - { - if (CanInsert(open[j], images[i].second, padding, targetWidth, targetHeight)) - { - // if it fits, subdivide the excess space in the slot, add it back to the open list and place the - // filled space into the closed vector - slotNotFound = false; - AtlasCoordinates spent(open[j].GetLeft(), - open[j].GetLeft() + images[i].second.m_width, - open[j].GetTop(), - open[j].GetTop() + images[i].second.m_height); - - // We are going to try pushing the object up / left to try to avoid creating tight open spaces. - bool needTrim = false; - AtlasCoordinates coords = spent; - // Modifying left will preserve width - coords.SetLeft(coords.GetLeft() - 1); - AddPadding(coords, padding, targetWidth, targetHeight); - while (spent.GetLeft() > 0 && !Collides(coords, closed)) - { - spent.SetLeft(coords.GetLeft()); - coords = spent; - coords.SetLeft(coords.GetLeft() - 1); - AddPadding(coords, padding, targetWidth, targetHeight); - needTrim = true; - } - // Refocus the search to see if we can push up - coords = spent; - coords.SetTop(coords.GetTop() - 1); - AddPadding(coords, padding, targetWidth, targetHeight); - while (spent.GetTop() > 0 && !Collides(coords, closed)) - { - spent.SetTop(coords.GetTop()); - coords = spent; - coords.SetTop(coords.GetTop() - 1); - AddPadding(coords, padding, targetWidth, targetHeight); - needTrim = true; - } - AddPadding(spent, padding, targetWidth, targetHeight); - if (needTrim) - { - TrimOverlap(open, spent); - closed.push_back(spent); - break; - } - AtlasCoordinates bigCoords; - AtlasCoordinates smallCoords; - - // Create the largest possible subdivision and another subdivision that uses the left over space - if (open[j].GetBottom() - spent.GetBottom() < open[j].GetRight() - spent.GetRight()) - { - smallCoords = AtlasCoordinates( - open[j].GetLeft(), spent.GetRight(), spent.GetBottom(), open[j].GetBottom()); - bigCoords = AtlasCoordinates(spent.GetRight(), open[j].GetRight(), open[j].GetTop(), smallCoords.GetBottom()); - } - else - { - bigCoords = AtlasCoordinates( - open[j].GetLeft(), open[j].GetRight(), spent.GetBottom(), open[j].GetBottom()); - smallCoords = AtlasCoordinates(spent.GetRight(), open[j].GetRight(), open[j].GetTop(), bigCoords.GetTop()); - } - - open.erase(open.begin() + j, open.begin() + j + 1); - if (bigCoords.GetHeight() > 0 && bigCoords.GetHeight() > 0) - { - InsertInOrder(open, bigCoords); - } - if (smallCoords.GetHeight() > 0 && smallCoords.GetHeight() > 0) - { - InsertInOrder(open, smallCoords); - } - - closed.push_back(spent); - break; - } - } - if (slotNotFound) - { - // If no single open slot can fit the object, do one last check to see if we can fit it in at any open - // corner. The reason we perform this check is in case the object can be fit across multiple different - // open spaces. If there is a space that an object can be fit in, it will probably involve the top left - // corner of that object in the top left corner of an open slot. This may miss some odd fits, but due to - // the nature of the packing algorithm, such solutions are highly unlikely to exist. If we wanted to - // expand the algorithm, we could theoretically base it on edges instead of corners to find all results, - // but it would not be time efficient. - for (size_t j = 0; j < open.size(); ++j) - { - AtlasCoordinates insert = AtlasCoordinates(open[j].GetLeft(), - open[j].GetLeft() + images[i].second.m_width, - open[j].GetTop(), - open[j].GetTop() + images[i].second.m_height); - AddPadding(insert, padding, targetWidth, targetHeight); - if (insert.GetRight() <= targetWidth && insert.GetBottom() <= targetHeight) - { - bool collision = Collides(insert, closed); - if (!collision) - { - closed.push_back(insert); - // Trim overlapping open slots - TrimOverlap(open, insert); - slotNotFound = false; - break; - } - } - } - } - } - // If we succeeded, update the output - if (!slotNotFound) - { - out = closed; - } - amountFit = amountFit > closed.size() ? amountFit : closed.size(); - return !slotNotFound; - } - - // Modifies slotList so that no items in slotList overlap with item - void AtlasBuilderWorker::TrimOverlap(AZStd::vector& slotList, AtlasCoordinates item) - { - for (size_t i = 0; i < slotList.size(); ++i) - { - if (Collides(slotList[i], item)) - { - // Subdivide the overlapping slot to seperate overlapping and non overlapping portions - AtlasCoordinates overlap = GetOverlap(item, slotList[i]); - AZStd::vector excess; - excess.push_back(AtlasCoordinates( - slotList[i].GetLeft(), overlap.GetRight(), slotList[i].GetTop(), overlap.GetTop())); - excess.push_back(AtlasCoordinates( - slotList[i].GetLeft(), overlap.GetLeft(), overlap.GetTop(), slotList[i].GetBottom())); - excess.push_back(AtlasCoordinates( - overlap.GetRight(), slotList[i].GetRight(), slotList[i].GetTop(), overlap.GetBottom())); - excess.push_back(AtlasCoordinates( - overlap.GetLeft(), slotList[i].GetRight(), overlap.GetBottom(), slotList[i].GetBottom())); - slotList.erase(slotList.begin() + i); - for (size_t j = 0; j < excess.size(); ++j) - { - if (excess[j].GetWidth() > 0 && excess[j].GetHeight() > 0) - { - InsertInOrder(slotList, excess[j]); - } - } - --i; - } - } - } - - // This function interprets input and performs the proper tightening option - bool AtlasBuilderWorker::TryTightening(AtlasBuilderInput input, - const ImageDimensionData& images, - int smallestWidth, - int smallestHeight, - int targetArea, - int padding, - int& resultWidth, - int& resultHeight, - size_t& amountFit, - AZStd::vector& out) - { - if (input.m_forceSquare) - { - return TryTighteningSquare(images, - smallestWidth > smallestHeight ? smallestWidth : smallestHeight, - input.m_maxDimension, - targetArea, - input.m_forcePowerOf2, - padding, - resultWidth, - resultHeight, - amountFit, - out); - } - else - { - return TryTighteningOptimal(images, - smallestWidth, - smallestHeight, - input.m_maxDimension, - targetArea, - input.m_forcePowerOf2, - padding, - resultWidth, - resultHeight, - amountFit, - out); - } - } - - // Finds the optimal square solution by starting with the ideal solution and expanding the size of the space until everything fits - bool AtlasBuilderWorker::TryTighteningSquare(const ImageDimensionData& images, - int lowerBound, - int maxDimension, - int targetArea, - bool powerOfTwo, - int padding, - int& resultWidth, - int& resultHeight, - size_t& amountFit, - AZStd::vector& out) - { - // Square solution cannot be smaller than the target area - int dimension = aznumeric_cast(sqrt(static_cast(targetArea))); - // Solution cannot be smaller than the smallest side - dimension = dimension > lowerBound ? dimension : lowerBound; - if (powerOfTwo) - { - // Starting dimension needs to be rounded up to the nearest power of two - dimension = aznumeric_cast(pow(2, 1 + IntegerLog2(static_cast(dimension - 1)))); - } - - AZStd::vector track; - // Expand the square until the contents fit - while (!TryPack(images, dimension, dimension, padding, amountFit, track) && dimension <= maxDimension) - { - // Step to the next valid value - dimension = powerOfTwo ? dimension * 2 : dimension + cellSize; - } - // Make sure we found a solution - if (dimension > maxDimension) - { - return false; - } - - resultHeight = dimension; - resultWidth = dimension; - out = track; - return true; - } - - // Finds the optimal solution by starting with a somewhat optimal solution and searching for better solutions - bool AtlasBuilderWorker::TryTighteningOptimal(const ImageDimensionData& images, - int smallestWidth, - int smallestHeight, - int maxDimension, - int targetArea, - bool powerOfTwo, - int padding, - int& resultWidth, - int& resultHeight, - size_t& amountFit, - AZStd::vector& out) - { - AZStd::vector track; - - // round max dimension down to a multiple of cellSize - AZ::u32 maxDimensionRounded = maxDimension - (maxDimension % cellSize); - - // The starting width is the larger of the widest individual texture and the width required - // to fit the total texture area given the max dimension - AZ::u32 smallestWidthDueToArea = targetArea / maxDimensionRounded; - AZ::u32 minWidth = AZStd::max(static_cast(smallestWidth), smallestWidthDueToArea); - - if (powerOfTwo) - { - // Starting dimension needs to be rounded up to the nearest power of two - minWidth = aznumeric_cast(pow(2, 1 + IntegerLog2(static_cast(minWidth - 1)))); - } - - // Round min width up to the nearest compression unit - minWidth = (minWidth + (cellSize - 1)) / cellSize * cellSize; - - AZ::u32 height = 0; - // Finds the optimal thin solution - // This uses a standard binary search to find the smallest width that can pack everything - AZ::u32 lower = minWidth; - AZ::u32 upper = maxDimensionRounded; - AZ::u32 width = 0; - while (lower <= upper) - { - AZ::u32 testWidth = (lower + upper) / 2; // must be divisible by cellSize because lower and upper are - bool canPack = TryPack(images, testWidth, maxDimension, padding, amountFit, track); - if (canPack) - { - // it packed, continue looking for smaller widths that pack - width = testWidth; // best fit so far - upper = testWidth - cellSize; - } - else - { - // it failed to pack, don't try any widths smaller than this - lower = testWidth + cellSize; - } - } - // Make sure we found a solution - if (width == 0) - { - return false; - } - - // Find the height of the solution - for (int i = 0; i < track.size(); ++i) - { - uint32 bottom = static_cast(AZStd::max(0, track[i].GetBottom())); - if (height < bottom) - { - height = bottom; - } - } - - // Fix height for power of two when applicable - if (powerOfTwo) - { - // Starting dimensions need to be rounded up to the nearest power of two - height = aznumeric_cast(pow(2, 1 + IntegerLog2(static_cast(height - 1)))); - } - - AZ::u32 resultArea = height * width; - // This for loop starts with the optimal thin width and makes it wider at each step. For each width, it - // calculates what height would be neccesary to have a more optimal solution than the stored solution. If the - // more optimal solution is valid, it tries shrinking the height until the solution fails. The loop ends when it - // is determined that a valid solution cannot exist at further steps - for (AZ::u32 testWidth = width; testWidth <= maxDimensionRounded && resultArea / testWidth >= static_cast(smallestHeight); - testWidth = powerOfTwo ? testWidth * 2 : testWidth + cellSize) - { - // The area of test height and width should be equal or less than resultArea - // Note: We don't need to force powers of two here because the Area and the width are already powers of two - int testHeight = resultArea / testWidth * cellSize / cellSize; - // Try the tighter pack - while (TryPack(images, static_cast(testWidth), testHeight, padding, amountFit, track)) - { - // Loop and continue to shrink the height until you cannot do so any further - width = testWidth; - height = testHeight; - resultArea = height * width; - // Try to step down a level - testHeight = powerOfTwo ? testHeight / 2 : testHeight - cellSize; - } - } - // Output the results of the function - out = track; - resultHeight = height; - resultWidth = width; - return true; - } - - // Allows us to keep the list of open spaces in order from lowest to highest area - void AtlasBuilderWorker::InsertInOrder(AZStd::vector& slotList, AtlasCoordinates item) - { - int area = item.GetWidth() * item.GetHeight(); - for (size_t i = 0; i < slotList.size(); ++i) - { - if (area < slotList[i].GetWidth() * slotList[i].GetHeight()) - { - slotList.insert(slotList.begin() + i, item); - return; - } - } - slotList.push_back(item); - } - - // Defines priority so that sorting can be meaningful. It may seem odd that larger items are "less than" smaller - // ones, but as this is a deduction of priority, not value, it is correct. - static bool operator<(ImageDimension a, ImageDimension b) - { - // Prioritize first by longest size - if ((a.m_width > a.m_height ? a.m_width : a.m_height) != (b.m_width > b.m_height ? b.m_width : b.m_height)) - { - return (a.m_width > a.m_height ? a.m_width : a.m_height) > (b.m_width > b.m_height ? b.m_width : b.m_height); - } - // Prioritize second by the length of the smaller side - if (a.m_width * a.m_height != b.m_width * b.m_height) - { - return a.m_width * a.m_height > b.m_width * b.m_height; - } - // Prioritize wider objects over taller objects for objects of the same size - else - { - return a.m_width > b.m_width; - } - } - - // Exposes priority logic to the sorting algorithm - static bool operator<(IndexImageDimension a, IndexImageDimension b) { return a.second < b.second; } - - // Tests if two coordinate sets intersect - bool Collides(AtlasCoordinates a, AtlasCoordinates b) - { - return !((a.GetRight() <= b.GetLeft()) || (a.GetBottom() <= b.GetTop()) || (b.GetRight() <= a.GetLeft()) - || (b.GetBottom() <= a.GetTop())); - } - - // Tests if an item collides with any items in a list - bool Collides(AtlasCoordinates item, AZStd::vector list) - { - for (size_t i = 0; i < list.size(); ++i) - { - if (Collides(list[i], item)) - { - return true; - } - } - return false; - } - - // Returns the overlap of two intersecting coordinate sets - AtlasCoordinates GetOverlap(AtlasCoordinates a, AtlasCoordinates b) - { - return AtlasCoordinates(b.GetLeft() > a.GetLeft() ? b.GetLeft() : a.GetLeft(), - b.GetRight() < a.GetRight() ? b.GetRight() : a.GetRight(), - b.GetTop() > a.GetTop() ? b.GetTop() : a.GetTop(), - b.GetBottom() < a.GetBottom() ? b.GetBottom() : a.GetBottom()); - } - - // Returns the width of the widest element in imageList - int AtlasBuilderWorker::GetWidest(const ImageDimensionData& imageList) - { - int max = 0; - for (size_t i = 0; i < imageList.size(); ++i) - { - if (max < imageList[i].second.m_width) - { - max = imageList[i].second.m_width; - } - } - return max; - } - - // Returns the height of the tallest element in imageList - int AtlasBuilderWorker::GetTallest(const ImageDimensionData& imageList) - { - int max = 0; - for (size_t i = 0; i < imageList.size(); ++i) - { - if (max < imageList[i].second.m_height) - { - max = imageList[i].second.m_height; - } - } - return max; - } - - // Performs an operation that copies a pixel to the output - void SetPixels(AZ::u8* dest, const AZ::u8* source, int destBytes) - { - if (destBytes >= bytesPerPixel) - { - memcpy(dest, source, bytesPerPixel); - int bytesCopied = bytesPerPixel; - while (bytesCopied * 2 < destBytes) - { - memcpy(dest + bytesCopied, dest, bytesCopied); - bytesCopied *= 2; - } - memcpy(dest + bytesCopied, dest, destBytes - bytesCopied); - } - } - - // Checks if we can insert an image into a slot - bool CanInsert(AtlasCoordinates slot, ImageDimension image, int padding, int farRight, int farBot) - { - int right = slot.GetLeft() + image.m_width; - if (slot.GetRight() < farRight) - { - // Add padding for my right border - right += padding; - // Round up to the nearest compression unit - right = (right + (cellSize - 1)) / cellSize * cellSize; - // Add padding for an adjacent unit's left border - right += padding; - } - - int bot = slot.GetTop() + image.m_height; - if (slot.GetBottom() < farBot) - { - // Add padding for my right border - bot += padding; - // Round up to the nearest compression unit - bot = (bot + (cellSize - 1)) / cellSize * cellSize; - // Add padding for an adjacent unit's left border - bot += padding; - } - - return slot.GetRight() >= right && slot.GetBottom() >= bot; - } - - // Adds the necessary padding to an Atlas Coordinate - void AddPadding(AtlasCoordinates& slot, int padding, [[maybe_unused]] int farRight, [[maybe_unused]] int farBot) - { - // Add padding for my right border - int right = slot.GetRight() + padding; - // Round up to the nearest compression unit - right = (right + (cellSize - 1)) / cellSize * cellSize; - // Add padding for an adjacent unit's left border - right += padding; - - // Add padding for my right border - int bot = slot.GetBottom() + padding; - // Round up to the nearest compression unit - bot = (bot + (cellSize - 1)) / cellSize * cellSize; - // Add padding for an adjacent unit's left border - bot += padding; - - slot.SetRight(right); - slot.SetBottom(bot); - } - -} diff --git a/Gems/ImageProcessing/Code/Source/AtlasBuilder/AtlasBuilderWorker.h b/Gems/ImageProcessing/Code/Source/AtlasBuilder/AtlasBuilderWorker.h deleted file mode 100644 index f28535998e..0000000000 --- a/Gems/ImageProcessing/Code/Source/AtlasBuilder/AtlasBuilderWorker.h +++ /dev/null @@ -1,221 +0,0 @@ -/* -* All or portions of this file Copyright(c) Amazon.com, Inc.or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -*or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -*WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ - -#pragma once - -#include -#include -#include -#include -#include - -namespace TextureAtlasBuilder -{ - //! Struct that is used to communicate input commands - struct AtlasBuilderInput - { - AZ_CLASS_ALLOCATOR(AtlasBuilderInput, AZ::SystemAllocator, 0); - AZ_TYPE_INFO(AtlasBuilderInput, "{F54477F9-1BDE-4274-8CC0-8320A3EF4A42}"); - - bool m_forceSquare; - bool m_forcePowerOf2; - // Includes a white default texture for the UI to use under certain circumstances - bool m_includeWhiteTexture; - int m_maxDimension; - // At least this much padding will surround each texture except on the edges of the atlas - int m_padding; - // Color used in wasted space - AZ::Color m_unusedColor; - // A preset to use for the texture atlas image processing - AZStd::string m_presetName; - - AZStd::vector m_filePaths; - AtlasBuilderInput(): - m_forceSquare(false), - m_forcePowerOf2(false), - m_includeWhiteTexture(true), - m_maxDimension(4096), - m_padding(1), - // Default color should be a non-transparent color that isn't used often in uis - m_unusedColor(.235f, .702f, .443f, 1) - { - } - - static void Reflect(AZ::ReflectContext* context); - - //! Attempts to read the input from a .texatlas file. "valid" is for reporting exceptions and telling the asset - //! proccesor to fail the job. Supports parsing through a human readable custom parser. - static AtlasBuilderInput ReadFromFile(const AZStd::string& path, const AZStd::string& directory, bool& valid); - - //! Resolves any wild cards in paths - static void AddFilesUsingWildCard(AZStd::vector& paths, const AZStd::string& insert); - - //! Removes anything that matches the wildcard - static void RemoveFilesUsingWildCard(AZStd::vector& paths, const AZStd::string& remove); - - //! Resolves any folder paths into image file paths - static void AddFolderContents(AZStd::vector& paths, const AZStd::string& insert, bool& valid); - - //! Resolves remove commands for folders - static void RemoveFolderContents(AZStd::vector& paths, const AZStd::string& remove); - }; - - //! Struct that is used to represent an object with a width and height in pixels - struct ImageDimension - { - int m_width; - int m_height; - - ImageDimension(int width, int height) - { - m_width = width; - m_height = height; - } - }; - - //! Typedef for an ImageDimension paired with an integer - using IndexImageDimension = AZStd::pair; - - //! Typedef for a list of ImageDimensions paired with integers - using ImageDimensionData = AZStd::vector; - - //! Typedef to simplify references to TextureAtlas::AtlasCoordinates - using AtlasCoordinates = TextureAtlasNamespace::AtlasCoordinates; - - //! Number of bytes in a pixel - const int bytesPerPixel = 4; - - //! The size of the padded sorting units (important for compression) - const int cellSize = 4; - - //! Indexes of the products - enum class Product - { - TexatlasidxProduct = 0, - DdsProduct = 1 - }; - - //! An asset builder for texture atlases - class AtlasBuilderWorker : public AssetBuilderSDK::AssetBuilderCommandBus::Handler - { - public: - AZ_RTTI(AtlasBuilderWorker, "{79036188-E017-4575-9EC0-8D39CB560EA6}"); - - AtlasBuilderWorker() = default; - ~AtlasBuilderWorker() = default; - - //! Asset Builder Callback Functions - - //! Called by asset processor to gather information on a job for a ".texatlas" file - void CreateJobs(const AssetBuilderSDK::CreateJobsRequest& request, - AssetBuilderSDK::CreateJobsResponse& response); - //! Called by asset proccessor when it wants us to execute a job - void ProcessJob(const AssetBuilderSDK::ProcessJobRequest& request, - AssetBuilderSDK::ProcessJobResponse& response); - - //! Returns the job related information used by the builder - static AssetBuilderSDK::JobDescriptor GetJobDescriptor(const AZStd::string& sourceFile, const AtlasBuilderInput& input); - - ////////////////////////////////////////////////////////////////////////// - //! AssetBuilderSDK::AssetBuilderCommandBus interface - void ShutDown() override; // if you get this you must fail all existing jobs and return. - ////////////////////////////////////////////////////////////////////////// - - private: - bool m_isShuttingDown = false; - - //! This is the main function that takes a set of inputs and attempts to pack them into an atlas of a given - //! size. Returns true if succesful, does not update out on failure. - static bool TryPack(const ImageDimensionData& images, - int targetWidth, - int targetHeight, - int padding, - size_t& amountFit, - AZStd::vector& out); - - //! Removes any overlap between slotList and the given item - static void TrimOverlap(AZStd::vector& slotList, AtlasCoordinates item); - - //! Uses the proper tightening method based on the input and returns the maximum number of items that were able to be fit - bool TryTightening(AtlasBuilderInput input, - const ImageDimensionData& images, - int smallestWidth, - int smallestHeight, - int targetArea, - int padding, - int& resultWidth, - int& resultHeight, - size_t& amountFit, - AZStd::vector& out); - - //! Finds the tightest square fit achievable by expanding a square area until a valid fit is found - bool TryTighteningSquare(const ImageDimensionData& images, - int lowerBound, - int maxDimension, - int targetArea, - bool powerOfTwo, - int padding, - int& resultWidth, - int& resultHeight, - size_t& amountFit, - AZStd::vector& out); - - //! Finds the tightest fit achievable by starting with the optimal thin solution and attempting to resize to be - //! a better shape - bool TryTighteningOptimal(const ImageDimensionData& images, - int smallestWidth, - int smallestHeight, - int maxDimension, - int targetArea, - bool powerOfTwo, - int padding, - int& resultWidth, - int& resultHeight, - size_t& amountFit, - AZStd::vector& out); - - //! Sorting logic for adding a slot to a sorted list in order to maintain increasing order - static void InsertInOrder(AZStd::vector& slotList, AtlasCoordinates item); - - //! Misc Logic For Estimating Target Shape - - //! Returns the width of the widest element - static int GetWidest(const ImageDimensionData& imageList); - - //! Returns the height of the tallest area - static int GetTallest(const ImageDimensionData& imageList); - }; - - //! Used for sorting ImageDimensions - static bool operator<(ImageDimension a, ImageDimension b); - - //! Used to expose the ImageDimension in a pair to AZStd::Sort - static bool operator<(IndexImageDimension a, IndexImageDimension b); - - //! Returns true if two coordinate sets overlap - static bool Collides(AtlasCoordinates a, AtlasCoordinates b); - - //! Returns true if item collides with any object in list - static bool Collides(AtlasCoordinates item, AZStd::vector list); - - //! Returns the portion of the second item that overlaps with the first - static AtlasCoordinates GetOverlap(AtlasCoordinates a, AtlasCoordinates b); - - //! Performs an operation that copies a pixel to the output - static void SetPixels(AZ::u8* dest, const AZ::u8* source, int destBytes); - - //! Checks if we can insert an image into a slot - static bool CanInsert(AtlasCoordinates slot, ImageDimension image, int padding, int farRight, int farBot); - - //! Adds the necessary padding to an Atlas Coordinate - static void AddPadding(AtlasCoordinates& slot, int padding, int farRight, int farBot); -} diff --git a/Gems/ImageProcessing/Code/Source/BuilderSettings/BuilderSettingManager.cpp b/Gems/ImageProcessing/Code/Source/BuilderSettings/BuilderSettingManager.cpp deleted file mode 100644 index f8b0a1651b..0000000000 --- a/Gems/ImageProcessing/Code/Source/BuilderSettings/BuilderSettingManager.cpp +++ /dev/null @@ -1,1114 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or 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 "ImageProcessing_precompiled.h" - -#include "BuilderSettingManager.h" -#include -#include -#include -#include -#include - -#include -#include -#include -#include -#include -#include -#include -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace ImageProcessing -{ - -#if defined(AZ_TOOLS_EXPAND_FOR_RESTRICTED_PLATFORMS) -#define AZ_RESTRICTED_PLATFORM_EXPANSION(CodeName, CODENAME, codename, PrivateName, PRIVATENAME, privatename, PublicName, PUBLICNAME, publicname, PublicAuxName1, PublicAuxName2, PublicAuxName3)\ - namespace ImageProcess##PrivateName\ - {\ - bool DoesSupport(AZStd::string);\ - } -AZ_TOOLS_EXPAND_FOR_RESTRICTED_PLATFORMS -#undef AZ_RESTRICTED_PLATFORM_EXPANSION -#endif //AZ_TOOLS_EXPAND_FOR_RESTRICTED_PLATFORMS - - const char* BuilderSettingManager::s_environmentVariableName = "ImageBuilderSettingManager"; - AZ::EnvironmentVariable BuilderSettingManager::s_globalInstance = nullptr; - AZStd::mutex BuilderSettingManager::s_instanceMutex; - const PlatformName BuilderSettingManager::s_defaultPlatform = AZ_TRAIT_IMAGEPROCESSING_DEFAULT_PLATFORM; - - AZ::Outcome, AZStd::string> GetPlatformNamesFromRC(AZStd::string& filePath) - { - QFile inputFile(filePath.c_str()); - - if (inputFile.exists() == false) - { - return AZ::Failure(AZStd::string::format("'%s' does not exist", filePath.c_str())); - } - - AZStd::vector all_platforms; - if (inputFile.open(QIODevice::ReadOnly)) - { - QTextStream in(&inputFile); - while (!in.atEnd()) - { - if (in.readLine() == "[_platform]") - { - QString name_line = in.readLine(); - if (name_line.contains("name=")) - { - QString name_value = name_line.split("=")[1]; - // Remove name alias after ',' - AZStd::string az_name_value = name_value.split(",")[0].toUtf8().constData(); - all_platforms.push_back(az_name_value); - } - } - } - inputFile.close(); - } - return AZ::Success(all_platforms); - } - - StringOutcome ParseKeyToData(QString settingKey, const QSettings& rcINI, PresetSettings& presetSettings) - { - // We may be parsing platform-specific settings denoted by a colon and a platform (ex. mintexturesize:ios=35). - // We always extract the actual setting name to determine the setting we are parsing. We must reference the key - // as a whole to properly index into the rcINI file content. - QString key = settingKey.split(":")[0]; - - // There is no standard way to map an enum to string-- - // Also, can't seem to make this static because it allocates something that the destructor doesn't catch. - const AZStd::map colorSpaceMap{ - { "linear" , ColorSpace::linear }, - { "sRGB" , ColorSpace::sRGB }, - { "auto" , ColorSpace::autoSelect } - }; - - const AZStd::map rgbWeightMap{ - { "uniform" , RGBWeight::uniform }, - { "luminance" , RGBWeight::luminance }, - { "ciexyz" , RGBWeight::ciexyz } - }; - - //cm_ftype: gaussian, cone, disc, cosine, cosine_power, ggx - const AZStd::map cubemapFilterTypeMap{ - { "cone" , CubemapFilterType::cone }, - { "gaussian" , CubemapFilterType::gaussian }, - { "ggx" , CubemapFilterType::ggx }, - { "cosine" , CubemapFilterType::cosine }, - { "cosine_power" , CubemapFilterType::cosine_power } - }; - - // To avoid abusing '#define', we use lambda instead. - auto INI_VALUE = [&rcINI, &settingKey]() { return rcINI.value(settingKey); }; - auto INI_VALUE_QSTRING = [&rcINI, &settingKey]() { return rcINI.value(settingKey).toString(); }; - - /************************************************************************/ - /* GENERAL PRESET SETTINGS */ - /************************************************************************/ - if (key == "rgbweights") - { - auto rgbWeightStr = INI_VALUE_QSTRING().toUtf8(); - auto rgbWeightIter = rgbWeightMap.find(rgbWeightStr); - if (rgbWeightIter != rgbWeightMap.end()) - { - presetSettings.m_rgbWeight = rgbWeightIter->second; - } - else - { - return AZ::Failure(AZStd::string("Unmapped rgbweights enum detected.")); - } - } - else if (key == "powof2") - { - presetSettings.m_isPowerOf2 = INI_VALUE().toBool(); - } - else if (key == "discardalpha") - { - presetSettings.m_discardAlpha = INI_VALUE().toBool(); - } - else if (key == "reduce") - { - int reduce = INI_VALUE().toInt(); - if (reduce > 0) - { - presetSettings.m_sizeReduceLevel = reduce; - } - } - else if (key == "ser") - { - presetSettings.m_suppressEngineReduce = INI_VALUE().toBool(); - } - else if (key == "colorchart") - { - presetSettings.m_isColorChart = INI_VALUE().toBool(); - } - else if (key == "highpass") - { - presetSettings.m_highPassMip = INI_VALUE().toInt(); - } - else if (key == "glossfromnormals") - { - presetSettings.m_glossFromNormals = INI_VALUE().toBool(); - } - else if (key == "glosslegacydist") - { - presetSettings.m_isLegacyGloss = INI_VALUE().toBool(); - } - else if (key == "swizzle") - { - presetSettings.m_swizzle = INI_VALUE_QSTRING().toUtf8().constData(); - } - else if (key == "mipnormalize") - { - presetSettings.m_isMipRenormalize = INI_VALUE().toBool(); - } - else if (key == "numstreamablemips") - { - presetSettings.m_numStreamableMips = INI_VALUE().toInt(); - } - else if (key == "colorspace") - { - // By default, RC.ini contains data written in non-standard INI format inherited from CryEngine. - // We need to parse in the value as string list. - // Example: - // - // [MyValues] - // colorspace=src,dst - // - QVariant paramValue = rcINI.value(key, QString()); - if (paramValue.type() != QVariant::StringList) - { - return AZ::Failure(AZStd::string("Expect ColorSpace parameter to be a string list!")); - } - QStringList stringValueList = paramValue.toStringList(); // The order of values for this key is... (SRC, DST) - - if (stringValueList.size() != 2) - { - return AZ::Failure(AZStd::string("Expect ColorSpace parameter list size to be 2!")); - } - - auto srcColorSpaceIter = colorSpaceMap.find(stringValueList[0]); - if (srcColorSpaceIter != colorSpaceMap.end()) - { - presetSettings.m_srcColorSpace = srcColorSpaceIter->second; - } - else - { - return AZ::Failure(AZStd::string("Unmapped ColorSpace enum detected.")); - } - - auto dstColorSpaceIter = colorSpaceMap.find(stringValueList[1]); - if (dstColorSpaceIter != colorSpaceMap.end()) - { - presetSettings.m_destColorSpace = dstColorSpaceIter->second; - } - else - { - return AZ::Failure(AZStd::string("Unmapped ColorSpace enum detected.")); - } - } - else if (key == "filemasks") - { - QVariant iniVariant = rcINI.value(settingKey); - QStringList stringValueList = iniVariant.toStringList(); - for (QString value : stringValueList) - { - //remove stars. For example: "*_ddna*" => "_ddna" - QString suffix = value.mid(1, value.length()-2); - QByteArray suffixByteArray = suffix.toUtf8(); - presetSettings.m_fileMasks.emplace_back(suffixByteArray.constData()); - } - } - else if (key == "pixelformat") - { - auto pixelFormatQBytes = INI_VALUE_QSTRING().toUtf8(); - const char* pixelFormatString = pixelFormatQBytes.constData(); - - EPixelFormat pixelFormatEnum = CPixelFormats::GetInstance().FindPixelFormatByLegacyName(pixelFormatString); - if (pixelFormatEnum == EPixelFormat::ePixelFormat_Unknown) - { - return AZ::Failure(AZStd::string::format("Unsupported ePixelFormat detected: %s", pixelFormatString)); - } - - presetSettings.m_pixelFormat = pixelFormatEnum; - presetSettings.m_pixelFormatName = CPixelFormats::GetInstance().GetPixelFormatInfo(pixelFormatEnum)->szName; - } - else if (key == "pixelformatalpha") - { - auto pixelFormatQBytes = INI_VALUE_QSTRING().toUtf8(); - const char* pixelFormatString = pixelFormatQBytes.constData(); - - EPixelFormat pixelFormatEnum = CPixelFormats::GetInstance().FindPixelFormatByLegacyName(pixelFormatString); - if (pixelFormatEnum == EPixelFormat::ePixelFormat_Unknown) - { - return AZ::Failure(AZStd::string::format("Unsupported ePixelFormat detected: %s", pixelFormatString)); - } - - presetSettings.m_pixelFormatAlpha = pixelFormatEnum; - presetSettings.m_pixelFormatAlphaName = CPixelFormats::GetInstance().GetPixelFormatInfo(pixelFormatEnum)->szName; - } - else if (key == "maxtexturesize") - { - bool isOk = false; - auto maxTextureSize = INI_VALUE().toUInt(&isOk); - if (isOk) - { - presetSettings.m_maxTextureSize = maxTextureSize; - } - else - { - return AZ::Failure(AZStd::string::format("Invalid number for key 'maxtexturesize' for [%s]", presetSettings.m_name.c_str())); - } - } - else if (key == "mintexturesize") - { - bool isOk = false; - auto minTextureSize = INI_VALUE().toUInt(&isOk); - if (isOk) - { - presetSettings.m_minTextureSize = minTextureSize; - } - else - { - return AZ::Failure(AZStd::string::format("Invalid number for key 'mintexturesize' for [%s]", presetSettings.m_name.c_str())); - } - } - /************************************************************************/ - /* CUBEMAP PRESET SETTINGS */ - /************************************************************************/ - else if (key == "cm") - { - if (presetSettings.m_cubemapSetting == nullptr && INI_VALUE().toBool()) - { - presetSettings.m_cubemapSetting = AZStd::make_unique(); - } - else - { - return AZ::Failure(AZStd::string("Multiple CubeMap settings detected. Reduce to a single settings entry.")); - } - } - else if (key == "cm_ftype") - { - if (presetSettings.m_cubemapSetting == nullptr) - { - if (rcINI.value("cm").toBool()) - { - presetSettings.m_cubemapSetting = AZStd::make_unique(); - } - } - - if (presetSettings.m_cubemapSetting) - { - auto filterTypeStr = INI_VALUE_QSTRING().toUtf8(); - auto filterTypeIter = cubemapFilterTypeMap.find(filterTypeStr); - if (filterTypeIter != cubemapFilterTypeMap.end()) - { - presetSettings.m_cubemapSetting->m_filter = filterTypeIter->second; - } - else - { - return AZ::Failure(AZStd::string("Unmapped cubemap filter type enum detected.")); - } - } - } - else if (key == "cm_fangle") - { - if (presetSettings.m_cubemapSetting == nullptr) - { - if (rcINI.value("cm").toBool()) - { - presetSettings.m_cubemapSetting = AZStd::make_unique(); - presetSettings.m_cubemapSetting->m_angle = INI_VALUE().toFloat(); - } - } - else - { - presetSettings.m_cubemapSetting->m_angle = INI_VALUE().toFloat(); - } - } - else if (key == "cm_fmipangle") - { - if (presetSettings.m_cubemapSetting == nullptr) - { - if (rcINI.value("cm").toBool()) - { - presetSettings.m_cubemapSetting = AZStd::make_unique(); - presetSettings.m_cubemapSetting->m_mipAngle = INI_VALUE().toFloat(); - } - } - else - { - presetSettings.m_cubemapSetting->m_mipAngle = INI_VALUE().toFloat(); - } - } - else if (key == "cm_fmipslope") - { - if (presetSettings.m_cubemapSetting == nullptr) - { - if (rcINI.value("cm").toBool()) - { - presetSettings.m_cubemapSetting = AZStd::make_unique(); - presetSettings.m_cubemapSetting->m_mipSlope = INI_VALUE().toFloat(); - } - } - else - { - presetSettings.m_cubemapSetting->m_mipSlope = INI_VALUE().toFloat(); - } - } - else if (key == "cm_edgefixup") - { - if (presetSettings.m_cubemapSetting == nullptr) - { - if (rcINI.value("cm").toBool()) - { - presetSettings.m_cubemapSetting = AZStd::make_unique(); - presetSettings.m_cubemapSetting->m_edgeFixup = INI_VALUE().toFloat(); - } - } - else - { - presetSettings.m_cubemapSetting->m_edgeFixup = INI_VALUE().toFloat(); - } - } - else if (key == "cm_diff") - { - if (presetSettings.m_cubemapSetting == nullptr) - { - if (rcINI.value("cm").toBool()) - { - presetSettings.m_cubemapSetting = AZStd::make_unique(); - presetSettings.m_cubemapSetting->m_generateDiff = INI_VALUE().toBool(); - } - } - else - { - presetSettings.m_cubemapSetting->m_generateDiff = INI_VALUE().toBool(); - } - } - else if (key == "cm_diffpreset") - { - QByteArray presetNameByteArray = INI_VALUE().toString().toUtf8(); - AZ::Uuid presetID = BuilderSettingManager::Instance()->GetPresetIdFromName(presetNameByteArray.constData()); - if (presetID.IsNull()) - { - return STRING_OUTCOME_ERROR(AZStd::string::format("Parsing error [cm_diffpreset]. Unable to find UUID for preset: %s", presetNameByteArray.constData())); - } - - if (presetSettings.m_cubemapSetting == nullptr) - { - if (rcINI.value("cm").toBool()) - { - presetSettings.m_cubemapSetting = AZStd::make_unique(); - presetSettings.m_cubemapSetting->m_diffuseGenPreset = presetID; - } - } - else - { - presetSettings.m_cubemapSetting->m_diffuseGenPreset = presetID; - } - } - /************************************************************************/ - /* MIPMAP PRESET SETTINGS */ - /************************************************************************/ - else if (key == "mipmaps") - { - // We convey whether 'mipmaps' is enabled/available by whether the pointer is valid or empty. - if (presetSettings.m_mipmapSetting == nullptr && INI_VALUE().toBool()) - { - presetSettings.m_mipmapSetting = AZStd::make_unique(); - } - } - else if (key == "mipgentype") - { - // We must handle parsing settings of missing/disabled parent settings ("mipmaps") - if (rcINI.value("mipmaps") == QVariant()) - { - return AZ::Failure(AZStd::string("'mipgentype' specified, but dependent 'mipmaps' setting is missing in rc.ini.")); - } - - // If we are missing the mipmap settings (possibly yet to be parsed)... - if (presetSettings.m_mipmapSetting == nullptr) - { - if (rcINI.value("mipmaps").toBool()) - { - presetSettings.m_mipmapSetting = AZStd::make_unique(); - } - else - { - return AZ::Failure(AZStd::string::format( - "Cannot assign 'mipgentype' because current Preset [%s] has 'mipmaps' disabled.", presetSettings.m_name.c_str())); - } - } - - presetSettings.m_mipmapSetting->m_type = MipGenType::blackmanHarris; - if ("average" == INI_VALUE_QSTRING().toUtf8()) - { - presetSettings.m_mipmapSetting->m_type = MipGenType::box; - } - } - else - { - QByteArray keyByteArray = key.toUtf8(); - return STRING_OUTCOME_WARNING(AZStd::string::format("Unsupported key parsed from RC.ini: %s", keyByteArray.constData())); - } - - return STRING_OUTCOME_SUCCESS; - } - - void LoadPresetAliasFromRC(QSettings& rcINI, AZStd::map & presetAliases) - { - rcINI.beginGroup("_presetAliases"); - - for (QString legacyPresetString : rcINI.childKeys()) - { - QString modernPresetString = rcINI.value(legacyPresetString).toString(); - - // We must store this intermediary data in order to convert to a c-string. - QByteArray legacyPresetUtf8 = legacyPresetString.toUtf8(); - QByteArray modernPresetUtf8 = modernPresetString.toUtf8(); - - PresetName legacyPresetName(legacyPresetUtf8.constData()); - PresetName modernPresetName(modernPresetUtf8.constData()); - - presetAliases.insert(AZStd::pair(legacyPresetName, modernPresetName)); - } - - rcINI.endGroup(); - } - - void BuilderSettingManager::Reflect(AZ::ReflectContext* context) - { - AZ::SerializeContext* serialize = azrtti_cast(context); - if (serialize) - { - serialize->Class() - ->Version(1) - ->Field("BuildSettings", &BuilderSettingManager::m_builderSettings) - ->Field("PresetAliases", &BuilderSettingManager::m_presetAliases) - ->Field("DefaultPresetsByFileMask", &BuilderSettingManager::m_defaultPresetByFileMask) - ->Field("DefaultPreset", &BuilderSettingManager::m_defaultPreset) - ->Field("DefaultPresetAlpha", &BuilderSettingManager::m_defaultPresetAlpha) - ->Field("DefaultPresetNonePOT", &BuilderSettingManager::m_defaultPresetNonePOT); - } - } - - BuilderSettingManager* BuilderSettingManager::Instance() - { - AZStd::lock_guard lock(s_instanceMutex); - - if (!s_globalInstance) - { - s_globalInstance = AZ::Environment::FindVariable(s_environmentVariableName); - } - AZ_Assert(s_globalInstance, "BuilderSettingManager not created!"); - - return s_globalInstance.Get(); - } - - void BuilderSettingManager::CreateInstance() - { - AZStd::lock_guard lock(s_instanceMutex); - - if (s_globalInstance) - { - AZ_Assert(false, "BuilderSettingManager already created!"); - return; - } - - if (!s_globalInstance) - { - s_globalInstance = AZ::Environment::CreateVariable(s_environmentVariableName); - } - if (!s_globalInstance.Get()) - { - s_globalInstance.Set(aznew BuilderSettingManager()); - } - } - - void BuilderSettingManager::DestroyInstance() - { - AZStd::lock_guard lock(s_instanceMutex); - AZ_Assert(s_globalInstance, "Invalid call to DestroyInstance - no instance exists."); - AZ_Assert(s_globalInstance.Get(), "You can only call DestroyInstance if you have called CreateInstance."); - - delete s_globalInstance.Get(); - s_globalInstance.Reset(); - } - - const PresetSettings* BuilderSettingManager::GetPreset(const AZ::Uuid presetId, const PlatformName& platform) - { - AZStd::lock_guard lock(m_presetMapLock); - PlatformName platformName = platform; - if (platformName.empty()) - { - platformName = BuilderSettingManager::s_defaultPlatform; - } - - if (m_builderSettings.find(platformName) != m_builderSettings.end()) - { - const BuilderSettings& platformBuilderSetting = m_builderSettings[platformName]; - auto settingsIter = platformBuilderSetting.m_presets.find(presetId); - if (settingsIter != platformBuilderSetting.m_presets.end()) - { - return &settingsIter->second; - } - else - { - AZ_Error("Image Processing", false, "Cannot find preset settings on platform [%s] for preset id: %s", platformName.c_str(), presetId.ToString().c_str()); - } - } - else - { - AZ_Error("Image Processing", false, "Cannot find platform [%s]", platformName.c_str()); - } - - return nullptr; - } - - - const BuilderSettings* BuilderSettingManager::GetBuilderSetting(const PlatformName& platform) - { - if (m_builderSettings.find(platform) != m_builderSettings.end()) - { - return &m_builderSettings[platform]; - } - return nullptr; - } - - const PlatformNameList BuilderSettingManager::GetPlatformList() - { - PlatformNameList platforms; - - for(auto& builderSetting : m_builderSettings) - { - if (builderSetting.second.m_enablePlatform) - { - platforms.push_back(builderSetting.first); - } - } - - return platforms; - } - - const AZStd::map >& BuilderSettingManager::GetPresetFilterMap() - { - AZStd::lock_guard lock(m_presetMapLock); - return m_presetFilterMap; - } - - const AZ::Uuid BuilderSettingManager::GetPresetIdFromName(const PresetName& presetName) - { - AZStd::lock_guard lock(m_presetMapLock); - - // Each preset shares the same UUID across platforms, therefore, it's safe to pick a random - // platform to search for the preset UUID. We'll use PC, in this case. - const PlatformName defaultPlatform = BuilderSettingManager::s_defaultPlatform; - if (m_builderSettings.find(defaultPlatform) != m_builderSettings.end()) - { - auto presets = m_builderSettings[defaultPlatform].m_presets; - - for (auto curIter : presets) - { - if (curIter.second.m_name == presetName) - { - return curIter.first; - } - } - } - - return AZ::Uuid::CreateNull(); - } - - const PresetName BuilderSettingManager::GetPresetNameFromId(const AZ::Uuid& presetId) - { - AZStd::lock_guard lock(m_presetMapLock); - const PlatformName defaultPlatform = BuilderSettingManager::s_defaultPlatform; - if (m_builderSettings.find(defaultPlatform) != m_builderSettings.end()) - { - auto& presetMap = m_builderSettings[defaultPlatform].m_presets; - auto presetIter = presetMap.find(presetId); - if (presetIter != presetMap.end()) - { - return presetIter->second.m_name; - } - } - - return "Unknown"; - } - - void BuilderSettingManager::ClearSettings() - { - AZStd::lock_guard lock(m_presetMapLock); - m_presetFilterMap.clear(); - m_presetAliases.clear(); - m_builderSettings.clear(); - } - - StringOutcome BuilderSettingManager::LoadBuilderSettings() - { - StringOutcome outcome = STRING_OUTCOME_ERROR(""); - // Construct the project setting path that is used by the tool for loading setting file - const char* gameFolderPath = nullptr; - AzToolsFramework::AssetSystemRequestBus::BroadcastResult(gameFolderPath, &AzToolsFramework::AssetSystemRequestBus::Events::GetAbsoluteDevGameFolderPath); - AZStd::string projectSettingPath = ""; - - if (gameFolderPath) - { - AzFramework::StringFunc::Path::Join(gameFolderPath, "Config/ImageBuilder/ImageBuilderPresets.settings", projectSettingPath); - outcome = LoadBuilderSettings(projectSettingPath); - } - - if (!outcome.IsSuccess()) - { - AZ_TracePrintf(AssetBuilderSDK::InfoWindow, "Failed to read project specific preset setting at [%s], will use default setting file.\n", projectSettingPath.c_str()); - // Construct the default setting path - const char* engineRoot = nullptr; - AzFramework::ApplicationRequests::Bus::BroadcastResult(engineRoot, &AzFramework::ApplicationRequests::GetEngineRoot); - - if (engineRoot) - { - AZStd::string defaultSettingPath = ""; - AzFramework::StringFunc::Path::Join(engineRoot, "Gems/ImageProcessing/Code/Source/ImageBuilderDefaultPresets.settings", defaultSettingPath); - outcome = LoadBuilderSettings(defaultSettingPath); - } - } - - return outcome; - } - - StringOutcome BuilderSettingManager::LoadBuilderSettings(AZStd::string filepath, AZ::SerializeContext* context) - { - // Ensure filepath exists. - AZ::IO::FileIOBase* fileReader = AZ::IO::FileIOBase::GetInstance(); - if(false == fileReader->Exists(filepath.c_str())) - { - return AZ::Failure(AZStd::string::format("Build settings file not found: %s", filepath.c_str())); - } - - AZ::IO::HandleType settingsFileHandle; - m_builderSettingsFileVersion = 0; - if (fileReader->Open(filepath.c_str(), AZ::IO::OpenMode::ModeRead | AZ::IO::OpenMode::ModeBinary, settingsFileHandle) == AZ::IO::ResultCode::Success) - { - // Read the contents of the file and hash it. The first u32 of the result of this will be used as a version - // number. Any changes to the builder settings file will then cause all textures to be reconverted to pick - // up that change. - AZStd::string settingsFileBuffer; - AZ::u64 settingsFileSize = 0; - fileReader->Size(settingsFileHandle, settingsFileSize); - settingsFileBuffer.resize_no_construct(settingsFileSize); - fileReader->Read(settingsFileHandle, settingsFileBuffer.data(), settingsFileSize); - fileReader->Close(settingsFileHandle); - - AZ::Sha1 block; - AZ::u32 hashDigest[5]; - block.ProcessBytes(settingsFileBuffer.data(), settingsFileSize); - block.GetDigest(hashDigest); - m_builderSettingsFileVersion = hashDigest[0]; - } - - auto loadedSettingsPtr = AZStd::unique_ptr(AZ::Utils::LoadObjectFromFile(filepath, context)); - - // Ensure file is loaded. - if (!loadedSettingsPtr) - { - return AZ::Failure(AZStd::string::format("Failed to read from file: %s", filepath.c_str())); - } - - m_presetMapLock.lock(); - // Normally, we would perform a deep-copy from the loaded settings onto 'this' via assignment operator overload. However, we have deleted our - // assignment operator overloads, because we intend for this class to be a singleton. Instead, we will manually perform a deep-copy - // in this function since it's the only time we require something akin to assignment operation. - m_builderSettings = loadedSettingsPtr->m_builderSettings; - m_presetAliases = loadedSettingsPtr->m_presetAliases; - m_defaultPresetByFileMask = loadedSettingsPtr->m_defaultPresetByFileMask; - m_defaultPreset = loadedSettingsPtr->m_defaultPreset; - m_defaultPresetAlpha = loadedSettingsPtr->m_defaultPresetAlpha; - m_defaultPresetNonePOT = loadedSettingsPtr->m_defaultPresetNonePOT; - - m_presetFilterMap.clear(); - - //enable builder settings for enabled restricted platforms. These settings should be disabled by default in the setting file -#if defined(AZ_TOOLS_EXPAND_FOR_RESTRICTED_PLATFORMS) -#define AZ_RESTRICTED_PLATFORM_EXPANSION(CodeName, CODENAME, codename, PrivateName, PRIVATENAME, privatename, PublicName, PUBLICNAME, publicname, PublicAuxName1, PublicAuxName2, PublicAuxName3)\ - for (auto& buildSetting : m_builderSettings)\ - {\ - if (ImageProcess##PrivateName::DoesSupport(buildSetting.first))\ - {\ - buildSetting.second.m_enablePlatform = true;\ - break;\ - }\ - } - AZ_TOOLS_EXPAND_FOR_RESTRICTED_PLATFORMS -#undef AZ_RESTRICTED_PLATFORM_EXPANSION -#endif //AZ_TOOLS_EXPAND_FOR_RESTRICTED_PLATFORMS - - //convert pixel format string to enum for each preset - for (auto& buildSetting : m_builderSettings) - { - for (auto& preset : buildSetting.second.m_presets) - { - preset.second.m_pixelFormat = CPixelFormats::GetInstance().FindPixelFormatByName(preset.second.m_pixelFormatName.c_str()); - preset.second.m_pixelFormatAlpha = CPixelFormats::GetInstance().FindPixelFormatByName(preset.second.m_pixelFormatAlphaName.c_str()); - } - } - m_presetMapLock.unlock(); - - RegenerateMappings(); - - return AZ::Success(AZStd::string()); - } - - StringOutcome BuilderSettingManager::WriteBuilderSettings(AZStd::string filepath, AZ::SerializeContext* context) - { - if( false == AZ::Utils::SaveObjectToFile(filepath, AZ::DataStream::StreamType::ST_XML, this, context)) - { - return STRING_OUTCOME_ERROR(AZStd::string::format("Failed to write file: %s", filepath.c_str())); - } - return STRING_OUTCOME_SUCCESS; - } - - const PresetName BuilderSettingManager::TranslateLegacyPresetName(const PresetName& legacyName) - { - auto iterResult = m_presetAliases.find(legacyName); - - if (iterResult == m_presetAliases.end()) - { - return legacyName; - } - - return iterResult->second; - } - - StringOutcome BuilderSettingManager::LoadBuilderSettingsFromRC(AZStd::string& filePath) - { - //Clear previous settings first - ClearSettings(); - - // Find all the platforms - auto outcome = GetPlatformNamesFromRC(filePath); - AZ_ENSURE_STRING_OUTCOME(outcome); - PlatformNameVector all_platforms = outcome.TakeValue(); - - m_presetMapLock.lock(); - // Register all the platforms with empty settings. - for (const AZStd::string& platformName : all_platforms) - { - auto newEntry = AZStd::pair(platformName, BuilderSettings()); - m_builderSettings.insert(newEntry); - } - - // Open settings for parsing - QSettings set(filePath.c_str(), QSettings::IniFormat); - - // Load the preset alias mapping - LoadPresetAliasFromRC(set, m_presetAliases); - - QStringList childGroups = set.childGroups(); - QStringList exemptGroups; - exemptGroups.append("_platform"); - exemptGroups.append("_presetAliases"); - - // We must generate new preset settings and UUID's prior to parsing the rest of the data, because - // some preset settings make references to other presets within RC.ini. We must make sure all presets - // are identified, before making references to them via their UUID. - for (QString groupName : childGroups) - { - auto newPresetUuid = AZ::Uuid::CreateRandom(); - PresetSettings newPresetSetting; - newPresetSetting.m_name = groupName.toUtf8().constData(); - newPresetSetting.m_uuid = newPresetUuid; - for (const PlatformName& platform : all_platforms) - { - m_builderSettings[platform].m_presets.insert(AZStd::make_pair(newPresetUuid, newPresetSetting)); - } - } - m_presetMapLock.unlock(); - - // Apply preset settings from file to the existing presets (process each platform). - for(QString groupName : childGroups) - { - // Only process Presets from here on out. - if (exemptGroups.contains(groupName)) - { - continue; - } - - auto outcome2 = ProcessPreset(groupName, set, all_platforms); - AZ_ENSURE_STRING_OUTCOME(outcome2); - } - - RegenerateMappings(); - - // The original rc.ini doesn't have the information below. Included here for GetSuggestedPreset() to work properly. - m_defaultPresetByFileMask["_diff"] = GetPresetIdFromName("Albedo"); - m_defaultPresetByFileMask["_spec"] = GetPresetIdFromName("Reflectance"); - m_defaultPresetByFileMask["_refl"] = GetPresetIdFromName("Reflectance"); - m_defaultPresetByFileMask["_ddn"] = GetPresetIdFromName("Normals"); - m_defaultPresetByFileMask["_ddna"] = GetPresetIdFromName("NormalsWithSmoothness"); - m_defaultPresetByFileMask["_cch"] = GetPresetIdFromName("ColorChart"); - m_defaultPresetByFileMask["_cm"] = GetPresetIdFromName("EnvironmentProbeHDR"); - - m_defaultPreset = GetPresetIdFromName("Albedo"); - m_defaultPresetAlpha = GetPresetIdFromName("AlbedoWithGenericAlpha"); - m_defaultPresetNonePOT = GetPresetIdFromName("ReferenceImage"); - - return STRING_OUTCOME_SUCCESS; - } - - AZ::u32 BuilderSettingManager::BuilderSettingsVersion() const - { - return m_builderSettingsFileVersion; - } - - void BuilderSettingManager::RegenerateMappings() - { - AZStd::lock_guard lock(m_presetMapLock); - - AZStd::string noFilter = AZStd::string(); - - m_presetFilterMap.clear(); - - for (auto& builderSettingIter : m_builderSettings) - { - const BuilderSettings& builderSetting = builderSettingIter.second; - for (auto& presetIter : builderSetting.m_presets) - { - //Put into no filter preset list - m_presetFilterMap[noFilter].insert(presetIter.second.m_name); - - //Put into file mask preset list if any - for (const PlatformName& filemask : presetIter.second.m_fileMasks) - { - m_presetFilterMap[filemask].insert(presetIter.second.m_name); - } - } - } - } - - StringOutcome BuilderSettingManager::ProcessPreset(QString& preset, QSettings& rcINI, PlatformNameVector& all_platforms) - { - // Early-out check. We should have the preset available before processing. - QByteArray presetByteArray = preset.toUtf8(); - AZ::Uuid parsingPresetUuid = GetPresetIdFromName(presetByteArray.constData()); - if (parsingPresetUuid.IsNull()) - { - return STRING_OUTCOME_ERROR(AZStd::string::format("Unable to find UUID for preset: %s", presetByteArray.constData())); - } - - rcINI.beginGroup(preset); - QStringList groupKeys = rcINI.allKeys(); - - // Build a list for common & platform-specific settings - QStringList commonPresetSettingKeys; - QStringList platformSpecificPresetSettingKeys; - for (QString key : groupKeys) - { - if (key.contains(":")) - { - platformSpecificPresetSettingKeys.append(key); - } - else - { - commonPresetSettingKeys.append(key); - } - } - - // Parse the common settings (retain preset name & uuid) - PresetSettings commonPresetSettings; - commonPresetSettings.m_name = presetByteArray.constData(); - commonPresetSettings.m_uuid = parsingPresetUuid; - for (QString settingKey : commonPresetSettingKeys) - { - AZ_ENSURE_STRING_OUTCOME(ParseKeyToData(settingKey, rcINI, commonPresetSettings)); - } - - // When loading a preset, the UUID is the same per-preset, regardless of the target-platform. - for (AZStd::string& platformId : all_platforms) - { - // Begin platform-specific settings loading with a copy of common Preset settings. - PresetSettings currentPlatformPresetSetting = commonPresetSettings; - - // Obtain platform-specific settings - QString platformFilter = QString(":%1").arg(platformId.c_str()); // Example results-> ":ios", ":osx", ":es3" - QStringList currentPlatformSettings = platformSpecificPresetSettingKeys.filter(platformFilter); - - // Overwrite values for platform-specific settings... - for (QString platformSetting : currentPlatformSettings) - { - AZ_ENSURE_STRING_OUTCOME(ParseKeyToData(platformSetting, rcINI, currentPlatformPresetSetting)); - } - - // Assign the overridden platform preset settings to the BuilderSettingManager. - m_builderSettings[platformId].m_presets[parsingPresetUuid] = currentPlatformPresetSetting; - } - - rcINI.endGroup(); - return STRING_OUTCOME_SUCCESS; - } - - void BuilderSettingManager::MetafilePathFromImagePath(const AZStd::string& imagePath, AZStd::string& metafilePath) - { - // Determine if we have a meta file (legacy or modern). - AZ::IO::LocalFileIO fileIO; - - AZStd::string modernMetaFilepath = imagePath + TextureSettings::modernExtensionName; - if (fileIO.Exists(modernMetaFilepath.c_str())) - { - metafilePath = modernMetaFilepath; - return; - } - - AZStd::string legacyMetaFilepath = imagePath + TextureSettings::legacyExtensionName; - if (fileIO.Exists(legacyMetaFilepath.c_str())) - { - metafilePath = legacyMetaFilepath; - return; - } - - // We found neither. - metafilePath = AZStd::string(); - } - - AZStd::string GetFileMask(const AZStd::string& imageFilePath) - { - //get file name - AZStd::string fileName; - QString lowerFileName = imageFilePath.c_str(); - lowerFileName = lowerFileName.toLower(); - AzFramework::StringFunc::Path::GetFileName(lowerFileName.toUtf8().constData(), fileName); - - //get the substring from last '_' - size_t lastUnderScore = fileName.find_last_of('_'); - if (lastUnderScore != AZStd::string::npos) - { - return fileName.substr(lastUnderScore); - } - - return AZStd::string(); - } - - AZ::Uuid BuilderSettingManager::GetSuggestedPreset(const AZStd::string& imageFilePath, IImageObjectPtr imageFromFile) - { - //load the image to get its size for later use - IImageObjectPtr image = imageFromFile; - //if the input image is empty we will try to load it from the path - if (imageFromFile == nullptr) - { - image = IImageObjectPtr(LoadImageFromFile(imageFilePath)); - } - - if (image == nullptr) - { - AZ_Error("Image Processing", image, "Cannot load image file [%s]. Invalid image format or corrupt data. Note that \"Indexed Color\" is not currently supported for .tga files.", imageFilePath.c_str()); - return AZ::Uuid::CreateNull(); - } - - //get file mask of this image file - AZStd::string fileMask = GetFileMask(imageFilePath); - - AZ::Uuid outPreset = AZ::Uuid::CreateNull(); - - if ("_diff" == fileMask && image->GetAlphaContent() != EAlphaContent::eAlphaContent_Absent) - { - outPreset = m_defaultPresetAlpha; - } - else - { - //check default presets for some file masks - if (m_defaultPresetByFileMask.find(fileMask) != m_defaultPresetByFileMask.end()) - { - outPreset = m_defaultPresetByFileMask[fileMask]; - } - } - - //use the preset filter map to find - if (outPreset.IsNull() && !fileMask.empty()) - { - auto& presetFilterMap = GetPresetFilterMap(); - if (presetFilterMap.find(fileMask) != presetFilterMap.end()) - { - AZStd::string presetName = *(presetFilterMap.find(fileMask)->second.begin()); - outPreset = GetPresetIdFromName(presetName); - } - } - - const PresetSettings* presetInfo = nullptr; - - if (!outPreset.IsNull()) - { - presetInfo = GetPreset(outPreset); - - //special case for cubemap - if (presetInfo && presetInfo->m_cubemapSetting) - { - if (CubemapLayout::GetCubemapLayoutInfo(image) == nullptr) - { - outPreset = AZ::Uuid::CreateNull(); - } - } - } - - if (outPreset.IsNull()) - { - if (!image->HasPowerOfTwoSizes()) - { - // The resource compiler used the non power of 2 preset if the width or the height is not power of 2 - // even if it would have been possible to compress the image, so this behavior is matched here. - return m_defaultPresetNonePOT; - } - else if (image->GetAlphaContent() == EAlphaContent::eAlphaContent_Absent) - { - outPreset = m_defaultPreset; - } - else - { - outPreset = m_defaultPresetAlpha; - } - } - - //get the pixel format for selected preset - presetInfo = GetPreset(outPreset); - - if (presetInfo) - { - //valid whether image size work with pixel format - if (CPixelFormats::GetInstance().IsImageSizeValid(presetInfo->m_pixelFormat, - image->GetWidth(0), image->GetHeight(0), false)) - { - return outPreset; - } - } - - //uncompressed one which could be used for almost everything - return m_defaultPresetNonePOT; - } - - bool BuilderSettingManager::DoesSupportPlatform(const AZStd::string& platformId) - { - bool rv = m_builderSettings.find(platformId) != m_builderSettings.end(); - return rv; - } - -} // namespace ImageProcessing diff --git a/Gems/ImageProcessing/Code/Source/BuilderSettings/BuilderSettingManager.h b/Gems/ImageProcessing/Code/Source/BuilderSettings/BuilderSettingManager.h deleted file mode 100644 index c6d03eae54..0000000000 --- a/Gems/ImageProcessing/Code/Source/BuilderSettings/BuilderSettingManager.h +++ /dev/null @@ -1,192 +0,0 @@ -/* -* All or portions of this file Copyright(c) Amazon.com, Inc.or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -*or, if provided, by the license below or the license accompanying this file. Do not -* remove or 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 - -class QSettings; -class QString; - -namespace AZ -{ - template class EnvironmentVariable; - class SerializeContext; -} - -namespace ImageProcessing -{ - class BuilderSettingManager - { - public: - AZ_TYPE_INFO(CBuilderSettingManager, "{DAA55241-64FA-4A9B-A37F-C0A36B36D536}"); - AZ_CLASS_ALLOCATOR(BuilderSettingManager, AZ::SystemAllocator, 0); - //load builder settings for all platform - //contain builder setting for all platforms - //this manager should be able to get texture setting for a platform - - - static BuilderSettingManager* Instance(); - // life cycle management: - static void CreateInstance(); - static void DestroyInstance(); - static void Reflect(AZ::ReflectContext* context); - - const PresetSettings* GetPreset(const AZ::Uuid presetId, const PlatformName& platform = ""); - - const BuilderSettings* GetBuilderSetting(const PlatformName& platform); - - /** - * Attempts to translate a legacy preset name into Open 3D Engine preset name. - * @param legacy preset name string - * @return A translated preset name. If no translation is available, returns the same value as input argument. - */ - const PresetName TranslateLegacyPresetName(const PresetName& legacyName); - - /** - * @return A list of platform supported - */ - const PlatformNameList GetPlatformList(); - - /** - * @return A map of preset settings based on their filemasks. - * @key filemask string, empty string means no filemask - * @value set of preset setting names supporting the specified filemask - */ - const AZStd::map>& GetPresetFilterMap(); - - /** - * Find preset id list based on the preset name. - * @param preset name string - * @return a map of preset ids whose name are specified by the input on different platforms - * @key platform name string - * @value uuid of the preset setting - */ - const AZ::Uuid GetPresetIdFromName(const PresetName& presetName); - - /** - * Find preset name based on the preset id. - * @param uuid of the preset setting - * @return preset name string - */ - const PresetName GetPresetNameFromId(const AZ::Uuid& presetId); - - /** - * Writes preset data to file using AZ::Serialization format. - * @param filepath string to the build settings xml - */ - StringOutcome WriteBuilderSettings(AZStd::string filepath, AZ::SerializeContext* context = nullptr); - - /** - * Loads preset data from file using AZ::Serialization format. - * @param filepath string to the build settings xml - */ - StringOutcome LoadBuilderSettings(AZStd::string filepath, AZ::SerializeContext* context = nullptr); - - /** - * Overload function. Loads preset data from project setting file if any - * Otherwise, the function will load default setting file inside the gem - */ - StringOutcome LoadBuilderSettings(); - - /** - * Loads preset data from legacy format found in RC.ini. - * @param filepath string to RC.ini - */ - StringOutcome LoadBuilderSettingsFromRC(AZStd::string& filePath); - - /** - * Returns the first u32 generated from a hash of the builder settings - * file that can be used as a version to detect changes to the file. - */ - AZ::u32 BuilderSettingsVersion() const; - - /** - * Provides a full path to the adjacent metafile of a given texture/image file. - * @param Filepath string to the texture/image file. - * @param Output filepath string to the adjacent texture/image metafile. - * Will output whichever metafile is present, whether it is legacy or modern format. - * If both are present, modern format is returned. - * If none are present, an empty string is returned. - */ - void MetafilePathFromImagePath(const AZStd::string& imagePath, AZStd::string& metafilePath); - - /** - * Find a suitable preset a given image file. - * @param imageFilePath: Filepath string of the image file. The function may load the image from the path for better detection - * @param image: an optional image object which can be used for preset selection if there is no match based file mask. - * @return suggested preset uuid. - */ - AZ::Uuid GetSuggestedPreset(const AZStd::string& imageFilePath, IImageObjectPtr image = nullptr); - - bool DoesSupportPlatform(const AZStd::string& platformId); - - static const char* s_environmentVariableName; - static AZ::EnvironmentVariable s_globalInstance; - static AZStd::mutex s_instanceMutex; - static const PlatformName s_defaultPlatform; - - BuilderSettingManager(){} - - private: // functions - AZ_DISABLE_COPY_MOVE(BuilderSettingManager); - - StringOutcome ProcessPreset(QString& preset, QSettings& rcINI, PlatformNameVector& all_platforms); - - /** - * Clear Builder Settings and any cached maps/lists - */ - void ClearSettings(); - - /** - * Regenerate Builder Settings and any cached maps/lists - */ - void RegenerateMappings(); - - private: // variables - - //builder settings for each platform - AZStd::map m_builderSettings; - AZStd::map m_presetAliases; - - /** - * Cached list of presets mapped by their file masks. - * @Key file mask, use empty string to indicate all presets without filtering - * @Value set of preset names that matches the file mask - */ - AZStd::map > m_presetFilterMap; - - /** - * A mutex to protect when modifying any map in this manager - */ - AZStd::mutex m_presetMapLock; - - //default presets for certian file masks - AZStd::map m_defaultPresetByFileMask; - - //default preset for none power of two image - AZ::Uuid m_defaultPresetNonePOT; - - //default preset for power of two - AZ::Uuid m_defaultPreset; - - //default preset for power of two with alpha - AZ::Uuid m_defaultPresetAlpha; - - //generated from hashing the builder settings file - AZ::u32 m_builderSettingsFileVersion; - }; -} // namespace ImageProcessing diff --git a/Gems/ImageProcessing/Code/Source/BuilderSettings/BuilderSettings.cpp b/Gems/ImageProcessing/Code/Source/BuilderSettings/BuilderSettings.cpp deleted file mode 100644 index 6f68ea7581..0000000000 --- a/Gems/ImageProcessing/Code/Source/BuilderSettings/BuilderSettings.cpp +++ /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. -* -*/ -#include "ImageProcessing_precompiled.h" -#include -#include - -namespace ImageProcessing -{ - void BuilderSettings::Reflect(AZ::ReflectContext* context) - { - AZ::SerializeContext* serialize = azrtti_cast(context); - if (serialize) - { - serialize->Class() - ->Version(1) - ->Field("GlossScale", &BuilderSettings::m_brdfGlossScale) - ->Field("GlossBias", &BuilderSettings::m_brdfGlossBias) - ->Field("Streaming", &BuilderSettings::m_enableStreaming) - ->Field("Enable", &BuilderSettings::m_enablePlatform) - ->Field("Presets", &BuilderSettings::m_presets); - } - } -} // namespace ImageProcessing diff --git a/Gems/ImageProcessing/Code/Source/BuilderSettings/CubemapSettings.cpp b/Gems/ImageProcessing/Code/Source/BuilderSettings/CubemapSettings.cpp deleted file mode 100644 index 43f2a50535..0000000000 --- a/Gems/ImageProcessing/Code/Source/BuilderSettings/CubemapSettings.cpp +++ /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. -* -*/ - -#include "ImageProcessing_precompiled.h" -#include -#include - -namespace ImageProcessing -{ - - bool CubemapSettings::operator!=(const CubemapSettings& other) - { - return !(*this == other); - } - - bool CubemapSettings::operator==(const CubemapSettings& other) - { - return - m_angle == other.m_angle && - m_mipAngle == other.m_mipAngle && - m_mipSlope == other.m_mipSlope && - m_edgeFixup == other.m_edgeFixup && - m_generateDiff == other.m_generateDiff && - m_diffuseGenPreset == other.m_diffuseGenPreset; - } - - void CubemapSettings::Reflect(AZ::ReflectContext* context) - { - AZ::SerializeContext* serialize = azrtti_cast(context); - if (serialize) - { - serialize->Class() - ->Version(1) - ->Field("Filter", &CubemapSettings::m_filter) - ->Field("Angle", &CubemapSettings::m_angle) - ->Field("MipAngle", &CubemapSettings::m_mipAngle) - ->Field("MipSlope", &CubemapSettings::m_mipSlope) - ->Field("EdgeFixup", &CubemapSettings::m_edgeFixup) - ->Field("GenerateDiff", &CubemapSettings::m_generateDiff) - ->Field("DiffuseProbePreset", &CubemapSettings::m_diffuseGenPreset); - } - } -} // namespace ImageProcessing diff --git a/Gems/ImageProcessing/Code/Source/BuilderSettings/CubemapSettings.h b/Gems/ImageProcessing/Code/Source/BuilderSettings/CubemapSettings.h deleted file mode 100644 index edfdde8cbe..0000000000 --- a/Gems/ImageProcessing/Code/Source/BuilderSettings/CubemapSettings.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. -* -*/ - -#pragma once - -#include -#include -#include -#include - -namespace ImageProcessing -{ - //! settings related to cubemap. Part of texture preset setting. only useful when cubemap enabled - struct CubemapSettings - { - AZ_TYPE_INFO(CubemapSettings, "{C6BDEB7B-8E05-4B2D-8F39-8F6275BC84E8}"); - AZ_CLASS_ALLOCATOR(CubemapSettings, AZ::SystemAllocator, 0); - bool operator!=(const CubemapSettings& other); - bool operator==(const CubemapSettings& other); - static void Reflect(AZ::ReflectContext* context); - - // "cm_ftype", cubemap angular filter type: gaussian, cone, disc, cosine, cosine_power, ggx - CubemapFilterType m_filter; - - // "cm_fangle", base filter angle for cubemap filtering(degrees), 0 - disabled - float m_angle; - - // "cm_fmipangle", initial mip filter angle for cubemap filtering(degrees), 0 - disabled - float m_mipAngle; - - // "cm_fmipslope", mip filter angle multiplier for cubemap filtering, 1 - default" - float m_mipSlope; - - // "cm_edgefixup", cubemap edge fix-up width, 0 - disabled - float m_edgeFixup; - - // "cm_diff", generate a diffuse illumination light-probe in addition - bool m_generateDiff; - - // "cm_diffpreset", the name of the preset to be used for the diffuse probe - AZ::Uuid m_diffuseGenPreset; - }; -} // namespace ImageProcessing diff --git a/Gems/ImageProcessing/Code/Source/BuilderSettings/ImageProcessingDefines.h b/Gems/ImageProcessing/Code/Source/BuilderSettings/ImageProcessingDefines.h deleted file mode 100644 index c9fa860240..0000000000 --- a/Gems/ImageProcessing/Code/Source/BuilderSettings/ImageProcessingDefines.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. -* -*/ - -#pragma once - -#include -#include -#include -#include -#include -#include - -/** -* Shorthand for checking a condition, and failing if false. -* Works with any function that returns AZ::Outcome<..., AZStd::string>. -* Unlike assert, it is not removed in release builds. -* Ensure all strings are passed with c_str(), as they are passed to AZStd::string::format(). -*/ -#define AZ_ENSURE_STRING_OUTCOME_CONDITION(cond, ...) if (!(cond)) { return AZ::Failure(AZStd::string::format(__VA_ARGS__)); } - -// Similar to above macro, but ensures on an AZ::Outcome. Not removed in release builds. -#define AZ_ENSURE_STRING_OUTCOME(outcome) if (!(outcome.IsSuccess())) { return AZ::Failure(outcome.GetError()); } - -namespace ImageProcessing -{ - //! Common return type for operations that can fail. - // Empty success string == Success. - // Populated success string == Warning. - // Populated error string == Failure. - using StringOutcome = AZ::Outcome; -#define STRING_OUTCOME_SUCCESS AZ::Success(AZStd::string()) -#define STRING_OUTCOME_WARNING(warning) AZ::Success(AZStd::string(warning)) -#define STRING_OUTCOME_ERROR(error) AZ::Failure(AZStd::string(error)) - - // Common typedefs (with dependent forward-declarations) - typedef AZStd::string PlatformName, PresetName, FileMask; - typedef AZStd::vector PlatformNameVector; - typedef AZStd::list PlatformNameList; - - //! min and max reduce level - static const unsigned int s_MinReduceLevel = 0; - static const unsigned int s_MaxReduceLevel = 5; - - static const int s_TotalSupportedImageExtensions = 8; - static const char* s_SupportedImageExtensions[s_TotalSupportedImageExtensions] = { - "*.tif", - "*.tiff", - "*.png", - "*.bmp", - "*.jpg", - "*.jpeg", - "*.tga", - "*.gif" - }; - - enum class RGBWeight : AZ::u32 - { - uniform, // uniform weights (1.0, 1.0, 1.0) (default) - luminance, // luminance-based weights (0.3086, 0.6094, 0.0820) - ciexyz // ciexyz-based weights (0.2126, 0.7152, 0.0722) - }; - - enum class ColorSpace : AZ::u32 - { - linear, - sRGB, - autoSelect, - }; - - enum class MipGenType : AZ::u32 - { - point, //Also called nearest neighbor - box, //Also called 'average'. When shrinking images it will average, and merge the pixels together. - triangle, //Also called linear or Bartlett window - quadratic, //Also called bilinear or Welch window - gaussian, //It remove high frequency noise in a highly controllable way. - blackmanHarris, - kaiserSinc //Good for foliage and tree assets exported from Speedtree. - }; - - enum class MipGenEvalType : AZ::u32 - { - sum, - max, - min - }; - - //cubemap angular filter type. Only two filter types were used in rc.ini - enum class CubemapFilterType : AZ::u32 - { - disc = 0, // same as CP_FILTER_TYPE_DISC in CubemapGen - cone = 1, // same as CP_FILTER_TYPE_CONE - cosine = 2, // same as CP_FILTER_TYPE_COSINE. only used for [EnvironmentProbeHDR_Irradiance] - gaussian = 3, // same as CP_FILTER_TYPE_ANGULAR_GAUSSIAN - cosine_power = 4, // same as CP_FILTER_TYPE_COSINE_POWER - ggx = 5 // same as CP_FILTER_TYPE_GGX. only used for [EnvironmentProbeHDR] - }; - -} // namespace ImageProcessing diff --git a/Gems/ImageProcessing/Code/Source/BuilderSettings/MipmapSettings.cpp b/Gems/ImageProcessing/Code/Source/BuilderSettings/MipmapSettings.cpp deleted file mode 100644 index 0285404f50..0000000000 --- a/Gems/ImageProcessing/Code/Source/BuilderSettings/MipmapSettings.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 "ImageProcessing_precompiled.h" -#include -#include -#include - -namespace ImageProcessing -{ - bool MipmapSettings::operator!=(const MipmapSettings& other) const - { - return !(*this == other); - } - - bool MipmapSettings::operator==(const MipmapSettings& other) const - { - return - m_type == other.m_type && - m_borderColor == other.m_borderColor && - m_normalize == other.m_normalize && - m_streamableMips == other.m_streamableMips; - } - - void MipmapSettings::Reflect(AZ::ReflectContext* context) - { - AZ::SerializeContext* serialize = azrtti_cast(context); - if (serialize) - { - serialize->Class() - ->Version(1) - ->Field("MipGenType", &MipmapSettings::m_type) - ->Field("BorderColor", &MipmapSettings::m_borderColor) - ->Field("Normalize", &MipmapSettings::m_normalize) - ->Field("StreamableMips", &MipmapSettings::m_streamableMips); - - AZ::EditContext* editContext = serialize->GetEditContext(); - if (editContext) - { - editContext->Class("Mipmap Setting", "") - ->DataElement(AZ::Edit::UIHandlers::ComboBox, &MipmapSettings::m_type, "Type", "") - ->EnumAttribute(MipGenType::point, "Point") - ->EnumAttribute(MipGenType::box, "Average") - ->EnumAttribute(MipGenType::triangle, "Linear") - ->EnumAttribute(MipGenType::quadratic, "Bilinear") - ->EnumAttribute(MipGenType::gaussian, "Gaussian") - ->EnumAttribute(MipGenType::blackmanHarris, "BlackmanHarris") - ->EnumAttribute(MipGenType::kaiserSinc, "KaiserSinc") - ->DataElement(AZ::Edit::UIHandlers::Color, &MipmapSettings::m_borderColor, "Color", "") - ->DataElement(AZ::Edit::UIHandlers::CheckBox, &MipmapSettings::m_normalize, "Normalized", "") - ->DataElement(AZ::Edit::UIHandlers::SpinBox, &MipmapSettings::m_streamableMips, "Streamable Mips", "") - ->Attribute(AZ::Edit::Attributes::Min, 0) - ; - } - } - } -} // namespace ImageProcessing diff --git a/Gems/ImageProcessing/Code/Source/BuilderSettings/MipmapSettings.h b/Gems/ImageProcessing/Code/Source/BuilderSettings/MipmapSettings.h deleted file mode 100644 index 4a2864d2b7..0000000000 --- a/Gems/ImageProcessing/Code/Source/BuilderSettings/MipmapSettings.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. -* -*/ - -#pragma once - -#include -#include -#include -#include -#include - -namespace ImageProcessing -{ - struct MipmapSettings - { - AZ_TYPE_INFO(MipmapSettings, "{9239618E-23A6-43C8-9B87-50528CBFA6FF}"); - AZ_CLASS_ALLOCATOR(MipmapSettings, AZ::SystemAllocator, 0); - bool operator!=(const MipmapSettings& other) const; - bool operator==(const MipmapSettings& other) const; - - static void Reflect(AZ::ReflectContext* context); - - MipGenType m_type = MipGenType::blackmanHarris; - - //Unused or duplicated properties. We may want to move same properties from perset setting to here. - AZ::Color m_borderColor; - bool m_normalize; - AZ::u32 m_streamableMips; - }; -} // namespace ImageProcessing diff --git a/Gems/ImageProcessing/Code/Source/BuilderSettings/PlatformSettings.h b/Gems/ImageProcessing/Code/Source/BuilderSettings/PlatformSettings.h deleted file mode 100644 index 5cfc7757b2..0000000000 --- a/Gems/ImageProcessing/Code/Source/BuilderSettings/PlatformSettings.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 -#include -#include - -namespace ImageProcessing -{ - //! default settings for platform - struct PlatformSetting - { - AZ_TYPE_INFO(PlatformSetting, "{19EF828B-DDFF-4591-AD5A-946801FCC98E}"); - AZ_CLASS_ALLOCATOR(PlatformSetting, AZ::SystemAllocator, 0); - - //! Platform's name - PlatformName m_name; - - //! pixel formats supported for the platform - AZStd::list m_availableFormat; - }; -} // namespace ImageProcessing diff --git a/Gems/ImageProcessing/Code/Source/BuilderSettings/PresetSettings.cpp b/Gems/ImageProcessing/Code/Source/BuilderSettings/PresetSettings.cpp deleted file mode 100644 index 8f904058d3..0000000000 --- a/Gems/ImageProcessing/Code/Source/BuilderSettings/PresetSettings.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. -* -*/ - -#include "ImageProcessing_precompiled.h" -#include -#include - -namespace ImageProcessing -{ - PresetSettings::PresetSettings() - : m_uuid(0) - , m_rgbWeight(RGBWeight::uniform) - , m_srcColorSpace(ColorSpace::sRGB) - , m_destColorSpace(ColorSpace::autoSelect) - , m_suppressEngineReduce(false) - , m_pixelFormat(ePixelFormat_R8G8B8A8) - , m_pixelFormatName("R8G8B8A8") - , m_pixelFormatAlpha(ePixelFormat_Unknown) - , m_pixelFormatAlphaName("") - , m_discardAlpha(false) - , m_maxTextureSize(0) - , m_minTextureSize(0) - , m_isPowerOf2(false) - , m_sizeReduceLevel(0) - , m_isColorChart(0) - , m_highPassMip(0) - , m_glossFromNormals(false) - , m_isMipRenormalize(false) - , m_numStreamableMips(100) - , m_isLegacyGloss(false) - { - - } - - PresetSettings::PresetSettings(const PresetSettings& other) - { - DeepCopyMembers(other); - } - - void PresetSettings::Reflect(AZ::ReflectContext* context) - { - AZ::SerializeContext* serialize = azrtti_cast(context); - if (serialize) - { - serialize->Class() - ->Version(1) - ->Field("UUID", &PresetSettings::m_uuid) - ->Field("Name", &PresetSettings::m_name) - ->Field("Description", &PresetSettings::m_description) - ->Field("RGB_Weight", &PresetSettings::m_rgbWeight) - ->Field("SourceColor", &PresetSettings::m_srcColorSpace) - ->Field("DestColor", &PresetSettings::m_destColorSpace) - ->Field("FileMasks", &PresetSettings::m_fileMasks) - ->Field("SuppressEngineReduce", &PresetSettings::m_suppressEngineReduce) - ->Field("PixelFormat", &PresetSettings::m_pixelFormatName) - ->Field("PixelFormatAlpha", &PresetSettings::m_pixelFormatAlphaName) - ->Field("DiscardAlpha", &PresetSettings::m_discardAlpha) - ->Field("MaxTextureSize", &PresetSettings::m_maxTextureSize) - ->Field("MinTextureSize", &PresetSettings::m_minTextureSize) - ->Field("IsPowerOf2", &PresetSettings::m_isPowerOf2) - ->Field("SizeReduceLevel", &PresetSettings::m_sizeReduceLevel) - ->Field("IsColorChart", &PresetSettings::m_isColorChart) - ->Field("HighPassMip", &PresetSettings::m_highPassMip) - ->Field("GlossFromNormal", &PresetSettings::m_glossFromNormals) - ->Field("UseLegacyGloss", &PresetSettings::m_isLegacyGloss) - ->Field("MipRenormalize", &PresetSettings::m_isMipRenormalize) - ->Field("NumberStreamableMips", &PresetSettings::m_numStreamableMips) - ->Field("Swizzle", &PresetSettings::m_swizzle) - ->Field("CubemapSettings", &PresetSettings::m_cubemapSetting) - ->Field("MipMapSetting", &PresetSettings::m_mipmapSetting); - } - } - - PresetSettings& PresetSettings::operator= (const PresetSettings& other) - { - DeepCopyMembers(other); - return *this; - } - - bool PresetSettings::operator==(const PresetSettings& other) const - { - bool arePointersEqual = true; - - /////// - // MipMap Settings - ////// - // If both pointers are allocated... - if (m_mipmapSetting && other.m_mipmapSetting) - { - // If the allocated values are different... - if (*m_mipmapSetting != *other.m_mipmapSetting) - { - arePointersEqual = false; - } - } - // Otherwise, one or both pointers are un-allocated. - // If only one pointer is allocated (via unequivalency)... - else if (m_mipmapSetting != other.m_mipmapSetting) - { - arePointersEqual = false; - } - /////// - // CubeMap Settings - ////// - // If both pointers are allocated... - if (m_cubemapSetting && other.m_cubemapSetting) - { - // If the allocated values are different... - if (*m_cubemapSetting != *other.m_cubemapSetting) - { - arePointersEqual = false; - } - } - // Otherwise, one or both pointers are un-allocated. - // If only one pointer is allocated (via unequivalency)... - else if (m_cubemapSetting != other.m_cubemapSetting) - { - arePointersEqual = false; - } - return - arePointersEqual && - m_uuid == other.m_uuid && - m_name == other.m_name && - m_description == other.m_description && - m_rgbWeight == other.m_rgbWeight && - m_srcColorSpace == other.m_srcColorSpace && - m_destColorSpace == other.m_destColorSpace && - m_fileMasks == other.m_fileMasks && - m_suppressEngineReduce == other.m_suppressEngineReduce && - m_pixelFormat == other.m_pixelFormat && - m_pixelFormatName == other.m_pixelFormatName && - m_pixelFormatAlpha == other.m_pixelFormatAlpha && - m_pixelFormatAlphaName == other.m_pixelFormatAlphaName && - m_discardAlpha == other.m_discardAlpha && - m_minTextureSize == other.m_minTextureSize && - m_maxTextureSize == other.m_maxTextureSize && - m_isPowerOf2 == other.m_isPowerOf2 && - m_sizeReduceLevel == other.m_sizeReduceLevel && - m_isColorChart == other.m_isColorChart && - m_highPassMip == other.m_highPassMip && - m_glossFromNormals == other.m_glossFromNormals && - m_isLegacyGloss == other.m_isLegacyGloss && - m_swizzle == other.m_swizzle && - m_isMipRenormalize == other.m_isMipRenormalize && - m_numStreamableMips == other.m_numStreamableMips; - } - - void PresetSettings::DeepCopyMembers(const PresetSettings & other) - { - if (this != &other) - { - if(other.m_mipmapSetting) - { - m_mipmapSetting = AZStd::make_unique(*other.m_mipmapSetting); - } - - if(other.m_cubemapSetting) - { - m_cubemapSetting = AZStd::make_unique(*other.m_cubemapSetting); - } - - m_uuid = other.m_uuid; - m_name = other.m_name; - m_description = other.m_description; - m_rgbWeight = other.m_rgbWeight; - m_srcColorSpace = other.m_srcColorSpace; - m_destColorSpace = other.m_destColorSpace; - m_fileMasks = other.m_fileMasks; - m_suppressEngineReduce = other.m_suppressEngineReduce; - m_pixelFormat = other.m_pixelFormat; - m_pixelFormatAlpha = other.m_pixelFormatAlpha; - m_pixelFormatName = other.m_pixelFormatName; - m_pixelFormatAlphaName = other.m_pixelFormatAlphaName; - m_discardAlpha = other.m_discardAlpha; - m_minTextureSize = other.m_minTextureSize; - m_maxTextureSize = other.m_maxTextureSize; - m_isPowerOf2 = other.m_isPowerOf2; - m_sizeReduceLevel = other.m_sizeReduceLevel; - m_isColorChart = other.m_isColorChart; - m_highPassMip = other.m_highPassMip; - m_glossFromNormals = other.m_glossFromNormals; - m_isLegacyGloss = other.m_isLegacyGloss; - m_swizzle = other.m_swizzle; - m_isMipRenormalize = other.m_isMipRenormalize; - m_numStreamableMips = other.m_numStreamableMips; - } - } - - AZ::Vector3 PresetSettings::GetColorWeight() - { - switch (m_rgbWeight) - { - case RGBWeight::uniform: - return AZ::Vector3(0.3333f, 0.3334f, 0.3333f); - case RGBWeight::ciexyz: - return AZ::Vector3(0.2126f, 0.7152f, 0.0722f); - case RGBWeight::luminance: - return AZ::Vector3(0.3086f, 0.6094f, 0.0820f); - default: - AZ_Assert(false, "color weight value need to be added to new rgbWeight enum"); - return AZ::Vector3(0.3333f, 0.3334f, 0.3333f); - } - } -} // namespace ImageProcessing diff --git a/Gems/ImageProcessing/Code/Source/BuilderSettings/PresetSettings.h b/Gems/ImageProcessing/Code/Source/BuilderSettings/PresetSettings.h deleted file mode 100644 index fa881e853b..0000000000 --- a/Gems/ImageProcessing/Code/Source/BuilderSettings/PresetSettings.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. -* -*/ - -#pragma once - -#include -#include -#include -#include -#include - -namespace ImageProcessing -{ - //settings for texture process preset - class PresetSettings - { - public: - AZ_TYPE_INFO(PresetSettings, "{935BCE3F-9E76-494E-9408-47C5937D7288}"); - AZ_CLASS_ALLOCATOR(PresetSettings, AZ::SystemAllocator, 0); - - PresetSettings(); - PresetSettings(const PresetSettings& other); - PresetSettings& operator= (const PresetSettings& other); - bool operator== (const PresetSettings& other) const; - static void Reflect(AZ::ReflectContext* context); - - //unique id for the preset - AZ::Uuid m_uuid; - - PresetName m_name; - - //a brief description for the usage of this Preset - AZStd::string m_description; - - //misc options - // "rgbweights". specify preset for weighting of R,G,B channels (used by compressor) - RGBWeight m_rgbWeight; - ColorSpace m_srcColorSpace; - ColorSpace m_destColorSpace; - - // file masks used for helping select default preset and option preset list in texture property dialog - AZStd::vector m_fileMasks; - - // "ser". Whether to enable supress reduce resolution (m_sizeReduceLevel) during loading, 0(default) - bool m_suppressEngineReduce; - - //pixel format - EPixelFormat m_pixelFormat; - AZStd::string m_pixelFormatName; - //pixel format for image which only contains alpha channel. this is for if we need to save alpha channel into a seperate image - EPixelFormat m_pixelFormatAlpha; - AZStd::string m_pixelFormatAlphaName; - bool m_discardAlpha; - - // Resolution related settings - - // "maxtexturesize", upper limit of the resolution of generated textures. It should be a power-of-2 number larger than 1 - // resulting texture will be downscaled if its width or height larger than this value - // 0 - no upper resolution limit (default) - unsigned int m_maxTextureSize; - - // "mintexturesize", lower limit of the resolution of generated textures.It should be a power-of-2 number larger than 1 - // resulting texture will be upscaled if its width or height smaller than this value - // 0 - no lower resolution limit (default) - unsigned int m_minTextureSize; - - bool m_isPowerOf2; - - //"reduce", 0=no size reduce /1=half resolution /2=quarter resolution, etc" - unsigned int m_sizeReduceLevel; - - //settings for cubemap generation. it's null if this preset is not for cubemap. - //"cm" equals 1 to enable cubemap in rc.ini - AZStd::unique_ptr m_cubemapSetting; - - //settings for mipmap generation. it's null if this preset disable mipmap. - AZStd::unique_ptr m_mipmapSetting; - - //some specific settings - // "colorchart". This is to indicate if need to extract color chart from the image and output the color chart data. - // This is very specific usage for cryEngine. Check ColorChart.cpp for better explaination. - bool m_isColorChart; - - //"highpass". Defines which mip level is subtracted when applying the high pass filter - //this is only used for terrain asset. we might remove it later since it can be done with source image directly - AZ::u32 m_highPassMip; - - //"glossfromnormals". Bake normal variance into smoothness stored in alpha channel - AZ::u32 m_glossFromNormals; - - //"mipnormalize". need normalize the rgb - bool m_isMipRenormalize; - - //function to get color's rgb weight in vec3 based on m_rgbWeight enum - //this is useful for squisher compression - AZ::Vector3 GetColorWeight(); - - //numstreamablemips - AZ::u32 m_numStreamableMips; - - //legacy options might be removed later - //"glosslegacydist". If the gloss map use legacy distribution. NW is still using legacy dist - bool m_isLegacyGloss; - - //"swizzle". need to be 4 character and each character need to be one of "rgba01" - AZStd::string m_swizzle; - - private: - void DeepCopyMembers(const PresetSettings& other); - }; -} // namespace ImageProcessing diff --git a/Gems/ImageProcessing/Code/Source/BuilderSettings/TextureSettings.cpp b/Gems/ImageProcessing/Code/Source/BuilderSettings/TextureSettings.cpp deleted file mode 100644 index b465ec81f3..0000000000 --- a/Gems/ImageProcessing/Code/Source/BuilderSettings/TextureSettings.cpp +++ /dev/null @@ -1,589 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or 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 "ImageProcessing_precompiled.h" -#include -#include -#include -#include -#include -#include -#include - -#include -#include - - -namespace ImageProcessing -{ - const char* TextureSettings::legacyExtensionName = ".exportsettings"; - const char* TextureSettings::modernExtensionName = ".imagesettings"; - - StringOutcome ParseLegacyTextureSettingString(AZStd::string& key, AZStd::string& value, TextureSettings& textureSettingOut) - { - // Parse only the settings we support for TextureSetting - if ("reduce" == key) // Example: reduce=0 - { - int reduce = AzFramework::StringFunc::ToInt(value.c_str()); - if (reduce >= 0) - { - textureSettingOut.m_sizeReduceLevel = reduce; - } - } - else if ("M" == key) // Example: M=50,50,0,50,50,50 - { - textureSettingOut.m_enableMipmap = true; - - AZStd::vector mipStringValues; - AzFramework::StringFunc::Tokenize(value.c_str(), mipStringValues, ','); - - for (size_t mipIndex = 0; mipIndex < mipStringValues.size(); ++mipIndex) - { - AZ::u32 mipValue = AzFramework::StringFunc::ToInt(mipStringValues[mipIndex].c_str()); - textureSettingOut.m_mipAlphaAdjust[mipIndex] = mipValue; - } - } - else if ("ser" == key) // Example: ser=1 - { - textureSettingOut.m_suppressEngineReduce = (value == "1"); - } - else if ("preset" == key) // Example: preset=NormalsWithSmoothness - { - AZ::Uuid presetUuid = BuilderSettingManager::Instance()->GetPresetIdFromName(value); - - // There's a chance the preset name still adheres to legacy preset naming convention (from CryEngine). - const PresetName translation = BuilderSettingManager::Instance()->TranslateLegacyPresetName(value); - AZ::Uuid translatedPresetUuid = BuilderSettingManager::Instance()->GetPresetIdFromName(translation); - - if (!presetUuid.IsNull()) - { - textureSettingOut.m_preset = presetUuid; - } - else if (!translatedPresetUuid.IsNull()) - { - textureSettingOut.m_preset = translatedPresetUuid; - } - else - { - AZ_Error("Image processing", false, "Can't find preset %s", value.c_str()); - } - } - else if ("mipgentype" == key) // Example: mipgentype=box - { - if ("box" == value || "average" == value) - { - textureSettingOut.m_mipGenType = MipGenType::box; - } - else if ("gauss" == value) - { - textureSettingOut.m_mipGenType = MipGenType::gaussian; - } - else if ("blackman-harris" == value) - { - textureSettingOut.m_mipGenType = MipGenType::blackmanHarris; - } - else if ("kaiser" == value) - { - textureSettingOut.m_mipGenType = MipGenType::kaiserSinc; - } - else if ("point" == value) - { - textureSettingOut.m_mipGenType = MipGenType::point; - } - else if ("quadric" == value) - { - textureSettingOut.m_mipGenType = MipGenType::quadratic; - } - else if ("triangle" == value) - { - textureSettingOut.m_mipGenType = MipGenType::triangle; - } - } - return STRING_OUTCOME_SUCCESS; - } - - TextureSettings::TextureSettings() - : m_preset(0) - , m_sizeReduceLevel(0) - , m_suppressEngineReduce(false) - , m_enableMipmap(true) - , m_maintainAlphaCoverage(false) - , m_mipGenEval(MipGenEvalType::sum) - , m_mipGenType(MipGenType::blackmanHarris) - { - const int defaultMipMapValue = 50; - - for (int i = 0; i < s_MaxMipMaps; ++i) - { - m_mipAlphaAdjust.push_back(defaultMipMapValue); - } - } - - void TextureSettings::Reflect(AZ::ReflectContext* context) - { - AZ::SerializeContext* serialize = azrtti_cast(context); - if (serialize) - { - serialize->Class() - ->Version(1) - ->Field("PresetID", &TextureSettings::m_preset) - ->Field("SizeReduceLevel", &TextureSettings::m_sizeReduceLevel) - ->Field("EngineReduce", &TextureSettings::m_suppressEngineReduce) - ->Field("EnableMipmap", &TextureSettings::m_enableMipmap) - ->Field("MaintainAlphaCoverage", &TextureSettings::m_maintainAlphaCoverage) - ->Field("MipMapAlphaAdjustments", &TextureSettings::m_mipAlphaAdjust) - ->Field("MipMapGenEval", &TextureSettings::m_mipGenEval) - ->Field("MipMapGenType", &TextureSettings::m_mipGenType) - ->Field("PlatformSpecificOverrides", &TextureSettings::m_platfromOverrides) - ->Field("OverridingPlatform", &TextureSettings::m_overridingPlatform); - - AZ::EditContext* edit = serialize->GetEditContext(); - if (edit) - { - edit->Class("Texture Setting", "") - ->ClassElement(AZ::Edit::ClassElements::EditorData, "") - ->Attribute(AZ::Edit::Attributes::AutoExpand, true) - ->Attribute(AZ::Edit::Attributes::Visibility, AZ::Edit::PropertyVisibility::ShowChildrenOnly) - ->DataElement(AZ::Edit::UIHandlers::Default, &TextureSettings::m_mipAlphaAdjust, "Alpha Test Bias", "Multiplies the mipmap's alpha with a scale value that is based on alpha coverage. \ - Set the mip 0 to mip 5 values to offset the alpha test values and ensure the mipmap's alpha coverage matches the original image. Specify a value from 0 to 100.") - ->Attribute(AZ::Edit::Attributes::AutoExpand, true) - ->Attribute(AZ::Edit::Attributes::ContainerCanBeModified, false) - ->ElementAttribute(AZ::Edit::UIHandlers::Handler, AZ::Edit::UIHandlers::Slider) - ->ElementAttribute(AZ::Edit::Attributes::Min, 0) - ->ElementAttribute(AZ::Edit::Attributes::Max, 100) - ->ElementAttribute(AZ::Edit::Attributes::Step, 1) - ->DataElement(AZ::Edit::UIHandlers::ComboBox, &TextureSettings::m_mipGenType, "Filter Method", "") - ->EnumAttribute(MipGenType::point, "Point") - ->EnumAttribute(MipGenType::box, "Average") - ->EnumAttribute(MipGenType::triangle, "Linear") - ->EnumAttribute(MipGenType::quadratic, "Bilinear") - ->EnumAttribute(MipGenType::gaussian, "Gaussian") - ->EnumAttribute(MipGenType::blackmanHarris, "BlackmanHarris") - ->EnumAttribute(MipGenType::kaiserSinc, "KaiserSinc") - ->DataElement(AZ::Edit::UIHandlers::ComboBox, &TextureSettings::m_mipGenEval, "Pixel Sampling Type", "") - ->EnumAttribute(MipGenEvalType::max, "Max") - ->EnumAttribute(MipGenEvalType::min, "Min") - ->EnumAttribute(MipGenEvalType::sum, "Sum") - ->DataElement(AZ::Edit::UIHandlers::CheckBox, &TextureSettings::m_maintainAlphaCoverage, "Maintain Alpha Coverage", "Select this option to manually adjust Alpha channel mipmaps.") - ; - } - } - - } - - bool TextureSettings::operator!=(const TextureSettings& other) const - { - return !(*this == other); - } - - bool TextureSettings::operator==(const TextureSettings& other) const - { - ///////////////////////////// - // Compare Alpha Adjust - ///////////////////////////// - bool matchingAlphaTestAdjust = true; - for (AZ::u8 curIndex = 0; curIndex < s_MaxMipMaps; ++curIndex) - { - if (m_mipAlphaAdjust[curIndex] != other.m_mipAlphaAdjust[curIndex]) - { - matchingAlphaTestAdjust = false; - break; - } - } - return - matchingAlphaTestAdjust && - m_preset == other.m_preset && - m_sizeReduceLevel == other.m_sizeReduceLevel && - m_suppressEngineReduce == other.m_suppressEngineReduce && - m_maintainAlphaCoverage == other.m_maintainAlphaCoverage && - m_mipGenEval == other.m_mipGenEval && - m_mipGenType == other.m_mipGenType; - } - - bool TextureSettings::Equals(const TextureSettings& other, AZ::SerializeContext* serializeContext) - { - ///////////////////////////// - // Compare Common Settings - ///////////////////////////// - if (*this != other) - { - return false; - } - - ///////////////////////////// - // Compare Overrides - ///////////////////////////// - const MultiplatformTextureSettings selfOverrides = GetMultiplatformTextureSetting(*this, serializeContext); - const MultiplatformTextureSettings otherOverrides = GetMultiplatformTextureSetting(other, serializeContext); - auto selfOverridesIter = selfOverrides.begin(); - auto otherOverridesIter = otherOverrides.begin(); - - while (selfOverridesIter != selfOverrides.end() && otherOverridesIter != otherOverrides.end()) - { - if (selfOverridesIter->second != otherOverridesIter->second) - { - return false; - } - otherOverridesIter++; - selfOverridesIter++; - } - - AZ_Assert(selfOverridesIter == selfOverrides.end() && otherOverridesIter == otherOverrides.end(), "Both iterators must be at the end by now.") - return true; - } - - float TextureSettings::ComputeMIPAlphaOffset(AZ::u32 mip) const - { - if (mip / 2 + 1 >= s_MaxMipMaps) - { - return 0; - } - - float fVal = static_cast(m_mipAlphaAdjust[s_MaxMipMaps - 1]); - if (mip / 2 + 1 < s_MaxMipMaps) - { - float fInterpolationSlider1 = static_cast(m_mipAlphaAdjust[mip / 2]); - float fInterpolationSlider2 = static_cast(m_mipAlphaAdjust[mip / 2 + 1]); - fVal = fInterpolationSlider1 + (fInterpolationSlider2 - fInterpolationSlider1) * (mip & 1) * 0.5f; - } - - return 0.5f - fVal / 100.0f; - } - - void TextureSettings::ApplyPreset(AZ::Uuid presetId) - { - const PresetSettings* presetSetting = BuilderSettingManager::Instance()->GetPreset(presetId); - if (presetSetting != nullptr) - { - m_sizeReduceLevel = presetSetting->m_sizeReduceLevel; - m_suppressEngineReduce = presetSetting->m_suppressEngineReduce; - if (presetSetting->m_mipmapSetting) - { - m_mipGenType = presetSetting->m_mipmapSetting->m_type; - } - - m_preset = presetId; - } - else - { - AZ_Error("Image Processing", false, "Cannot set an invalid preset %s!", presetId.ToString().c_str()); - } - } - - StringOutcome TextureSettings::LoadTextureSetting(const AZStd::string& filepath, TextureSettings& textureSettingPtrOut, AZ::SerializeContext* serializeContext /*= nullptr*/) - { - auto loadedTextureSettingPtr = AZStd::unique_ptr(AZ::Utils::LoadObjectFromFile(filepath, serializeContext)); - - if (!loadedTextureSettingPtr) - { - return AZ::Failure(AZStd::string()); - } - - textureSettingPtrOut = *loadedTextureSettingPtr; - return AZ::Success(AZStd::string()); - } - - StringOutcome TextureSettings::WriteTextureSetting(const AZStd::string& filepath, TextureSettings& textureSetting, AZ::SerializeContext* serializeContext) - { - if(false == AZ::Utils::SaveObjectToFile(filepath, AZ::DataStream::StreamType::ST_XML, &textureSetting, serializeContext)) - { - return STRING_OUTCOME_ERROR("Failed to write to file: " + filepath); - } - - return STRING_OUTCOME_SUCCESS; - } - - StringOutcome TextureSettings::LoadLegacyTextureSetting(const AZStd::string& imagePath, const AZStd::string& contentString, TextureSettings& textureSettingOut, AZ::SerializeContext* serializeContext) - { - AZStd::string trimmedContent = contentString; - AzFramework::StringFunc::TrimWhiteSpace(trimmedContent, true /* leading */, true /* trailing */); - if (trimmedContent.empty()) - { - return STRING_OUTCOME_ERROR("Empty legacy texture setting!"); - } - - AZStd::vector settings; - AZStd::vector overrideSettings; - - // Each setting begins with a forward-slash. - AzFramework::StringFunc::Tokenize(trimmedContent.c_str(), settings, " /"); // requires space character. - - // For each setting pair (field & value)... - for (AZStd::string& settingPair : settings) - { - // Split setting pair into key & value. - AZStd::string key, value; - { - AZStd::vector key_value; - AzFramework::StringFunc::Tokenize(settingPair.c_str(), key_value, '='); - if (key_value.size() == 2) - { - key = key_value[0]; - value = key_value[1]; - } - else - { - return STRING_OUTCOME_ERROR("Invalid format found in legacy texture setting: " + settingPair); - } - } - - bool containsPlatformOverrides = !value.empty() && (value[0] == '"' && value[value.length() - 1] == '"'); - if (containsPlatformOverrides) - { - // Process platform-specific overrides on the next loop. - overrideSettings.push_back(&settingPair); - continue; - } - - // Parse the common settings. - ParseLegacyTextureSettingString(key, value, textureSettingOut); - } - - // Some setting file won't assign a proper preset for the image, need to assign a suggested one here - if (textureSettingOut.m_preset.IsNull()) - { - textureSettingOut.m_preset = BuilderSettingManager::Instance()->GetSuggestedPreset(imagePath); - } - - // Store a temporary settings of all platforms intended to have overrides within this preset. - // We will collate all overrides per-platform to generate PatchData at the end. - MultiplatformTextureSettings overrideCache; - - // For each platform-specific override setting pair - for (AZStd::string* overrideSettingPair : overrideSettings) - { - // Split setting pair into key & value. - AZStd::string key, value; - { - AZStd::vector key_value; - AzFramework::StringFunc::Tokenize(overrideSettingPair->c_str(), key_value, '='); - - if (key_value.size() == 2) - { - key = key_value[0]; - value = key_value[1]; - } - else - { - return STRING_OUTCOME_ERROR("Invalid format found in legacy texture setting: " + *overrideSettingPair); - } - } - - // Chop the surrounding quotation marks. - AzFramework::StringFunc::LChop(value, 1); - AzFramework::StringFunc::RChop(value, 1); - - // Split the collection of platforms overrides into entries in a vector. - // Layout: { [platform0],[value0],[platform1],[value1],[platform2],[value2] } - AZStd::vector override_platform_value; - AzFramework::StringFunc::Tokenize(value.c_str(), override_platform_value, ",:"); - - if (override_platform_value.size() % 2 != 0) - { - return STRING_OUTCOME_ERROR("Invalid format found in legacy texture setting: " + value); - } - - for (int platformIdx = 0, valueIdx = 1; - valueIdx < override_platform_value.size(); - platformIdx += 2, valueIdx = platformIdx + 1) - { - PlatformName& overridePlatform = override_platform_value[platformIdx]; - AZStd::string& overrideValue = override_platform_value[valueIdx]; - - // Insert a copy of the base settings we've parsed from the legacy metafile. - overrideCache.insert(AZStd::pair(overridePlatform, textureSettingOut)); - - ParseLegacyTextureSettingString(key, overrideValue, overrideCache[overridePlatform]); - overrideCache[overridePlatform].m_overridingPlatform = overridePlatform; - overrideCache[overridePlatform].m_platfromOverrides.clear(); - } - } - - // Store the final result in a temp variable to do a whole-sale copy at the end. - TextureSettings finalResult = textureSettingOut; - - // Use the override cache to generate a DataPatch per-platform. - for (auto& overridePair : overrideCache) - { - // Every DataPatch is only a diff between a vanilla common-settings (with no platform-specific overrides) and the specified platform's override. - AZ::DataPatch platformOverridePatch; - platformOverridePatch.Create(&textureSettingOut, &overridePair.second,AZ::DataPatch::FlagsMap(), AZ::DataPatch::FlagsMap(), serializeContext); - finalResult.m_platfromOverrides.insert(AZStd::pair(overridePair.first, platformOverridePatch)); - } - - // Fully overwrite output variable. The only difference should be properly filled-out overrides. - textureSettingOut = finalResult; - - return STRING_OUTCOME_SUCCESS; - } - - StringOutcome TextureSettings::LoadLegacyTextureSettingFromFile(const AZStd::string& imagePath, const AZStd::string& filepath, TextureSettings& textureSettingOut, AZ::SerializeContext* serializeContext) - { - AZStd::string fileContents; - - // Perform file I/O to read the contents of the metafile into the string above. - auto fileIoPtr = AZ::IO::FileIOBase::GetInstance(); - AZ::IO::HandleType fileHandle; - fileIoPtr->Open(filepath.c_str(), AZ::IO::OpenMode::ModeRead, fileHandle); - AZ::u64 fileSize = 0; - AZ::u64 bytesRead = 0; - fileIoPtr->Size(fileHandle, fileSize); - char* fileString = new char[fileSize + 1]; - fileIoPtr->Read(fileHandle, fileString, fileSize, false, &bytesRead); - fileIoPtr->Close(fileHandle); - fileString[bytesRead] = 0; - fileContents = fileString; - delete[] fileString; - - - return LoadLegacyTextureSetting(imagePath, fileContents, textureSettingOut, serializeContext); - } - - MultiplatformTextureSettings TextureSettings::GenerateDefaultMultiplatformTextureSettings(const AZStd::string& imageFilepath) - { - MultiplatformTextureSettings settings; - PlatformNameList platformsList = BuilderSettingManager::Instance()->GetPlatformList(); - AZ::Uuid suggestedPreset = BuilderSettingManager::Instance()->GetSuggestedPreset(imageFilepath); - if (!suggestedPreset.IsNull()) - { - for (PlatformName& platform : platformsList) - { - TextureSettings textureSettings; - textureSettings.ApplyPreset(suggestedPreset); - settings.insert(AZStd::pair(platform, textureSettings)); - } - } - return settings; - } - - StringOutcome TextureSettings::GetPlatformSpecificTextureSetting(const PlatformName& platformName, const TextureSettings& baseTextureSettings, - TextureSettings& textureSettingsOut, AZ::SerializeContext* serializeContext) - { - // Obtain the DataPatch (if platform exists) - auto overrideIter = baseTextureSettings.m_platfromOverrides.find(platformName); - if (overrideIter == baseTextureSettings.m_platfromOverrides.end()) - { - return STRING_OUTCOME_ERROR(AZStd::string::format("TextureSettings preset [%s] does not have override for platform [%s]", - baseTextureSettings.m_preset.ToString().c_str(), platformName.c_str())); - } - AZ::DataPatch& platformOverride = const_cast(overrideIter->second); - - // Update settings instance with override values. - if (platformOverride.IsData()) - { - // Apply the AZ::DataPatch to obtain a platform-overridden version of the TextureSettings. - AZStd::unique_ptr platformSpecificTextureSettings(platformOverride.Apply(&baseTextureSettings, serializeContext)); - AZ_Assert(platformSpecificTextureSettings->m_mipAlphaAdjust.size() == s_MaxMipMaps, "Unexpected m_mipAlphaAdjust size."); - - // Adjust overrides data to imply 'platformSpecificTextureSettings' *IS* the override. - platformSpecificTextureSettings->m_platfromOverrides.clear(); - platformSpecificTextureSettings->m_overridingPlatform = platformName; - textureSettingsOut = *platformSpecificTextureSettings; - } - else - { - textureSettingsOut = baseTextureSettings; - } - - return STRING_OUTCOME_SUCCESS; - } - - const MultiplatformTextureSettings TextureSettings::GetMultiplatformTextureSetting(const TextureSettings& textureSettings, AZ::SerializeContext* serializeContext) - { - MultiplatformTextureSettings loadedSettingsReturn; - PlatformNameList platformsList = BuilderSettingManager::Instance()->GetPlatformList(); - // Generate MultiplatformTextureSettings based on existing available overrides. - for (const PlatformName& curPlatformName : platformsList) - { - // Start with a copy of the base settings - TextureSettings curPlatformOverride = textureSettings; - if (!GetPlatformSpecificTextureSetting(curPlatformName, textureSettings, curPlatformOverride, serializeContext).IsSuccess()) - { - // We have failed to obtain an override. Maintain base settings to indicate zero overrides. - // We still want to designate these TextureSettings as an (empty) override. - curPlatformOverride.m_platfromOverrides.clear(); - curPlatformOverride.m_overridingPlatform = curPlatformName; - } - - // Add as an entry to the multiplatform texture settings - loadedSettingsReturn.insert(AZStd::pair(curPlatformName, curPlatformOverride)); - } - - // return a copy of the results - return loadedSettingsReturn; - } - - const MultiplatformTextureSettings TextureSettings::GetMultiplatformTextureSetting(const AZStd::string& imageFilepath, bool& canOverridePreset, AZ::SerializeContext* serializeContext) - { - TextureSettings loadedTextureSetting; - - // Attempt to get metadata filepath from image path. - AZStd::string legacyMetadataFilepath = imageFilepath + legacyExtensionName; - AZStd::string modernMetadataFilepath = imageFilepath + modernExtensionName; - bool hasLegacyMetafile = AZ::IO::SystemFile::Exists(legacyMetadataFilepath.c_str()); - bool hasModernMetafile = AZ::IO::SystemFile::Exists(modernMetadataFilepath.c_str()); - - // If the image has an accompanying metadata... - if(hasModernMetafile) - { - // Parse the metadata file. - if (!LoadTextureSetting(modernMetadataFilepath, loadedTextureSetting, serializeContext).IsSuccess()) - { - canOverridePreset = true; - return GenerateDefaultMultiplatformTextureSettings(imageFilepath); - } - } - else if (hasLegacyMetafile) - { - if (!LoadLegacyTextureSettingFromFile(imageFilepath, legacyMetadataFilepath, loadedTextureSetting, serializeContext).IsSuccess()) - { - canOverridePreset = true; - return GenerateDefaultMultiplatformTextureSettings(imageFilepath); - } - } - else - { - canOverridePreset = true; // RC could override settings if it was loaded from the image so this is set to - // true regardless of whether settings existed in the texture for compatibility. - // Try to load from image file if it has embedded setting file - AZStd::string embeddedString = LoadEmbeddedSettingFromFile(imageFilepath); - if (!LoadLegacyTextureSetting(imageFilepath, embeddedString, loadedTextureSetting, serializeContext).IsSuccess()) - { - // If the texture has neither of legacy/modern meta file nor embedded setting, generate data for a new metadata file. - return GenerateDefaultMultiplatformTextureSettings(imageFilepath); - } - } - - // Generate MultiplatformTextureSettings based on the loaded texture setting. - return GetMultiplatformTextureSetting(loadedTextureSetting, serializeContext); - } - - StringOutcome TextureSettings::ApplySettings(const TextureSettings& settings, const PlatformName& overridePlatform, AZ::SerializeContext* serializeContext) - { - if (overridePlatform.empty()) - { - *this = settings; - } - else - { - AZ::DataPatch newOverride; - if (false == newOverride.Create(this, &settings, AZ::DataPatch::FlagsMap(), AZ::DataPatch::FlagsMap(), serializeContext)) - { - return STRING_OUTCOME_ERROR("Failed to create TextureSettings platform override data. See AZ_Error log for details."); - } - - m_platfromOverrides[overridePlatform] = newOverride; - } - - return STRING_OUTCOME_SUCCESS; - } -} diff --git a/Gems/ImageProcessing/Code/Source/BuilderSettings/TextureSettings.h b/Gems/ImageProcessing/Code/Source/BuilderSettings/TextureSettings.h deleted file mode 100644 index 2ecc2c0a96..0000000000 --- a/Gems/ImageProcessing/Code/Source/BuilderSettings/TextureSettings.h +++ /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. -* -*/ - -#pragma once - -#include -#include -#include -#include - -namespace ImageProcessing -{ - class TextureSettings; - typedef AZStd::map MultiplatformTextureSettings; - - class TextureSettings - { - public: - AZ_TYPE_INFO(TextureSettings, "{CC3ED018-7FF7-4233-AAD8-6D3115FD844A}"); - AZ_CLASS_ALLOCATOR(TextureSettings, AZ::SystemAllocator, 0); - - TextureSettings(); - float ComputeMIPAlphaOffset(AZ::u32 mip) const; - void ApplyPreset(AZ::Uuid presetId); - - /** - * Performs a comprehensive comparison between two TextureSettings instances. - * @param Reference to the settings which will be compared. - * @param Optional. Serialize context. Will use global context if none is provided. - * @return True, is both instances are equivalent. - */ - bool Equals(const TextureSettings& other, AZ::SerializeContext* serializeContext = nullptr); - - /** - * Applies texture settings to the instance (including overrides). Common settings are applied, unless specific platform is specified. - * @param Reference to the settings which will be applied. - * @param Optional. Applies settings as a platform override if a platform is specified. - * @param Optional. Serialize context. Will use global context if none is provided. - * @return Status outcome result. - */ - StringOutcome ApplySettings(const TextureSettings& settings, const PlatformName& overridePlatform = PlatformName(), AZ::SerializeContext* serializeContext = nullptr); - - /** - * Gets platform-specific texture settings obtained from the base settings version of a pre-loaded TextureSettings instance. - * @param Name of platform to get the settings from. - * @param Base TextureSettings which we will get overrides from. - * @param Output TextureSettings which will contain the result of the function. - * @param Optional. Serialize context. Will use global context if none is provided. - * @return Status outcome result. - */ - static StringOutcome GetPlatformSpecificTextureSetting(const PlatformName& platformName, const TextureSettings& baseTextureSettings, TextureSettings& textureSettingsOut, AZ::SerializeContext* serializeContext = nullptr); - - static void Reflect(AZ::ReflectContext* context); - - - /** - * Loads base texture settings obtained from ".exportsettings" file (legacy setting) - * @param ImagePath absolute/relative path of the image file. - * @param FilePath absolute/relative path of the ".exportsettings" file. - * @param Output TextureSettings which contain the result of the function, it may contains platform-specific overrides. - * @param Optional. Serialize context. Will use global context if none is provided. - * @return Status outcome result. - */ - static StringOutcome LoadLegacyTextureSettingFromFile(const AZStd::string& imagePath, const AZStd::string& filepath, TextureSettings& textureSettingOut, AZ::SerializeContext* serializeContext = nullptr); - - /** - * Loads base texture settings obtained from a legacy setting string - * @param ImagePath absolute/relative path of the image file. - * @param Content string of the legacy setting to be read. - * @param Output TextureSettings which contain the result of the function, it may contains platform-specific overrides. - * @param Optional. Serialize context. Will use global context if none is provided. - * @return Status outcome result. - */ - static StringOutcome LoadLegacyTextureSetting(const AZStd::string& imagePath, const AZStd::string& contentString, TextureSettings& textureSettingOut, AZ::SerializeContext* serializeContext = nullptr); - - /** - * Loads base texture settings obtained from ".imagesettings" file (modern setting) - * @param FilePath absolute/relative path of the ".imagesettings" file. - * @param Output TextureSettings which contain the result of the function, it may contains platform-specific overrides. - * @param Optional. Serialize context. Will use global context if none is provided. - * @return Status outcome result. - */ - static StringOutcome LoadTextureSetting(const AZStd::string& filepath, TextureSettings& textureSettingPtrOut, AZ::SerializeContext* serializeContext = nullptr); - - /** - * Writes base texture settings to a ".imagesettings" file (modern setting) - * @param FilePath absolute/relative path of the ".imagesettings" file. - * @param TextureSetting to be written on the disk, it may contains platform-specific overrides. - * @param Optional. Serialize context. Will use global context if none is provided. - * @return Status outcome result. - */ - static StringOutcome WriteTextureSetting(const AZStd::string& filepath, TextureSettings& textureSetting, AZ::SerializeContext* serializeContext = nullptr); - - // Generates a MultiplatformTextureSettings collection with default texture settings for all - static MultiplatformTextureSettings GenerateDefaultMultiplatformTextureSettings(const AZStd::string& imageFilepath); - - /** - * Generates a TextureSetting instance of a particular image file for each supported platform. - * @param filepath - A path to the texture file. - * @param canOverridePreset - Returns whether the preset can be overriden. Will return false if the preset was selecting from a settings file created by the user. - * @param serializeContext - Optional. Serialize context used for reflection/serialization - * @return - The collection of TextureSetting instances. If error occurs, a default MultiplatformTextureSettings is returned (see GenerateDefaultMultiplatformTextureSettings()). - */ - static const MultiplatformTextureSettings GetMultiplatformTextureSetting(const AZStd::string& filepath, bool& canOverridePreset, AZ::SerializeContext* serializeContext = nullptr); - - /** - * Generates a TextureSetting instance of a particular image file for each supported platform. - * @param textureSettings - A reference to an already-loaded texture settings. - * @param serializeContext - Optional. Serialize context used for reflection/serialization - * @return - The collection of TextureSetting instances. If error occurs, a default MultiplatformTextureSettings is returned (see GenerateDefaultMultiplatformTextureSettings()). - */ - static const MultiplatformTextureSettings GetMultiplatformTextureSetting(const TextureSettings& textureSettings, AZ::SerializeContext* serializeContext = nullptr); - - static const char* legacyExtensionName; - static const char* modernExtensionName; - static const size_t s_MaxMipMaps = 6; - - // uuid of selected preset for this texture - AZ::Uuid m_preset; - - // texture size reduce level. the value of this variable will override the same variable in PresetSettings - unsigned int m_sizeReduceLevel; - - // "ser". Whether to enable supress reduce resolution (m_sizeReduceLevel) during loading, 0(default) - // the value of this variable will override the same variable in PresetSettings - bool m_suppressEngineReduce; - - //enable generate mipmap or not - bool m_enableMipmap; - - //"mc". not used in rc.ini. experiemental - //maybe relate to http://the-witness.net/news/2010/09/computing-alpha-mipmaps/ - bool m_maintainAlphaCoverage; - - // "M", adjust mipalpha, 0..50=normal..100. associate with ComputeMIPAlphaOffset function - // only useful if m_maintainAlphaCoverage set to true. - // This data type MUST be an AZStd::vector, even though we treat is as a fixed array. This is due to a limitation - // during AZ::DataPatch serialization, where an element is allocated one by one while extending the container.. - AZStd::vector m_mipAlphaAdjust; - - MipGenEvalType m_mipGenEval; - - MipGenType m_mipGenType; - - private: - // Platform overrides in form of DataPatch. Each entry is a patch for a specified platform. - // This map is used to generate TextureSettings with overridden values. The map is empty if - // the instance is for platform-specific settings. - AZStd::map m_platfromOverrides; - - // The platform which these settings override. - // Blank if the instance is for common settings. - PlatformName m_overridingPlatform; - - // Comparison operators only compare the base settings, they do not compare overrides. - // For a comprehensive equality comparison, use Equals() function. - bool operator==(const TextureSettings& other) const; - bool operator!=(const TextureSettings& other) const; - - }; - -} // namespace ImageProcessing diff --git a/Gems/ImageProcessing/Code/Source/Compressors/CTSquisher.cpp b/Gems/ImageProcessing/Code/Source/Compressors/CTSquisher.cpp deleted file mode 100644 index efb9d85cab..0000000000 --- a/Gems/ImageProcessing/Code/Source/Compressors/CTSquisher.cpp +++ /dev/null @@ -1,387 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or 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 ImageProcessing -{ - struct CrySquisherCallbackUserData - { - IImageObjectPtr m_pImageObject; - AZ::u8* m_dstMem; - AZ::u32 m_dstOffset; - }; - - // callbacks for the CryTextureSquisher - void CrySquisherOutputCallback(const CryTextureSquisher::CompressorParameters& compress, const void* data, AZ::u32 size, AZ::u32 oy, AZ::u32 ox) - { - CrySquisherCallbackUserData* const pUserData = (CrySquisherCallbackUserData*)compress.userPtr; - - AZ::u32 stride = (compress.width + 3) >> 2; - AZ::u32 blocks = (compress.height + 3) >> 2; - memcpy(pUserData->m_dstMem + size * (stride * oy + ox), data, size); - pUserData->m_dstOffset = size * (stride * blocks); - } - - void CrySquisherInputCallback(const CryTextureSquisher::DecompressorParameters& decompress, void* data, AZ::u32 size, AZ::u32 oy, AZ::u32 ox) - { - CrySquisherCallbackUserData* const pUserData = (CrySquisherCallbackUserData*)decompress.userPtr; - AZ::u32 stride = (decompress.width + 3) >> 2; - AZ::u32 blocks = (decompress.height + 3) >> 2; - - //assert(CPixelFormats::GetPixelFormatInfo(pUserData->m_pImageObject->GetPixelFormat())->bCompressed); - - memcpy(data, pUserData->m_dstMem + size * (stride * oy + ox), size); - - pUserData->m_dstOffset = size * (stride * blocks); - } - - - CryTextureSquisher::ECodingPreset CTSquisher::GetCompressPreset(EPixelFormat compressFmt, EPixelFormat uncompressFmt) - { - CryTextureSquisher::ECodingPreset preset = CryTextureSquisher::eCompressorPreset_Num; - switch (compressFmt) - { - case ePixelFormat_BC1: - preset = CryTextureSquisher::eCompressorPreset_BC1U; - break; - case ePixelFormat_BC1a: - preset = CryTextureSquisher::eCompressorPreset_BC1Ua; - break; - case ePixelFormat_BC3: - preset = CryTextureSquisher::eCompressorPreset_BC3U; - break; - case ePixelFormat_BC3t: - preset = CryTextureSquisher::eCompressorPreset_BC3Ut; - break; - case ePixelFormat_BC4: - preset = (CPixelFormats::GetInstance().IsFormatSingleChannel(uncompressFmt) - ? CryTextureSquisher::eCompressorPreset_BC4Ua // a-channel - : CryTextureSquisher::eCompressorPreset_BC4U); // r-channel - break; - case ePixelFormat_BC4s: - preset = (CPixelFormats::GetInstance().IsFormatSingleChannel(uncompressFmt) - ? CryTextureSquisher::eCompressorPreset_BC4Sa // a-channel - : CryTextureSquisher::eCompressorPreset_BC4S); // r-channel - break; - case ePixelFormat_BC5: - preset = CryTextureSquisher::eCompressorPreset_BC5Un; - break; - case ePixelFormat_BC5s: - preset = CryTextureSquisher::eCompressorPreset_BC5Sn; - break; - case ePixelFormat_BC6UH: - preset = CryTextureSquisher::eCompressorPreset_BC6UH; - break; - case ePixelFormat_BC7: - preset = CryTextureSquisher::eCompressorPreset_BC7U; - break; - case ePixelFormat_BC7t: - preset = CryTextureSquisher::eCompressorPreset_BC7Ut; - break; - default: - AZ_Assert(false, "%s: Unexpected pixel format (in compressing an image). Inform an RC programmer.", __FUNCTION__); - } - - return preset; - } - - bool CTSquisher::IsCompressedPixelFormatSupported(EPixelFormat fmt) - { - switch (fmt) - { - case ePixelFormat_BC1: - case ePixelFormat_BC1a: - case ePixelFormat_BC3: - case ePixelFormat_BC3t: - case ePixelFormat_BC4: - case ePixelFormat_BC4s: - case ePixelFormat_BC5: - case ePixelFormat_BC5s: - case ePixelFormat_BC6UH: - case ePixelFormat_BC7: - case ePixelFormat_BC7t: - return true; - default: - return false; - } - } - - bool CTSquisher::IsUncompressedPixelFormatSupported(EPixelFormat fmt) - { - switch (fmt) - { - case ePixelFormat_R8: - case ePixelFormat_A8: - case ePixelFormat_R8G8B8A8: - case ePixelFormat_R8G8B8X8: - case ePixelFormat_R32F: - case ePixelFormat_R32G32B32A32F: - return true; - default: - return false; - } - } - - bool CTSquisher::DoesSupportDecompress([[maybe_unused]] EPixelFormat fmtDst) - { - return true; - } - - EPixelFormat CTSquisher::GetSuggestedUncompressedFormat(EPixelFormat compressedfmt, EPixelFormat uncompressedfmt) - { - //special cases - if (compressedfmt == ePixelFormat_BC6UH || compressedfmt == ePixelFormat_BC5 || compressedfmt == ePixelFormat_BC5s) - { - return ePixelFormat_R32G32B32A32F; - } - - if (IsUncompressedPixelFormatSupported(uncompressedfmt)) - { - return uncompressedfmt; - } - - //for fmt dont support, convert to supported uncompressed formats: ePixelFormat_A8, ePixelFormat_R8, ePixelFormat_A8R8G8B8, - // ePixelFormat_X8R8G8B8, ePixelFormat_R32F, ePixelFormat_A32B32G32R32F - - switch (uncompressedfmt) - { - case ePixelFormat_R8G8: - case ePixelFormat_R16G16: - return ePixelFormat_R8G8B8X8; - case ePixelFormat_R16: - return ePixelFormat_R8; - case ePixelFormat_R16G16B16A16: - case ePixelFormat_B8G8R8A8: - return ePixelFormat_R8G8B8A8; - case ePixelFormat_R9G9B9E5: - case ePixelFormat_R32G32F: - case ePixelFormat_R16G16B16A16F: - case ePixelFormat_R16G16F: - return ePixelFormat_R32G32B32A32F; - case ePixelFormat_R16F: - return ePixelFormat_R32F; - default: - //this shouldn't happen. but we could handle it with uncompressed data anyway - if (CPixelFormats::GetInstance().IsPixelFormatWithoutAlpha(uncompressedfmt)) - { - return ePixelFormat_R8G8B8X8; - } - else - { - return ePixelFormat_R8G8B8A8; - } - } - } - - IImageObjectPtr CTSquisher::DecompressImage(IImageObjectPtr srcImage, EPixelFormat fmtDst) - { - // Decompressing - // the output pixel format could only have one channel or four channels. need to find out more - EPixelFormat fmtSrc = srcImage->GetPixelFormat(); - - //src format need to be compressed and dst format need to uncompressed. - if (!IsCompressedPixelFormatSupported(fmtSrc) || !IsUncompressedPixelFormatSupported(fmtDst)) - { - return nullptr; - } - - IImageObjectPtr dstImage(srcImage->AllocateImage(fmtDst)); - - //clear the dstImage to (0, 0, 0, 1) since some compression format only write to certain channels - dstImage->ClearColor(0, 0, 0, 1); - - //for each mipmap - const AZ::u32 mipCount = srcImage->GetMipCount(); - for (AZ::u32 dwMip = 0; dwMip < mipCount; ++dwMip) - { - const AZ::u32 dwLocalWidth = srcImage->GetWidth(dwMip); - const AZ::u32 dwLocalHeight = srcImage->GetHeight(dwMip); - - AZ::u8* pSrcMem; - AZ::u32 dwSrcPitch; - srcImage->GetImagePointer(dwMip, pSrcMem, dwSrcPitch); - - AZ::u8* pDstMem; - AZ::u32 dwDstPitch; - dstImage->GetImagePointer(dwMip, pDstMem, dwDstPitch); - - CrySquisherCallbackUserData userData; - userData.m_pImageObject = srcImage; - userData.m_dstOffset = 0; - userData.m_dstMem = pSrcMem; - - CryTextureSquisher::DecompressorParameters decompress; - - decompress.dstBuffer = pDstMem; - decompress.width = dwLocalWidth; - decompress.height = dwLocalHeight; - decompress.pitch = dwDstPitch; - - decompress.dstType = (CPixelFormats::GetInstance().IsFormatFloatingPoint(fmtDst, true) ? - CryTextureSquisher::eBufferType_ufloat : CryTextureSquisher::eBufferType_uint8); - - if (CPixelFormats::GetInstance().IsFormatSigned(fmtSrc)) - { - decompress.dstType = (decompress.dstType == CryTextureSquisher::eBufferType_ufloat ? - CryTextureSquisher::eBufferType_sfloat : CryTextureSquisher::eBufferType_sint8); - } - - decompress.userPtr = &userData; - decompress.userInputFunction = CrySquisherInputCallback; - decompress.preset = GetCompressPreset(fmtSrc, fmtDst); - - CryTextureSquisher::Decompress(decompress); - } - - // CTsquish operates on native normal vectors when floating-point - // buffers are used. Apply bias and scale when returning a normal-map. - if (fmtSrc == ePixelFormat_BC5 || fmtSrc == ePixelFormat_BC5s) - { - if (fmtDst == ePixelFormat_R32G32B32A32F) - { - //conver from [-1, 1] to [0, 1]. And set alpha to 1. - dstImage->ScaleAndBiasChannels(0, 100, - AZ::Vector4(0.5f, 0.5f, 0.5f, 0.0f), - AZ::Vector4(0.5f, 0.5f, 0.5f, 1.0f)); - } - } - - return dstImage; - } - - /////////////////////////////////////////////////////////////////////////////////// - IImageObjectPtr CTSquisher::CompressImage(IImageObjectPtr srcImage, EPixelFormat fmtDst, - const CompressOption *compressOption) - { - // Compressing - EPixelFormat fmtSrc = srcImage->GetPixelFormat(); - - //src format need to be uncompressed and dst format need to compressed. - if (!IsUncompressedPixelFormatSupported(fmtSrc) || !IsCompressedPixelFormatSupported(fmtDst)) - { - return nullptr; - } - - IImageObjectPtr dstImage(srcImage->AllocateImage(fmtDst)); - - //passing compress option - ICompressor::EQuality quality = ICompressor::eQuality_Normal; - AZ::Vector3 weights = AZ::Vector3(0.3333f, 0.3334f, 0.3333f); - if (compressOption) - { - quality = compressOption->compressQuality; - weights = compressOption->rgbWeight; - } - - //do some clamp for float - if (fmtSrc == ePixelFormat_R32G32B32A32F) - { - const uint32 nMips = srcImage->GetMipCount(); - - // NOTES: - // - all incoming images are unsigned, even normal maps - // - all mipmaps of incoming images can contain out-of-range values from mipmap filtering - // - 3Dc/BC5 is synonymous with "is a normal map" because they are not tagged explicitly as such - if (fmtDst == ePixelFormat_BC5 || fmtDst == ePixelFormat_BC5s) - { - srcImage->ScaleAndBiasChannels(0, nMips, - AZ::Vector4(2.0f, 2.0f, 2.0f, 1.0f), - AZ::Vector4(-1.0f, -1.0f, -1.0f, 0.0f)); - srcImage->ClampChannels(0, nMips, - AZ::Vector4(-1.0f, -1.0f, -1.0f, -1.0f), - AZ::Vector4(1.0f, 1.0f, 1.0f, 1.0f)); - } - else if (fmtDst == ePixelFormat_BC6UH) - { - srcImage->ClampChannels(0, nMips, - AZ::Vector4(0.0f, 0.0f, 0.0f, 0.0f), - AZ::Vector4(FLT_MAX, FLT_MAX, FLT_MAX, FLT_MAX)); - } - else - { - srcImage->ClampChannels(0, nMips, - AZ::Vector4(0.0f, 0.0f, 0.0f, 0.0f), - AZ::Vector4(1.0f, 1.0f, 1.0f, 1.0f)); - } - } - - const uint32 mipCount = dstImage->GetMipCount(); - for (uint32 dwMip = 0; dwMip < mipCount; ++dwMip) - { - uint32 dwLocalWidth = srcImage->GetWidth(dwMip); - uint32 dwLocalHeight = srcImage->GetHeight(dwMip); - - uint8* pSrcMem; - uint32 dwSrcPitch; - srcImage->GetImagePointer(dwMip, pSrcMem, dwSrcPitch); - - uint8* pDstMem; - uint32 dwDstPitch; - dstImage->GetImagePointer(dwMip, pDstMem, dwDstPitch); - - { - CrySquisherCallbackUserData userData; - userData.m_pImageObject = dstImage; - userData.m_dstOffset = 0; - userData.m_dstMem = pDstMem; - - CryTextureSquisher::CompressorParameters compress; - - compress.srcBuffer = pSrcMem; - compress.width = dwLocalWidth; - compress.height = dwLocalHeight; - compress.pitch = dwSrcPitch; - - compress.srcType = (CPixelFormats::GetInstance().IsFormatFloatingPoint(fmtSrc, true) ? - CryTextureSquisher::eBufferType_ufloat : CryTextureSquisher::eBufferType_uint8); - if (CPixelFormats::GetInstance().IsFormatSigned(fmtDst)) - { - compress.srcType = (compress.srcType == CryTextureSquisher::eBufferType_ufloat ? - CryTextureSquisher::eBufferType_sfloat : CryTextureSquisher::eBufferType_sint8); - } - - const AZ::Vector3 uniform = AZ::Vector3(0.3333f, 0.3334f, 0.3333f); - - compress.weights[0] = weights.GetX(); - compress.weights[1] = weights.GetY(); - compress.weights[2] = weights.GetZ(); - - compress.perceptual = - (compress.weights[0] != uniform.GetX()) || - (compress.weights[1] != uniform.GetY()) || - (compress.weights[2] != uniform.GetZ()); - - compress.quality = - (quality == eQuality_Preview ? CryTextureSquisher::eQualityProfile_Low : - (quality == eQuality_Fast ? CryTextureSquisher::eQualityProfile_Low : - (quality == eQuality_Slow ? CryTextureSquisher::eQualityProfile_High : - CryTextureSquisher::eQualityProfile_Medium))); - - compress.userPtr = &userData; - compress.userOutputFunction = CrySquisherOutputCallback; - compress.preset = GetCompressPreset(fmtDst, fmtSrc); - - CryTextureSquisher::Compress(compress); - } - } // for: all mips - - return dstImage; - } - -} //namespace ImageProcessing diff --git a/Gems/ImageProcessing/Code/Source/Compressors/CTSquisher.h b/Gems/ImageProcessing/Code/Source/Compressors/CTSquisher.h deleted file mode 100644 index 6cb08ac295..0000000000 --- a/Gems/ImageProcessing/Code/Source/Compressors/CTSquisher.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 -#include - -namespace ImageProcessing -{ - //Cry Texture Squisher for all the BC compressions - class CTSquisher : public ICompressor - { - public: - static bool IsCompressedPixelFormatSupported(EPixelFormat fmt); - static bool IsUncompressedPixelFormatSupported(EPixelFormat fmt); - static bool DoesSupportDecompress(EPixelFormat fmtDst); - - IImageObjectPtr CompressImage(IImageObjectPtr srcImage, EPixelFormat fmtDst, const CompressOption *compressOption) override; - IImageObjectPtr DecompressImage(IImageObjectPtr srcImage, EPixelFormat fmtDst) override; - - EPixelFormat GetSuggestedUncompressedFormat(EPixelFormat compressedfmt, EPixelFormat uncompressedfmt) override; - - - private: - static CryTextureSquisher::ECodingPreset GetCompressPreset(EPixelFormat compressFmt, EPixelFormat uncompressFmt); - }; - -} // namespace ImageProcessing diff --git a/Gems/ImageProcessing/Code/Source/Compressors/Compressor.cpp b/Gems/ImageProcessing/Code/Source/Compressors/Compressor.cpp deleted file mode 100644 index fe151d8954..0000000000 --- a/Gems/ImageProcessing/Code/Source/Compressors/Compressor.cpp +++ /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. -* -*/ - -#include - -#include -#include -#include - -namespace ImageProcessing -{ - ICompressorPtr ICompressor::FindCompressor(EPixelFormat fmt, bool isCompressing) - { - if (CTSquisher::IsCompressedPixelFormatSupported(fmt)) - { - if (isCompressing || (!isCompressing && CTSquisher::DoesSupportDecompress(fmt))) - { - return ICompressorPtr(new CTSquisher()); - } - } - - // Both ETC2Compressor and PVRTCCompressor can process ETC formats - // According to Mobile team, Etc2Com is faster than PVRTexLib, so we check with ETC2Compressor before PVRTCCompressor - // Note: with the test I have done, I found out it cost similar time for both Etc2Com and PVRTexLib to compress - // a 2048x2048 test texture to EAC_R11 and EAC_RG11. It was around 7 minutes for EAC_R11 and 14 minutes for EAC_RG11 - if (ETC2Compressor::IsCompressedPixelFormatSupported(fmt)) - { - if (isCompressing || (!isCompressing && ETC2Compressor::DoesSupportDecompress(fmt))) - { - return ICompressorPtr(new ETC2Compressor()); - } - } - - if (PVRTCCompressor::IsCompressedPixelFormatSupported(fmt)) - { - if (isCompressing || (!isCompressing && PVRTCCompressor::DoesSupportDecompress(fmt))) - { - return ICompressorPtr(new PVRTCCompressor()); - } - } - - return nullptr; - } - - ICompressor::~ICompressor() - { - - } -} // namespace ImageProcessing diff --git a/Gems/ImageProcessing/Code/Source/Compressors/Compressor.h b/Gems/ImageProcessing/Code/Source/Compressors/Compressor.h deleted file mode 100644 index 14fb6d2b9a..0000000000 --- a/Gems/ImageProcessing/Code/Source/Compressors/Compressor.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 - -namespace ImageProcessing -{ - class ICompressor; - typedef AZStd::shared_ptr ICompressorPtr; - - //the interface base class for any compressors which can decompress/compress image with compressed pixel format - class ICompressor - { - public: - enum EQuality - { - eQuality_Preview, // for the 256x256 preview only - eQuality_Fast, - eQuality_Normal, - eQuality_Slow, - }; - - //some extra information required for different compressors. - //keep is a simple structure for now. - struct CompressOption - { - EQuality compressQuality = eQuality_Normal; - //required for CTSquisher - AZ::Vector3 rgbWeight = AZ::Vector3(0.3333f, 0.3334f, 0.3333f); - }; - - public: - //compress the source image to desired compressed pixel format - virtual IImageObjectPtr CompressImage(IImageObjectPtr srcImage, EPixelFormat fmtDst, const CompressOption *compressOption) = 0; - virtual IImageObjectPtr DecompressImage(IImageObjectPtr srcImage, EPixelFormat fmtDst) = 0; - virtual EPixelFormat GetSuggestedUncompressedFormat(EPixelFormat compressedfmt, EPixelFormat uncompressedfmt) = 0; - - //find compressor for specified compressed pixel format. isCompressing to indicate if it's for compressing or decompressing - static ICompressorPtr FindCompressor(EPixelFormat fmt, bool isCompressing); - - virtual ~ICompressor() = 0; - }; - -} // namespace ImageProcessing diff --git a/Gems/ImageProcessing/Code/Source/Compressors/CryTextureSquisher/ColorBlockRGBA4x4c.cpp b/Gems/ImageProcessing/Code/Source/Compressors/CryTextureSquisher/ColorBlockRGBA4x4c.cpp deleted file mode 100644 index b436e7bbc2..0000000000 --- a/Gems/ImageProcessing/Code/Source/Compressors/CryTextureSquisher/ColorBlockRGBA4x4c.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 - -#include - -#include "ColorBlockRGBA4x4c.h" - -namespace ImageProcessing -{ - static_assert(sizeof(int) == 4, "Expected size of int to be 4 bytes!"); - - void ColorBlockRGBA4x4c::setRGBA8(const void* imgBGRA8, unsigned int const width, unsigned int const height, unsigned int const pitch, unsigned int x, unsigned int y) - { - AZ_Assert(imgBGRA8, "%s: Unexpected image pointer", __FUNCTION__); - AZ_Assert((width & 3) == 0, "%s: Unexpected image width", __FUNCTION__); - AZ_Assert((height & 3) == 0, "%s: Unexpected image height", __FUNCTION__); - AZ_Assert(pitch >= width * sizeof(ColorRGBA8), "%s: Unexpected image pitch", __FUNCTION__); - AZ_Assert(x < width, "%s: Unexpected pixel position x", __FUNCTION__); - AZ_Assert(y < height, "%s: Unexpected pixel position y", __FUNCTION__); - - const unsigned int bw = AZ::GetMin(width - x, 4U); - const unsigned int bh = AZ::GetMin(height - y, 4U); - - // note: it's allowed for source data to be not aligned to 4 byte boundary - // (so, we cannot cast source data pointer to ColorBGRA8* in code below) - - if ((bw == 4) && (bh == 4)) - { - for (unsigned int row = 0; row < 4; ++row) - { - const uint8* const pSrc = ((const uint8*)imgBGRA8) + (pitch * (y + row)) + (x * sizeof(ColorRGBA8)); - - ColorRGBA8* const pDst = &m_color[row << 2]; - - pDst[0].setRGBA(&pSrc[0 * sizeof(ColorRGBA8) / sizeof(*pSrc)]); - pDst[1].setRGBA(&pSrc[1 * sizeof(ColorRGBA8) / sizeof(*pSrc)]); - pDst[2].setRGBA(&pSrc[2 * sizeof(ColorRGBA8) / sizeof(*pSrc)]); - pDst[3].setRGBA(&pSrc[3 * sizeof(ColorRGBA8) / sizeof(*pSrc)]); - } - } - else - { - // Rare case: block is smaller than 4x4. - // Let's repeat pixels in this case. - // It will keep frequency of colors, except the case - // when width and/or height equals 3. But, this case - // is very rare because images usually are "power of 2" sized, and even - // if they are not, nobody will notice that the resulting encoding - // for such block is not ideal. - - static unsigned int remainder[] = - { - 0, 0, 0, 0, - 0, 1, 0, 1, - 0, 1, 2, 0, - 0, 1, 2, 3, - }; - - for (unsigned int row = 0; row < 4; ++row) - { - const unsigned int by = remainder[(bh - 1) * 4 + row]; - const uint8* const pSrc = ((const uint8*)imgBGRA8) + pitch * (y + by); - - ColorRGBA8* pDst = &m_color[row * 4]; - - for (unsigned int col = 0; col < 4; ++col) - { - const unsigned int bx = remainder[(bw - 1) * 4 + col]; - - pDst[col].setRGBA(&pSrc[(x + bx) * sizeof(ColorRGBA8) / sizeof(*pSrc)]); - } - } - } - } - - void ColorBlockRGBA4x4c::getRGBA8(void* imgRGBA8, unsigned int const width, unsigned int const height, unsigned int const pitch, unsigned int x, unsigned int y) - { - AZ_Assert(imgRGBA8, "%s: Unexpected image pointer", __FUNCTION__); - AZ_Assert((width & 3) == 0, "%s: Unexpected image width", __FUNCTION__); - AZ_Assert((height & 3) == 0, "%s: Unexpected image height", __FUNCTION__); - AZ_Assert(pitch >= width * sizeof(ColorRGBA8), "%s: Unexpected image pitch", __FUNCTION__); - AZ_Assert(x < width, "%s: Unexpected pixel position x", __FUNCTION__); - AZ_Assert(y < height, "%s: Unexpected pixel position y", __FUNCTION__); - - const unsigned int bw = AZ::GetMin(width - x, 4U); - const unsigned int bh = AZ::GetMin(height - y, 4U); - - // note: it's allowed for source data to be not aligned to 4 byte boundary - // (so, we cannot cast source data pointer to ColorBGRA8* in code below) - - if ((bw == 4) && (bh == 4)) - { - for (unsigned int row = 0; row < 4; ++row) - { - uint8* const pDst = ((uint8*)imgRGBA8) + (pitch * (y + row)) + (x * sizeof(ColorRGBA8)); - - const ColorRGBA8* const pSrc = &m_color[row << 2]; - - pSrc[0].getRGBA(&pDst[0 * sizeof(ColorRGBA8) / sizeof(*pDst)]); - pSrc[1].getRGBA(&pDst[1 * sizeof(ColorRGBA8) / sizeof(*pDst)]); - pSrc[2].getRGBA(&pDst[2 * sizeof(ColorRGBA8) / sizeof(*pDst)]); - pSrc[3].getRGBA(&pDst[3 * sizeof(ColorRGBA8) / sizeof(*pDst)]); - } - } - else - { - // Rare case: block is smaller than 4x4. - // Let's repeat pixels in this case. - // It will keep frequency of colors, except the case - // when width and/or height equals 3. But, this case - // is very rare because images usually are "power of 2" sized, and even - // if they are not, nobody will notice that the resulting encoding - // for such block is not ideal. - - static unsigned int remainder[] = - { - 0, 0, 0, 0, - 0, 1, 0, 1, - 0, 1, 2, 0, - 0, 1, 2, 3, - }; - - for (unsigned int row = 0; row < 4; ++row) - { - const unsigned int by = remainder[(bh - 1) * 4 + row]; - uint8* const pDst = ((uint8*)imgRGBA8) + pitch * (y + by); - - const ColorRGBA8* const pSrc = &m_color[row * 4]; - - for (unsigned int col = 0; col < 4; ++col) - { - const unsigned int bx = remainder[(bw - 1) * 4 + col]; - - pSrc[col].getRGBA(&pDst[(x + bx) * sizeof(ColorRGBA8) / sizeof(*pSrc)]); - } - } - } - } - - void ColorBlockRGBA4x4c::setA8(const void* imgA8, unsigned int const width, unsigned int const height, unsigned int const pitch, unsigned int x, unsigned int y) - { - AZ_Assert(imgA8, "%s: Unexpected image pointer", __FUNCTION__); - AZ_Assert((width & 3) == 0, "%s: Unexpected image width", __FUNCTION__); - AZ_Assert((height & 3) == 0, "%s: Unexpected image height", __FUNCTION__); - AZ_Assert(pitch >= width * sizeof(uint8), "%s: Unexpected image pitch", __FUNCTION__); - AZ_Assert(x < width, "%s: Unexpected pixel position x", __FUNCTION__); - AZ_Assert(y < height, "%s: Unexpected pixel position y", __FUNCTION__); - - const unsigned int bw = AZ::GetMin(width - x, 4U); - const unsigned int bh = AZ::GetMin(height - y, 4U); - - // note: it's allowed for source data to be not aligned to 4 byte boundary - // (so, we cannot cast source data pointer to ColorBGRA8* in code below) - - if ((bw == 4) && (bh == 4)) - { - for (unsigned int row = 0; row < 4; ++row) - { - const uint8* const pSrc = ((const uint8*)imgA8) + (pitch * (y + row)) + (x * sizeof(uint8)); - - ColorRGBA8* const pDst = &m_color[row << 2]; - - pDst[0].setRGBA(0, 0, 0, pSrc[0]); - pDst[1].setRGBA(0, 0, 0, pSrc[1]); - pDst[2].setRGBA(0, 0, 0, pSrc[2]); - pDst[3].setRGBA(0, 0, 0, pSrc[3]); - } - } - else - { - // Rare case: block is smaller than 4x4. - // Let's repeat pixels in this case. - // It will keep frequency of colors, except the case - // when width and/or height equals 3. But, this case - // is very rare because images usually are "power of 2" sized, and even - // if they are not, nobody will notice that the resulting encoding - // for such block is not ideal. - - static unsigned int remainder[] = - { - 0, 0, 0, 0, - 0, 1, 0, 1, - 0, 1, 2, 0, - 0, 1, 2, 3, - }; - - for (unsigned int row = 0; row < 4; ++row) - { - const unsigned int by = remainder[(bh - 1) * 4 + row]; - const uint8* const pSrc = ((const uint8*)imgA8) + pitch * (y + by); - - ColorRGBA8* pDst = &m_color[row * 4]; - - for (unsigned int col = 0; col < 4; ++col) - { - const unsigned int bx = remainder[(bw - 1) * 4 + col]; - - pDst[col].setRGBA(0, 0, 0, pSrc[x + bx]); - } - } - } - } - - void ColorBlockRGBA4x4c::getA8(void* imgA8, unsigned int const width, unsigned int const height, unsigned int const pitch, unsigned int x, unsigned int y) - { - AZ_Assert(imgA8, "%s: Unexpected image pointer", __FUNCTION__); - AZ_Assert((width & 3) == 0, "%s: Unexpected image width", __FUNCTION__); - AZ_Assert((height & 3) == 0, "%s: Unexpected image height", __FUNCTION__); - AZ_Assert(pitch >= width * sizeof(uint8), "%s: Unexpected image pitch", __FUNCTION__); - AZ_Assert(x < width, "%s: Unexpected pixel position x", __FUNCTION__); - AZ_Assert(y < height, "%s: Unexpected pixel position y", __FUNCTION__); - - const unsigned int bw = AZ::GetMin(width - x, 4U); - const unsigned int bh = AZ::GetMin(height - y, 4U); - - // note: it's allowed for source data to be not aligned to 4 byte boundary - // (so, we cannot cast source data pointer to ColorBGRA8* in code below) - - if ((bw == 4) && (bh == 4)) - { - for (unsigned int row = 0; row < 4; ++row) - { - uint8* const pDst = ((uint8*)imgA8) + (pitch * (y + row)) + (x * sizeof(uint8)); - uint8 r, g, b; - - const ColorRGBA8* const pSrc = &m_color[row << 2]; - - pSrc[0].getRGBA(r, g, b, pDst[0]); - pSrc[1].getRGBA(r, g, b, pDst[1]); - pSrc[2].getRGBA(r, g, b, pDst[2]); - pSrc[3].getRGBA(r, g, b, pDst[3]); - } - } - else - { - // Rare case: block is smaller than 4x4. - // Let's repeat pixels in this case. - // It will keep frequency of colors, except the case - // when width and/or height equals 3. But, this case - // is very rare because images usually are "power of 2" sized, and even - // if they are not, nobody will notice that the resulting encoding - // for such block is not ideal. - - static unsigned int remainder[] = - { - 0, 0, 0, 0, - 0, 1, 0, 1, - 0, 1, 2, 0, - 0, 1, 2, 3, - }; - - for (unsigned int row = 0; row < 4; ++row) - { - const unsigned int by = remainder[(bh - 1) * 4 + row]; - uint8* const pDst = ((uint8*)imgA8) + pitch * (y + by); - uint8 r, g, b; - - const ColorRGBA8* const pSrc = &m_color[row * 4]; - - for (unsigned int col = 0; col < 4; ++col) - { - const unsigned int bx = remainder[(bw - 1) * 4 + col]; - - pSrc[col].getRGBA(r, g, b, pDst[x + bx]); - } - } - } - } - - bool ColorBlockRGBA4x4c::isSingleColorIgnoringAlpha() const - { - for (unsigned int i = 1; i < COLOR_COUNT; ++i) - { - if ((m_color[0].b != m_color[i].b) || - (m_color[0].g != m_color[i].g) || - (m_color[0].r != m_color[i].r)) - { - return false; - } - } - - return true; - } - -} // namespace ImageProcessing diff --git a/Gems/ImageProcessing/Code/Source/Compressors/CryTextureSquisher/ColorBlockRGBA4x4c.h b/Gems/ImageProcessing/Code/Source/Compressors/CryTextureSquisher/ColorBlockRGBA4x4c.h deleted file mode 100644 index 06f0ac00ed..0000000000 --- a/Gems/ImageProcessing/Code/Source/Compressors/CryTextureSquisher/ColorBlockRGBA4x4c.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. - -#pragma once - - -#include "ColorTypes.h" - -namespace ImageProcessing -{ - // Uncompressed 4x4 color block of 8bit integers. - struct ColorBlockRGBA4x4c - { - ColorBlockRGBA4x4c() - { - } - - void setRGBA8(const void* imgBGRA8, unsigned int width, unsigned int height, unsigned int pitch, unsigned int x, unsigned int y); - void getRGBA8(void* imgBGRA8, unsigned int width, unsigned int height, unsigned int pitch, unsigned int x, unsigned int y); - - void setA8(const void* imgA8, unsigned int width, unsigned int height, unsigned int pitch, unsigned int x, unsigned int y); - void getA8(void* imgA8, unsigned int width, unsigned int height, unsigned int pitch, unsigned int x, unsigned int y); - - bool isSingleColorIgnoringAlpha() const; - - const ColorRGBA8* colors() const - { - return m_color; - } - - ColorRGBA8* colors() - { - return m_color; - } - - ColorRGBA8 color(unsigned int i) const - { - return m_color[i]; - } - - ColorRGBA8& color(unsigned int i) - { - return m_color[i]; - } - - private: - static const unsigned int COLOR_COUNT = 4 * 4; - - ColorRGBA8 m_color[COLOR_COUNT]; - }; - -} // namespace ImageProcessing diff --git a/Gems/ImageProcessing/Code/Source/Compressors/CryTextureSquisher/ColorBlockRGBA4x4f.cpp b/Gems/ImageProcessing/Code/Source/Compressors/CryTextureSquisher/ColorBlockRGBA4x4f.cpp deleted file mode 100644 index 20db26100a..0000000000 --- a/Gems/ImageProcessing/Code/Source/Compressors/CryTextureSquisher/ColorBlockRGBA4x4f.cpp +++ /dev/null @@ -1,282 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS 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 "ColorBlockRGBA4x4f.h" - -namespace ImageProcessing -{ - static_assert(sizeof(int) == 4, "Expected size of int to be 4 bytes!"); - - void ColorBlockRGBA4x4f::setRGBAf(const void* imgRGBAf, unsigned int const width, unsigned int const height, unsigned int const pitch, unsigned int x, unsigned int y) - { - AZ_Assert(imgRGBAf, "%s: Unexpected image pointer", __FUNCTION__); - AZ_Assert((width & 3) == 0, "%s: Unexpected image width", __FUNCTION__); - AZ_Assert((height & 3) == 0, "%s: Unexpected image height", __FUNCTION__); - AZ_Assert(pitch >= width * sizeof(ColorRGBAf), "%s: Unexpected image pitch", __FUNCTION__); - AZ_Assert(x < width, "%s: Unexpected pixel position x", __FUNCTION__); - AZ_Assert(y < height, "%s: Unexpected pixel position y", __FUNCTION__); - - const unsigned int bw = AZ::GetMin(width - x, 4U); - const unsigned int bh = AZ::GetMin(height - y, 4U); - - // note: it's allowed for source data to be not aligned to 4 byte boundary - // (so, we cannot cast source data pointer to ColorRGBAf* in code below) - - if ((bw == 4) && (bh == 4)) - { - for (unsigned int row = 0; row < 4; ++row) - { - const float* const pSrc = (const float*)(((const uint8*)imgRGBAf) + (pitch * (y + row)) + (x * sizeof(ColorRGBAf))); - - ColorRGBAf* const pDst = &m_color[row << 2]; - - pDst[0].setRGBA(&pSrc[0 * sizeof(ColorRGBAf) / sizeof(*pSrc)]); - pDst[1].setRGBA(&pSrc[1 * sizeof(ColorRGBAf) / sizeof(*pSrc)]); - pDst[2].setRGBA(&pSrc[2 * sizeof(ColorRGBAf) / sizeof(*pSrc)]); - pDst[3].setRGBA(&pSrc[3 * sizeof(ColorRGBAf) / sizeof(*pSrc)]); - } - } - else - { - // Rare case: block is smaller than 4x4. - // Let's repeat pixels in this case. - // It will keep frequency of colors, except the case - // when width and/or height equals 3. But, this case - // is very rare because images usually are "power of 2" sized, and even - // if they are not, nobody will notice that the resulting encoding - // for such block is not ideal. - - static unsigned int remainder[] = - { - 0, 0, 0, 0, - 0, 1, 0, 1, - 0, 1, 2, 0, - 0, 1, 2, 3, - }; - - for (unsigned int row = 0; row < 4; ++row) - { - const unsigned int by = remainder[(bh - 1) * 4 + row]; - const float* const pSrc = (const float*)(((const uint8*)imgRGBAf) + pitch * (y + by)); - - ColorRGBAf* pDst = &m_color[row * 4]; - - for (unsigned int col = 0; col < 4; ++col) - { - const unsigned int bx = remainder[(bw - 1) * 4 + col]; - - pDst[col].setRGBA(&pSrc[(x + bx) * sizeof(ColorRGBAf) / sizeof(*pSrc)]); - } - } - } - } - - void ColorBlockRGBA4x4f::getRGBAf(void* imgRGBAf, unsigned int const width, unsigned int const height, unsigned int const pitch, unsigned int x, unsigned int y) - { - AZ_Assert(imgRGBAf, "%s: Unexpected image pointer", __FUNCTION__); - AZ_Assert((width & 3) == 0, "%s: Unexpected image width", __FUNCTION__); - AZ_Assert((height & 3) == 0, "%s: Unexpected image height", __FUNCTION__); - AZ_Assert(pitch >= width * sizeof(ColorRGBAf), "%s: Unexpected image pitch", __FUNCTION__); - AZ_Assert(x < width, "%s: Unexpected pixel position x", __FUNCTION__); - AZ_Assert(y < height, "%s: Unexpected pixel position y", __FUNCTION__); - - const unsigned int bw = AZ::GetMin(width - x, 4U); - const unsigned int bh = AZ::GetMin(height - y, 4U); - - // note: it's allowed for source data to be not aligned to 4 byte boundary - // (so, we cannot cast source data pointer to ColorRGBAf* in code below) - - if ((bw == 4) && (bh == 4)) - { - for (unsigned int row = 0; row < 4; ++row) - { - float* const pDst = (float*)(((uint8*)imgRGBAf) + (pitch * (y + row)) + (x * sizeof(ColorRGBAf))); - - const ColorRGBAf* const pSrc = &m_color[row << 2]; - - pSrc[0].getRGBA(&pDst[0 * sizeof(ColorRGBAf) / sizeof(*pDst)]); - pSrc[1].getRGBA(&pDst[1 * sizeof(ColorRGBAf) / sizeof(*pDst)]); - pSrc[2].getRGBA(&pDst[2 * sizeof(ColorRGBAf) / sizeof(*pDst)]); - pSrc[3].getRGBA(&pDst[3 * sizeof(ColorRGBAf) / sizeof(*pDst)]); - } - } - else - { - // Rare case: block is smaller than 4x4. - // Let's repeat pixels in this case. - // It will keep frequency of colors, except the case - // when width and/or height equals 3. But, this case - // is very rare because images usually are "power of 2" sized, and even - // if they are not, nobody will notice that the resulting encoding - // for such block is not ideal. - - static unsigned int remainder[] = - { - 0, 0, 0, 0, - 0, 1, 0, 1, - 0, 1, 2, 0, - 0, 1, 2, 3, - }; - - for (unsigned int row = 0; row < 4; ++row) - { - const unsigned int by = remainder[(bh - 1) * 4 + row]; - float* const pDst = (float*)(((uint8*)imgRGBAf) + pitch * (y + by)); - - const ColorRGBAf* const pSrc = &m_color[row * 4]; - - for (unsigned int col = 0; col < 4; ++col) - { - const unsigned int bx = remainder[(bw - 1) * 4 + col]; - - pSrc[col].getRGBA(&pDst[(x + bx) * sizeof(ColorRGBAf) / sizeof(*pDst)]); - } - } - } - } - - void ColorBlockRGBA4x4f::setAf(const void* imgAf, unsigned int const width, unsigned int const height, unsigned int const pitch, unsigned int x, unsigned int y) - { - AZ_Assert(imgAf, "%s: Unexpected image pointer", __FUNCTION__); - AZ_Assert((width & 3) == 0, "%s: Unexpected image width", __FUNCTION__); - AZ_Assert((height & 3) == 0, "%s: Unexpected image height", __FUNCTION__); - AZ_Assert(pitch >= width * sizeof(float), "%s: Unexpected image pitch", __FUNCTION__); - AZ_Assert(x < width, "%s: Unexpected pixel position x", __FUNCTION__); - AZ_Assert(y < height, "%s: Unexpected pixel position y", __FUNCTION__); - - const unsigned int bw = AZ::GetMin(width - x, 4U); - const unsigned int bh = AZ::GetMin(height - y, 4U); - - // note: it's allowed for source data to be not aligned to 4 byte boundary - // (so, we cannot cast source data pointer to ColorRGBAf* in code below) - - if ((bw == 4) && (bh == 4)) - { - for (unsigned int row = 0; row < 4; ++row) - { - const float* const pSrc = (const float*)(((const uint8*)imgAf) + (pitch * (y + row)) + (x * sizeof(float))); - - ColorRGBAf* const pDst = &m_color[row << 2]; - - pDst[0].setRGBA(0, 0, 0, pSrc[0]); - pDst[1].setRGBA(0, 0, 0, pSrc[1]); - pDst[2].setRGBA(0, 0, 0, pSrc[2]); - pDst[3].setRGBA(0, 0, 0, pSrc[3]); - } - } - else - { - // Rare case: block is smaller than 4x4. - // Let's repeat pixels in this case. - // It will keep frequency of colors, except the case - // when width and/or height equals 3. But, this case - // is very rare because images usually are "power of 2" sized, and even - // if they are not, nobody will notice that the resulting encoding - // for such block is not ideal. - - static unsigned int remainder[] = - { - 0, 0, 0, 0, - 0, 1, 0, 1, - 0, 1, 2, 0, - 0, 1, 2, 3, - }; - - for (unsigned int row = 0; row < 4; ++row) - { - const unsigned int by = remainder[(bh - 1) * 4 + row]; - const float* const pSrc = (const float*)(((const uint8*)imgAf) + (pitch * (y + by))); - - ColorRGBAf* pDst = &m_color[row * 4]; - - for (unsigned int col = 0; col < 4; ++col) - { - const unsigned int bx = remainder[(bw - 1) * 4 + col]; - - pDst[col].setRGBA(0, 0, 0, pSrc[x + bx]); - } - } - } - } - - void ColorBlockRGBA4x4f::getAf(void* imgAf, unsigned int const width, unsigned int const height, unsigned int const pitch, unsigned int x, unsigned int y) - { - AZ_Assert(imgAf, "%s: Unexpected image pointer", __FUNCTION__); - AZ_Assert((width & 3) == 0, "%s: Unexpected image width", __FUNCTION__); - AZ_Assert((height & 3) == 0, "%s: Unexpected image height", __FUNCTION__); - AZ_Assert(pitch >= width * sizeof(float), "%s: Unexpected image pitch", __FUNCTION__); - AZ_Assert(x < width, "%s: Unexpected pixel position x", __FUNCTION__); - AZ_Assert(y < height, "%s: Unexpected pixel position y", __FUNCTION__); - - const unsigned int bw = AZ::GetMin(width - x, 4U); - const unsigned int bh = AZ::GetMin(height - y, 4U); - - // note: it's allowed for source data to be not aligned to 4 byte boundary - // (so, we cannot cast source data pointer to ColorRGBAf* in code below) - - if ((bw == 4) && (bh == 4)) - { - for (unsigned int row = 0; row < 4; ++row) - { - float* const pDst = (float*)(((uint8*)imgAf) + (pitch * (y + row)) + (x * sizeof(float))); - float r, g, b; - - const ColorRGBAf* const pSrc = &m_color[row << 2]; - - pSrc[0].getRGBA(r, g, b, pDst[0]); - pSrc[1].getRGBA(r, g, b, pDst[1]); - pSrc[2].getRGBA(r, g, b, pDst[2]); - pSrc[3].getRGBA(r, g, b, pDst[3]); - } - } - else - { - // Rare case: block is smaller than 4x4. - // Let's repeat pixels in this case. - // It will keep frequency of colors, except the case - // when width and/or height equals 3. But, this case - // is very rare because images usually are "power of 2" sized, and even - // if they are not, nobody will notice that the resulting encoding - // for such block is not ideal. - - static unsigned int remainder[] = - { - 0, 0, 0, 0, - 0, 1, 0, 1, - 0, 1, 2, 0, - 0, 1, 2, 3, - }; - - for (unsigned int row = 0; row < 4; ++row) - { - const unsigned int by = remainder[(bh - 1) * 4 + row]; - float* const pDst = (float*)(((uint8*)imgAf) + pitch * (y + by)); - float r, g, b; - - const ColorRGBAf* const pSrc = &m_color[row * 4]; - - for (unsigned int col = 0; col < 4; ++col) - { - const unsigned int bx = remainder[(bw - 1) * 4 + col]; - - pSrc[col].getRGBA(r, g, b, pDst[x + bx]); - } - } - } - } - -} // namespace ImageProcessing diff --git a/Gems/ImageProcessing/Code/Source/Compressors/CryTextureSquisher/ColorBlockRGBA4x4f.h b/Gems/ImageProcessing/Code/Source/Compressors/CryTextureSquisher/ColorBlockRGBA4x4f.h deleted file mode 100644 index 0235dd18db..0000000000 --- a/Gems/ImageProcessing/Code/Source/Compressors/CryTextureSquisher/ColorBlockRGBA4x4f.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 - -#include "ColorTypes.h" - -namespace ImageProcessing -{ - // Uncompressed 4x4 color block of single precision floating points. - struct ColorBlockRGBA4x4f - { - ColorBlockRGBA4x4f() - { - } - - void setRGBAf(const void* imgARGBf, unsigned int width, unsigned int height, unsigned int pitch, unsigned int x, unsigned int y); - void getRGBAf(void* imgARGBf, unsigned int width, unsigned int height, unsigned int pitch, unsigned int x, unsigned int y); - - void setAf(const void* imgAf, unsigned int width, unsigned int height, unsigned int pitch, unsigned int x, unsigned int y); - void getAf(void* imgAf, unsigned int width, unsigned int height, unsigned int pitch, unsigned int x, unsigned int y); - - const ColorRGBAf* colors() const - { - return m_color; - } - - ColorRGBAf* colors() - { - return m_color; - } - - ColorRGBAf color(unsigned int i) const - { - return m_color[i]; - } - - ColorRGBAf& color(unsigned int i) - { - return m_color[i]; - } - - private: - static const unsigned int COLOR_COUNT = 4 * 4; - - ColorRGBAf m_color[COLOR_COUNT]; - }; - -} // namespace ImageProcessing diff --git a/Gems/ImageProcessing/Code/Source/Compressors/CryTextureSquisher/ColorBlockRGBA4x4s.cpp b/Gems/ImageProcessing/Code/Source/Compressors/CryTextureSquisher/ColorBlockRGBA4x4s.cpp deleted file mode 100644 index 9e95a23f17..0000000000 --- a/Gems/ImageProcessing/Code/Source/Compressors/CryTextureSquisher/ColorBlockRGBA4x4s.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 - -#include - -#include "ColorBlockRGBA4x4s.h" - -namespace ImageProcessing -{ - static_assert(sizeof(int) == 4, "Expected size of int to be 4 bytes!"); - - void ColorBlockRGBA4x4s::setRGBA16(const void* imgBGRA16, unsigned int const width, unsigned int const height, unsigned int const pitch, unsigned int x, unsigned int y) - { - AZ_Assert(imgBGRA16, "%s: Unexpected image pointer", __FUNCTION__); - AZ_Assert((width & 3) == 0, "%s: Unexpected image width", __FUNCTION__); - AZ_Assert((height & 3) == 0, "%s: Unexpected image height", __FUNCTION__); - AZ_Assert(pitch >= width * sizeof(ColorRGBA16), "%s: Unexpected image pitch", __FUNCTION__); - AZ_Assert(x < width, "%s: Unexpected pixel position x", __FUNCTION__); - AZ_Assert(y < height, "%s: Unexpected pixel position y", __FUNCTION__); - - const unsigned int bw = AZ::GetMin(width - x, 4U); - const unsigned int bh = AZ::GetMin(height - y, 4U); - - // note: it's allowed for source data to be not aligned to 4 byte boundary - // (so, we cannot cast source data pointer to ColorBGRA16* in code below) - - if ((bw == 4) && (bh == 4)) - { - for (unsigned int row = 0; row < 4; ++row) - { - const uint16* const pSrc = (const uint16*)(((const uint8*)imgBGRA16) + (pitch * (y + row)) + (x * sizeof(ColorRGBA16))); - - ColorRGBA16* const pDst = &m_color[row << 2]; - - pDst[0].setRGBA(&pSrc[0 * sizeof(ColorRGBA16) / sizeof(*pSrc)]); - pDst[1].setRGBA(&pSrc[1 * sizeof(ColorRGBA16) / sizeof(*pSrc)]); - pDst[2].setRGBA(&pSrc[2 * sizeof(ColorRGBA16) / sizeof(*pSrc)]); - pDst[3].setRGBA(&pSrc[3 * sizeof(ColorRGBA16) / sizeof(*pSrc)]); - } - } - else - { - // Rare case: block is smaller than 4x4. - // Let's repeat pixels in this case. - // It will keep frequency of colors, except the case - // when width and/or height equals 3. But, this case - // is very rare because images usually are "power of 2" sized, and even - // if they are not, nobody will notice that the resulting encoding - // for such block is not ideal. - - static unsigned int remainder[] = - { - 0, 0, 0, 0, - 0, 1, 0, 1, - 0, 1, 2, 0, - 0, 1, 2, 3, - }; - - for (unsigned int row = 0; row < 4; ++row) - { - const unsigned int by = remainder[(bh - 1) * 4 + row]; - const uint16* const pSrc = (const uint16*)(((const uint8*)imgBGRA16) + pitch * (y + by)); - - ColorRGBA16* pDst = &m_color[row * 4]; - - for (unsigned int col = 0; col < 4; ++col) - { - const unsigned int bx = remainder[(bw - 1) * 4 + col]; - - pDst[col].setRGBA(&pSrc[(x + bx) * sizeof(ColorRGBA16) / sizeof(*pSrc)]); - } - } - } - } - - void ColorBlockRGBA4x4s::getRGBA16(void* imgBGRA16, unsigned int const width, unsigned int const height, unsigned int const pitch, unsigned int x, unsigned int y) - { - AZ_Assert(imgBGRA16, "%s: Unexpected image pointer", __FUNCTION__); - AZ_Assert((width & 3) == 0, "%s: Unexpected image width", __FUNCTION__); - AZ_Assert((height & 3) == 0, "%s: Unexpected image height", __FUNCTION__); - AZ_Assert(pitch >= width * sizeof(ColorRGBA16), "%s: Unexpected image pitch", __FUNCTION__); - AZ_Assert(x < width, "%s: Unexpected pixel position x", __FUNCTION__); - AZ_Assert(y < height, "%s: Unexpected pixel position y", __FUNCTION__); - - const unsigned int bw = AZ::GetMin(width - x, 4U); - const unsigned int bh = AZ::GetMin(height - y, 4U); - - // note: it's allowed for source data to be not aligned to 4 byte boundary - // (so, we cannot cast source data pointer to ColorBGRA16* in code below) - - if ((bw == 4) && (bh == 4)) - { - for (unsigned int row = 0; row < 4; ++row) - { - uint16* const pDst = (uint16*)(((uint8*)imgBGRA16) + (pitch * (y + row)) + (x * sizeof(ColorRGBA16))); - - const ColorRGBA16* const pSrc = &m_color[row << 2]; - - pSrc[0].getRGBA(&pDst[0 * sizeof(ColorRGBA16) / sizeof(*pDst)]); - pSrc[1].getRGBA(&pDst[1 * sizeof(ColorRGBA16) / sizeof(*pDst)]); - pSrc[2].getRGBA(&pDst[2 * sizeof(ColorRGBA16) / sizeof(*pDst)]); - pSrc[3].getRGBA(&pDst[3 * sizeof(ColorRGBA16) / sizeof(*pDst)]); - } - } - else - { - // Rare case: block is smaller than 4x4. - // Let's repeat pixels in this case. - // It will keep frequency of colors, except the case - // when width and/or height equals 3. But, this case - // is very rare because images usually are "power of 2" sized, and even - // if they are not, nobody will notice that the resulting encoding - // for such block is not ideal. - - static unsigned int remainder[] = - { - 0, 0, 0, 0, - 0, 1, 0, 1, - 0, 1, 2, 0, - 0, 1, 2, 3, - }; - - for (unsigned int row = 0; row < 4; ++row) - { - const unsigned int by = remainder[(bh - 1) * 4 + row]; - uint16* const pDst = (uint16*)(((uint8*)imgBGRA16) + pitch * (y + by)); - - const ColorRGBA16* const pSrc = &m_color[row * 4]; - - for (unsigned int col = 0; col < 4; ++col) - { - const unsigned int bx = remainder[(bw - 1) * 4 + col]; - - pSrc[col].getRGBA(&pDst[(x + bx) * sizeof(ColorRGBA16) / sizeof(*pSrc)]); - } - } - } - } - - void ColorBlockRGBA4x4s::setA16(const void* imgA16, unsigned int const width, unsigned int const height, unsigned int const pitch, unsigned int x, unsigned int y) - { - AZ_Assert(imgA16, "%s: Unexpected image pointer", __FUNCTION__); - AZ_Assert((width & 3) == 0, "%s: Unexpected image width", __FUNCTION__); - AZ_Assert((height & 3) == 0, "%s: Unexpected image height", __FUNCTION__); - AZ_Assert(pitch >= width * sizeof(uint8), "%s: Unexpected image pitch", __FUNCTION__); - AZ_Assert(x < width, "%s: Unexpected pixel position x", __FUNCTION__); - AZ_Assert(y < height, "%s: Unexpected pixel position y", __FUNCTION__); - - const unsigned int bw = AZ::GetMin(width - x, 4U); - const unsigned int bh = AZ::GetMin(height - y, 4U); - - // note: it's allowed for source data to be not aligned to 4 byte boundary - // (so, we cannot cast source data pointer to ColorBGRA16* in code below) - - if ((bw == 4) && (bh == 4)) - { - for (unsigned int row = 0; row < 4; ++row) - { - const uint16* const pSrc = (const uint16*)(((const uint8*)imgA16) + (pitch * (y + row)) + (x * sizeof(uint16))); - - ColorRGBA16* const pDst = &m_color[row << 2]; - - pDst[0].setRGBA(0, 0, 0, pSrc[0]); - pDst[1].setRGBA(0, 0, 0, pSrc[1]); - pDst[2].setRGBA(0, 0, 0, pSrc[2]); - pDst[3].setRGBA(0, 0, 0, pSrc[3]); - } - } - else - { - // Rare case: block is smaller than 4x4. - // Let's repeat pixels in this case. - // It will keep frequency of colors, except the case - // when width and/or height equals 3. But, this case - // is very rare because images usually are "power of 2" sized, and even - // if they are not, nobody will notice that the resulting encoding - // for such block is not ideal. - - static unsigned int remainder[] = - { - 0, 0, 0, 0, - 0, 1, 0, 1, - 0, 1, 2, 0, - 0, 1, 2, 3, - }; - - for (unsigned int row = 0; row < 4; ++row) - { - const unsigned int by = remainder[(bh - 1) * 4 + row]; - const uint16* const pSrc = (const uint16*)(((const uint8*)imgA16) + pitch * (y + by)); - - ColorRGBA16* pDst = &m_color[row * 4]; - - for (unsigned int col = 0; col < 4; ++col) - { - const unsigned int bx = remainder[(bw - 1) * 4 + col]; - - pDst[col].setRGBA(0, 0, 0, pSrc[x + bx]); - } - } - } - } - - void ColorBlockRGBA4x4s::getA16(void* imgA16, unsigned int const width, unsigned int const height, unsigned int const pitch, unsigned int x, unsigned int y) - { - AZ_Assert(imgA16, "%s: Unexpected image pointer", __FUNCTION__); - AZ_Assert((width & 3) == 0, "%s: Unexpected image width", __FUNCTION__); - AZ_Assert((height & 3) == 0, "%s: Unexpected image height", __FUNCTION__); - AZ_Assert(pitch >= width * sizeof(uint8), "%s: Unexpected image pitch", __FUNCTION__); - AZ_Assert(x < width, "%s: Unexpected pixel position x", __FUNCTION__); - AZ_Assert(y < height, "%s: Unexpected pixel position y", __FUNCTION__); - - const unsigned int bw = AZ::GetMin(width - x, 4U); - const unsigned int bh = AZ::GetMin(height - y, 4U); - - // note: it's allowed for source data to be not aligned to 4 byte boundary - // (so, we cannot cast source data pointer to ColorBGRA16* in code below) - - if ((bw == 4) && (bh == 4)) - { - for (unsigned int row = 0; row < 4; ++row) - { - uint16* const pDst = (uint16*)(((uint8*)imgA16) + (pitch * (y + row)) + (x * sizeof(uint16))); - uint16 r, g, b; - - const ColorRGBA16* const pSrc = &m_color[row << 2]; - - pSrc[0].getRGBA(r, g, b, pDst[0]); - pSrc[1].getRGBA(r, g, b, pDst[1]); - pSrc[2].getRGBA(r, g, b, pDst[2]); - pSrc[3].getRGBA(r, g, b, pDst[3]); - } - } - else - { - // Rare case: block is smaller than 4x4. - // Let's repeat pixels in this case. - // It will keep frequency of colors, except the case - // when width and/or height equals 3. But, this case - // is very rare because images usually are "power of 2" sized, and even - // if they are not, nobody will notice that the resulting encoding - // for such block is not ideal. - - static unsigned int remainder[] = - { - 0, 0, 0, 0, - 0, 1, 0, 1, - 0, 1, 2, 0, - 0, 1, 2, 3, - }; - - for (unsigned int row = 0; row < 4; ++row) - { - const unsigned int by = remainder[(bh - 1) * 4 + row]; - uint16* const pDst = (uint16*)(((uint8*)imgA16) + pitch * (y + by)); - uint16 r, g, b; - - const ColorRGBA16* const pSrc = &m_color[row * 4]; - - for (unsigned int col = 0; col < 4; ++col) - { - const unsigned int bx = remainder[(bw - 1) * 4 + col]; - - pSrc[col].getRGBA(r, g, b, pDst[x + bx]); - } - } - } - } - - bool ColorBlockRGBA4x4s::isSingleColorIgnoringAlpha() const - { - for (unsigned int i = 1; i < COLOR_COUNT; ++i) - { - if ((m_color[0].b != m_color[i].b) || - (m_color[0].g != m_color[i].g) || - (m_color[0].r != m_color[i].r)) - { - return false; - } - } - - return true; - } - -} // namespace ImageProcessing diff --git a/Gems/ImageProcessing/Code/Source/Compressors/CryTextureSquisher/ColorBlockRGBA4x4s.h b/Gems/ImageProcessing/Code/Source/Compressors/CryTextureSquisher/ColorBlockRGBA4x4s.h deleted file mode 100644 index 3c4b47cae7..0000000000 --- a/Gems/ImageProcessing/Code/Source/Compressors/CryTextureSquisher/ColorBlockRGBA4x4s.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. - -#pragma once - - -#include "ColorTypes.h" - -namespace ImageProcessing -{ - // Uncompressed 4x4 color block of 16bit integers. - struct ColorBlockRGBA4x4s - { - ColorBlockRGBA4x4s() - { - } - - void setRGBA16(const void* imgRGBA16, unsigned int width, unsigned int height, unsigned int pitch, unsigned int x, unsigned int y); - void getRGBA16(void* imgRGBA16, unsigned int width, unsigned int height, unsigned int pitch, unsigned int x, unsigned int y); - - void setA16(const void* imgA16, unsigned int width, unsigned int height, unsigned int pitch, unsigned int x, unsigned int y); - void getA16(void* imgA16, unsigned int width, unsigned int height, unsigned int pitch, unsigned int x, unsigned int y); - - bool isSingleColorIgnoringAlpha() const; - - const ColorRGBA16* colors() const - { - return m_color; - } - - ColorRGBA16* colors() - { - return m_color; - } - - ColorRGBA16 color(unsigned int i) const - { - return m_color[i]; - } - - ColorRGBA16& color(unsigned int i) - { - return m_color[i]; - } - - private: - static const unsigned int COLOR_COUNT = 4 * 4; - - ColorRGBA16 m_color[COLOR_COUNT]; - }; - -} // namespace ImageProcessing diff --git a/Gems/ImageProcessing/Code/Source/Compressors/CryTextureSquisher/ColorTypes.h b/Gems/ImageProcessing/Code/Source/Compressors/CryTextureSquisher/ColorTypes.h deleted file mode 100644 index 2d5c8eb1e3..0000000000 --- a/Gems/ImageProcessing/Code/Source/Compressors/CryTextureSquisher/ColorTypes.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. - -#pragma once - -namespace ImageProcessing -{ - // 32 bit 8888 RGBA color - struct ColorRGBA8 - { - ColorRGBA8() - { - } - - ColorRGBA8(const ColorRGBA8& a_c) - : u(a_c.u) - { - } - - ColorRGBA8(uint8 a_r, uint8 a_g, uint8 a_b, uint8 a_a) - : r(a_r) - , g(a_g) - , b(a_b) - , a(a_a) - { - } - - explicit ColorRGBA8(uint32 a_u) - : u(a_u) - { - } - - void setRGBA(uint8 a_r, uint8 a_g, uint8 a_b, uint8 a_a) - { - r = a_r; - g = a_g; - b = a_b; - a = a_a; - } - - void setRGBA(const uint8* a_pRGBA8) - { - r = a_pRGBA8[0]; - g = a_pRGBA8[1]; - b = a_pRGBA8[2]; - a = a_pRGBA8[3]; - } - - void getRGBA(uint8& a_r, uint8& a_g, uint8& a_b, uint8& a_a) const - { - a_r = r; - a_g = g; - a_b = b; - a_a = a; - } - - void getRGBA(uint8* a_pRGBA8) const - { - a_pRGBA8[0] = r; - a_pRGBA8[1] = g; - a_pRGBA8[2] = b; - a_pRGBA8[3] = a; - } - - union - { - struct - { - uint8 r; - uint8 g; - uint8 b; - uint8 a; - }; - uint32 u; - }; - }; - - // 64 bit 16161616 RGBA color - struct ColorRGBA16 - { - ColorRGBA16() - { - } - - ColorRGBA16(const ColorRGBA16& a_c) - : u(a_c.u) - { - } - - ColorRGBA16(uint16 a_r, uint16 a_g, uint16 a_b, uint16 a_a) - : r(a_r) - , g(a_g) - , b(a_b) - , a(a_a) - { - } - - explicit ColorRGBA16(AZ::u64 a_u) - : u(a_u) - { - } - - void setRGBA(uint16 a_r, uint16 a_g, uint16 a_b, uint16 a_a) - { - r = a_r; - g = a_g; - b = a_b; - a = a_a; - } - - void setRGBA(const uint16* a_pRGBA16) - { - r = a_pRGBA16[0]; - g = a_pRGBA16[1]; - b = a_pRGBA16[2]; - a = a_pRGBA16[3]; - } - - - void getRGBA(uint16& a_r, uint16& a_g, uint16& a_b, uint16& a_a) const - { - a_r = r; - a_g = g; - a_b = b; - a_a = a; - } - - void getRGBA(uint16* a_pRGBA16) const - { - a_pRGBA16[0] = r; - a_pRGBA16[1] = g; - a_pRGBA16[2] = b; - a_pRGBA16[3] = a; - } - - union - { - struct - { - uint16 r; - uint16 g; - uint16 b; - uint16 a; - }; - AZ::u64 u; - }; - }; - - // 128 bit (4 floats) RGBA color - struct ColorRGBAf - { - ColorRGBAf() - { - } - - ColorRGBAf(const ColorRGBAf& a_c) - : r(a_c.r) - , g(a_c.g) - , b(a_c.b) - , a(a_c.a) - { - } - - ColorRGBAf(float a_r, float a_g, float a_b, float a_a) - : r(a_r) - , g(a_g) - , b(a_b) - , a(a_a) - { - } - - void setRGBA(float a_r, float a_g, float a_b, float a_a) - { - r = a_r; - g = a_g; - b = a_b; - a = a_a; - } - - void setRGBA(const float* a_pRGBAf) - { - r = a_pRGBAf[0]; - g = a_pRGBAf[1]; - b = a_pRGBAf[2]; - a = a_pRGBAf[3]; - } - - void getRGBA(float& a_r, float& a_g, float& a_b, float& a_a) const - { - a_r = r; - a_g = g; - a_b = b; - a_a = a; - } - - void getRGBA(float* a_pRGBAf) const - { - a_pRGBAf[0] = r; - a_pRGBAf[1] = g; - a_pRGBAf[2] = b; - a_pRGBAf[3] = a; - } - - union - { - struct - { - float r; - float g; - float b; - float a; - }; - }; - }; - static_assert(sizeof(ColorRGBA8) == 4, "Expected size of ColorRGBA8 to be 4 bytes!"); - static_assert(sizeof(ColorRGBA16) == 8, "Expected size of ColorRGBA16 to be 4 bytes!"); - static_assert(sizeof(ColorRGBAf) == 16, "Expected size of ColorRGBAf to be 4 bytes!"); -} // namespace ImageProcessing diff --git a/Gems/ImageProcessing/Code/Source/Compressors/CryTextureSquisher/CryTextureSquisher.cpp b/Gems/ImageProcessing/Code/Source/Compressors/CryTextureSquisher/CryTextureSquisher.cpp deleted file mode 100644 index 27bb11a35b..0000000000 --- a/Gems/ImageProcessing/Code/Source/Compressors/CryTextureSquisher/CryTextureSquisher.cpp +++ /dev/null @@ -1,657 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS 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 "ColorBlockRGBA4x4c.h" -#include "ColorBlockRGBA4x4s.h" -#include "ColorBlockRGBA4x4f.h" -#include "CryTextureSquisher.h" - -#include - -#if defined(__clang__) -# pragma clang diagnostic push -# pragma clang diagnostic ignored "-Wnull-dereference" -# pragma clang diagnostic ignored "-Wsometimes-uninitialized" -# pragma clang diagnostic ignored "-Wshift-negative-value" -#endif - -#if AZ_TRAIT_IMAGEPROCESSING_SQUISH_DO_NOT_USE_FASTCALL -#define __fastcall -#define _fastcall -#define __assume(x) -#endif - -#include - -#if defined(__clang__) -# pragma clang diagnostic pop -#endif - -// number of bytes per block per type -#define BLOCKSIZE_BC1 8 -#define BLOCKSIZE_BC2 16 -#define BLOCKSIZE_BC3 16 -#define BLOCKSIZE_BC4 8 -#define BLOCKSIZE_BC5 16 -#define BLOCKSIZE_BC6 16 -#define BLOCKSIZE_BC7 16 -#define BLOCKSIZE_CTX1 8 -#define BLOCKSIZE_LIMIT 16 - -#define PTROFFSET_R 0 -#define PTROFFSET_G 1 -#define PTROFFSET_B 2 -#define PTROFFSET_A 3 - -namespace ImageProcessing -{ - AZStd::mutex s_squishLock; - - -/* ------------------------------------------------------------------------------------------------------------- - * internal presets - */ - static struct ParameterMatrix - { - int flagsBaseline; - int flagsUniform; - int flagsPerceptual; - int flagsQuality[CryTextureSquisher::EQualityProfile::eQualityProfile_Num]; - - size_t offset; - bool alphaOnly; - } P2P[] = - { - // eCompressorPreset_BC1U, - { - squish::kBtc1 + squish::kExcludeAlphaFromPalette, - squish::kColourMetricUniform, - squish::kColourMetricPerceptual, - { squish::kColourRangeFit, squish::kColourClusterFit, squish::kColourIterativeClusterFit, squish::kColourIterativeClusterFit }, - - 0, false - }, - // eCompressorPreset_BC2U, - { - squish::kBtc2, - squish::kColourMetricUniform, - squish::kColourMetricPerceptual, - { squish::kColourRangeFit, squish::kColourClusterFit, squish::kColourIterativeClusterFit, squish::kColourIterativeClusterFit }, - - 0, false - }, - // eCompressorPreset_BC3U, - { - squish::kBtc3, - squish::kColourMetricUniform, - squish::kColourMetricPerceptual, - { squish::kColourRangeFit, squish::kColourClusterFit + squish::kAlphaIterativeFit, squish::kColourIterativeClusterFit + squish::kAlphaIterativeFit, squish::kColourIterativeClusterFit + squish::kAlphaIterativeFit }, - - 0, false - }, - // eCompressorPreset_BC4U, - { - squish::kBtc4, - squish::kColourMetricUniform, - squish::kColourMetricUniform, - { 0, squish::kAlphaIterativeFit, squish::kAlphaIterativeFit, squish::kAlphaIterativeFit }, - - PTROFFSET_R, false - }, - // eCompressorPreset_BC5U, - { - squish::kBtc5, - squish::kColourMetricUniform, - squish::kColourMetricPerceptual, - { 0, squish::kAlphaIterativeFit, squish::kAlphaIterativeFit, squish::kAlphaIterativeFit }, - - PTROFFSET_R, false - }, - // eCompressorPreset_BC6UH, - { - squish::kBtc6, - squish::kColourMetricUniform, - squish::kColourMetricPerceptual, - { squish::kColourRangeFit, squish::kColourRangeFit, squish::kColourRangeFit, squish::kColourRangeFit }, - - 0, false - }, - // eCompressorPreset_BC7U, - { - squish::kBtc7, - squish::kColourMetricUniform, - squish::kColourMetricPerceptual, - { squish::kColourRangeFit, squish::kColourRangeFit, squish::kColourClusterFit, squish::kColourIterativeClusterFit }, - - 0, false - }, - - // eCompressorPreset_BC4S, - { - squish::kBtc4 + squish::kSignedInternal, - squish::kColourMetricUniform, - squish::kColourMetricUniform, - { 0, squish::kAlphaIterativeFit, squish::kAlphaIterativeFit, squish::kAlphaIterativeFit }, - - PTROFFSET_R, false - }, - // eCompressorPreset_BC5S, - { - squish::kBtc5 + squish::kSignedInternal, - squish::kColourMetricUniform, - squish::kColourMetricPerceptual, - { 0, squish::kAlphaIterativeFit, squish::kAlphaIterativeFit, squish::kAlphaIterativeFit }, - - PTROFFSET_R, false - }, - - // eCompressorPreset_BC1Un, - { - squish::kBtc1 + squish::kExcludeAlphaFromPalette, - squish::kColourMetricUnit, - squish::kColourMetricUnit, - { squish::kNormalRangeFit, squish::kNormalRangeFit, squish::kNormalRangeFit, squish::kNormalRangeFit }, - - 0, false - }, - // eCompressorPreset_BC2Un, - { - squish::kBtc2, - squish::kColourMetricUnit, - squish::kColourMetricUnit, - { squish::kNormalRangeFit, squish::kNormalRangeFit, squish::kNormalRangeFit, squish::kNormalRangeFit }, - - 0, false - }, - // eCompressorPreset_BC3Un, - { - squish::kBtc3, - squish::kColourMetricUnit, - squish::kColourMetricUnit, - { squish::kNormalRangeFit, squish::kNormalRangeFit + squish::kAlphaIterativeFit, squish::kNormalRangeFit + squish::kAlphaIterativeFit, squish::kNormalRangeFit + squish::kAlphaIterativeFit }, - - 0, false - }, - // eCompressorPreset_BC4Un, - { - squish::kBtc4, - squish::kColourMetricUniform, - squish::kColourMetricUniform, - { 0, squish::kAlphaIterativeFit, squish::kAlphaIterativeFit, squish::kAlphaIterativeFit }, - - PTROFFSET_B, false - }, - // eCompressorPreset_BC5Un, - { - squish::kBtc5, - squish::kColourMetricUnit, - squish::kColourMetricUnit, - { 0, 0, squish::kNormalIterativeFit, squish::kNormalIterativeFit }, - - PTROFFSET_R, false - }, - // eCompressorPreset_BC6UHn, - { - squish::kBtc6, - squish::kColourMetricUnit, - squish::kColourMetricUnit, - { squish::kNormalRangeFit, squish::kNormalRangeFit, squish::kNormalRangeFit, squish::kNormalRangeFit }, - - 0, false - }, - // eCompressorPreset_BC7Un, - { - squish::kBtc7, - squish::kColourMetricUnit, - squish::kColourMetricUnit, - { squish::kColourRangeFit, squish::kColourRangeFit, squish::kColourClusterFit, squish::kColourIterativeClusterFit }, - - 0, false - }, - - // eCompressorPreset_BC4Sn, - { - squish::kBtc4 + squish::kSignedInternal, - squish::kColourMetricUniform, - squish::kColourMetricUniform, - { 0, squish::kAlphaIterativeFit, squish::kAlphaIterativeFit, squish::kAlphaIterativeFit }, - - PTROFFSET_B, false - }, - // eCompressorPreset_BC5Sn, - { - squish::kBtc5 + squish::kSignedInternal, - squish::kColourMetricUnit, - squish::kColourMetricUnit, - { 0, 0, squish::kNormalIterativeFit, squish::kNormalIterativeFit }, - - PTROFFSET_R, false - }, - - // eCompressorPreset_BC1Ua, - { - squish::kBtc1 + squish::kWeightColourByAlpha, - squish::kColourMetricUniform, - squish::kColourMetricPerceptual, - { squish::kColourRangeFit, squish::kColourClusterFit, squish::kColourIterativeClusterFit, squish::kColourIterativeClusterFit }, - - 0, false - }, - // eCompressorPreset_BC2Ut, - { - squish::kBtc2 + squish::kWeightColourByAlpha, - squish::kColourMetricUniform, - squish::kColourMetricPerceptual, - { squish::kColourRangeFit, squish::kColourClusterFit, squish::kColourIterativeClusterFit, squish::kColourIterativeClusterFit }, - - 0, false - }, - // eCompressorPreset_BC3Ut, - { - squish::kBtc3 + squish::kWeightColourByAlpha, - squish::kColourMetricUniform, - squish::kColourMetricPerceptual, - { squish::kColourRangeFit, squish::kColourClusterFit + squish::kAlphaIterativeFit, squish::kColourIterativeClusterFit + squish::kAlphaIterativeFit, squish::kColourIterativeClusterFit + squish::kAlphaIterativeFit }, - - 0, false - }, - // eCompressorPreset_BC4Ua, - { - squish::kBtc4, - squish::kColourMetricUniform, - squish::kColourMetricUniform, - { 0, squish::kAlphaIterativeFit, squish::kAlphaIterativeFit, squish::kAlphaIterativeFit }, - - PTROFFSET_A, true - }, - // eCompressorPreset_BC7Ut - { - squish::kBtc7 + squish::kWeightColourByAlpha, - squish::kColourMetricUniform, - squish::kColourMetricPerceptual, - { squish::kColourRangeFit, squish::kColourRangeFit, squish::kColourClusterFit, squish::kColourIterativeClusterFit }, - - 0, false - }, - - // eCompressorPreset_BC4Sa, - { - squish::kBtc4 + squish::kSignedInternal, - squish::kColourMetricUniform, - squish::kColourMetricUniform, - { 0, squish::kAlphaIterativeFit, squish::kAlphaIterativeFit, squish::kAlphaIterativeFit }, - - PTROFFSET_A, true - }, - - // eCompressorPreset_BC7Ug - { - squish::kBtc7, - squish::kColourMetricUniform, - squish::kColourMetricUniform, - { squish::kColourRangeFit, squish::kColourClusterFit, squish::kColourClusterFit * 15, squish::kColourClusterFit * 15 }, - - 0, false - }, - - // eCompressorPreset_CTX1U - { - squish::kCtx1, - squish::kColourMetricUniform, - squish::kColourMetricUniform, - { squish::kColourRangeFit, squish::kColourClusterFit, squish::kColourIterativeClusterFit, squish::kColourIterativeClusterFit }, - - 0, false - }, - // eCompressorPreset_CTX1Un - { - squish::kCtx1, - squish::kColourMetricUnit, - squish::kColourMetricUnit, - { squish::kNormalRangeFit, squish::kNormalRangeFit, squish::kNormalRangeFit, squish::kNormalRangeFit }, - - 0, false - }, - }; - - /* ------------------------------------------------------------------------------------------------------------- - * compression functions - */ - void CryTextureSquisher::Compress(const CryTextureSquisher::CompressorParameters& compress) - { - const unsigned int w = compress.width; - const unsigned int h = compress.height; - const size_t offset = P2P[compress.preset].offset; - int flags = P2P[compress.preset].flagsBaseline + P2P[compress.preset].flagsQuality[compress.quality] + - (!compress.perceptual ? P2P[compress.preset].flagsUniform : P2P[compress.preset].flagsPerceptual); - const bool bAlphaOnly = P2P[compress.preset].alphaOnly; - - squish::sqio::dtp datatype; - switch (compress.srcType) - { - case eBufferType_sint8: - flags += squish::kSignedExternal; - case eBufferType_uint8: - datatype = squish::sqio::dtp::DT_U8; - break; - case eBufferType_sint16: - flags += squish::kSignedExternal; - case eBufferType_uint16: - datatype = squish::sqio::dtp::DT_U16; - break; - case eBufferType_sfloat: - flags += squish::kSignedExternal; - case eBufferType_ufloat: - datatype = squish::sqio::dtp::DT_F23; - break; - default: - __assume(0); - break; - } - - if (compress.perceptual && (flags & squish::kColourMetricPerceptual)) - { - flags |= squish::kColourMetricCustom; - } - - const struct squish::sqio sqio = squish::GetSquishIO(w, h, datatype, flags); - - if (compress.perceptual && (flags & squish::kColourMetricPerceptual)) - { - s_squishLock.lock(); - } - if (compress.perceptual && (flags & squish::kColourMetricPerceptual)) - { - squish::SetWeights(sqio.flags, &compress.weights[0]); - } - - AZ_Assert(!(h & 3), "%s: Unexpected compress parameter of height", __FUNCTION__); - - switch (compress.srcType) - { - // compress an unsigned 8bit texture -------------------------------------------------- - // compress a signed 8bit texture ----------------------------------------------------- - case eBufferType_uint8: - case eBufferType_sint8: - { - for (unsigned int y = 0U; y < h; y += 4U) - { - ColorBlockRGBA4x4c srcBlock; - uint8 dstBlock[BLOCKSIZE_LIMIT]; - - uint8* const targetBlock = dstBlock; - const uint8* const sourceRgba = (const uint8*)srcBlock.colors() + offset; - - for (unsigned int x = 0U; x < w; x += 4U) - { - if (!bAlphaOnly) - { - srcBlock.setRGBA8(compress.srcBuffer, w, h, compress.pitch, x, y); - } - else - { - srcBlock.setA8(compress.srcBuffer, w, h, compress.pitch, x, y); - } - - sqio.encoder(sourceRgba, 0xFFFF, targetBlock, sqio.flags); - - if (compress.userOutputFunction) - { - compress.userOutputFunction(compress, targetBlock, sqio.blocksize, y >> 2, x >> 2); - } - } - } - } - break; - // compress an unsigned 16bit texture ------------------------------------------------- - // compress a signed 16bit texture ---------------------------------------------------- - case eBufferType_uint16: - case eBufferType_sint16: - { - for (unsigned int y = 0U; y < h; y += 4U) - { - ColorBlockRGBA4x4s srcBlock; - uint8 dstBlock[BLOCKSIZE_LIMIT]; - - uint8* const targetBlock = dstBlock; - const float* const sourceRgba = (const float*)srcBlock.colors() + offset; - - for (unsigned int x = 0U; x < w; x += 4U) - { - if (!bAlphaOnly) - { - srcBlock.setRGBA16(compress.srcBuffer, w, h, compress.pitch, x, y); - } - else - { - srcBlock.setA16(compress.srcBuffer, w, h, compress.pitch, x, y); - } - - sqio.encoder(sourceRgba, 0xFFFF, targetBlock, sqio.flags); - - if (compress.userOutputFunction) - { - compress.userOutputFunction(compress, targetBlock, sqio.blocksize, y >> 2, x >> 2); - } - } - } - } - break; - // compress an unsigned floating point texture ---------------------------------------- - // compress a signed floating point texture ------------------------------------------- - case eBufferType_ufloat: - case eBufferType_sfloat: - { - for (unsigned int y = 0U; y < h; y += 4U) - { - ColorBlockRGBA4x4f srcBlock; - uint8 dstBlock[BLOCKSIZE_LIMIT]; - - uint8* const targetBlock = dstBlock; - const float* const sourceRgba = (const float*)srcBlock.colors() + offset; - - for (unsigned int x = 0U; x < w; x += 4U) - { - if (!bAlphaOnly) - { - srcBlock.setRGBAf(compress.srcBuffer, w, h, compress.pitch, x, y); - } - else - { - srcBlock.setAf(compress.srcBuffer, w, h, compress.pitch, x, y); - } - - sqio.encoder(sourceRgba, 0xFFFF, targetBlock, sqio.flags); - - if (compress.userOutputFunction) - { - compress.userOutputFunction(compress, targetBlock, sqio.blocksize, y >> 2, x >> 2); - } - } - } - } - break; - default: - AZ_Assert(false, "%s: Unexpected compress source type", __FUNCTION__); - break; - } - - if (compress.perceptual && (flags & squish::kColourMetricPerceptual)) - { - s_squishLock.unlock(); - } - } - - void CryTextureSquisher::Decompress(const DecompressorParameters& decompress) - { - const unsigned int w = decompress.width; - const unsigned int h = decompress.height; - const size_t offset = P2P[decompress.preset].offset; - int flags = P2P[decompress.preset].flagsBaseline + - P2P[decompress.preset].flagsUniform; - const bool bAlphaOnly = P2P[decompress.preset].alphaOnly; - - squish::sqio::dtp datatype; - switch (decompress.dstType) - { - case eBufferType_sint8: - flags += squish::kSignedExternal; - case eBufferType_uint8: - datatype = squish::sqio::dtp::DT_U8; - break; - case eBufferType_sint16: - flags += squish::kSignedExternal; - case eBufferType_uint16: - datatype = squish::sqio::dtp::DT_U16; - break; - case eBufferType_sfloat: - flags += squish::kSignedExternal; - case eBufferType_ufloat: - datatype = squish::sqio::dtp::DT_F23; - break; - default: - __assume(0); - break; - } - - const struct squish::sqio sqio = squish::GetSquishIO(w, h, datatype, flags); - - AZ_Assert(!(h & 3), "%s: Unexpected compress parameter of height", __FUNCTION__); - - switch (decompress.dstType) - { - // decompress an unsigned 8bit texture -------------------------------------------------- - // decompress a signed 8bit texture ----------------------------------------------------- - case eBufferType_uint8: - case eBufferType_sint8: - { - for (unsigned int y = 0U; y < h; y += 4U) - { - uint8 srcBlock[BLOCKSIZE_LIMIT]; - ColorBlockRGBA4x4c dstBlock; - - uint8* const sourceBlock = srcBlock; - uint8* const targetRgba = (uint8*)dstBlock.colors() + offset; - - for (unsigned int x = 0U; x < w; x += 4U) - { - if (decompress.userInputFunction) - { - decompress.userInputFunction(decompress, sourceBlock, sqio.blocksize, y >> 2, x >> 2); - } - - if (!bAlphaOnly) - { - dstBlock.setRGBA8(decompress.dstBuffer, w, h, decompress.pitch, x, y); - } - - sqio.decoder(targetRgba, sourceBlock, sqio.flags); - - if (!bAlphaOnly) - { - dstBlock.getRGBA8(decompress.dstBuffer, w, h, decompress.pitch, x, y); - } - else - { - dstBlock.getA8(decompress.dstBuffer, w, h, decompress.pitch, x, y); - } - } - } - } - break; - // decompress an unsigned 16bit texture ------------------------------------------------- - // decompress a signed 16bit texture ---------------------------------------------------- - case eBufferType_uint16: - case eBufferType_sint16: - { - for (unsigned int y = 0U; y < h; y += 4U) - { - uint8 srcBlock[BLOCKSIZE_LIMIT]; - ColorBlockRGBA4x4s dstBlock; - - uint8* const sourceBlock = srcBlock; - uint16* const targetRgba = (uint16*)dstBlock.colors() + offset; - - for (unsigned int x = 0U; x < w; x += 4U) - { - if (decompress.userInputFunction) - { - decompress.userInputFunction(decompress, sourceBlock, sqio.blocksize, y >> 2, x >> 2); - } - - if (!bAlphaOnly) - { - dstBlock.setRGBA16(decompress.dstBuffer, w, h, decompress.pitch, x, y); - } - - sqio.decoder(targetRgba, sourceBlock, sqio.flags); - - if (!bAlphaOnly) - { - dstBlock.setRGBA16(decompress.dstBuffer, w, h, decompress.pitch, x, y); - } - else - { - dstBlock.getA16(decompress.dstBuffer, w, h, decompress.pitch, x, y); - } - } - } - } - break; - // decompress an unsigned floating point texture ---------------------------------------- - // decompress a signed floating point texture ------------------------------------------- - case eBufferType_ufloat: - case eBufferType_sfloat: - { - for (unsigned int y = 0U; y < h; y += 4U) - { - uint8 srcBlock[BLOCKSIZE_LIMIT]; - ColorBlockRGBA4x4f dstBlock; - - uint8* const sourceBlock = srcBlock; - float* const targetRgba = (float*)dstBlock.colors() + offset; - - for (unsigned int x = 0U; x < w; x += 4U) - { - if (decompress.userInputFunction) - { - decompress.userInputFunction(decompress, sourceBlock, sqio.blocksize, y >> 2, x >> 2); - } - - if (!bAlphaOnly) - { - dstBlock.setRGBAf(decompress.dstBuffer, w, h, decompress.pitch, x, y); - } - sqio.decoder(targetRgba, sourceBlock, sqio.flags); - - if (!bAlphaOnly) - { - dstBlock.getRGBAf(decompress.dstBuffer, w, h, decompress.pitch, x, y); - } - else - { - dstBlock.getAf(decompress.dstBuffer, w, h, decompress.pitch, x, y); - } - } - } - } - break; - default: - AZ_Assert(false, "%s: Unexpected compress destination type", __FUNCTION__); - break; - } - } - -} // namespace ImageProcessing diff --git a/Gems/ImageProcessing/Code/Source/Compressors/CryTextureSquisher/CryTextureSquisher.h b/Gems/ImageProcessing/Code/Source/Compressors/CryTextureSquisher/CryTextureSquisher.h deleted file mode 100644 index 2aa7117d46..0000000000 --- a/Gems/ImageProcessing/Code/Source/Compressors/CryTextureSquisher/CryTextureSquisher.h +++ /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. - -#pragma once - -namespace ImageProcessing -{ - class CryTextureSquisher - { - public: - enum EBufferType - { - eBufferType_uint8, // native support: BC1-5/7,CTX1 - eBufferType_sint8, // native support: BC4-5 - eBufferType_uint16, // native support: BC1-7,CTX1 - eBufferType_sint16, // native support: BC4-6 - eBufferType_ufloat, // native support: BC1-7,CTX1 - eBufferType_sfloat, // native support: BC4-6 - }; - - enum EQualityProfile - { - eQualityProfile_Low = 0,// as-fast-as-possible - eQualityProfile_Medium, // not so bad (nightly builds) - eQualityProfile_High, // relative good (weekly builds) - eQualityProfile_Best, // as-best-as-possible (final build for release) - - eQualityProfile_Num - }; - - enum ECodingPreset - { - eCompressorPreset_BC1U = 0, - eCompressorPreset_BC2U, - eCompressorPreset_BC3U, - eCompressorPreset_BC4U, // r-channel from RGBA - eCompressorPreset_BC5U, // rg-channels from RGBA - eCompressorPreset_BC6UH, - eCompressorPreset_BC7U, - - eCompressorPreset_BC4S, // r-channel from RGBA - eCompressorPreset_BC5S, // rg-channels from RGBA - - // normal vectors -> unit metric - eCompressorPreset_BC1Un, - eCompressorPreset_BC2Un, - eCompressorPreset_BC3Un, - eCompressorPreset_BC4Un, // z-channel from XYZD - eCompressorPreset_BC5Un, // xy-channels from XYZD, xyz must be a valid unit-vector - eCompressorPreset_BC6UHn, - eCompressorPreset_BC7Un, - - eCompressorPreset_BC4Sn, // z-channel from XYZD - eCompressorPreset_BC5Sn, // xy-channels from XYZD, xyz must be a valid unit-vector - - // transparency -> weighted alpha - eCompressorPreset_BC1Ua, - eCompressorPreset_BC2Ut, - eCompressorPreset_BC3Ut, - eCompressorPreset_BC4Ua, // a-channel from RGBA - eCompressorPreset_BC7Ut, - - eCompressorPreset_BC4Sa, // a-channel from RGBA - - // grey-scale -> 12+ bits of precision - eCompressorPreset_BC7Ug, - - // special ones - eCompressorPreset_CTX1U, // rg-channels from RGBA - eCompressorPreset_CTX1Un, // xy-channels from XYZD, xyz must be a valid unit-vector - - eCompressorPreset_Num - }; - - struct CompressorParameters - { - // source's parameters - EBufferType srcType; - const void* srcBuffer; - unsigned int width; - unsigned int height; - unsigned int pitch; - - // coding preset - ECodingPreset preset; - EQualityProfile quality; - - // either if "srgb==1" or if "rgbweights!=uniform" - bool perceptual; - float weights[4]; - - void* userPtr; - int userInt; - - void(*userOutputFunction)(const CompressorParameters& compress, const void* compressedData, unsigned int compressedSize, unsigned int oy, unsigned int ox); - }; - - struct DecompressorParameters - { - // destination's parameters - EBufferType dstType; - void* dstBuffer; - unsigned int width; - unsigned int height; - unsigned int pitch; - - // coding preset - ECodingPreset preset; - - void* userPtr; - int userInt; - - void(*userInputFunction)(const DecompressorParameters& decompress, void* compressedData, unsigned int compressedSize, unsigned int oy, unsigned int ox); - }; - - public: - static void Compress(const CompressorParameters& compress); - static void Decompress(const DecompressorParameters& decompress); - }; - -} //namespace ImageProcessing - diff --git a/Gems/ImageProcessing/Code/Source/Compressors/ETC2.cpp b/Gems/ImageProcessing/Code/Source/Compressors/ETC2.cpp deleted file mode 100644 index 3d43fe7dda..0000000000 --- a/Gems/ImageProcessing/Code/Source/Compressors/ETC2.cpp +++ /dev/null @@ -1,229 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or 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 - -namespace ImageProcessing -{ - //limited to 1 thread because AP requires so. We may change to n when AP allocate n thread to a job in the furture - static const int MAX_COMP_JOBS = 1; - static const int MIN_COMP_JOBS = 1; - static const float ETC_LOW_EFFORT_LEVEL = 25.0f; - static const float ETC_MED_EFFORT_LEVEL = 40.0f; - static const float ETC_HIGH_EFFORT_LEVEL = 80.0f; - - //Grab the Etc2Comp specific pixel format enum - static Etc::Image::Format FindEtc2PixelFormat(EPixelFormat fmt) - { - switch (fmt) - { - case ePixelFormat_EAC_RG11: - return Etc::Image::Format::RG11; - case ePixelFormat_EAC_R11: - return Etc::Image::Format::R11; - case ePixelFormat_ETC2: - return Etc::Image::Format::RGB8; - case ePixelFormat_ETC2a: - return Etc::Image::Format::RGBA8; - default: - return Etc::Image::Format::FORMATS; - } - } - - //Get the errmetric required for the compression - static Etc::ErrorMetric FindErrMetric(Etc::Image::Format fmt) - { - switch (fmt) - { - case Etc::Image::Format::RG11: - return Etc::ErrorMetric::NORMALXYZ; - case Etc::Image::Format::R11: - return Etc::ErrorMetric::NUMERIC; - case Etc::Image::Format::RGB8: - return Etc::ErrorMetric::RGBX; - case Etc::Image::Format::RGBA8: - return Etc::ErrorMetric::RGBA; - default: - return Etc::ErrorMetric::ERROR_METRICS; - } - - } - - //Convert to sRGB format - static Etc::Image::Format FindGammaEtc2PixelFormat(Etc::Image::Format fmt) - { - switch (fmt) - { - case Etc::Image::Format::RGB8: - return Etc::Image::Format::SRGB8; - case Etc::Image::Format::RGBA8: - return Etc::Image::Format::SRGBA8; - case Etc::Image::Format::RGB8A1: - return Etc::Image::Format::SRGB8A1; - default: - return Etc::Image::Format::FORMATS; - } - } - - bool ETC2Compressor::IsCompressedPixelFormatSupported(EPixelFormat fmt) - { - return (FindEtc2PixelFormat(fmt) != Etc::Image::Format::FORMATS); - } - - bool ETC2Compressor::IsUncompressedPixelFormatSupported(EPixelFormat fmt) - { - //for uncompress format - if (fmt == ePixelFormat_R8G8B8A8) - { - return true; - } - return false; - } - - EPixelFormat ETC2Compressor::GetSuggestedUncompressedFormat([[maybe_unused]] EPixelFormat compressedfmt, [[maybe_unused]] EPixelFormat uncompressedfmt) - { - return ePixelFormat_R8G8B8A8; - } - - bool ETC2Compressor::DoesSupportDecompress([[maybe_unused]] EPixelFormat fmtDst) - { - return false; - } - - IImageObjectPtr ETC2Compressor::CompressImage(IImageObjectPtr srcImage, EPixelFormat fmtDst, - const CompressOption *compressOption) - { - const size_t srcPixelSize = 4; - - //validate input - EPixelFormat fmtSrc = srcImage->GetPixelFormat(); - - //src format need to be uncompressed and dst format need to compressed. - if (!IsUncompressedPixelFormatSupported(fmtSrc) || !IsCompressedPixelFormatSupported(fmtDst)) - { - return nullptr; - } - - IImageObjectPtr dstImage(srcImage->AllocateImage(fmtDst)); - - //determinate compression quality - ICompressor::EQuality quality = ICompressor::eQuality_Normal; - //get setting from compression option - if (compressOption) - { - quality = compressOption->compressQuality; - } - - float qualityEffort = 0.0f; - switch (quality) - { - case eQuality_Preview: - case eQuality_Fast: - { - qualityEffort = ETC_LOW_EFFORT_LEVEL; - break; - } - case eQuality_Normal: - { - qualityEffort = ETC_MED_EFFORT_LEVEL; - break; - } - default: - { - qualityEffort = ETC_HIGH_EFFORT_LEVEL; - } - } - - Etc::Image::Format dstEtc2Format = FindEtc2PixelFormat(fmtDst); - if (srcImage->GetImageFlags() & EIF_SRGBRead) - { - dstEtc2Format = FindGammaEtc2PixelFormat(dstEtc2Format); - } - - //use to read pixel data from src image - IPixelOperationPtr pixelOp = CreatePixelOperation(fmtSrc); - //get count of bytes per pixel for images - AZ::u32 pixelBytes = CPixelFormats::GetInstance().GetPixelFormatInfo(fmtSrc)->bitsPerBlock / 8; - - const AZ::u32 mipCount = dstImage->GetMipCount(); - for (AZ::u32 mip = 0; mip < mipCount; ++mip) - { - const AZ::u32 width = srcImage->GetWidth(mip); - const AZ::u32 height = srcImage->GetHeight(mip); - - // Prepare source data - AZ::u8* srcMem; - AZ::u32 srcPitch; - srcImage->GetImagePointer(mip, srcMem, srcPitch); - const AZ::u32 pixelCount = srcImage->GetPixelCount(mip); - - Etc::ColorFloatRGBA* rgbaPixels = new Etc::ColorFloatRGBA[pixelCount]; - Etc::ColorFloatRGBA* rgbaPixelPtr = rgbaPixels; - float r, g, b, a; - for (AZ::u32 pixelIdx = 0; pixelIdx < pixelCount; pixelIdx++, srcMem += pixelBytes, rgbaPixelPtr++) - { - pixelOp->GetRGBA(srcMem, r, g, b, a); - rgbaPixelPtr->fA = a; - rgbaPixelPtr->fR = r; - rgbaPixelPtr->fG = g; - rgbaPixelPtr->fB = b; - } - - //Call into etc2Comp lib to compress. https://medium.com/@duhroach/building-a-blazing-fast-etc2-compressor-307f3e9aad99 - Etc::ErrorMetric errMetric = FindErrMetric(dstEtc2Format); - unsigned char* paucEncodingBits; - unsigned int uiEncodingBitsBytes; - unsigned int uiExtendedWidth; - unsigned int uiExtendedHeight; - int iEncodingTime_ms; - - Etc::Encode(reinterpret_cast(rgbaPixels), - width, height, - dstEtc2Format, - errMetric, - qualityEffort, - MIN_COMP_JOBS, - MAX_COMP_JOBS, - &paucEncodingBits, &uiEncodingBitsBytes, - &uiExtendedWidth, &uiExtendedHeight, - &iEncodingTime_ms); - - AZ::u8* dstMem; - AZ::u32 dstPitch; - dstImage->GetImagePointer(mip, dstMem, dstPitch); - - memcpy(dstMem, paucEncodingBits, uiEncodingBitsBytes); - delete[] rgbaPixels; - } - - return dstImage; - } - - IImageObjectPtr ETC2Compressor::DecompressImage(IImageObjectPtr srcImage, [[maybe_unused]] EPixelFormat fmtDst) - { - //etc2Comp doesn't support decompression - //Since PVRTexLib support ETC formats too. It may take over the decompression. - return nullptr; - } - -} // namespace ImageProcessing diff --git a/Gems/ImageProcessing/Code/Source/Compressors/ETC2.h b/Gems/ImageProcessing/Code/Source/Compressors/ETC2.h deleted file mode 100644 index d862bead68..0000000000 --- a/Gems/ImageProcessing/Code/Source/Compressors/ETC2.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. -* -*/ - -#pragma once - -#include - -namespace ImageProcessing -{ - class ETC2Compressor : public ICompressor - { - public: - static bool IsCompressedPixelFormatSupported(EPixelFormat fmt); - static bool IsUncompressedPixelFormatSupported(EPixelFormat fmt); - static bool DoesSupportDecompress(EPixelFormat fmtDst); - - IImageObjectPtr CompressImage(IImageObjectPtr srcImage, EPixelFormat fmtDst, const CompressOption *compressOption) override; - IImageObjectPtr DecompressImage(IImageObjectPtr srcImage, EPixelFormat fmtDst) override; - - EPixelFormat GetSuggestedUncompressedFormat(EPixelFormat compressedfmt, EPixelFormat uncompressedfmt) override; - }; - -} // namespace ImageProcessing diff --git a/Gems/ImageProcessing/Code/Source/Compressors/PVRTC.cpp b/Gems/ImageProcessing/Code/Source/Compressors/PVRTC.cpp deleted file mode 100644 index 64fee3b747..0000000000 --- a/Gems/ImageProcessing/Code/Source/Compressors/PVRTC.cpp +++ /dev/null @@ -1,389 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or 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 - -#if AZ_TRAIT_IMAGEPROCESSING_PVRTEXLIB_USE_WINDLL_IMPORT -//_WINDLL_IMPORT need to be defined before including PVRTexLib header files to avoid linking error on windows. -#define _WINDLL_IMPORT -// NOMINMAX needs to be defined before including PVRTexLib header files (which include Windows.h) -// so that Windows.h doesn't define min/max. Otherwise, a compile error may arise in Uber builds -#ifndef NOMINMAX -#define NOMINMAX -#endif -#endif -#include -#include - - -namespace ImageProcessing -{ - // Note: PVRTexLib supports ASTC formats, ETC formats, PVRTC formats and BC formats - // We haven't tested the performace to compress BC formats compare to CTSquisher - // For PVRTC formats, we only added PVRTC 1 support for now - // The compression for ePVRTPF_EAC_R11 and ePVRTPF_EAC_RG11 are very slow. It takes 7 and 14 minutes for a 2048x2048 texture. - EPVRTPixelFormat FindPvrPixelFormat(EPixelFormat fmt) - { - switch (fmt) - { - case ePixelFormat_ASTC_4x4: - return ePVRTPF_ASTC_4x4; - case ePixelFormat_ASTC_5x4: - return ePVRTPF_ASTC_5x4; - case ePixelFormat_ASTC_5x5: - return ePVRTPF_ASTC_5x5; - case ePixelFormat_ASTC_6x5: - return ePVRTPF_ASTC_6x5; - case ePixelFormat_ASTC_6x6: - return ePVRTPF_ASTC_6x6; - case ePixelFormat_ASTC_8x5: - return ePVRTPF_ASTC_8x5; - case ePixelFormat_ASTC_8x6: - return ePVRTPF_ASTC_8x6; - case ePixelFormat_ASTC_8x8: - return ePVRTPF_ASTC_8x8; - case ePixelFormat_ASTC_10x5: - return ePVRTPF_ASTC_10x5; - case ePixelFormat_ASTC_10x6: - return ePVRTPF_ASTC_10x6; - case ePixelFormat_ASTC_10x8: - return ePVRTPF_ASTC_10x8; - case ePixelFormat_ASTC_10x10: - return ePVRTPF_ASTC_10x10; - case ePixelFormat_ASTC_12x10: - return ePVRTPF_ASTC_12x10; - case ePixelFormat_ASTC_12x12: - return ePVRTPF_ASTC_12x12; - case ePixelFormat_PVRTC2: - return ePVRTPF_PVRTCI_2bpp_RGBA; - case ePixelFormat_PVRTC4: - return ePVRTPF_PVRTCI_4bpp_RGBA; - case ePixelFormat_EAC_R11: - return ePVRTPF_EAC_R11; - case ePixelFormat_EAC_RG11: - return ePVRTPF_EAC_RG11; - case ePixelFormat_ETC2: - return ePVRTPF_ETC2_RGB; - case ePixelFormat_ETC2a: - return ePVRTPF_ETC2_RGBA; - default: - return ePVRTPF_NumCompressedPFs; - } - } - - bool PVRTCCompressor::IsCompressedPixelFormatSupported(EPixelFormat fmt) - { - return (FindPvrPixelFormat(fmt) != ePVRTPF_NumCompressedPFs); - } - - bool PVRTCCompressor::IsUncompressedPixelFormatSupported(EPixelFormat fmt) - { - //for uncompress format - if (fmt == ePixelFormat_R8G8B8A8) - { - return true; - } - return false; - } - - - EPixelFormat PVRTCCompressor::GetSuggestedUncompressedFormat([[maybe_unused]] EPixelFormat compressedfmt, [[maybe_unused]] EPixelFormat uncompressedfmt) - { - return ePixelFormat_R8G8B8A8; - } - - - bool PVRTCCompressor::DoesSupportDecompress([[maybe_unused]] EPixelFormat fmtDst) - { - return true; - } - - IImageObjectPtr PVRTCCompressor::CompressImage(IImageObjectPtr srcImage, EPixelFormat fmtDst, - const CompressOption *compressOption) - { - //validate input - EPixelFormat fmtSrc = srcImage->GetPixelFormat(); - - //src format need to be uncompressed and dst format need to compressed. - if (!IsUncompressedPixelFormatSupported(fmtSrc) || !IsCompressedPixelFormatSupported(fmtDst)) - { - return nullptr; - } - - IImageObjectPtr dstImage(srcImage->AllocateImage(fmtDst)); - - //determinate compression quality - pvrtexture::ECompressorQuality internalQuality = pvrtexture::eETCFast; - ICompressor::EQuality quality = ICompressor::eQuality_Normal; - AZ::Vector3 uniformWeights = AZ::Vector3(0.3333f, 0.3334f, 0.3333f); - AZ::Vector3 weights = uniformWeights; - bool isUniform = true; - //get setting from compression option - if (compressOption) - { - quality = compressOption->compressQuality; - weights = compressOption->rgbWeight; - isUniform = (weights == uniformWeights); - } - - if (IsETCFormat(fmtDst)) - { - if ((quality <= eQuality_Normal) && isUniform) - { - internalQuality = pvrtexture::eETCFast; - } - else if (quality <= eQuality_Normal) - { - internalQuality = pvrtexture::eETCNormal; - } - else if (isUniform) - { - internalQuality = pvrtexture::eETCSlow; - } - else - { - internalQuality = pvrtexture::eETCSlow; - } - } - else if (IsASTCFormat(fmtDst)) - { - if (quality == eQuality_Preview) - { - internalQuality = pvrtexture::eASTCVeryFast; - } - else if (quality == eQuality_Fast) - { - internalQuality = pvrtexture::eASTCFast; - } - else if (quality == eQuality_Normal) - { - internalQuality = pvrtexture::eASTCMedium; - } - else - { - internalQuality = pvrtexture::eASTCThorough; - } - } - else - { - if (quality == eQuality_Preview) - { - internalQuality = pvrtexture::ePVRTCFastest; - } - else if (quality == eQuality_Fast) - { - internalQuality = pvrtexture::ePVRTCFast; - } - else if (quality == eQuality_Normal) - { - internalQuality = pvrtexture::ePVRTCNormal; - } - else - { - internalQuality = pvrtexture::ePVRTCHigh; - } - } - - // setup color space - EPVRTColourSpace cspace = ePVRTCSpacelRGB; - if (srcImage->GetImageFlags() & EIF_SRGBRead) - { - cspace = ePVRTCSpacesRGB; - } - - //setup src texture for compression - const pvrtexture::PixelType srcPixelType('r', 'g', 'b', 'a', 8, 8, 8, 8); - const AZ::u32 dstMips = dstImage->GetMipCount(); - for (AZ::u32 mip = 0; mip < dstMips; ++mip) - { - const AZ::u32 width = srcImage->GetWidth(mip); - const AZ::u32 height = srcImage->GetHeight(mip); - - // Prepare source data - AZ::u8* srcMem; - uint32 srcPitch; - srcImage->GetImagePointer(mip, srcMem, srcPitch); - - const pvrtexture::CPVRTextureHeader srcHeader( - srcPixelType.PixelTypeID, // AZ::u64 u64PixelFormat, - width, // uint32 u32Height=1, - height, // uint32 u32Width=1, - 1, // uint32 u32Depth=1, - 1, // uint32 u32NumMipMaps=1, - 1, // uint32 u32NumArrayMembers=1, - 1, // uint32 u32NumFaces=1, - cspace, // EPVRTColourSpace eColourSpace=ePVRTCSpacelRGB, - ePVRTVarTypeUnsignedByteNorm, // EPVRTVariableType eChannelType=ePVRTVarTypeUnsignedByteNorm, - false); // bool bPreMultiplied=false); - - pvrtexture::CPVRTexture compressTexture(srcHeader, srcMem); - - //compressing - bool isSuccess = false; -#if AZ_TRAIT_IMAGEPROCESSING_SUPPORT_TRY_CATCH - try -#endif // AZ_TRAIT_IMAGEPROCESSING_SUPPORT_TRY_CATCH - { - isSuccess = pvrtexture::Transcode( - compressTexture, - pvrtexture::PixelType(FindPvrPixelFormat(fmtDst)), - ePVRTVarTypeUnsignedByteNorm, - cspace, - internalQuality); - } -#if AZ_TRAIT_IMAGEPROCESSING_SUPPORT_TRY_CATCH - catch (...) - { - AZ_Error("Image Processing", false, "Unknown exception in PVRTexLib"); - return nullptr; - } -#endif // AZ_TRAIT_IMAGEPROCESSING_SUPPORT_TRY_CATCH - - if (!isSuccess) - { - AZ_Error("Image Processing", false, "Failed to compress image with PVRTexLib. You may not have astcenc.exe for compressing ASTC formates"); - return nullptr; - } - - // Getting compressed data - const void* const compressedData = compressTexture.getDataPtr(); - if (!compressedData) - { - AZ_Error("Image Processing", false, "Failed to obtain compressed image data by using PVRTexLib"); - return nullptr; - } - - const AZ::u32 compressedDataSize = compressTexture.getDataSize(); - if (dstImage->GetMipBufSize(mip) != compressedDataSize) - { - AZ_Error("Image Processing", false, "Compressed image data size mismatch while using PVRTexLib"); - return nullptr; - } - - //save compressed data to dst image - AZ::u8* dstMem; - AZ::u32 dstPitch; - dstImage->GetImagePointer(mip, dstMem, dstPitch); - memcpy(dstMem, compressedData, compressedDataSize); - } - - return dstImage; - } - - IImageObjectPtr PVRTCCompressor::DecompressImage(IImageObjectPtr srcImage, EPixelFormat fmtDst) - { - //validate input - EPixelFormat fmtSrc = srcImage->GetPixelFormat(); //compressed - - if (!IsCompressedPixelFormatSupported(fmtSrc) || !IsUncompressedPixelFormatSupported(fmtDst)) - { - return nullptr; - } - - EPVRTColourSpace colorSpace = ePVRTCSpacelRGB; - if (srcImage->GetImageFlags() & EIF_SRGBRead) - { - colorSpace = ePVRTCSpacesRGB; - } - - IImageObjectPtr dstImage(srcImage->AllocateImage(fmtDst)); - - const AZ::u32 mipCount = dstImage->GetMipCount(); - for (AZ::u32 mip = 0; mip < mipCount; ++mip) - { - const AZ::u32 width = srcImage->GetWidth(mip); - const AZ::u32 height = srcImage->GetHeight(mip); - - // Preparing source compressed data - const pvrtexture::CPVRTextureHeader compressedHeader( - FindPvrPixelFormat(fmtSrc), // AZ::u64 u64PixelFormat, - width, // uint32 u32Height=1, - height, // uint32 u32Width=1, - 1, // uint32 u32Depth=1, - 1, // uint32 u32NumMipMaps=1, - 1, // uint32 u32NumArrayMembers=1, - 1, // uint32 u32NumFaces=1, - colorSpace, // EPVRTColourSpace eColourSpace=ePVRTCSpacelRGB, - ePVRTVarTypeUnsignedByteNorm, // EPVRTVariableType eChannelType=ePVRTVarTypeUnsignedByteNorm, - false); // bool bPreMultiplied=false); - - const AZ::u32 compressedDataSize = compressedHeader.getDataSize(); - if (srcImage->GetMipBufSize(mip) != compressedDataSize) - { - AZ_Error("Image Processing", false, "Decompressed image data size mismatch while using PVRTexLib"); - return nullptr; - } - - AZ::u8* srcMem; - AZ::u32 srcPitch; - srcImage->GetImagePointer(mip, srcMem, srcPitch); - pvrtexture::CPVRTexture cTexture(compressedHeader, srcMem); - - // Decompress - bool bOk = false; -#if AZ_TRAIT_IMAGEPROCESSING_SUPPORT_TRY_CATCH - try - { -#endif // AZ_TRAIT_IMAGEPROCESSING_SUPPORT_TRY_CATCH - bOk = pvrtexture::Transcode( - cTexture, - pvrtexture::PVRStandard8PixelType, - ePVRTVarTypeUnsignedByteNorm, - colorSpace, - pvrtexture::ePVRTCHigh); - -#if AZ_TRAIT_IMAGEPROCESSING_SUPPORT_TRY_CATCH - } - catch (...) - { - AZ_Error("Image Processing", false, "Unknown exception in PVRTexLib when decompressing"); - return nullptr; - } -#endif // AZ_TRAIT_IMAGEPROCESSING_SUPPORT_TRY_CATCH - - if (!bOk) - { - AZ_Error("Image Processing", false, "Failed to decompress an image by using PVRTexLib"); - return nullptr; - } - - // Getting decompressed data - const void* const pDecompressedData = cTexture.getDataPtr(); - if (!pDecompressedData) - { - AZ_Error("Image Processing", false, "Failed to obtain decompressed image data by using PVRTexLib"); - return nullptr; - } - - const AZ::u32 decompressedDataSize = cTexture.getDataSize(); - if (dstImage->GetMipBufSize(mip) != decompressedDataSize) - { - AZ_Error("Image Processing", false, "Decompressed image data size mismatch while using PVRTexLib"); - return nullptr; - } - - //save decompressed image to dst image - AZ::u8* dstMem; - AZ::u32 dstPitch; - dstImage->GetImagePointer(mip, dstMem, dstPitch); - memcpy(dstMem, pDecompressedData, decompressedDataSize); - } - - return dstImage; - } - -} //namespace ImageProcessing diff --git a/Gems/ImageProcessing/Code/Source/Compressors/PVRTC.h b/Gems/ImageProcessing/Code/Source/Compressors/PVRTC.h deleted file mode 100644 index 648990a819..0000000000 --- a/Gems/ImageProcessing/Code/Source/Compressors/PVRTC.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. -* -*/ - -#pragma once - -#include - -namespace ImageProcessing -{ - class PVRTCCompressor : public ICompressor - { - public: - static bool IsCompressedPixelFormatSupported(EPixelFormat fmt); - static bool IsUncompressedPixelFormatSupported(EPixelFormat fmt); - static bool DoesSupportDecompress(EPixelFormat fmtDst); - - IImageObjectPtr CompressImage(IImageObjectPtr srcImage, EPixelFormat fmtDst, const CompressOption *compressOption) override; - IImageObjectPtr DecompressImage(IImageObjectPtr srcImage, EPixelFormat fmtDst) override; - - EPixelFormat GetSuggestedUncompressedFormat(EPixelFormat compressedfmt, EPixelFormat uncompressedfmt) override; - }; - -} // namespace ImageProcessing diff --git a/Gems/ImageProcessing/Code/Source/Converters/AlphaCoverage.cpp b/Gems/ImageProcessing/Code/Source/Converters/AlphaCoverage.cpp deleted file mode 100644 index 46444d8d87..0000000000 --- a/Gems/ImageProcessing/Code/Source/Converters/AlphaCoverage.cpp +++ /dev/null @@ -1,121 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or 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 - -/////////////////////////////////////////////////////////////////////////////////// -//functions for maintaining alpha coverage. - -namespace ImageProcessing -{ - void CImageObject::TransferAlphaCoverage(const TextureSettings* textureSetting, const IImageObjectPtr srcImg) - { - EPixelFormat srcFmt = srcImg->GetPixelFormat(); - //both this image and src image need to be uncompressed - if (!CPixelFormats::GetInstance().IsPixelFormatUncompressed(m_pixelFormat) - || !CPixelFormats::GetInstance().IsPixelFormatUncompressed(srcFmt)) - { - AZ_Assert(false, "Both source image and dest image need to be uncompressed"); - return; - } - - const float fAlphaRef = 0.5f; // Seems to give good overall results - const float fDesiredAlphaCoverage = srcImg->ComputeAlphaCoverage(0, fAlphaRef); - - //create pixel operation function - IPixelOperationPtr pixelOp = CreatePixelOperation(m_pixelFormat); - //get count of bytes per pixel - AZ::u32 pixelBytes = CPixelFormats::GetInstance().GetPixelFormatInfo(m_pixelFormat)->bitsPerBlock / 8; - - for (uint32 mip = 0; mip < GetMipCount(); mip++) - { - const float fAlphaOffset = textureSetting->ComputeMIPAlphaOffset(mip); - const float fAlphaScale = ComputeAlphaCoverageScaleFactor(mip, fDesiredAlphaCoverage, fAlphaRef); - - AZ::u8* pixelBuf = m_mips[mip]->m_pData; - const AZ::u32 pixelCount = GetPixelCount(mip); - - for (AZ::u32 i = 0; i < pixelCount; ++i, pixelBuf += pixelBytes) - { - float r, g, b, a; - pixelOp->GetRGBA(pixelBuf, r, g, b, a); - a = AZ::GetMin(a * fAlphaScale + fAlphaOffset, 1.0f); - pixelOp->SetRGBA(pixelBuf, r, g, b, a); - } - } - } - - float CImageObject::ComputeAlphaCoverageScaleFactor(AZ::u32 mip, float fDesiredCoverage, float fAlphaRef) const - { - float minAlphaRef = 0.0f; - float maxAlphaRef = 1.0f; - float midAlphaRef = 0.5f; - - // Find best alpha test reference value using a binary search - for (int i = 0; i < 10; i++) - { - const float currentCoverage = ComputeAlphaCoverage(mip, midAlphaRef); - - if (currentCoverage > fDesiredCoverage) - { - minAlphaRef = midAlphaRef; - } - else if (currentCoverage < fDesiredCoverage) - { - maxAlphaRef = midAlphaRef; - } - else - { - break; - } - - midAlphaRef = (minAlphaRef + maxAlphaRef) * 0.5f; - } - - return fAlphaRef / midAlphaRef; - } - - float CImageObject::ComputeAlphaCoverage(AZ::u32 mip, float fAlphaRef) const - { - //This function only works with uncompressed image - if (!CPixelFormats::GetInstance().IsPixelFormatUncompressed(m_pixelFormat)) - { - AZ_Assert(false, "This image need to be uncompressed"); - return 0; - } - - uint32 coverage = 0; - - //create pixel operation function - IPixelOperationPtr pixelOp = CreatePixelOperation(m_pixelFormat); - //get count of bytes per pixel - AZ::u32 pixelBytes = CPixelFormats::GetInstance().GetPixelFormatInfo(m_pixelFormat)->bitsPerBlock / 8; - - AZ::u8* pixelBuf = m_mips[mip]->m_pData; - const AZ::u32 pixelCount = GetPixelCount(mip); - - for (AZ::u32 i = 0; i < pixelCount; ++i, pixelBuf += pixelBytes) - { - float r, g, b, a; - pixelOp->GetRGBA(pixelBuf, r, g, b, a); - coverage += a > fAlphaRef; - } - - return (float)coverage / (float)(pixelCount); - } - -} // namespace ImageProcessing diff --git a/Gems/ImageProcessing/Code/Source/Converters/ColorChart.cpp b/Gems/ImageProcessing/Code/Source/Converters/ColorChart.cpp deleted file mode 100644 index 63067a57b5..0000000000 --- a/Gems/ImageProcessing/Code/Source/Converters/ColorChart.cpp +++ /dev/null @@ -1,314 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or 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 ImageProcessing -{ - const int COLORCHART_IMAGE_WIDTH = 78; - const int COLORCHART_IMAGE_HEIGHT = 66; - - // color chart in cry engine is a special image data, with size 78x66, you may see in game screenshot which is defined by a rectangle - // area with a yellow-black dash line boarder - // Create color chart function is to read that block of image data and convert it to a color table then save it to another image - // with size 256x16. - - class C3dLutColorChart - { - public: - C3dLutColorChart() {} - ~C3dLutColorChart() {}; - - //generate default color chart data - void GenerateDefault(); - - //generate color chart data from input image - bool GenerateFromInput(IImageObjectPtr image); - - //ouput the color chart data to an image object - IImageObjectPtr GenerateChartImage(); - - protected: - //extract color chart data from specified location in an image - void ExtractFromImageAt(IImageObjectPtr pImg, AZ::u32 x, AZ::u32 y); - - //find color chart location in an image - static bool FindColorChart(const IImageObjectPtr pImg, AZ::u32& outLocX, AZ::u32& outLocY); - - //if there is a color chart at specified location - static bool IsColorChartAt(AZ::u32 x, AZ::u32 y, void* pData, AZ::u32 pitch); - - private: - enum EPrimaryShades - { - ePS_Red = 16, - ePS_Green = 16, - ePS_Blue = 16, - - ePS_NumColors = ePS_Red * ePS_Green * ePS_Blue - }; - - struct SColor - { - unsigned char r, g, b, _padding; - }; - - typedef AZStd::vector ColorMapping; - - ColorMapping m_mapping; - }; - - void C3dLutColorChart::GenerateDefault() - { - m_mapping.reserve(ePS_NumColors); - - for (int b = 0; b < ePS_Blue; ++b) - { - for (int g = 0; g < ePS_Green; ++g) - { - for (int r = 0; r < ePS_Red; ++r) - { - SColor col; - col.r = 255 * r / (ePS_Red); - col.g = 255 * g / (ePS_Green); - col.b = 255 * b / (ePS_Blue); - int l = 255 - (col.r * 3 + col.g * 6 + col.b) / 10; - col.r = col.g = col.b = (unsigned char)l; - m_mapping.push_back(col); - } - } - } - } - - //find color chart location in a image - bool C3dLutColorChart::FindColorChart(const IImageObjectPtr pImg, AZ::u32& outLocX, AZ::u32& outLocY) - { - const AZ::u32 width = pImg->GetWidth(0); - const AZ::u32 height = pImg->GetHeight(0); - - //the origin image is too small to have a color chart - if (width < COLORCHART_IMAGE_WIDTH || height < COLORCHART_IMAGE_HEIGHT) - { - return false; - } - - AZ::u8* pData; - AZ::u32 pitch; - pImg->GetImagePointer(0, pData, pitch); - - //check all the posible start location on whether there might be a color chart - for (AZ::u32 y = 0; y <= height - COLORCHART_IMAGE_HEIGHT; ++y) - { - for (AZ::u32 x = 0; x <= width - COLORCHART_IMAGE_WIDTH; ++x) - { - if (IsColorChartAt(x, y, pData, pitch)) - { - outLocX = x; - outLocY = y; - return true; - } - } - } - - return false; - } - - bool C3dLutColorChart::GenerateFromInput(IImageObjectPtr image) - { - AZ::u32 outLocX, outLocY; - if (FindColorChart(image, outLocX, outLocY)) - { - ExtractFromImageAt(image, outLocX, outLocY); - return true; - } - return false; - } - - IImageObjectPtr C3dLutColorChart::GenerateChartImage() - { - const AZ::u32 mipCount = 1; - IImageObjectPtr image( IImageObject::CreateImage(ePS_Red * ePS_Blue, ePS_Green, 1, ePixelFormat_R8G8B8A8)); - - { - AZ::u8* pData; - AZ::u32 pitch; - image->GetImagePointer(0, pData, pitch); - - size_t nSlicePitch = (pitch / ePS_Blue); - AZ::u32 src = 0; - for (int b = 0; b < ePS_Blue; ++b) - { - for (int g = 0; g < ePS_Green; ++g) - { - - AZ::u8* p = pData + g * pitch + b * nSlicePitch; - for (int r = 0; r < ePS_Red; ++r) - { - const SColor& c = m_mapping[src]; - p[0] = c.r; - p[1] = c.g; - p[2] = c.b; - p[3] = 255; - ++src; - p += 4; - } - } - } - } - - return image; - } - - void C3dLutColorChart::ExtractFromImageAt(IImageObjectPtr image, AZ::u32 x, AZ::u32 y) - { - int ox = x + 1; - int oy = y + 1; - - AZ::u8* pData; - AZ::u32 pitch; - image->GetImagePointer(0, pData, pitch); - - m_mapping.reserve(ePS_NumColors); - - for (int b = 0; b < ePS_Blue; ++b) - { - int px = ox + ePS_Red * (b % 4); - int py = oy + ePS_Green * (b / 4); - - for (int g = 0; g < ePS_Green; ++g) - { - for (int r = 0; r < ePS_Red; ++r) - { - AZ::u8* p = pData + pitch * (py + g) + (px + r) * 4; - - SColor col; - col.r = p[0]; - col.g = p[1]; - col.b = p[2]; - m_mapping.push_back(col); - } - } - } - } - - //check if image data at location x and y could be a color chart - //based on if the boarder is dash lines with two pixel each segement - //the idea and implementation are both coming from CryEngine. - bool C3dLutColorChart::IsColorChartAt(AZ::u32 x, AZ::u32 y, void* pData, AZ::u32 pitch) - { - struct Color - { - private: - int c[3]; - - public: - Color(AZ::u32 x, AZ::u32 y, void* pPixels, AZ::u32 pitch) - { - const uint8* p = (const uint8*)pPixels + pitch * y + x * 4; - c[0] = p[0]; - c[1] = p[1]; - c[2] = p[2]; - } - - bool isSimilar(const Color& a, int maxDiff) const - { - return - abs(a.c[0] - c[0]) <= maxDiff && - abs(a.c[1] - c[1]) <= maxDiff && - abs(a.c[2] - c[2]) <= maxDiff; - } - }; - - const Color colorRef[2] = - { - Color(x, y, pData, pitch), - Color(x + 2, y, pData, pitch) - }; - - // We require two colors of the border to be at least a bit different - if (colorRef[0].isSimilar(colorRef[1], 15)) - { - return false; - } - - static const int kMaxDiff = 3; - - int refIdx = 0; - //rectangle's top - for (int i = 0; i < COLORCHART_IMAGE_WIDTH; i += 2) - { - if (!colorRef[refIdx].isSimilar(Color(x + i, y, pData, pitch), kMaxDiff) || - !colorRef[refIdx].isSimilar(Color(x + i + 1, y, pData, pitch), kMaxDiff)) - { - return false; - } - refIdx ^= 1; - } - - refIdx = 0; - //left - for (int i = 0; i < COLORCHART_IMAGE_HEIGHT; i += 2) - { - if (!colorRef[refIdx].isSimilar(Color(x, y + i, pData, pitch), kMaxDiff) || - !colorRef[refIdx].isSimilar(Color(x, y + i + 1, pData, pitch), kMaxDiff)) - { - return false; - } - refIdx ^= 1; - } - - refIdx = 0; - //right - for (int i = 0; i < COLORCHART_IMAGE_HEIGHT; i += 2) - { - if (!colorRef[refIdx].isSimilar(Color(x + COLORCHART_IMAGE_WIDTH - 1, y + i, pData, pitch), kMaxDiff) || - !colorRef[refIdx].isSimilar(Color(x + COLORCHART_IMAGE_WIDTH - 1, y + i + 1, pData, pitch), kMaxDiff)) - { - return false; - } - refIdx ^= 1; - } - - refIdx = 0; - //bottom - for (int i = 0; i < COLORCHART_IMAGE_WIDTH; i += 2) - { - if (!colorRef[refIdx].isSimilar(Color(x + i, y + COLORCHART_IMAGE_HEIGHT - 1, pData, pitch), kMaxDiff) || - !colorRef[refIdx].isSimilar(Color(x + i + 1, y + COLORCHART_IMAGE_HEIGHT - 1, pData, pitch), kMaxDiff)) - { - return false; - } - refIdx ^= 1; - } - - return true; - } - - - void ImageToProcess::CreateColorChart() - { - C3dLutColorChart colorChart; - - //get color chart data from source image. - if (!colorChart.GenerateFromInput(m_img)) - { - //if load from image failed then generate default color data - colorChart.GenerateDefault(); - } - - //save color chart data to an image and save as current - m_img = colorChart.GenerateChartImage(); - } -} diff --git a/Gems/ImageProcessing/Code/Source/Converters/ConvertPixelFormat.cpp b/Gems/ImageProcessing/Code/Source/Converters/ConvertPixelFormat.cpp deleted file mode 100644 index 9a49bf9b63..0000000000 --- a/Gems/ImageProcessing/Code/Source/Converters/ConvertPixelFormat.cpp +++ /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. -* -*/ - -#include - -#include -#include -#include - -#include -#include - -/////////////////////////////////////////////////////////////////////////////////// -//functions for maintaining alpha coverage. - -namespace ImageProcessing -{ - void ImageToProcess::ConvertFormat(EPixelFormat fmtDst) - { - //pixel format before convertion - EPixelFormat fmtSrc = Get()->GetPixelFormat(); - - //return directly if the image already has the desired pixel format - if (fmtDst == fmtSrc) - { - return; - } - - uint32 dwWidth, dwHeight, dwMips; - dwWidth = Get()->GetWidth(0); - dwHeight = Get()->GetHeight(0); - dwMips = Get()->GetMipCount(); - - //if the output image size doesn't work the desired pixel format. set to fallback format - const PixelFormatInfo* dstFmtInfo = CPixelFormats::GetInstance().GetPixelFormatInfo(fmtDst); - if (!CPixelFormats::GetInstance().IsImageSizeValid(fmtDst, dwWidth, dwHeight, true)) - { - AZ_Warning("Image Processing", false, "Output pixel format %d doesn't work with output image size %d x %d", - fmtDst, dwWidth, dwHeight); - - //fall back to safe texture format - if (dstFmtInfo->nChannels == 1) - { - fmtDst = dstFmtInfo->bHasAlpha ? ePixelFormat_A8 : ePixelFormat_R8; - } - else if (dstFmtInfo->nChannels == 2) - { - fmtDst = ePixelFormat_R8G8; - } - else - { - fmtDst = dstFmtInfo->bHasAlpha ? ePixelFormat_R8G8B8A8 : ePixelFormat_R8G8B8X8; - } - } - - //convert src image to uncompressed formats if it's compressed format - bool isSrcUncompressed = CPixelFormats::GetInstance().IsPixelFormatUncompressed(fmtSrc); - bool isDstUncompressed = CPixelFormats::GetInstance().IsPixelFormatUncompressed(fmtDst); - - if (isSrcUncompressed && isDstUncompressed) - {//both are uncompressed - ConvertFormatUncompressed(fmtDst); - } - else if (!isSrcUncompressed && !isDstUncompressed) - { //both are compressed - AZ_Assert(false, "unusual user case. but we can still handle it"); - } - else - { //one fmt is compressed format - //use the compressed format to find right compressor - EPixelFormat compressedFmt = isSrcUncompressed ? fmtDst : fmtSrc; - EPixelFormat uncompressedFmt = isSrcUncompressed ? fmtSrc : fmtDst; - ICompressorPtr compressor = ICompressor::FindCompressor(compressedFmt, isSrcUncompressed); - - if (compressor == nullptr) - { - //no avaible compressor for compressed format - AZ_Warning("Image Processing", false, "No avaliable compressor for pixel format %d", compressedFmt); - return; - } - - //check if the uncompressed fmt also supported by the compressor - EPixelFormat desiredUncompressedFmt = compressor->GetSuggestedUncompressedFormat(compressedFmt, uncompressedFmt); - if (desiredUncompressedFmt != uncompressedFmt) - { - //we need to do intermedia convertion to convert to the temperory format - ConvertFormat(desiredUncompressedFmt); - ConvertFormat(fmtDst); - } - else - { - IImageObjectPtr dstImage = nullptr; - if (isSrcUncompressed) - { - dstImage = compressor->CompressImage(Get(), fmtDst, &m_compressOption); - } - else - { - dstImage = compressor->DecompressImage(Get(), fmtDst); - } - - Set(dstImage); - } - - if (Get() == nullptr) - { - AZ_Error("Image Processing", false, "The selected compressor failed to compress this image"); - } - } - } - - void ImageToProcess::ConvertFormatUncompressed(EPixelFormat fmtTo) - { - IImageObjectPtr srcImage = m_img; - EPixelFormat srcFmt = srcImage->GetPixelFormat(); - EPixelFormat dstFmt = fmtTo; - - if (!(CPixelFormats::GetInstance().IsPixelFormatUncompressed(srcFmt) - && CPixelFormats::GetInstance().IsPixelFormatUncompressed(dstFmt))) - { - AZ_Assert(false, "both source and dest images' pixel format need to be uncompressed"); - return; - } - - IImageObjectPtr dstImage(m_img->AllocateImage(fmtTo)); - - AZ_Assert(srcImage->GetPixelCount(0) == dstImage->GetPixelCount(0), "dest image has different size than source image"); - - //create pixel operation function for src and dst images - IPixelOperationPtr srcOp = CreatePixelOperation(srcFmt); - IPixelOperationPtr dstOp = CreatePixelOperation(dstFmt); - - //get count of bytes per pixel for both src and dst images - uint32 srcPixelBytes = CPixelFormats::GetInstance().GetPixelFormatInfo(srcFmt)->bitsPerBlock / 8; - uint32 dstPixelBytes = CPixelFormats::GetInstance().GetPixelFormatInfo(dstFmt)->bitsPerBlock / 8; - - const uint32 dwMips = dstImage->GetMipCount(); - float r, g, b, a; - for (uint32 dwMip = 0; dwMip < dwMips; ++dwMip) - { - uint8* srcPixelBuf; - uint32 srcPitch; - srcImage->GetImagePointer(dwMip, srcPixelBuf, srcPitch); - uint8* dstPixelBuf; - uint32 dstPitch; - dstImage->GetImagePointer(dwMip, dstPixelBuf, dstPitch); - - const uint32 pixelCount = srcImage->GetPixelCount(dwMip); - - for (uint32 i = 0; i < pixelCount; ++i, srcPixelBuf += srcPixelBytes, dstPixelBuf += dstPixelBytes) - { - srcOp->GetRGBA(srcPixelBuf, r, g, b, a); - dstOp->SetRGBA(dstPixelBuf, r, g, b, a); - } - } - - m_img = dstImage; - } - - -} // namespace ImageProcessing diff --git a/Gems/ImageProcessing/Code/Source/Converters/Cubemap.cpp b/Gems/ImageProcessing/Code/Source/Converters/Cubemap.cpp deleted file mode 100644 index 71e629b553..0000000000 --- a/Gems/ImageProcessing/Code/Source/Converters/Cubemap.cpp +++ /dev/null @@ -1,620 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or 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 - -namespace ImageProcessing -{ - CubemapLayoutInfo CubemapLayout::s_layoutList[CubemapLayoutTypeCount]; - - template - inline bool IsPowerOfTwo(TInteger x) - { - return (x & (x - 1)) == 0; - } - - CubemapLayoutInfo::CubemapLayoutInfo() - : m_type(CubemapLayoutNone) - , m_rows(0) - , m_columns(0) - { - - } - - void CubemapLayoutInfo::SetFaceInfo(CubemapFace face, AZ::u8 row, AZ::u8 col, CubemapFaceDirection dir) - { - m_faceInfos[face].row = row; - m_faceInfos[face].column = col; - m_faceInfos[face].direction = dir; - } - - void CubemapLayout::InitCubemapLayoutInfos() - { - //CubemapLayoutHorizontal - //left , right, front, back, top, bottom; - //NOTE: this layout is widely used in game projects by Jan 2018 since other layouts weren't supported correctly - //but the faces in one has unusual directions compare to other format. - //The direction matters when using it as input for Cubemap generation filter. - //Left: rotated left 90 degree. Right: rotated right 90 degree - //Front: rotated 180 degree. Back: no rotation - //Top: rotate 180 degree. Bottom: no rotation - CubemapLayoutInfo *info = &s_layoutList[CubemapLayoutHorizontal]; - info->m_rows = 1; - info->m_columns = 6; - info->m_type = CubemapLayoutHorizontal; - info->SetFaceInfo(FaceLeft, 0, 0, CubemapFaceDirection::DirRotateLeft90); - info->SetFaceInfo(FaceRight, 0, 1, CubemapFaceDirection::DirRotateRight90); - info->SetFaceInfo(FaceFront, 0, 2, CubemapFaceDirection::DirRotate180); - info->SetFaceInfo(FaceBack, 0, 3, CubemapFaceDirection::DirNoRotation); - info->SetFaceInfo(FaceTop, 0, 4, CubemapFaceDirection::DirRotate180); - info->SetFaceInfo(FaceBottom, 0, 5, CubemapFaceDirection::DirNoRotation); - - //CubemapLayoutHorizontalCross - // top - // left front right back - // bottom - info = &s_layoutList[CubemapLayoutHorizontalCross]; - info->m_rows = 3; - info->m_columns = 4; - info->m_type = CubemapLayoutHorizontalCross; - info->SetFaceInfo(FaceLeft, 1, 0, CubemapFaceDirection::DirNoRotation); - info->SetFaceInfo(FaceRight, 1, 2, CubemapFaceDirection::DirNoRotation); - info->SetFaceInfo(FaceFront, 1, 1, CubemapFaceDirection::DirNoRotation); - info->SetFaceInfo(FaceBack, 1, 3, CubemapFaceDirection::DirNoRotation); - info->SetFaceInfo(FaceTop, 0, 1, CubemapFaceDirection::DirNoRotation); - info->SetFaceInfo(FaceBottom, 2, 1, CubemapFaceDirection::DirNoRotation); - - //CubemapLayoutVerticalCross - // top - // left front right - // bottom - // back - info = &s_layoutList[CubemapLayoutVerticalCross]; - info->m_rows = 4; - info->m_columns = 3; - info->m_type = CubemapLayoutVerticalCross; - info->SetFaceInfo(FaceLeft, 1, 0, CubemapFaceDirection::DirNoRotation); - info->SetFaceInfo(FaceRight, 1, 2, CubemapFaceDirection::DirNoRotation); - info->SetFaceInfo(FaceFront, 1, 1, CubemapFaceDirection::DirNoRotation); - info->SetFaceInfo(FaceBack, 3, 1, CubemapFaceDirection::DirRotate180); - info->SetFaceInfo(FaceTop, 0, 1, CubemapFaceDirection::DirNoRotation); - info->SetFaceInfo(FaceBottom, 2, 1, CubemapFaceDirection::DirNoRotation); - - //CubemapLayoutVertical - // left - // right - // front - // back - // top - // bottom - info = &s_layoutList[CubemapLayoutVertical]; - info->m_rows = 6; - info->m_columns = 1; - info->m_type = CubemapLayoutVertical; - info->SetFaceInfo(FaceLeft, 0, 0, CubemapFaceDirection::DirRotateLeft90); - info->SetFaceInfo(FaceRight, 1, 0, CubemapFaceDirection::DirRotateRight90); - info->SetFaceInfo(FaceFront, 2, 0, CubemapFaceDirection::DirRotate180); - info->SetFaceInfo(FaceBack, 3, 0, CubemapFaceDirection::DirNoRotation); - info->SetFaceInfo(FaceTop, 4, 0, CubemapFaceDirection::DirRotate180); - info->SetFaceInfo(FaceBottom, 5, 0, CubemapFaceDirection::DirNoRotation); - - //make sure all types were initialized - for (int i = 0; i < CubemapLayoutTypeCount; i++) - { - AZ_Assert(s_layoutList[i].m_type == i, "layout %d is not initialized", i); - } - } - - const float* GetTransformMatrix(CubemapFaceDirection dir, bool isInvert) - { - switch (dir) - { - case CubemapFaceDirection::DirNoRotation: - { - static const float mat[] = { 1, 0, 0, 1 }; - return mat; - } - case CubemapFaceDirection::DirRotateLeft90: - { - //thelta = 90 degree - //{cos, -sin, sin, cos} - if (isInvert) - { - return GetTransformMatrix(CubemapFaceDirection::DirRotateRight90, false); - } - static const float mat[] = { 0, -1, 1, 0 }; - return mat; - } - case CubemapFaceDirection::DirRotateRight90: - { - //thelta = -90 degree - if (isInvert) - { - return GetTransformMatrix(CubemapFaceDirection::DirRotateLeft90, false); - } - static const float mat[] = { 0, 1, -1, 0 }; - return mat; - } - case CubemapFaceDirection::DirRotate180: - { - //thelta = 180 degree - static const float mat[] = { -1, 0, 0, -1 }; - return mat; - } - case CubemapFaceDirection::DirMirrorHorizontal: - { - static const float mat[] = { 1, 0, 0, -1 }; - return mat; - } - default: - { - AZ_Assert(false, "unimplemented direction matrix"); - static const float mat[] = { 1, 0, 0, 1 }; - return mat; - } - } - } - - void TransformImage(CubemapFaceDirection srcDir, CubemapFaceDirection dstDir, const AZ::u8* srcImageBuf, - AZ::u8* dstImageBuf, AZ::u8 bytePerPixel, AZ::u32 rectSize) - { - //get final matrix to transform dst back to src - const float* m1 = GetTransformMatrix(dstDir, true); - const float* m2 = GetTransformMatrix(srcDir, false); - float mtx[4]; - mtx[0] = m1[0] * m2[0] + m1[1] * m2[2]; - mtx[1] = m1[0] * m2[1] + m1[1] * m2[3]; - mtx[2] = m1[2] * m2[0] + m1[3] * m2[2]; - mtx[3] = m1[2] * m2[1] + m1[3] * m2[3]; - - const float* noRotate = GetTransformMatrix(CubemapFaceDirection::DirNoRotation, false); - - if (memcmp(noRotate, mtx, 4 * sizeof(float)) == 0) - { - memcpy(dstImageBuf, srcImageBuf, rectSize*rectSize*bytePerPixel); - return; - } - - //for each pixel in dst image, find it's location in src and copy the data from there - float halfSize = rectSize / 2; - for (AZ::u32 row = 0; row < rectSize; row++) - { - for (AZ::u32 col = 0; col < rectSize; col++) - { - //coordinate in image center as origin and right as positive X, up as positive Y - float dstX = col + 0.5f - halfSize; - float dstY = halfSize - row - 0.5f; - float srcX = dstX * mtx[0] + dstY * mtx[1]; - float srcY = dstX * mtx[2] + dstY * mtx[3]; - AZ::u32 srcCol = srcX + halfSize; - AZ::u32 srcRow = halfSize - srcY; - - memcpy(&dstImageBuf[(row*rectSize + col)*bytePerPixel], - &srcImageBuf[(srcRow*rectSize + srcCol)*bytePerPixel], bytePerPixel); - } - } - } - - CubemapLayout::CubemapLayout() - : m_info(nullptr) - , m_image(nullptr) - , m_faceSize(256) - { - } - - CubemapLayout* CubemapLayout::CreateCubemapLayout(IImageObjectPtr image) - { - //only support uncompressed format. - if (!CPixelFormats::GetInstance().IsPixelFormatUncompressed(image->GetPixelFormat())) - { - AZ_Assert(false, "CubemapLayout only support uncompressed image"); - return nullptr; - } - - CubemapLayout* layout = nullptr; - CubemapLayoutInfo* info = GetCubemapLayoutInfo(image); - if (info) - { - layout = new CubemapLayout(); - layout->m_info = GetCubemapLayoutInfo(image); - layout->m_image = image; - layout->m_faceSize = image->GetWidth(0)/layout->m_info->m_columns; - } - return layout; - } - - - CubemapLayoutInfo* CubemapLayout::GetCubemapLayoutInfo(CubemapLayoutType type) - { - if (type == CubemapLayoutNone) - { - return nullptr; - } - - //if it's never initialized - if (s_layoutList[0].m_type == CubemapLayoutNone) - { - InitCubemapLayoutInfos(); - } - - return &s_layoutList[type]; - } - - CubemapLayoutInfo* CubemapLayout::GetCubemapLayoutInfo(IImageObjectPtr image) - { - //if it's never initialized - if (s_layoutList[0].m_type == CubemapLayoutNone) - { - InitCubemapLayoutInfos(); - } - - if (image == nullptr) - { - return nullptr; - } - - uint32 width, height; - width = image->GetWidth(0); - height = image->GetHeight(0); - CubemapLayoutInfo* info = nullptr; - - for (int i = 0; i < CubemapLayoutTypeCount; i++) - { - if (width * s_layoutList[i].m_rows == height*s_layoutList[i].m_columns) - { - info = &s_layoutList[i]; - - //we require the face size need to be power of two - if (IsPowerOfTwo(width / info->m_columns)) - { - return info; - } - else - { - return nullptr; - } - } - } - return nullptr; - } - - //public functions to get faces information for associated image - AZ::u32 CubemapLayout::GetFaceSize() - { - return m_faceSize; - } - - CubemapLayoutInfo* CubemapLayout::GetLayoutInfo() - { - return m_info; - } - - CubemapFaceDirection CubemapLayout::GetFaceDirection(CubemapFace face) - { - return m_info->m_faceInfos[face].direction; - } - - void CubemapLayout::GetFaceData(CubemapFace face, void* outBuffer, AZ::u32& outSize) - { - //only valid for uncompressed - AZ::u32 sizePerPixel = CPixelFormats::GetInstance().GetPixelFormatInfo(m_image->GetPixelFormat())->bitsPerBlock / 8; - - AZ::u8* imageBuf; - AZ::u32 dwPitch; - m_image->GetImagePointer(0, imageBuf, dwPitch); - AZ::u8* dstBuf = (AZ::u8*)outBuffer; - - AZ::u32 startX = m_info->m_faceInfos[face].column * m_faceSize; - AZ::u32 startY = m_info->m_faceInfos[face].row * m_faceSize; - - //face size is same as rows for uncompressed format - for (AZ::u32 y = 0; y < m_faceSize; y++) - { - AZ::u32 scanlineSize = m_faceSize*sizePerPixel; - AZ::u8* srcBuf = &imageBuf[(startY + y) * dwPitch + startX*sizePerPixel]; - memcpy(dstBuf, srcBuf, scanlineSize); - dstBuf += scanlineSize; - } - - outSize = m_faceSize*m_faceSize*sizePerPixel; - - } - - void CubemapLayout::SetFaceData(CubemapFace face, void* dataBuffer, [[maybe_unused]] AZ::u32 dataSize) - { - //only valid for uncompressed - AZ::u32 sizePerPixel = CPixelFormats::GetInstance().GetPixelFormatInfo(m_image->GetPixelFormat())->bitsPerBlock / 8; - - AZ::u8* imageBuf; - AZ::u32 dwPitch; - m_image->GetImagePointer(0, imageBuf, dwPitch); - AZ::u8* srcBuf = (AZ::u8*)dataBuffer; - - AZ::u32 startX = m_info->m_faceInfos[face].column * m_faceSize; - AZ::u32 startY = m_info->m_faceInfos[face].row * m_faceSize; - - //face size is same as rows for uncompressed format - for (AZ::u32 y = 0; y < m_faceSize; y++) - { - AZ::u32 scanlineSize = m_faceSize*sizePerPixel; - AZ::u8* dstBuf = &imageBuf[(startY + y) * dwPitch + startX*sizePerPixel]; - memcpy(dstBuf, srcBuf, scanlineSize); - srcBuf += scanlineSize; - } - } - - void* CubemapLayout::GetFaceMemBuffer(AZ::u32 mip, CubemapFace face, AZ::u32& outPitch) - { - if (CubemapLayoutVertical != m_info->m_type) - { - AZ_Assert(false, "this should only be used for CubemapLayoutVertical which has continous memory for each face"); - return nullptr; - } - - AZ::u32 faceSize = m_faceSize >> mip; - AZ::u8* imageBuf; - m_image->GetImagePointer(mip, imageBuf, outPitch); - AZ::u32 startY = m_info->m_faceInfos[face].row * faceSize; - - //use startY is same as rows from m_image since the pixel format is uncompressed - return &imageBuf[startY * outPitch]; - } - - void CubemapLayout::SetToFaceMemBuffer(AZ::u32 mip, CubemapFace face, void* dataBuffer) - { - if (CubemapLayoutVertical != m_info->m_type) - { - AZ_Assert(false, "this should only be used for CubemapLayoutVertical which has continuous memory for each face"); - return; - } - - AZ::u32 faceSize = m_faceSize >> mip; - AZ::u32 pitch; - AZ::u8* imageBuf; - m_image->GetImagePointer(mip, imageBuf, pitch); - AZ::u32 startY = m_info->m_faceInfos[face].row * faceSize; - - //use startY is same as rows from m_image since the pixel format is uncompressed - memcpy(&imageBuf[startY * pitch], dataBuffer, faceSize*pitch); - } - - void CubemapLayout::GetRectForFace(AZ::u32 mip, CubemapFace face, QRect& outRect) - { - AZ::u32 faceSize = m_faceSize >> mip; - AZ::u32 startY = m_info->m_faceInfos[face].row * faceSize; - AZ::u32 startX = m_info->m_faceInfos[face].column * faceSize; - - outRect.setRect(startX, startY, faceSize, faceSize); - } - - bool ImageToProcess::ConvertCubemapLayout(CubemapLayoutType dstLayoutType) - { - const EPixelFormat srcPixelFormat = m_img->GetPixelFormat(); - - //it need to be uncompressed format - if (!CPixelFormats::GetInstance().IsPixelFormatUncompressed(srcPixelFormat)) - { - AZ_Assert(false, "Please convert the image to uncompressed pixel format before calling ConvertCubemapLayout"); - return false; - } - - //check if it's valid cubemap size - CubemapLayoutInfo* layoutInfo = CubemapLayout::GetCubemapLayoutInfo(m_img); - if (layoutInfo == nullptr) - { - AZ_Error("Image Processing", false, "The original image doesn't have a valid size (layout) as cubemap"); - return false; - } - - //if the source is same as output layout, return directly - if (layoutInfo->m_type == dstLayoutType) - { - return true; - } - - CubemapLayoutInfo* dstLayoutInfo = CubemapLayout::GetCubemapLayoutInfo(dstLayoutType); - - //create cubemap layout for source image for later operation. - CubemapLayout *srcCubemap = CubemapLayout::CreateCubemapLayout(m_img); - AZ::u32 faceSize = srcCubemap->GetFaceSize(); - - //create new image with same pixel format and copy prperties from source image - IImageObjectPtr newImage(IImageObject::CreateImage(faceSize * dstLayoutInfo->m_columns, - faceSize*dstLayoutInfo->m_rows, 1, srcPixelFormat)); - CubemapLayout *dstCubemap = CubemapLayout::CreateCubemapLayout(newImage); - newImage->CopyPropertiesFrom(newImage); - - //copy data from src cube to dst cube for each face - //temp buf for copy over data - AZ::u32 sizePerPixel = CPixelFormats::GetInstance().GetPixelFormatInfo(srcPixelFormat)->bitsPerBlock/8; //only valid for uncompressed - AZ::u8 *buf = new AZ::u8[faceSize*faceSize*sizePerPixel]; - AZ::u8 *tempBuf = new AZ::u8[faceSize*faceSize*sizePerPixel]; - - for (AZ::u32 faceIdx = 0; faceIdx < FaceCount; faceIdx++) - { - AZ::u32 outSize = 0; - CubemapFace face = (CubemapFace)faceIdx; - srcCubemap->GetFaceData(face, buf, outSize); - CubemapFaceDirection srcDir = srcCubemap->GetFaceDirection(face); - CubemapFaceDirection dstDir = dstCubemap->GetFaceDirection(face); - if (srcDir == dstDir) - { - dstCubemap->SetFaceData(face, buf, outSize); - } - else - { - //transform the image - TransformImage(srcDir, dstDir, buf, tempBuf, sizePerPixel, faceSize); - dstCubemap->SetFaceData(face, tempBuf, outSize); - } - } - - //clean up - delete[] buf; - delete[] tempBuf; - delete srcCubemap; - delete dstCubemap; - - newImage->AddImageFlags(EIF_Cubemap); - m_img = newImage; - return true; - } - - bool ImageConvertProcess::FillCubemapMipmaps() - { - //this function only works with pixel format rgba32f - const EPixelFormat srcPixelFormat = m_image->Get()->GetPixelFormat(); - if (srcPixelFormat != ePixelFormat_R32G32B32A32F) - { - AZ_Assert(false, "%s only works with pixel format rgba32f", __FUNCTION__); - return false; - } - - //only if the src image has one mip - if (m_image->Get()->GetMipCount() != 1) - { - AZ_Assert(false, "%s called for a mipmapped image. ", __FUNCTION__); - return false; - } - - CubemapLayout *srcCubemap = CubemapLayout::CreateCubemapLayout(m_image->Get()); - - uint32 outWidth; - uint32 outHeight; - uint32 outReduce = 0; - AZ::u32 srcFaceSize = srcCubemap->GetFaceSize(); - //get output face size - GetOutputExtent(srcFaceSize, srcFaceSize, outWidth, outHeight, outReduce, &m_textureSetting, &m_presetSetting); - AZ_Assert(outWidth == outHeight, "something wrong with GetOutputExtent function"); - - //get final cubemap image size - outWidth *= srcCubemap->GetLayoutInfo()->m_columns; - outHeight *= srcCubemap->GetLayoutInfo()->m_rows; - - //max mipmap count - uint32 maxMipCount; - if (m_presetSetting.m_mipmapSetting == nullptr || !m_textureSetting.m_enableMipmap) - { - maxMipCount = 1; - } - else - { - //calculate based on face size, and use final export format which may save some low level mip calculation - maxMipCount = CPixelFormats::GetInstance().ComputeMaxMipCount(m_presetSetting.m_pixelFormat, srcFaceSize, srcFaceSize); - - //the FilterImage function won't do well with rect size 1. avoiding cubemap with face size 1 - if (srcFaceSize >> maxMipCount == 1 && maxMipCount > 1) - { - maxMipCount -= 1; - } - } - - //create new new output image with proper face - IImageObjectPtr outImage(IImageObject::CreateImage(outWidth, outHeight, maxMipCount, srcPixelFormat)); - outImage->CopyPropertiesFrom(m_image->Get()); - CubemapLayout *dstCubemap = CubemapLayout::CreateCubemapLayout(outImage); - AZ::u32 outFaceSize = dstCubemap->GetFaceSize(); - AZ::u32 dstMipCount = outImage->GetMipCount(); - - //filter the image for top mip first - for (int iSide = 0; iSide < 6; ++iSide) - { - QRect srcRect; - QRect dstRect; - - srcRect.setLeft(0); - srcRect.setRight(srcFaceSize); - srcRect.setTop(iSide * srcFaceSize); - srcRect.setBottom((iSide + 1) * srcFaceSize); - - dstRect.setLeft(0); - dstRect.setRight(outFaceSize); - dstRect.setTop(iSide * outFaceSize); - dstRect.setBottom((iSide + 1) * outFaceSize); - - FilterImage(m_textureSetting.m_mipGenType, m_textureSetting.m_mipGenEval, 0, 0, m_image->Get(), 0, - outImage, 0, &srcRect, &dstRect); - } - - - CCubeMapProcessor atiCubemanGen; - //ATI's cubemap generator to filter the image edges to avoid seam problem - // https://gpuopen.com/archive/gamescgi/cubemapgen/ - - //the thread support was done with windows thread function so it's removed for multi-dev platform support - atiCubemanGen.m_NumFilterThreads = 0; - - // input and output cubemap set to have save dimensions, - atiCubemanGen.Init(outFaceSize, outFaceSize, dstMipCount, 4); - - // Load the 6 faces of the input cubemap and copy them into the cubemap processor - void* pMem; - uint32 nPitch; - - for (int iFace = 0; iFace < 6; ++iFace) - { - pMem = dstCubemap->GetFaceMemBuffer(0, (CubemapFace)iFace, nPitch); - atiCubemanGen.SetInputFaceData( - iFace, // FaceIdx, - CP_VAL_FLOAT32, // SrcType, - 4, // SrcNumChannels, - nPitch, // SrcPitch, - pMem, // SrcDataPtr, - 1000000.0f, // MaxClamp, - 1.0f, // Degamma, - 1.0f); // Scale - } - - //Filter cubemap - atiCubemanGen.InitiateFiltering( - m_presetSetting.m_cubemapSetting->m_angle, //BaseFilterAngle, - m_presetSetting.m_cubemapSetting->m_mipAngle, //InitialMipAngle, - m_presetSetting.m_cubemapSetting->m_mipSlope, //MipAnglePerLevelScale, - (int)m_presetSetting.m_cubemapSetting->m_filter, //FilterType, CP_FILTER_TYPE_COSINE for diffuse cube - m_presetSetting.m_cubemapSetting->m_edgeFixup > 0? CP_FIXUP_PULL_LINEAR : CP_FIXUP_NONE, //FixupType, CP_FIXUP_PULL_LINEAR if FixupWidth> 0 - m_presetSetting.m_cubemapSetting->m_edgeFixup, //FixupWidth, - true, //bUseSolidAngle, - 16, //GlossScale, - 0, //GlossBias - 128); //SampleCountGGX - - // Download data into it - for (int iFace = 0; iFace < 6; ++iFace) - { - for (unsigned int dstMip = 0; dstMip < dstMipCount; ++dstMip) - { - pMem = dstCubemap->GetFaceMemBuffer(dstMip, (CubemapFace)iFace, nPitch); - atiCubemanGen.GetOutputFaceData(iFace, dstMip, CP_VAL_FLOAT32, 4, nPitch, pMem, 1.0f, 1.0f); - } - } - - delete srcCubemap; - delete dstCubemap; - - //set back to image - m_image->Set(outImage); - return true; - } - -} // namespace ImageProcessing diff --git a/Gems/ImageProcessing/Code/Source/Converters/Cubemap.h b/Gems/ImageProcessing/Code/Source/Converters/Cubemap.h deleted file mode 100644 index 76dd8d2c30..0000000000 --- a/Gems/ImageProcessing/Code/Source/Converters/Cubemap.h +++ /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. -* -*/ - -#pragma once - -#include - -namespace ImageProcessing -{ - // note: O3DE is right hand Z up coordinate - // please don't change the order of the enum since we are using it to match the face id defined in AMD's CubemapGen - // and they are using left hand Y up coordinate - enum CubemapFace - { - FaceLeft = 0, - FaceRight, - FaceFront, - FaceBack, - FaceTop, - FaceBottom, - FaceCount - }; - - //we are treating the orientation of faces in 4x3 layout as the original direction. - enum class CubemapFaceDirection - { - DirNoRotation = 0, - DirRotateLeft90, - DirRotateRight90, - DirRotate180, - DirMirrorHorizontal - }; - - //this class contains information to describe a cubemap layout - class CubemapLayoutInfo - { - public: - struct FaceInfo - { - AZ::u8 row; - AZ::u8 column; - CubemapFaceDirection direction; - }; - - //rows and columns of how cubemap's faces laid - AZ::u8 m_rows; - AZ::u8 m_columns; - - //the type of this layout info for - CubemapLayoutType m_type; - - //the index of row and column where all the faces located - FaceInfo m_faceInfos[FaceCount]; - - CubemapLayoutInfo(); - void SetFaceInfo(CubemapFace face, AZ::u8 row, AZ::u8 col, CubemapFaceDirection dir); - }; - - //class to help doing operations with faces for an image as cubemap - class CubemapLayout - { - public: - //create a cubemapLayout object for the image. It can be used later to get image information as a cubemap - static CubemapLayout* CreateCubemapLayout(IImageObjectPtr image); - - //get layout info for input layout type - static CubemapLayoutInfo* GetCubemapLayoutInfo(CubemapLayoutType type); - - //get layout info for input image based on its size - static CubemapLayoutInfo* GetCubemapLayoutInfo(IImageObjectPtr image); - - //public functions to get faces information for associated image - AZ::u32 GetFaceSize(); - - //get the rect where the face in the image - void GetRectForFace(AZ::u32 mip, CubemapFace face, QRect& outRect); - - CubemapLayoutInfo* GetLayoutInfo(); - - //set/get pixels' data from/to specific face. only works for mip 0 - void GetFaceData(CubemapFace face, void* outBuffer, AZ::u32& outSize); - void SetFaceData(CubemapFace face, void* dataBuffer, AZ::u32 dataSize); - - //get the face's direction - CubemapFaceDirection GetFaceDirection(CubemapFace face); - - //get memory for a face from Image data. only works for CubemapLayoutVertical since its memory for each face is continuous - void* GetFaceMemBuffer(AZ::u32 mip, CubemapFace face, AZ::u32& outPitch); - void SetToFaceMemBuffer(AZ::u32 mip, CubemapFace face, void* dataBuffer); - - private: - //information for all supported cubemap layouts - static CubemapLayoutInfo s_layoutList[CubemapLayoutTypeCount]; - - //the image associated for this CubemapLayout - IImageObjectPtr m_image; - //the layout information of m_image - CubemapLayoutInfo *m_info; - //the size of the cubemap's face (which is square and power of 2). - uint32 m_faceSize; - - //private constructor. User should always use CreateCubemapLayout create a layout for an image object - CubemapLayout(); - - //initialize information of all available cubemap layouts - static void InitCubemapLayoutInfos(); - }; - -}//end namspace ImageProcessing diff --git a/Gems/ImageProcessing/Code/Source/Converters/FIR-Filter.cpp b/Gems/ImageProcessing/Code/Source/Converters/FIR-Filter.cpp deleted file mode 100644 index 8d1b8f2877..0000000000 --- a/Gems/ImageProcessing/Code/Source/Converters/FIR-Filter.cpp +++ /dev/null @@ -1,1285 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or 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 - -/* #################################################################################################################### - */ -#define mallocAligned(sze) _aligned_malloc(sze, 16) -#define freeAligned(ptr) _aligned_free(ptr) - -/* #################################################################################################################### - */ - -namespace ImageProcessing -{ - class Rect2D - { - public: - /* ================================================================================================================== - * Rect2D = ??? - */ - Rect2D() { } - Rect2D(const int x, const int y) { visual[0] = x; visual[1] = y; } - - private: - int visual[2]; - - public: - /* ================================================================================================================== - * Access operators - * M(i, j) == [row i][col j] - */ - inline int& operator () (int i) { return visual[i]; } - inline int operator () (int i) const { return visual[i]; } - - inline int& operator [] (int i) { return visual[i]; } - inline int operator [] (int i) const { return visual[i]; } - - /* ================================================================================================================== - * Logical operators - */ - inline bool operator == (const Rect2D& tht) - { - return (visual[0] == tht.visual[0]) && - (visual[1] == tht.visual[1]); - } - }; - - /* #################################################################################################################### - */ - template - class Plane2D - { - public: - /* ================================================================================================================== - * Plane2D = ??? - */ - Plane2D(const int x, const int y, const int p) { planes = p; allocatedC[0] = x; allocatedC[1] = y; used = allocatedC; aligned[0] = (allocatedC[0] + 15) & (~15); aligned[1] = allocatedC[1]; allocate(); } - Plane2D(const Rect2D& i, const int p) { planes = p; allocatedC = i; used = allocatedC; aligned[0] = (allocatedC[0] + 15) & (~15); aligned[1] = allocatedC[1]; allocate(); } - - ~Plane2D() { deallocate(); } - - /* ================================================================================================================== - * ??? = Plane2D - */ - inline operator Rect2D() const { return used; } - inline operator int () const { return planes; } - - inline operator DataType* () const { return buffers; } - inline operator DataType*** () const { return rows; } - inline operator const DataType* () const { return (const DataType*)buffers; } - inline operator const DataType*** () const { return (const DataType***)rows; } - - public: - inline void locate(Rect2D take) - { - taken = take; - - if ((taken[0] > aligned[0]) || - (taken[1] > abs(aligned[1]))) - { - abort(); - } - - /* align column#length */ - used[0] = (taken[0] + 15) & (~15); - used[1] = taken[1]; - - for (int p = 0; p < planes; p++) - { - /* we may need to replicate the row-unsigned __int64 over all rows only (y < 0) */ - const unsigned long int rowsize = (aligned[1] <= 0 ? 0 : aligned[0] * sizeof(DataType)); - int r; - char* buffer; - AZ_Assert((rowsize % 16) == 0, "%s: Unexpected row size!", __FUNCTION__); - - /* first block contains the row*-pointers */ - rows[p] = (DataType**)((char*)(rows + planes) + rowblocksize * p) + excess; - - /* "excess" empty pointers on negative offsets ----------------------------- */ - buffer = (char*)NULL; - AZ_Assert((reinterpret_cast(buffer) % 16) == 0, "%s: Unexpected buffer size!", __FUNCTION__); - - - for (r = -excess; r < 0; r++) - { - rows[p][r] = (DataType*)buffer; - } - - /* regular row-pointers ---------------------------------------------------- */ - buffer = (char*)buffers + (planesize * p); - AZ_Assert((reinterpret_cast(buffer) % 16) == 0, "%s: Unexpected buffer size!", __FUNCTION__); - - for (r = 0; r < abs(aligned[1]); r++, buffer += rowsize) - { - rows[p][r] = (DataType*)buffer; - } - - /* overhanging row-pointers show on the first valid row (loop) ------------- */ - buffer = (char*)buffers + (planesize * p); - AZ_Assert((reinterpret_cast(buffer) % 16) == 0, "%s: Unexpected buffer size!", __FUNCTION__); - - - for (r = abs(aligned[1]); r < abs(aligned[1]) + excess; r++, buffer += rowsize) - { - rows[p][r] = (DataType*)buffer; - } - } - } - - inline void clear() - { - memset(buffers, 0, planesize * planes); - } - - inline void delocate() - { - memset(buffers, 0, planesize * planes); - memset(rows, 0, sizeof(DataType * *) * planes + rowblocksize * planes); - } - - inline void relocate(Rect2D take) - { - delocate(); - locate(take); - } - - protected: - inline void allocate () - { - /* adjust rows */ - allocatedC[0] = allocatedC[0]; - allocatedC[1] = maximum(1, allocatedC[1]); - - /* if "(y < 0)", we allocate exactly 1 row and replicate it over "abs(y)" */ - planesize = sizeof(DataType) * aligned[0] * maximum(1, aligned[1]); - rowblocksize = sizeof(DataType*) * (abs(aligned[1]) + (2 * excess) + 16); - - /* all planes after each other: - * - * start -> plane0 -> plane1 -> ... - */ - buffers = (DataType* )AZ_OS_MALLOC(planesize * planes, 16); - /* all pointers after each other: - * - * start -> unsigned __int64 to planes -> unsigned __int64 to rows of planes - */ - rows = (DataType***)AZ_OS_MALLOC(sizeof(DataType * *) * planes + rowblocksize * planes, 16); - - /* ensure the blocks are aligned */ - AZ_Assert(((AZ::s64)buffers % 16) == 0, "%s: Expect blocks are aligned!", __FUNCTION__); - /* ensure the planes concat aligned */ - AZ_Assert((planesize % 16) == 0, "%s: Expect planes concat is aligned!", __FUNCTION__); - - locate(allocatedC); - } - - inline void deallocate() - { - AZ_OS_FREE(buffers); - AZ_OS_FREE(rows); - } - - Rect2D allocatedC, aligned; // real buffer sizes and its aligned counterpart - Rect2D taken, used; // actually taken sizes and its aligned counterpart - - int planes; - long int planesize, rowblocksize; - DataType* buffers; - DataType*** rows; - }; - - /* #################################################################################################################### \ - */ - #define filterTVariables(filterVxNNum, dtyp, wtyp, reps) \ - /* addition of c-pointers already takes care of datatype-sizes */ \ - const signed long int dy = /*parm->mirror ? -1 :*/ 1; \ - const unsigned int stridei = parm->incols * 1 * 1; \ - const unsigned int stridet = parm->subcols * 1 * 1; \ - const unsigned int strideo = parm->outcols * 1 * 1; \ - /* offset and shift calculations still require the unmodified values */ \ - const unsigned int strideiraw = parm->incols; \ - const unsigned int stridetraw = parm->subcols; \ - const unsigned int strideoraw = parm->outcols; \ - \ - class Plane2D tmp(tmpcols, tmprows, 4); \ - dtyp*** t = (dtyp***)tmp; \ - int srcPos, dstPos; \ - bool plusminush = false; const bool of = true; \ - bool plusminusv = false; const bool nc = false; \ - FilterWeights* fwh = calculateFilterWeights(parm->resample.colrem, parm->caged ? 0 : 0 - parm->region.subtop, parm->caged ? srccols : parm->subrows - parm->region.subtop, \ - parm->resample.colquo, 0, dstcols, reps, parm->resample.colblur, parm->resample.wf, parm->resample.operation != eWindowEvaluation_Sum, plusminush); \ - FilterWeights* fwv = calculateFilterWeights(parm->resample.rowrem, parm->caged ? 0 : 0 - parm->region.intop, parm->caged ? srcrows : parm->inrows - parm->region.intop, \ - parm->resample.rowquo, 0, dstrows, reps, parm->resample.rowblur, parm->resample.wf, parm->resample.operation != eWindowEvaluation_Sum, plusminusv); \ - - #define filterFTVariables(filterVxNNum) \ - filterTVariables(filterVxNNum, float, signed short, 1) - - /* #################################################################################################################### \ - */ - #define filterTCleanUp(filterVxNNum) \ - delete[] fwh; \ - delete[] fwv; - - /* #################################################################################################################### \ - */ - #define filterTInitLoop() - - /* ******************************************************************************************************************** \ - */ - #define filterTExitLoop() - - /* #################################################################################################################### \ - */ - #define filter4xNf(srcOffs, srcSize, srcSkip, dstOffs, dstSize, dstSkip, init, next, fetch, store, exit, op, pm, hv, dtyp, atyp) \ - init(srcOffs, srcSize, srcSkip, dstOffs, dstSize, dstSkip); \ - \ - dstPos = 0; do { \ - FilterWeights& fw = *(hv + dstPos); \ - const signed short* w = fw.weights; \ - \ - next(srcOffs, srcSize, srcSkip, dstOffs, dstSize, dstSkip); \ - \ - atyp res0 = (op != eWindowEvaluation_Min ? 0 : 32768); \ - atyp res1 = (op != eWindowEvaluation_Min ? 0 : 32768); \ - atyp res2 = (op != eWindowEvaluation_Min ? 0 : 32768); \ - atyp res3 = (op != eWindowEvaluation_Min ? 0 : 32768); \ - \ - srcPos = fw.first; do { \ - /* get value */ \ - fetch(srcOffs, srcSize, srcSkip, dstOffs, dstSize, dstSkip); \ - \ - /* build result using sign inverted weights [32767,-32768] */ \ - if constexpr (op == eWindowEvaluation_Sum) { \ - res0 -= ((atyp)_0 * *w); \ - res1 -= ((atyp)_1 * *w); \ - res2 -= ((atyp)_2 * *w); \ - res3 -= ((atyp)_3 * *w++); \ - } \ - else if constexpr (op == eWindowEvaluation_Max) { \ - res0 = maximum(res0, -(atyp)_0 * *w); \ - res1 = maximum(res1, -(atyp)_1 * *w); \ - res2 = maximum(res2, -(atyp)_2 * *w); \ - res3 = maximum(res3, -(atyp)_3 * *w++); \ - } \ - else if constexpr (op == eWindowEvaluation_Min) { \ - res0 = (atyp)32768.0 - maximum((atyp)32768.0 - res0, -(atyp)(1.0f - _0) * *w); \ - res1 = (atyp)32768.0 - maximum((atyp)32768.0 - res1, -(atyp)(1.0f - _1) * *w); \ - res2 = (atyp)32768.0 - maximum((atyp)32768.0 - res2, -(atyp)(1.0f - _2) * *w); \ - res3 = (atyp)32768.0 - maximum((atyp)32768.0 - res3, -(atyp)(1.0f - _3) * *w++); \ - } \ - } while (++srcPos < fw.last); \ - \ - /* dtyp _0 = ldexp((dtyp)res0, -15); */ \ - /* dtyp _1 = ldexp((dtyp)res1, -15); */ \ - /* dtyp _2 = ldexp((dtyp)res2, -15); */ \ - /* dtyp _3 = ldexp((dtyp)res3, -15); */ \ - \ - dtyp _0 = (dtyp)res0 * (dtyp)(1.0 / 32768.0); \ - dtyp _1 = (dtyp)res1 * (dtyp)(1.0 / 32768.0); \ - dtyp _2 = (dtyp)res2 * (dtyp)(1.0 / 32768.0); \ - dtyp _3 = (dtyp)res3 * (dtyp)(1.0 / 32768.0); \ - \ - /* put value */ \ - store(srcOffs, srcSize, srcSkip, dstOffs, dstSize, dstSkip); \ - } while (++dstPos < (signed)dstSize); \ - \ - exit(srcOffs, srcSize, srcSkip, dstOffs, dstSize, dstSkip); - - #define filterF4xNHor(srcOffs, srcSize, srcSkip, dstOffs, dstSize, dstSkip, init, next, fetch, store, exit, op, pm) \ - filter4xNf(srcOffs, srcSize, srcSkip, dstOffs, dstSize, dstSkip, init, next, fetch, store, exit, op, 0, fwh, float, float /*double*/) - - #define filterF4xNVer(srcOffs, srcSize, srcSkip, dstOffs, dstSize, dstSkip, init, next, fetch, store, exit, op, pm) \ - filter4xNf(srcOffs, srcSize, srcSkip, dstOffs, dstSize, dstSkip, init, next, fetch, store, exit, op, 0, fwv, float, float /*double*/) - - /* #################################################################################################################### \ - */ - #define resampleF4xNFromPlane(stride) \ - float _0, _1, _2, _3; \ - \ - _0 = (*i0)[ix], i0 += (stride) * dy; \ - _1 = (*i1)[ix], i1 += (stride) * dy; \ - _2 = (*i2)[ix], i2 += (stride) * dy; \ - _3 = (*i3)[ix], i3 += (stride) * dy; - - /* ******************************************************************************************************************** \ - */ - #define resampleF4xNFromStream(stride, instream) \ - float _0, _1, _2, _3; \ - \ - _0 = instream[0]; \ - _1 = instream[1]; \ - _2 = instream[2]; \ - _3 = instream[3], instream += (stride) * 4; - - /* ******************************************************************************************************************** \ - */ - #define resampleF4xNFromStreamSwapped(stride, instream) \ - float _0, _1, _2, _3; \ - \ - _3 = instream[0]; \ - _2 = instream[1]; \ - _1 = instream[2]; \ - _0 = instream[3], instream += (stride) * 4; - - /* #################################################################################################################### \ - */ - #define resampleF4xNToPlane(stride) \ - (*o0)[ox] = _0; \ - (*o1)[ox] = _1; \ - (*o2)[ox] = _2; \ - (*o3)[ox] = _3, ox += (1) * 1; - - /* ******************************************************************************************************************** \ - */ - #define resampleF4xNToStream(stride, outstream) \ - outstream[0] = _0; \ - outstream[1] = _1; \ - outstream[2] = _2; \ - outstream[3] = _3, outstream += (1) * 4; - - /* ******************************************************************************************************************** \ - */ - #define resampleF4xNToStreamSwapped(stride, outstream) \ - outstream[0] = _3; \ - outstream[1] = _2; \ - outstream[2] = _1; \ - outstream[3] = _0, outstream += (1) * 4; - - /* #################################################################################################################### \ - */ - #undef filterF4xNFromPlane - #define filterF4xNFromPlane(stride) \ - resampleF4xNFromPlane(stride) - - /* ******************************************************************************************************************** \ - */ - #undef filterF4xNFromStream - #define filterF4xNFromStream(stride, instream) \ - resampleF4xNFromStream(stride, instream) - - /* ******************************************************************************************************************** \ - */ - #undef filterF4xNFromStreamSwapped - #define filterF4xNFromStreamSwapped(stride, instream) \ - resampleF4xNFromStreamSwapped(stride, instream) - - /* #################################################################################################################### \ - */ - #undef filterF4xNToPlane - #define filterF4xNToPlane(stride) \ - resampleF4xNToPlane(stride) - - /* ******************************************************************************************************************** \ - */ - #undef filterF4xNToStream - #define filterF4xNToStream(stride, outstream) \ - resampleF4xNToStream(stride, outstream) - - /* ******************************************************************************************************************** \ - */ - #undef filterF4xNToStreamSwapped - #define filterF4xNToStreamSwapped(stride, outstream) \ - resampleF4xNToStreamSwapped(stride, outstream) - - /* #################################################################################################################### \ - */ - #define loopEnter(id, untill, advance) \ - unsigned int id; for (id = 0; id < untill; id += advance) { - #define loopLeave(id, untill, advance) \ - } - - /* #################################################################################################################### \ - */ - #define all4InitSwappablePlanePointers(left, top, row, rows, pp, swap, dtyp) \ - dtyp * pp##0, *pp##1, *pp##2, *pp##3; \ - \ - pp##0 = pp[0][/*parm->mirror ? (rows - 1) - (row + top) :*/ (row + top)] + left; /* r */ \ - pp##1 = pp[1][/*parm->mirror ? (rows - 1) - (row + top) :*/ (row + top)] + left; /* g */ \ - pp##2 = pp[2][/*parm->mirror ? (rows - 1) - (row + top) :*/ (row + top)] + left; /* b */ \ - pp##3 = pp[3][/*parm->mirror ? (rows - 1) - (row + top) :*/ (row + top)] + left; /* a */ - - #define allF4InitSwappablePlanePointers(left, top, row, rows, pp, swap) \ - all4InitSwappablePlanePointers(left, top, row, rows, pp, swap, float) - - /* #################################################################################################################### \ - */ - #define all4InitFixedPlanePointers(left, top, row, rows, pp, swap, dtyp) \ - dtyp * pp##0, *pp##1, *pp##2, *pp##3; \ - \ - pp##0 = pp[0][(row + top)] + left; /* r */ \ - pp##1 = pp[1][(row + top)] + left; /* g */ \ - pp##2 = pp[2][(row + top)] + left; /* b */ \ - pp##3 = pp[3][(row + top)] + left; /* a */ - - #define allF4InitFixedPlanePointers(left, top, row, rows, pp, swap) \ - all4InitFixedPlanePointers(left, top, row, rows, pp, swap, float) - - /* #################################################################################################################### \ - */ - #define all4InitSwappablePlaneReferences(left, offs, top, row, rows, pp, swap, dtyp) \ - unsigned long int pp##x = left + offs; \ - dtyp** pp##0; \ - dtyp** pp##1; \ - dtyp** pp##2; \ - dtyp** pp##3; \ - \ - pp##0 = pp[0] + (/*parm->mirror ? (rows - 1) - (row + top) :*/ (row + top)); /* r */ \ - pp##1 = pp[1] + (/*parm->mirror ? (rows - 1) - (row + top) :*/ (row + top)); /* g */ \ - pp##2 = pp[2] + (/*parm->mirror ? (rows - 1) - (row + top) :*/ (row + top)); /* b */ \ - pp##3 = pp[3] + (/*parm->mirror ? (rows - 1) - (row + top) :*/ (row + top)); /* a */ - - #define allF4InitSwappablePlaneReferences(left, offs, top, row, rows, pp, swap) \ - all4InitSwappablePlaneReferences(left, offs, top, row, rows, pp, swap, float) - - /* #################################################################################################################### \ - */ - #define all4InitFixedPlaneReferences(left, row, rows, pp, ps, dtyp) \ - unsigned long int pp##x = left; \ - dtyp** pp##0; \ - dtyp** pp##1; \ - dtyp** pp##2; \ - dtyp** pp##3; \ - \ - pp##0 = ps[0] + (row); /* r */ \ - pp##1 = ps[1] + (row); /* g */ \ - pp##2 = ps[2] + (row); /* b */ \ - pp##3 = ps[3] + (row); /* a */ - - #define allF4InitFixedPlaneReferences(left, row, rows, pp, ps) \ - all4InitFixedPlaneReferences(left, row, rows, pp, ps, float) - - /* #################################################################################################################### \ - */ - #define allF4AdvanceSwappablePlaneReferences(row, rows, pp) \ - pp##0 += (rows - row) * dy; /* r */ \ - pp##1 += (rows - row) * dy; /* g */ \ - pp##2 += (rows - row) * dy; /* b */ \ - pp##3 += (rows - row) * dy; /* a */ - - /* #################################################################################################################### \ - */ - #define allF4AdvanceFixedPlaneReferences(row, rows, pp) \ - allF4AdvanceSwappablePlaneReferences(row, rows, pp) - - /* #################################################################################################################### \ - */ - #define allF4AdvanceStreamPointer(left, col, cols, sp) \ - sp += ((cols) - (left + col)) * 4; - - /* ******************************************************************************************************************** \ - */ - #define allF4AdvNMULStreamPointer(top, stride, sp) \ - sp -= ((stride) * (top)) * 4; - - /* ******************************************************************************************************************** \ - */ - #define allF4AdvPMULStreamPointer(top, stride, sp) \ - sp += ((stride) * (top)) * 4; - - /* ******************************************************************************************************************** \ - */ - #define allF4AdvSUBMStreamPointer(left, top, stride, sp) \ - sp -= (((stride) * (top)) - (left)) * 4; - - /* ******************************************************************************************************************** \ - */ - #define allF4AdvADDMStreamPointer(left, top, stride, sp) \ - sp += ((left) + ((stride) * (top))) * 4; - - /* ******************************************************************************************************************** \ - */ - #define allF4AdvPADDStreamPointer(offs, sp) \ - sp += (offs) * 4; - - /* ******************************************************************************************************************** \ - */ - #define allF4AdvSSUBStreamPointer(top, shift, offs, sp) \ - sp += (((top) << (shift)) - (offs)) * 4; - - /* ******************************************************************************************************************** \ - */ - #define allF4AdvNAMAStreamPointer(left, top, offs, stride, sp) \ - sp -= ((left) + (((top) + (offs)) * (stride))) * 4; - - /* ################################################################################################################### \ - */ - #undef comcpyFNum - #define comcpyFNum 1 - #undef orderedFNum - #define orderedFNum 1 - #undef orderedFShift - #define orderedFShift 0 - #undef interleavedFNum - #define interleavedFNum 1 - - /* #################################################################################################################### \ - */ - # define allTInitFixedOutPlaneReferences allF4InitFixedPlaneReferences - # define allTInitFixedInPlaneReferences allF4InitFixedPlaneReferences - # define allCInitSwappableInPlaneReferences /*allF4InitSwappablePlaneReferences*/ - # define allCInitSwappableOutPlaneReferences /*allF4InitSwappablePlaneReferences*/ - - # define allCAdvADDMInStreamPointer allF4AdvADDMStreamPointer - # define allCAdvPADDInStreamPointer allF4AdvPADDStreamPointer - # define allCAdvPMULInStreamPointer allF4AdvPMULStreamPointer - # define allCAdvNMULInStreamPointer allF4AdvNMULStreamPointer - # define allCAdvADDMOutStreamPointer allF4AdvADDMStreamPointer - # define allCAdvSSUBOutStreamPointer allF4AdvSSUBStreamPointer - - # define getCxNFromStreamSwapped /*filterF4xNFromStreamSwapped*/ - # define getCxNFromStream filterF4xNFromStream - # define getCxNFromPlane /*filterF4xNFromPlane*/ - # define getTxNFromPlane filterF4xNFromPlane - - # define filterHor filterF4xNHor - # define filterVer filterF4xNVer - - # define comcpyCCheckHiLo() /*orderedF4CheckHiLo*/ - # define comcpyCCoVar() /*orderedF4CoVar*/ - # define comcpyCHistogram() /*orderedF4Histogram*/ - - # define putCxNToStreamSwapped /*filterF4xNToStreamSwapped*/ - # define putCxNToStream filterF4xNToStream - # define putCxNToPlane /*filterF4xNToPlane*/ - # define putTxNToPlane filterF4xNToPlane - - # define orderedNum orderedFNum - # define orderedShift orderedFShift - - # define comcpyCMergeHiLo(orderedNum) /*comcpyFTMergeHiLo*/ - # define comcpyCCompleteCoVar(orderedNum) /*comcpyFTCompleteCoVar*/ - # define comcpyCCompleteHistogram(orderedNum) /*comcpyFTCompleteHistogram*/ - - # define hiloCVariables /*hiloFTVariables*/ - # define covarCVariables /*covarFTVariables*/ - # define histoCVariables /*histoFTVariables*/ - - # define filterCVariables filterFTVariables - - # define orderedTInitLoop() /*orderedTInitLoop*/ - # define hiloTInitLoop() /*hiloTInitLoop*/ - # define covarTInitLoop() /*covarTInitLoop*/ - # define histoTInitLoop() /*histoTInitLoop*/ - - # define orderedTExitLoop() /*orderedTExitLoop*/ - # define hiloTExitLoop() /*hiloTExitLoop*/ - # define covarTExitLoop() /*covarTExitLoop*/ - # define histoTExitLoop() /*histoTExitLoop*/ - - # define filterCCleanUp filterTCleanUp - - /* #################################################################################################################### \ - */ - - struct prcparm - { - /* configuration -------------------------------------------------------------------------------- */ - - /* dimensions of the source/destination image */ - int inrows, outrows, subrows; - int incols, outcols, subcols; - - /* region to process the stuff in */ - bool regional; - /* don't fetch data from outside the region */ - bool caged; - struct - { - /* offsets to the source/destination image-region */ - int intop, outtop, subtop; - int inleft, outleft, subleft; - - /* dimensions of the source/destination image-region */ - int inrows, outrows, subrows; - int incols, outcols, subcols; - } region; - - /* parameters ----------------------------------------------------------------------------------- */ - - /* parameters for resampling */ - struct - { - /* we don't give floating-point x/y-factor, it's not exact enough */ - unsigned int rowquo, rowrem; - unsigned int colquo, colrem; - - /* over/under-blurring (window minification/magnification) */ - float rowblur, colblur; - - /* the windowing-function for the filtering */ - IWindowFunction* wf; - - /* operation to perform the filter with */ - int operation; - } resample; - - /* private stuff -------------------------------------------------------------------------------- */ - - /* what really has do be done after choosing/recalculation */ - int dorows, docols; - }; - - static void CheckBoundaries(const void* i, void* o, struct prcparm* parm) - { - /* the parameter evaluation ----------------------------------------------- */ - const bool scaler = true; - - /* this is fairly straightforward */ - if (!parm->regional) - { - int rgrows = parm->inrows; - int rgcols = parm->incols; - - /* compare out-region against available out-size */ - if (o) - { - int dorows = parm->outrows; - int docols = parm->outcols; - - /* scale up */ - if (scaler) - { - dorows = dorows * parm->resample.rowrem / parm->resample.rowquo; - docols = docols * parm->resample.colrem / parm->resample.colquo; - } - - /* compare in scaled space */ - rgrows = maximum(rgrows, dorows); - rgcols = maximum(rgcols, docols); - - /* scale down */ - if (scaler) - { - rgrows = rgrows * parm->resample.rowquo / parm->resample.rowrem; - rgcols = rgcols * parm->resample.colquo / parm->resample.colrem; - } - } - - parm->dorows = rgrows; - parm->docols = rgcols; - } - /* this may need some adjustment */ - else - { - int rgrows = parm->region.inrows; - int rgcols = parm->region.incols; - - /* compare in/out-region against available out-size */ - if (o) - { - int dorows = parm->region.outrows; - int docols = parm->region.outcols; - - /* compare out-region against available in-size */ - if (dorows > parm->outrows - parm->region.outtop) - { - dorows = parm->outrows - parm->region.outtop; - } - if (docols > parm->outcols - parm->region.outleft) - { - docols = parm->outcols - parm->region.outleft; - } - - /* scale to in */ - if (scaler) - { - dorows = dorows * parm->resample.rowrem / parm->resample.rowquo; - docols = docols * parm->resample.colrem / parm->resample.colquo; - } - - /* compare in scaled space */ - rgrows = maximum(rgrows, dorows); - rgcols = maximum(rgcols, docols); - - /* compare in-region against available in-size */ - if (i) - { - if (rgrows > parm->inrows - parm->region.intop) - { - rgrows = parm->inrows - parm->region.intop; - } - if (rgcols > parm->incols - parm->region.inleft) - { - rgcols = parm->incols - parm->region.inleft; - } - } - - /* scale to out */ - if (scaler) - { - rgrows = rgrows * parm->resample.rowquo / parm->resample.rowrem; - rgcols = rgcols * parm->resample.colquo / parm->resample.colrem; - } - } - else - { - /* compare in-region against available in-size */ - if (i) - { - if (rgrows > parm->inrows - parm->region.intop) - { - rgrows = parm->inrows - parm->region.intop; - } - if (rgcols > parm->incols - parm->region.inleft) - { - rgcols = parm->incols - parm->region.inleft; - } - } - } - - parm->dorows = rgrows; - parm->docols = rgcols; - } - - AZ_Assert(parm->dorows > 0, "%s: Expect row count to be above zero!", __FUNCTION__); - AZ_Assert(parm->docols > 0, "%s: Expect column count to be above zero!", __FUNCTION__); - } - - /* #################################################################################################################### \ - * multi-threadable if needed - */ - static void RunAlgorithm(const float* i, float* o, struct prcparm* parm) - { - /* make these local, so no indirect access is needed */ - const unsigned int srcrows = parm->dorows * parm->resample.rowrem / parm->resample.rowquo; - const unsigned int srccols = parm->docols * parm->resample.colrem / parm->resample.colquo; - const unsigned int dstrows = parm->dorows; - const unsigned int dstcols = parm->docols; - const unsigned int cstZero = 0; - - /* temporary buffer region */ - parm->subrows = srccols; - parm->subcols = dstrows; - parm->region.subleft = 0; - parm->region.subtop = 0; - parm->region.subcols = parm->subcols; - parm->region.subrows = parm->subrows; - - if (!parm->caged) - { - int oleft; - int oright; - - /* check for out-of-region access rectangle */ - calculateFilterRange(srccols, oleft, oright, dstcols, 0, dstcols, parm->resample.colblur, parm->resample.wf); - - /* round down left, round up right */ - oleft = oleft & (~(orderedNum - 1)); - oright = (oright + (orderedNum - 1)) & (~(orderedNum - 1)); - - /* clamp to available image-rectangle */ - if ((oleft < (signed)parm->region.subtop) || - (oright > (signed)parm->subrows)) - { - oleft = maximum(oleft, -(signed)parm->region.inleft); - oright = minimum(oright, (signed)parm->incols); - } - - /* readjust temporary buffer region to include out-of-region accesses */ - parm->region.inleft += oleft; //rm->docols -= oleft; //rm->docols += (oright - srccols); - parm->region.subtop -= oleft; - parm->subrows -= oleft; - parm->subrows += (oright - srccols); - } - - const unsigned int tmprows = parm->subrows; - const unsigned int tmpcols = parm->subcols; - - /* -------------------------------------------------------------------------------------------- - * common resampling - */ - - /* init t */ - filterCVariables(orderedNum); - - filterTInitLoop(); - - /* -------------------------------------------------------------------------------------------- - * reading rows, writing cols (xy-flip) - * - * make srccol x inrow -> dstrow x srccol - * - * we are reading vertical, and writing horizontal - * in effect we can use fast parallel-reads, but need - * slow interleaved-writes - * as reads are slower (ask+receive) than writes (send) - * this should even be gracefully fast - */ - allCAdvADDMInStreamPointer(parm->region.inleft, parm->region.intop, parm->incols, i); - - #define filterRowInit(srcOffs, srcSize, srcSkip, dstOffs, dstSize, dstSkip) \ - allTInitFixedOutPlaneReferences(cstZero, srcOffs, -, o, t); - - #define filterRowNext(srcOffs, srcSize, srcSkip, dstOffs, dstSize, dstSkip) \ - /* every in/out-put may swap */ \ - allCInitSwappableInPlaneReferences(parm->region.inleft, srcOffs, parm->region.intop, fw.first, parm->inrows, i, false); \ - /* because the filter moves back and forth, we always have to reposition from 0 */ \ - allCAdvPMULInStreamPointer(srcSkip##raw, fw.first, i); - - #define filterRowFetch(srcOffs, srcSize, srcSkip, dstOffs, dstSize, dstSkip) \ - /* vertical stride, horizontal fetch */ \ - getCxNFromStreamSwapped(srcSkip, i); \ - getCxNFromStream(srcSkip, i); \ - getCxNFromPlane(1); \ - \ - /*srcPos++;*/ - - #define filterRowStore(srcOffs, srcSize, srcSkip, dstOffs, dstSize, dstSkip) \ - /* because the filter moves back and forth, we always have to reposition to 0 */ \ - allCAdvNMULInStreamPointer(srcSkip##raw, fw.last, i); \ - \ - /* horizontal stride, vertical store */ \ - putTxNToPlane(1); \ - \ - /*dstPos++;*/ - - #define filterRowExit(srcOffs, srcSize, srcSkip, dstOffs, dstSize, dstSkip) \ - allCAdvPADDInStreamPointer(orderedNum, i); - - if (parm->resample.operation == eWindowEvaluation_Sum) - { - loopEnter(tmprow, tmprows, orderedNum); - - { - filterVer(tmprow, srcrows, stridei, - tmprow, dstrows, stridet, filterRowInit, filterRowNext, filterRowFetch, filterRowStore, filterRowExit, eWindowEvaluation_Sum, of); - } - - loopLeave(tmprow, tmprows, orderedNum); - } - else if (parm->resample.operation == eWindowEvaluation_Max) - { - loopEnter(tmprow, tmprows, orderedNum); - - { - filterVer(tmprow, srcrows, stridei, - tmprow, dstrows, stridet, filterRowInit, filterRowNext, filterRowFetch, filterRowStore, filterRowExit, eWindowEvaluation_Max, of); - } - - loopLeave(tmprow, tmprows, orderedNum); - } - else if (parm->resample.operation == eWindowEvaluation_Min) - { - loopEnter(tmprow, tmprows, orderedNum); - - { - filterVer(tmprow, srcrows, stridei, - tmprow, dstrows, stridet, filterRowInit, filterRowNext, filterRowFetch, filterRowStore, filterRowExit, eWindowEvaluation_Min, of); - } - - loopLeave(tmprow, tmprows, orderedNum); - } - - /* 1st resampling end - * -------------------------------------------------------------------------------------------- - */ - filterTExitLoop(); - - /* return collected min/max */ - hiloCVariables(orderedNum); - covarCVariables(orderedNum); - histoCVariables(orderedNum); - - /* --------------------------------------------------------------- */ - orderedTInitLoop(); - filterTInitLoop(); - - hiloTInitLoop(); - covarTInitLoop(); - histoTInitLoop(); - - /* -------------------------------------------------------------------------------------------- - * reading rows, writing cols (xy-flip) - * - * make dstrow x srccol -> outcol x dstrow - * - * we are reading vertical, and writing horizontal - * in effect we can use fast parallel-reads, but need - * slow interleaved-writes - * as reads are slower (ask+receive) than writes (send) - * this should even be gracefully fast - */ - allCAdvADDMOutStreamPointer(parm->region.outleft, parm->region.outtop, parm->outcols, o); - - #define filterColInit(srcOffs, srcSize, srcSkip, dstOffs, dstSize, dstSkip) \ - allCInitSwappableOutPlaneReferences(parm->region.outleft, cstZero, parm->region.outtop, srcOffs, parm->outrows, o, false); - - #define filterColNext(srcOffs, srcSize, srcSkip, dstOffs, dstSize, dstSkip) \ - /* every in/out-put may swap */ \ - allTInitFixedInPlaneReferences(srcOffs, parm->region.subtop + fw.first, -, i, t); - - #define filterColFetch(srcOffs, srcSize, srcSkip, dstOffs, dstSize, dstSkip) \ - /* vertical stride, horizontal fetch */ \ - getTxNFromPlane(1); \ - \ - /*srcPos++;*/ - - #define filterColStore(srcOffs, srcSize, srcSkip, dstOffs, dstSize, dstSkip) \ - comcpyCCheckHiLo(); \ - comcpyCCoVar(); \ - comcpyCHistogram(); \ - \ - /* horizontal stride, vertical store */ \ - putCxNToStreamSwapped(dstSkip, o); \ - putCxNToStream(dstSkip, o); \ - putCxNToPlane(1); \ - \ - /*dstPos++;*/ - - #define filterColExit(srcOffs, srcSize, srcSkip, dstOffs, dstSize, dstSkip) \ - allCAdvSSUBOutStreamPointer(dstSkip##raw, orderedShift, dstPos, o); - - if (parm->resample.operation == eWindowEvaluation_Sum) - { - loopEnter(dstrow, dstrows, orderedNum); - - { - filterHor(dstrow, srccols, stridet, - dstrow, dstcols, strideo, filterColInit, filterColNext, filterColFetch, filterColStore, filterColExit, eWindowEvaluation_Sum, of); - } - - loopLeave(dstrow, dstrows, orderedNum); - } - else if (parm->resample.operation == eWindowEvaluation_Max) - { - loopEnter(dstrow, dstrows, orderedNum); - - { - filterHor(dstrow, srccols, stridet, - dstrow, dstcols, strideo, filterColInit, filterColNext, filterColFetch, filterColStore, filterColExit, eWindowEvaluation_Max, of); - } - - loopLeave(dstrow, dstrows, orderedNum); - } - else if (parm->resample.operation == eWindowEvaluation_Min) - { - loopEnter(dstrow, dstrows, orderedNum); - - { - filterHor(dstrow, srccols, stridet, - dstrow, dstcols, strideo, filterColInit, filterColNext, filterColFetch, filterColStore, filterColExit, eWindowEvaluation_Min, of); - } - - loopLeave(dstrow, dstrows, orderedNum); - } - - /* 2nd resampling end - * -------------------------------------------------------------------------------------------- - */ - histoTExitLoop(); - covarTExitLoop(); - hiloTExitLoop(); - - filterTExitLoop(); - orderedTExitLoop(); - /* --------------------------------------------------------------- */ - - /* return collected min/max */ - comcpyCMergeHiLo(orderedNum); - comcpyCCompleteCoVar(orderedNum); - comcpyCCompleteHistogram(orderedNum); - - /* exit t */ - filterCCleanUp(orderedNum); - } - - // TODO: not working yet, debug and enable - //static void SplitAlgorithm(const void* i, void* o, struct prcparm* templ, int threads = 8) - //{ - // struct prcparm fraction[32]; - // int t, istart = 0, sstart = 0, ostart = 0; - // const bool scaler = true; - - // int theight = 0; - - // /* prepare data to be emitted to the threads */ - // for (t = 0; t < threads; t++) - // { - // fraction[t] = *templ; - - // /* adjust the processing-region according to the available threads */ - // { - //#undef split /* only prefix-threads need aligned transpose (for not trashing suffix-thread data) */ - //#define split(rows) !scaler \ - // ? ((rows * (t + 1)) / threads) & (~(t != threads - 1 ? 15 : 0)) \ - // : ((rows * (t + 1)) / threads) & (~0) - - // /* area covered */ - // const int inrows = (fraction[t].regional ? fraction[t].region.inrows : fraction[t].inrows); - // const int incols = (fraction[t].regional ? fraction[t].region.incols : fraction[t].incols); - // const int subrows = (fraction[t].regional ? fraction[t].region.subrows : fraction[t].subrows); - // const int subcols = (fraction[t].regional ? fraction[t].region.subcols : fraction[t].subcols); - // const int outrows = (fraction[t].regional ? fraction[t].region.outrows : fraction[t].outrows); - // const int outcols = (fraction[t].regional ? fraction[t].region.outcols : fraction[t].outcols); - - // /* splitting blocks */ - // const int istop = split(inrows), sstop = split(subrows), ostop = split(outrows); - // const int irows = istop - istart, srows = sstop - sstart, orows = ostop - ostart; - // const int icols = incols, scols = subcols, ocols = outcols; - - // AZ_Assert(irows > 0, "%s: Expect row count to be above zero!", __FUNCTION__); - // AZ_Assert(orows > 0, "%s: Expect row count to be above zero!", __FUNCTION__); - // AZ_Assert(icols > 0, "%s: Expect column count to be above zero!", __FUNCTION__); - // AZ_Assert(ocols > 0, "%s: Expect column count to be above zero!", __FUNCTION__); - - // /* now we are regional */ - // fraction[t].regional = true; - - // /* take previous regionality into account */ - // fraction[t].region.intop += istart; - // fraction[t].region.subtop += sstart; - // fraction[t].region.outtop += ostart; - // fraction[t].region.inrows = irows; - // fraction[t].region.subrows = srows; - // fraction[t].region.outrows = orows; - - // /* take previous regionality into account */ - // fraction[t].region.inleft += 0; - // fraction[t].region.subleft += 0; - // fraction[t].region.outleft += 0; - // fraction[t].region.incols = icols; - // fraction[t].region.subcols = scols; - // fraction[t].region.outcols = ocols; - - // /* advance block */ - // istart = istop; - // sstart = sstop; - // ostart = ostop; - - // /* check */ - // theight += irows; - // } - - // // the algorithm supports "i" and "o" pointing to the same memory - // CheckBoundaries((float*)i, (float*)o, &fraction[t]); - // RunAlgorithm((float*)i, (float*)o, &fraction[t]); - // } - - // AZ_Assert(theight >= (templ->regional ? templ->region.inrows : templ->inrows), "%s: Invalid height!", __FUNCTION__); - //} - - /* #################################################################################################################### \ - */ - void FilterImage(int filterIndex, int filterOp, float blurH, float blurV, const IImageObjectPtr srcImg, int srcMip, - IImageObjectPtr dstImg, int dstMip, QRect* srcRect, QRect* dstRect) - { - //only support ePixelFormat_R32G32B32A32F - if (srcImg->GetPixelFormat() != ePixelFormat_R32G32B32A32F || dstImg->GetPixelFormat() != ePixelFormat_R32G32B32A32F) - { - AZ_Assert(false, "FilterImage only support both source and dest image objects have pixel format R32G32B32A32F"); - return; - } - - uint32 srcWidth, srcHeight; - uint8* pSrcMem; - uint32 dwSrcPitch; - - srcImg->GetImagePointer(srcMip, pSrcMem, dwSrcPitch); - - srcWidth = srcImg->GetWidth(srcMip); - srcHeight = srcImg->GetHeight(srcMip); - - uint32 dstWidth, dstHeight; - uint8* pDestMem; - uint32 dwDestPitch; - - dstImg->GetImagePointer(dstMip, pDestMem, dwDestPitch); - - dstWidth = dstImg->GetWidth(dstMip); - dstHeight = dstImg->GetHeight(dstMip); - - { - struct prcparm parm; - memset(&parm, 0, sizeof(parm)); - - parm.incols = srcWidth; - parm.inrows = srcHeight; - parm.outcols = dstWidth; - parm.outrows = dstHeight; - parm.regional = false; - parm.caged = false; - - if (srcRect || dstRect) - { - parm.regional = true; - parm.caged = true; - - parm.region.inleft = (!srcRect ? 0 : srcRect->left()); - parm.region.intop = (!srcRect ? 0 : srcRect->top()); - parm.region.incols = (!srcRect ? parm.incols : srcRect->right() - srcRect->left()); - parm.region.inrows = (!srcRect ? parm.inrows : srcRect->bottom() - srcRect->top()); - - parm.region.outleft = (!dstRect ? 0 : dstRect->left()); - parm.region.outtop = (!dstRect ? 0 : dstRect->top()); - parm.region.outcols = (!dstRect ? parm.outcols : dstRect->right() - dstRect->left()); - parm.region.outrows = (!dstRect ? parm.outrows : dstRect->bottom() - dstRect->top()); - - if (!srcRect) - { - parm.region.inleft = parm.region.outleft * srcHeight / dstHeight; - parm.region.intop = parm.region.outtop * srcWidth / dstWidth; - } - - if (!dstRect) - { - parm.region.outleft = parm.region.inleft * dstHeight / srcHeight; - parm.region.outtop = parm.region.intop * dstWidth / srcWidth; - } - } - - parm.resample.colquo = dstWidth; - parm.resample.colrem = srcWidth; - parm.resample.rowquo = dstHeight; - parm.resample.rowrem = srcHeight; - parm.resample.rowblur = blurH; - parm.resample.colblur = blurV; - parm.resample.operation = filterOp; - - switch (filterIndex) - { - // case eWindowFunction_COMBINER : parm.resample.wf = new CombinerWindowFunction(..., ...); break; - case eWindowFunction_Point: - parm.resample.wf = new PointWindowFunction(); - break; - case eWindowFunction_Box: - parm.resample.wf = new BoxWindowFunction(); - break; - case eWindowFunction_Triangle: - parm.resample.wf = new TriangleWindowFunction(); - break; - case eWindowFunction_Quadric: - parm.resample.wf = new QuadricWindowFunction(); - break; - case eWindowFunction_Cubic: - parm.resample.wf = new CubicWindowFunction(); - break; - case eWindowFunction_Hermite: - parm.resample.wf = new HermiteWindowFunction(); - break; - case eWindowFunction_Catrom: - parm.resample.wf = new CatromWindowFunction(); - break; - case eWindowFunction_Sine: - parm.resample.wf = new SineWindowFunction(); - break; - case eWindowFunction_Sinc: - parm.resample.wf = new SincWindowFunction(); - break; - case eWindowFunction_Bessel: - parm.resample.wf = new BesselWindowFunction(); - break; - case eWindowFunction_Lanczos: - parm.resample.wf = new LanczosWindowFunction(); - break; - case eWindowFunction_Gaussian: - parm.resample.wf = new GaussianWindowFunction(); - break; - case eWindowFunction_Normal: - parm.resample.wf = new NormalWindowFunction(); - break; - case eWindowFunction_Mitchell: - parm.resample.wf = new MitchellWindowFunction(); - break; - case eWindowFunction_Hann: - parm.resample.wf = new HannWindowFunction(); - break; - case eWindowFunction_BartlettHann: - parm.resample.wf = new BartlettHannWindowFunction(); - break; - case eWindowFunction_Hamming: - parm.resample.wf = new HammingWindowFunction(); - break; - case eWindowFunction_Blackman: - parm.resample.wf = new BlackmanWindowFunction(); - break; - case eWindowFunction_BlackmanHarris: - parm.resample.wf = new BlackmanHarrisWindowFunction(); - break; - case eWindowFunction_BlackmanNuttall: - parm.resample.wf = new BlackmanNuttallWindowFunction(); - break; - case eWindowFunction_Flattop: - parm.resample.wf = new FlatTopWindowFunction(); - break; - case eWindowFunction_Kaiser: - parm.resample.wf = new KaiserWindowFunction(); - break; - - case eWindowFunction_SigmaSix: - parm.resample.wf = new SigmaSixWindowFunction(); - break; - case eWindowFunction_KaiserSinc: - parm.resample.wf = new CombinerWindowFunction(new SincWindowFunction(), new KaiserWindowFunction()); - break; - - default: - abort(); - break; - } - - // TODO: not working yet, debug and enable - // SplitAlgorithm(pSrcMem, pDestMem, &parm); - - // the algorithm supports "pSrcMem" and "pDestMem" pointing to the same memory - CheckBoundaries((float*)pSrcMem, (float*)pDestMem, &parm); - RunAlgorithm((float*)pSrcMem, (float*)pDestMem, &parm); - - delete parm.resample.wf; - } - } - - int MipGenTypeToFilterIndex(MipGenType filterType) - { - switch (filterType) - { - case MipGenType::point: - return eWindowFunction_Point; - case MipGenType::box: - return eWindowFunction_Box; - case MipGenType::triangle: - return eWindowFunction_Triangle; - case MipGenType::quadratic: - return eWindowFunction_Bilinear; - case MipGenType::gaussian: - return eWindowFunction_Gaussian; - case MipGenType::blackmanHarris: - return eWindowFunction_BlackmanHarris; - case MipGenType::kaiserSinc: - return eWindowFunction_KaiserSinc; - default: - AZ_Assert(false, "unable find filter type for mipmap gen type %d", filterType); - return eWindowFunction_BlackmanHarris; - } - } - - /* #################################################################################################################### \ - */ - void FilterImage(MipGenType filterType, MipGenEvalType evalType, float blurH, float blurV, const IImageObjectPtr srcImg, int srcMip, - IImageObjectPtr dstImg, int dstMip, QRect* srcRect, QRect* dstRect) - { - int filterIndex = MipGenTypeToFilterIndex(filterType); - int filterOp = static_cast(evalType); - FilterImage(filterIndex, filterOp, blurH, blurV, srcImg, srcMip, dstImg, dstMip, srcRect, dstRect); - } - -} diff --git a/Gems/ImageProcessing/Code/Source/Converters/FIR-Weights.cpp b/Gems/ImageProcessing/Code/Source/Converters/FIR-Weights.cpp deleted file mode 100644 index d5d9d617c4..0000000000 --- a/Gems/ImageProcessing/Code/Source/Converters/FIR-Weights.cpp +++ /dev/null @@ -1,329 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS 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 "FIR-Weights.h" - -/* #################################################################################################################### - */ - -namespace ImageProcessing -{ - void calculateFilterRange(unsigned int srcFactor, int& srcFirst, int& srcLast, - unsigned int dstFactor, int dstFirst, int dstLast, - double blurFactor, class IWindowFunction* windowFunction) - { - double s, t, u, scaleFactor; /* scale factors */ - double srcRadius, srcCenter; /* window position and size */ - -#define s0 0 -#define s1 srcFactor -#define d0 0 -#define d1 dstFactor - - /* the mapping from discrete destination coordinates to continuous source coordinates: */ -#define MAP(b, scaleFactor, offset) ((b) + (offset)) / (scaleFactor) - - /* relation of dstFactor to srcFactor */ - s = (double)dstFactor / srcFactor; - t = d0 - s * (s0 - 0.5) - 0.5; - - /* compute offsets for MAP */ - u = d0 - s * (s0 - 0.5) - t; - - /* find scale of filter - * when minifying, scaleFactor = 1/s, but when magnifying, scaleFactor = 1 - */ - scaleFactor = (blurFactor == 0.0 ? 1.0 : (blurFactor > 0.0 ? (1.0 + blurFactor) : 1.0 / (1.0 - blurFactor))) * maximum(1., 1. / s); - - /* find support radius of scaled filter - * if the window's length is <= 0.5 then we've got point sampling. - */ - srcRadius = maximum(0.5, scaleFactor * windowFunction->getLength()); - - /* sample the continuous filter, scaled by scaleFactor and - * positioned at continuous source coordinate srcCenter - */ - { - srcCenter = MAP(dstFirst + 0, s, u); - - /* find the source coordinate range of this positioned filter window */ - srcFirst = int(floor(srcCenter - srcRadius + 0.5)); - } - - { - srcCenter = MAP(dstLast - 1, s, u); - - /* find the source coordinate range of this positioned filter window */ - srcLast = int(floor(srcCenter + srcRadius + 0.5)); - } - } - - template<> - FilterWeights* calculateFilterWeights(unsigned int srcFactor, int srcFirst, int srcLast, - unsigned int dstFactor, int dstFirst, int dstLast, signed short int numRepetitions, - double blurFactor, class IWindowFunction* windowFunction, - bool peaknorm, bool& plusminus) - - { -#define WEIGHTBITS 15 -#define WEIGHTONE (1 << WEIGHTBITS) /* filter weight of one */ - - double s, t, u, scaleFactor; /* scale factors */ - double srcRadius, srcCenter; /* window position and size */ - double sumfWeights, neg, pos, nrmWeights, fWeight; /* window position and size */ - int i, i0, i1; /* window position and size */ - int dstPosition; - signed short int n; - bool trimZeros = true, stillzero; - int lastnonzero, hWeight, highest; - signed int sumiWeights, iWeight; - signed short int* weightsPtr, *weightsMem; - FilterWeights* weightsObjs; - bool pm, pma = false; - - /* pre-calculate filter window solutions for all rows - */ - weightsObjs = new FilterWeights[dstLast - dstFirst]; - -#define s0 0 -#define s1 srcFactor -#define d0 0 -#define d1 dstFactor - - /* relation of dstFactor to srcFactor */ - s = (double)dstFactor / srcFactor; - t = d0 - s * (s0 - 0.5) - 0.5; - - /* compute offsets for MAP */ - u = d0 - s * (s0 - 0.5) - t; - - /* find scale of filter - * when minifying, scaleFactor = 1/s, but when magnifying, scaleFactor = 1 - */ - scaleFactor = (blurFactor == 0.0 ? 1.0 : (blurFactor > 0.0 ? (1.0 + blurFactor) : 1.0 / (1.0 - blurFactor))) * maximum(1., 1. / s); - - /* find support radius of scaled filter - * if the window's length is <= 0.5 then we've got point sampling. - */ - srcRadius = maximum(0.5, scaleFactor * windowFunction->getLength()); - - /* sample the continuous filter, scaled by ap->scaleFactor and - * positioned at continuous source coordinate srcCenter, for source coordinates in - * the range [0..len-1], writing the weights into wtab. - * Scale the weights so they sum up to WEIGHTONE, and trim leading and trailing - * zeros if trimZeros is true. - */ -#undef NORMALIZE_SUMMED_PEAK -#define NORMALIZE_MAXXED_PEAK - for (dstPosition = dstFirst, pm = false; dstPosition < dstLast; dstPosition++) - { - srcCenter = MAP(dstPosition, s, u); - - /* find the source coordinate range of this positioned filter window */ - i0 = int(floor(srcCenter - srcRadius + 0.5)); - i1 = int(floor(srcCenter + srcRadius + 0.5)); - - /* clip against the source-range */ - if (i0 < srcFirst) - { - i0 = srcFirst; - } - if (i1 > srcLast) - { - i1 = srcLast; - } - - /* this is possible if we hit the final line */ - if (i1 <= i0) - { - if (i1 >= srcLast) - { - i0 = i1 - 1; - } - else - { - i1 = i0 + 1; - } - } - - AZ_Assert(i0 >= srcFirst, "%s: Invalid source coordinate range!", __FUNCTION__); - AZ_Assert(i1 <= srcLast, "%s: Invalid source coordinate range!", __FUNCTION__); - AZ_Assert(i0 < i1, "%s: Invalid source coordinate range!", __FUNCTION__); - - /* find maximum peak to normalize the filter */ - for (sumfWeights = 0, pos = 0, neg = 0, i = i0; i < i1; i++) - { - /* evaluate the filter function: */ - fWeight = (*windowFunction)((i + 0.5 - srcCenter) / scaleFactor); - -#if defined(NORMALIZE_SUMMED_PEAK) - /* get positive and negative summed peaks */ - if (fWeight >= 0) - { - pos += fWeight; - } - else - { - neg += fWeight; - } -#elif defined(NORMALIZE_MAXXED_PEAK) - /* get positive and negative maximum peaks */ - minmax(fWeight, neg, pos); -#endif - - sumfWeights += fWeight; - } - - /* the range of source samples to buffer: */ - weightsMem = new signed short int[(i1 - i0) * abs(numRepetitions)]; - - /* set nrmWeights so that sumWeights of windowFunction() is approximately WEIGHTONE - * this needs to be adjusted because the maximum weight-coefficient - * is NOT allowed to leave [-32768,32767] - * a case like {+1.25,-0.25} does produce a sumWeights of 1.0 BUT - * produced a weight much too high (-40000) - */ -#if defined(NORMALIZE_SUMMED_PEAK) - sumfWeights = maximum(-neg, pos); -#elif defined(NORMALIZE_MAXXED_PEAK) - sumfWeights = maximum(sumfWeights, maximum(-neg, pos)); -#endif - - if (!peaknorm) - { - nrmWeights = (sumfWeights == 0. ? WEIGHTONE : (-neg > pos ? WEIGHTONE - 1 : WEIGHTONE) / sumfWeights); - } - else - { - nrmWeights = (sumfWeights == 0. ? WEIGHTONE : (-neg > pos ? WEIGHTONE - 1 : WEIGHTONE) / maximum(-neg, pos)); - } - - /* compute the discrete, sampled filter coefficients */ - stillzero = trimZeros; - for (sumiWeights = 0, hWeight = -WEIGHTONE, weightsPtr = weightsMem, i = i0; i < i1; i++) - { - /* evaluate the filter function: */ - fWeight = (*windowFunction)((i + 0.5 - srcCenter) / scaleFactor); - - /* normalize against the peak sumWeights, because the sums are not allowed to leave -32768/32767 */ - fWeight = fWeight * nrmWeights; - iWeight = int(round(fWeight)); - - /* find first nonzero */ - if (stillzero && (iWeight == 0)) - { - i0++; - } - else - { - AZ_Assert((-fWeight >= -32768.5) && (-fWeight <= 32767.5), "%s:The weight exceeded the maximum weight-coefficient.", __FUNCTION__); - - if (!peaknorm) - { - sumiWeights += iWeight; - } - else - { - sumiWeights = maximum(sumiWeights, iWeight); - } - -#define sgnextend(n, iWeight) (n & 1 ? (iWeight < 0 ? -1 : 0) : iWeight) - if (numRepetitions < 0) - { - /* add weight to table, interleaved sign */ - for (n = 0; n < -numRepetitions; n++) - { - *weightsPtr++ = sgnextend(n, -iWeight); - } - } - else - { - /* add weight to table */ - for (n = 0; n < numRepetitions; n++) - { - *weightsPtr++ = -iWeight; - } - } - - stillzero = false; - - /* find last nonzero */ - if (iWeight != 0) - { - lastnonzero = i; - } - - /* check for negative values */ - if (iWeight < 0) - { - pm = pma = true; - } - - /* find most influential value */ - if (iWeight >= hWeight) - { - highest = i; - hWeight = iWeight; - } - } - } - - if (sumiWeights == 0) - { - i0 = (i0 + i1) >> 1; - i1 = (i0 + 1); - - for (n = 0, weightsPtr = weightsMem; n < numRepetitions; n++) - { - *weightsPtr++ = -WEIGHTONE; - } - } - else - { - /* skip leading and trailing zeros */ - if (trimZeros) - { - /* set i0 and i1 to the nonzero support of the filter */ - i0 = i0; - i1 = i1 = lastnonzero + 1; - } - - if (sumiWeights != WEIGHTONE) - { - /* Fudge with the highest value */ - i = highest; - - /* fudge srcCenter sample */ - iWeight = WEIGHTONE - sumiWeights; - - for (n = 0, weightsPtr = weightsMem + (i - i0) * numRepetitions; n < numRepetitions; n++) - { - *weightsPtr++ -= iWeight; - } - } - } - - /* the new adjusted range of source samples to buffer: */ - weightsObjs[dstPosition].first = i0; - weightsObjs[dstPosition].last = i1; - weightsObjs[dstPosition].hasNegativeWeights = pm; - weightsObjs[dstPosition].weights = weightsMem; - } - - plusminus = pma; - return weightsObjs; - } -} diff --git a/Gems/ImageProcessing/Code/Source/Converters/FIR-Weights.h b/Gems/ImageProcessing/Code/Source/Converters/FIR-Weights.h deleted file mode 100644 index 0dee77aa1a..0000000000 --- a/Gems/ImageProcessing/Code/Source/Converters/FIR-Weights.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 "FIR-Windows.h" - -namespace ImageProcessing -{ - /* #################################################################################################################### - */ - template - inline DataType abs (const DataType& ths) { return (ths < 0 ? -ths : ths); } - template - inline void minmax (const DataType& ths, DataType& mn, DataType& mx) { mn = (mn > ths ? ths : mn); mx = (mx < ths ? ths : mx); } - template - inline DataType minimum(const DataType& ths, const DataType& tht) { return (ths < tht ? ths : tht); } - template - inline DataType maximum(const DataType& ths, const DataType& tht) { return (ths > tht ? ths : tht); } - - /* #################################################################################################################### - */ - - template - class FilterWeights - { - public: - FilterWeights() - : weights(nullptr) - { - } - - ~FilterWeights() - { - delete[] weights; - } - - public: - // window-position - int first, last; - - // do we encounter positive as well as negative weights - bool hasNegativeWeights; - - /* weights, summing up to -(1 << 15), - * means weights are given negative - * that enables us to use signed short - * multiplication while occupying 0x8000 - */ - T* weights; - }; - - /* #################################################################################################################### - */ - - void calculateFilterRange (unsigned int srcFactor, int& srcFirst, int& srcLast, - unsigned int dstFactor, int dstFirst, int dstLast, - double blurFactor, class IWindowFunction* windowFunction); - - template - FilterWeights* calculateFilterWeights(unsigned int srcFactor, int srcFirst, int srcLast, - unsigned int dstFactor, int dstFirst, int dstLast, signed short int numRepetitions, - double blurFactor, class IWindowFunction* windowFunction, - bool peaknorm, bool& plusminus); - - template<> - FilterWeights* calculateFilterWeights(unsigned int srcFactor, int srcFirst, int srcLast, - unsigned int dstFactor, int dstFirst, int dstLast, signed short int numRepetitions, - double blurFactor, class IWindowFunction* windowFunction, - bool peaknorm, bool& plusminus); - - -} //end namespace ImageProcessing diff --git a/Gems/ImageProcessing/Code/Source/Converters/FIR-Windows.h b/Gems/ImageProcessing/Code/Source/Converters/FIR-Windows.h deleted file mode 100644 index b814d911d0..0000000000 --- a/Gems/ImageProcessing/Code/Source/Converters/FIR-Windows.h +++ /dev/null @@ -1,1283 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS 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 collection of window functions with Finite Impulse Response FIR -// and some helper window functions with Infinite Impulse Response IIR - -#pragma once -#include -#include - -/* #################################################################################################################### - */ -#ifndef M_PI -#define M_PI 3.14159265358979323846 /* pi */ -#endif - -//the original file was from cry's RC.exe with all the filters. We decided we would only use few of them for users -namespace ImageProcessing -{ - template - F cube(const F& op) { return op * op * op; } - - template - F square(F fOp) { return(fOp * fOp); } - - enum EWindowFunction - { - eWindowFunction_Combiner = 0, - - /*--------------- unit-area filters for unit-spaced samples ----------------*/ - eWindowFunction_Point = 1, - - eWindowFunction_Box = 2, // box, pulse, Fourier window, 1st order (constant) b-spline - eWindowFunction_Triangle = 3, // triangle, Bartlett window, 2nd order (linear) b-spline - eWindowFunction_Linear = eWindowFunction_Triangle, - eWindowFunction_Bartlett = eWindowFunction_Triangle, - - eWindowFunction_Quadric = 4, // 3rd order (quadratic) b-spline - eWindowFunction_Bilinear = eWindowFunction_Quadric, - eWindowFunction_Welch = eWindowFunction_Quadric, - eWindowFunction_Cubic = 5, // 4th order (cubic) b-spline - eWindowFunction_Hermite = 6, // 4th order (cubic hermite) b-spline - eWindowFunction_Catrom = 7, // Catmull-Rom spline, Overhauser spline - - eWindowFunction_Sine = 8, // IIR - eWindowFunction_Sinc = 9, // Sinc, perfect lowpass filter (infinite) - eWindowFunction_Bessel = 10, // Bessel (for circularly symm. 2-d filt, inf) - eWindowFunction_Lanczos = 11, // Lanczos filtering, windowed Sinc - - /*------------------ filters for non-unit spaced samples -------------------*/ - eWindowFunction_Gaussian = 12, // Gaussian (infinite) - eWindowFunction_Normal = 13, // Normal distribution (infinite) - - /*------------------------- parameterized filters --------------------------*/ - eWindowFunction_Mitchell = 14, // Mitchell & Netravali's two-param cubic - - /*--------------------------- window functions -----------------------------*/ - eWindowFunction_Hann = 15, // Hanning window - eWindowFunction_BartlettHann = 16, - eWindowFunction_Hamming = 17, // Hamming window - eWindowFunction_Blackman = 18, // Blackman window - eWindowFunction_BlackmanHarris = 19, - eWindowFunction_BlackmanNuttall = 20, - eWindowFunction_Flattop = 21, - - /*------------------------- parameterized windows --------------------------*/ - eWindowFunction_Kaiser = 22, // parameterized Kaiser window - - /*---------------------------- custom windows ------------------------------*/ - eWindowFunction_SigmaSix = 23, // two Normal distributions - eWindowFunction_KaiserSinc = 24, // Kaiser and Sinc - - eWindowFunction_Num = eWindowFunction_KaiserSinc + 1, - }; - - enum EWindowEvaluation - { - eWindowEvaluation_Sum, - eWindowEvaluation_Max, - eWindowEvaluation_Min, - }; - - /* #################################################################################################################### - */ - template - class IWindowFunction - { - public: - virtual ~IWindowFunction() {} - - virtual const char* getName() const = 0; - virtual T getLength() const = 0; - - virtual bool isCardinal() const = 0; - virtual bool isInfinite() const = 0; - virtual bool isUnitSpaced() const = 0; - virtual bool isCentered() const = 0; - - public: - virtual T operator () (T pos) const = 0; - }; - - /* #################################################################################################################### - * box, pulse, Fourier window, - * box function also know as rectangle function - * 1st order (constant) b-spline - */ - template - class BoxWindowFunction - : public IWindowFunction - { - public: - virtual const char* getName() const - { - return "Box-window"; - } - virtual T getLength() const - { - return 0.5; - } - - virtual bool isCardinal() const - { - return true; - } - virtual bool isInfinite() const - { - return false; - } - virtual bool isUnitSpaced() const - { - return true; - } - virtual bool isCentered() const - { - return true; - } - - public: - virtual T operator () (T pos) const - { - if (pos < 0.0) - { - pos = -pos; - } - if (pos <= 0.5) - { - return 1.0; - } - return 0.0; - } - }; - - /* -------------------------------------------------------------------------------------------------------------------- - * triangle, Bartlett window, - * triangle function also known as lambda function - * 2nd order (linear) b-spline - */ - template - class TriangleWindowFunction - : public IWindowFunction - { - public: - virtual const char* getName() const - { - return "Triangle-window"; - } - virtual T getLength() const - { - return 1.0; - } - - virtual bool isCardinal() const - { - return true; - } - virtual bool isInfinite() const - { - return false; - } - virtual bool isUnitSpaced() const - { - return true; - } - virtual bool isCentered() const - { - return true; - } - - public: - virtual T operator () (T pos) const - { - if (pos < 0.0) - { - pos = -pos; - } - if (pos < 1.0) - { - return 1.0 - pos; - } - return 0.0; - } - }; - - /* #################################################################################################################### - * 3rd order (quadratic) b-spline - */ - template - class QuadricWindowFunction - : public IWindowFunction - { - public: - virtual const char* getName() const - { - return "Quadric-window"; - } - virtual T getLength() const - { - return 1.5; - } - - virtual bool isCardinal() const - { - return false; - } - virtual bool isInfinite() const - { - return false; - } - virtual bool isUnitSpaced() const - { - return true; - } - virtual bool isCentered() const - { - return true; - } - - public: - virtual T operator () (T pos) const - { - if (pos < 0.0) - { - pos = -pos; - } - if (pos < 0.5) - { - return 0.75 - square(pos); - } - if (pos < 1.5) - { - return 0.50 * square(pos - 1.5); - } - return 0.0; - } - }; - - /* -------------------------------------------------------------------------------------------------------------------- - * 4th order (cubic) b-spline - */ - template - class CubicWindowFunction - : public IWindowFunction - { - public: - virtual const char* getName() const - { - return "Cubic-window"; - } - virtual T getLength() const - { - return 2.0; - } - - virtual bool isCardinal() const - { - return false; - } - virtual bool isInfinite() const - { - return false; - } - virtual bool isUnitSpaced() const - { - return true; - } - virtual bool isCentered() const - { - return true; - } - - public: - virtual T operator () (T pos) const - { - if (pos < 0.0) - { - pos = -pos; - } - if (pos < 1.0) - { - return 0.5 * cube(pos) - square(pos) + 2.0 / 3.0; - } - if (pos < 2.0) - { - return cube(2.0 - pos) / 6.0; - } - return 0.0; - } - }; - - /* -------------------------------------------------------------------------------------------------------------------- - * Hermite filter - * f(x) = 2|x|^3 - 3|x|^2 + 1, -1 <= x <= 1 - */ - template - class HermiteWindowFunction - : public IWindowFunction - { - public: - virtual const char* getName() const - { - return "Hermite-window"; - } - virtual T getLength() const - { - return 1.0; - } - - virtual bool isCardinal() const - { - return false; - } - virtual bool isInfinite() const - { - return false; - } - virtual bool isUnitSpaced() const - { - return true; - } - virtual bool isCentered() const - { - return true; - } - - public: - virtual T operator () (T pos) const - { - if (pos < 0.0) - { - pos = -pos; - } - if (pos < 1.0) - { - return 2.0 * cube(pos) - 3.0 * square(pos) + 1.0; - } - return 0.0; - } - }; - - /* -------------------------------------------------------------------------------------------------------------------- - * Catmull-Rom spline, Overhauser spline - */ - template - class CatromWindowFunction - : public IWindowFunction - { - public: - CatromWindowFunction() { } - - public: - virtual const char* getName() const - { - return "Catrom-window"; - } - virtual T getLength() const - { - return 2.0; - } - - virtual bool isCardinal() const - { - return true; - } - virtual bool isInfinite() const - { - return false; - } - virtual bool isUnitSpaced() const - { - return false; - } - virtual bool isCentered() const - { - return true; - } - - public: - virtual T operator () (T pos) const - { - if (pos < 0.0) - { - pos = -pos; - } - if (pos < 1.0) - { - return 1.5 * cube(pos) - 2.5 * square(pos) + 1.0; - } - if (pos < 2.0) - { - return -0.5 * cube(pos) + 2.5 * square(pos) - 4.0 * pos + 2.0; - } - return 0.0; - } - }; - - /* #################################################################################################################### - */ - template - class SineWindowFunction - : public IWindowFunction - { - public: - virtual const char* getName() const - { - return "Sine-window"; - } - virtual T getLength() const - { - return 0.0; - } - - virtual bool isCardinal() const - { - return true; - } - virtual bool isInfinite() const - { - return true; - } - virtual bool isUnitSpaced() const - { - return true; - } - virtual bool isCentered() const - { - return true; - } - - public: - virtual T operator () (T pos) const - { - return sin(pos); - } - }; - - /* -------------------------------------------------------------------------------------------------------------------- - * sinc, perfect lowpass filter (infinite) - * - * Note: Some people say sinc(x) is sin(x)/x. Others say it's - * sin(PI*x)/(PI*x), a horizontal compression of the former which is - * zero at integer values. We use the latter, whose Fourier transform - * is a canonical rectangle function (edges at -1/2, +1/2, height 1). - */ - template - class SincWindowFunction - : public IWindowFunction - { - public: - virtual const char* getName() const - { - return "Sinc-window"; - } - virtual T getLength() const - { - return 4.0; - } - - virtual bool isCardinal() const - { - return true; - } - virtual bool isInfinite() const - { - return true; - } - virtual bool isUnitSpaced() const - { - return false; - } - virtual bool isCentered() const - { - return true; - } - - public: - virtual T operator () (T pos) const - { - if (pos == 0.0) - { - return 1.0; - } - - return sin(M_PI * pos) / (M_PI * pos); - } - }; - - /* -------------------------------------------------------------------------------------------------------------------- - * Bessel (for circularly symm. 2-d filt, infinite) - * See Pratt "Digital Image Processing" p. 97 for Bessel functions - */ - template - class BesselWindowFunction - : public IWindowFunction - { - public: - virtual const char* getName() const - { - return "Bessel-window"; - } - virtual T getLength() const - { - return 3.2383; - } - - virtual bool isCardinal() const - { - return false; - } - virtual bool isInfinite() const - { - return true; - } - virtual bool isUnitSpaced() const - { - return false; - } - virtual bool isCentered() const - { - return true; - } - - public: - virtual T operator () (T pos) const - { - if (pos == 0.0) - { - return M_PI / 4.0; - } - return AZ_TRAIT_IMAGEPROCESSING_BESSEL_FUNCTION_FIRST_ORDER(M_PI * pos) / (2.0 * pos); - } - }; - - /* -------------------------------------------------------------------------------------------------------------------- - * Lanczos filter - */ - template - class LanczosWindowFunction - : public SincWindowFunction - { - public: - LanczosWindowFunction(T tap = 3.0) - { - this->tap = AZ::GetMax(3.0, tap); - } - - protected: - T tap; - - public: - virtual const char* getName() const - { - return "Lanczos-window"; - } - virtual T getLength() const - { - return tap; - } - - virtual bool isCardinal() const - { - return false; - } - virtual bool isInfinite() const - { - return false; - } - virtual bool isUnitSpaced() const - { - return false; - } - virtual bool isCentered() const - { - return true; - } - - public: - virtual T operator () (T pos) const - { - if (pos < 0.0) - { - pos = -pos; - } - if (pos < tap) - { - return ((SincWindowFunction) * this)(pos) * ((SincWindowFunction) * this)(pos / tap); - } - return 0.0; - } - }; - - /* -------------------------------------------------------------------------------------------------------------------- - * Gaussian filter (infinite) - */ - template - class GaussianWindowFunction - : public IWindowFunction - { - public: - virtual const char* getName() const - { - return "Gaussian-window"; - } - virtual T getLength() const - { - return 1.25; - } - - virtual bool isCardinal() const - { - return false; - } - virtual bool isInfinite() const - { - return true; - } - virtual bool isUnitSpaced() const - { - return true; - } - virtual bool isCentered() const - { - return true; - } - - public: - virtual T operator () (T pos) const - { - return exp(-2.0 * square(pos)) * sqrt(2.0 / M_PI); - } - }; - - /* -------------------------------------------------------------------------------------------------------------------- - * normal distribution (infinite) - * Normal(x) = Gaussian(x/2)/2 - */ - template - class NormalWindowFunction - : public IWindowFunction - { - public: - virtual const char* getName() const - { - return "Normal-window"; - } - virtual T getLength() const - { - return 2.5; - } - - virtual bool isCardinal() const - { - return false; - } - virtual bool isInfinite() const - { - return true; - } - virtual bool isUnitSpaced() const - { - return false; - } - virtual bool isCentered() const - { - return true; - } - - public: - virtual T operator () (T pos) const - { - return exp(-square(pos) / 2.0) / sqrt(2.0 * M_PI); - } - }; - - /* -------------------------------------------------------------------------------------------------------------------- - */ - template - class SigmaSixWindowFunction - : public IWindowFunction - { - public: - SigmaSixWindowFunction(T diameter = 1.0, T negative = 0.0) - { - // we aim for 6 * sigma = 99,99996% of all values - const T sigma = 1.0 / 3.0; - - s2 = sigma * sigma * 2.0; - d2 = s2 / (diameter * diameter); - d = diameter; - n = negative; - } - - protected: - T s2, d2, d, n; - - public: - virtual const char* getName() const - { - return "SigmaSix-window"; - } - virtual T getLength() const - { - return 1.44; - } - - virtual bool isCardinal() const - { - return false; - } - virtual bool isInfinite() const - { - return true; - } - virtual bool isUnitSpaced() const - { - return false; - } - virtual bool isCentered() const - { - return true; - } - - public: - virtual T operator () (T pos) const - { - if (pos < 0.0) - { - pos = -pos; - } - T o = exp(-square(pos) / s2) - (1.0 - 0.9999996); - T i = exp(-square(pos) / d2) - (1.0 - 0.9999996); - return (pos >= d ? 0.0 : i) - o * n; - } - }; - - /* -------------------------------------------------------------------------------------------------------------------- - * Mitchell & Netravali's two-param cubic - * see Mitchell & Netravali, - * "Reconstruction Filters in Computer Graphics", SIGGRAPH 88 - */ - template - class MitchellWindowFunction - : public IWindowFunction - { - public: - MitchellWindowFunction(T b = 1.0 / 3.0, T c = 1.0 / 3.0) - { - p0 = (6. - 2. * b) / 6.; - p2 = (-18. + 12. * b + 6. * c) / 6.; - p3 = (12. - 9. * b - 6. * c) / 6.; - q0 = (8. * b + 24. * c) / 6.; - q1 = (-12. * b - 48. * c) / 6.; - q2 = (6. * b + 30. * c) / 6.; - q3 = (-b - 6. * c) / 6.; - } - - protected: - T p0, p2, p3, q0, q1, q2, q3; - - public: - virtual const char* getName() const - { - return "Mitchell-window"; - } - virtual T getLength() const - { - return 2.0; - } - - virtual bool isCardinal() const - { - return false; - } - virtual bool isInfinite() const - { - return false; - } - virtual bool isUnitSpaced() const - { - return false; - } - virtual bool isCentered() const - { - return true; - } - - public: - virtual T operator () (T pos) const - { - if (pos < 0.0) - { - pos = -pos; - } - if (pos < 1.0) - { - return p3 * cube(pos) + p2 * square(pos) + p0; - } - if (pos < 2.0) - { - return q3 * cube(pos) + q2 * square(pos) + q1 * pos + q0; - } - return 0.0; - } - }; - - /* #################################################################################################################### - * Hanning window (infinite) - */ - template - class HannWindowFunction - : public IWindowFunction - { - public: - virtual const char* getName() const - { - return "Hann-window"; - } - virtual T getLength() const - { - return 1.0; - } - - virtual bool isCardinal() const - { - return true; - } - virtual bool isInfinite() const - { - return true; - } - virtual bool isUnitSpaced() const - { - return true; - } - virtual bool isCentered() const - { - return true; - } - - public: - virtual T operator () (T pos) const - { - return 0.5 + 0.5 * cos(M_PI * pos); - } - }; - - /* -------------------------------------------------------------------------------------------------------------------- - * BartlettHanning window (infinite) - */ - template - class BartlettHannWindowFunction - : public IWindowFunction - { - public: - virtual const char* getName() const - { - return "Bartlett-Hann-window"; - } - virtual T getLength() const - { - return 1.0; - } - - virtual bool isCardinal() const - { - return true; - } - virtual bool isInfinite() const - { - return true; - } - virtual bool isUnitSpaced() const - { - return true; - } - virtual bool isCentered() const - { - return true; - } - - public: - virtual T operator () (T pos) const - { - return 0.62 + 0.48 * (1.0 - pos) + 0.38 * cos(M_PI * pos); - } - }; - - /* -------------------------------------------------------------------------------------------------------------------- - * Hamming window (infinite) - */ - template - class HammingWindowFunction - : public IWindowFunction - { - public: - virtual const char* getName() const - { - return "Hamming-window"; - } - virtual T getLength() const - { - return 1.0; - } - - virtual bool isCardinal() const - { - return true; - } - virtual bool isInfinite() const - { - return true; - } - virtual bool isUnitSpaced() const - { - return true; - } - virtual bool isCentered() const - { - return true; - } - - public: - virtual T operator () (T pos) const - { - return 0.53836 + 0.46164 * cos(M_PI * pos); - } - }; - - /* -------------------------------------------------------------------------------------------------------------------- - * Blackman window (infinite) - */ - template - class BlackmanWindowFunction - : public IWindowFunction - { - public: - virtual const char* getName() const - { - return "Blackman-window"; - } - virtual T getLength() const - { - return 1.0; - } - - virtual bool isCardinal() const - { - return true; - } - virtual bool isInfinite() const - { - return true; - } - virtual bool isUnitSpaced() const - { - return true; - } - virtual bool isCentered() const - { - return true; - } - - public: - virtual T operator () (T pos) const - { - return 0.42659 - + 0.49656 * cos(M_PI * pos) - + 0.07685 * cos(2.0 * M_PI * pos); - } - }; - - /* -------------------------------------------------------------------------------------------------------------------- - * BlackmanHarris window (infinite) - */ - template - class BlackmanHarrisWindowFunction - : public IWindowFunction - { - public: - virtual const char* getName() const - { - return "Blackman-Harris-window"; - } - virtual T getLength() const - { - return 1.0; - } - - virtual bool isCardinal() const - { - return true; - } - virtual bool isInfinite() const - { - return true; - } - virtual bool isUnitSpaced() const - { - return true; - } - virtual bool isCentered() const - { - return true; - } - - public: - virtual T operator () (T pos) const - { - return 0.35875 - + 0.48829 * cos(M_PI * pos) - + 0.14128 * cos(2.0 * M_PI * pos) - + 0.01168 * cos(3.0 * M_PI * pos); - } - }; - - /* -------------------------------------------------------------------------------------------------------------------- - * BlackmanNuttall window (infinite) - */ - template - class BlackmanNuttallWindowFunction - : public IWindowFunction - { - public: - virtual const char* getName() const - { - return "Blackman-Nuttall-window"; - } - virtual T getLength() const - { - return 1.0; - } - - virtual bool isCardinal() const - { - return true; - } - virtual bool isInfinite() const - { - return true; - } - virtual bool isUnitSpaced() const - { - return true; - } - virtual bool isCentered() const - { - return true; - } - - public: - virtual T operator () (T pos) const - { - return 0.3635819 - + 0.4891775 * cos(M_PI * pos) - + 0.1365995 * cos(2.0 * M_PI * pos) - + 0.0106411 * cos(3.0 * M_PI * pos); - } - }; - - /* -------------------------------------------------------------------------------------------------------------------- - * FlatTop window (infinite) - */ - template - class FlatTopWindowFunction - : public IWindowFunction - { - public: - virtual const char* getName() const - { - return "Flat-Top-window"; - } - virtual T getLength() const - { - return 1.0; - } - - virtual bool isCardinal() const - { - return true; - } - virtual bool isInfinite() const - { - return true; - } - virtual bool isUnitSpaced() const - { - return true; - } - virtual bool isCentered() const - { - return true; - } - - public: - virtual T operator () (T pos) const - { - return 0.215578948 - + 0.416631580 * cos(M_PI * pos) - + 0.277263158 * cos(2.0 * M_PI * pos) - + 0.083578947 * cos(3.0 * M_PI * pos) - + 0.006947368 * cos(4.0 * M_PI * pos); - } - }; - - /* -------------------------------------------------------------------------------------------------------------------- - * parameterized Kaiser window (infinite) - * from Oppenheim & Schafer, Hamming - */ - template - class KaiserWindowFunction - : public IWindowFunction - { - public: - KaiserWindowFunction(T a = 6.5) - { - /* typically 4a = a; - this->i0a = 1. / bessel_i0(a); - } - - protected: - T a, i0a; - - /* modified zeroth order Bessel function of the first kind. */ - static T bessel_i0(T x) - { - #define EPSILON 1e-7 - const T y = square(x) / 4.0; - - T sum = 1.0; - T t = y; - - for (int i = 2; t > EPSILON; i++) - { - sum += t; - t *= y / square(i); - } - - return sum; - - #undef EPSILON - } - - public: - virtual const char* getName() const - { - return "Kaiser-window"; - } - virtual T getLength() const - { - return 1.0; - } - - virtual bool isCardinal() const - { - return true; - } - virtual bool isInfinite() const - { - return true; - } - virtual bool isUnitSpaced() const - { - return true; - } - virtual bool isCentered() const - { - return true; - } - - public: - virtual T operator () (T pos) const - { - return i0a * bessel_i0(a * sqrt(1.0 - square(pos))); - } - }; - - /* #################################################################################################################### - */ - template - class CombinerWindowFunction - : public IWindowFunction - { - public: - CombinerWindowFunction(IWindowFunction* fu, IWindowFunction* wi) - { - shaper = fu; - restrictor = wi; - } - - protected: - IWindowFunction* shaper; - IWindowFunction* restrictor; - - public: - virtual const char* getName() const - { - return "Combiner of two window-generators"; - } - virtual T getLength() const - { - return shaper->getLength(); - } - - virtual bool isCardinal() const - { - return shaper->isCardinal() && restrictor->isCardinal(); - } - virtual bool isInfinite() const - { - return shaper->isInfinite() && restrictor->isInfinite(); - } - virtual bool isUnitSpaced() const - { - return shaper->isUnitSpaced() && restrictor->isUnitSpaced(); - } - virtual bool isCentered() const - { - return shaper->isCentered() && restrictor->isCentered(); - } - - public: - virtual T operator () (T pos) const - { - return (*shaper)(pos) * (*restrictor)(pos / shaper->getLength()); - } - }; - - /* -------------------------------------------------------------------------------------------------------------------- - */ - template - class PointWindowFunction - : public BoxWindowFunction - { - public: - PointWindowFunction() - : BoxWindowFunction() { } - - public: - virtual const char* getName() const - { - return "Point-window"; - } - virtual T getLength() const - { - return 0.0; - } - }; -} //end namespace ImageProcessing - diff --git a/Gems/ImageProcessing/Code/Source/Converters/Gamma.cpp b/Gems/ImageProcessing/Code/Source/Converters/Gamma.cpp deleted file mode 100644 index c30385c608..0000000000 --- a/Gems/ImageProcessing/Code/Source/Converters/Gamma.cpp +++ /dev/null @@ -1,260 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or 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 ImageProcessing -{ - /////////////////////////////////////////////////////////////////////////////////// - // Lookup table for a function 'float fn(float x)'. - // Computed function values are stored in the table for x in [0.0; 1.0]. - // - // If passed x is less than xMin (xMin must be >= 0) or greater than 1.0, - // then the original function is called. - // Otherwise, a value from the table (linearly interpolated) - // is returned. - template - class FunctionLookupTable - { - public: - FunctionLookupTable(float(*fn)(float x), float xMin, float maxAllowedDifference) - : m_fn(fn) - , m_xMin(xMin) - , m_fMaxDiff(maxAllowedDifference) - { - } - - void Initialize() const - { - m_initialized = true; - AZ_Assert(m_xMin >= 0.0f, "wrong initial data for m_xMin"); - for (int i = 0; i <= TABLE_SIZE; ++i) - { - const float x = i / (float)TABLE_SIZE; - const float y = (*m_fn)(x); - m_table[i] = y; - } - } - - inline float compute(float x) const - { - if (x < m_xMin || x > 1) - { - return m_fn(x); - } - - const float f = x * TABLE_SIZE; - - const int i = int(f); - - if (!m_initialized) - { - Initialize(); - } - - if (i >= TABLE_SIZE) - { - return m_table[TABLE_SIZE]; - } - - const float alpha = f - i; - return (1 - alpha) * m_table[i] + alpha * m_table[i + 1]; - } - - public: - bool Test(const float maxDifferenceAllowed) const - { - if (int(-0.99f) != 0 || - int(+0.00f) != 0 || - int(+0.01f) != 0 || - int(+0.99f) != 0 || - int(+1.00f) != 1 || - int(+1.01f) != 1 || - int(+1.99f) != 1 || - int(+2.00f) != 2 || - int(+2.01f) != 2) - { - return false; - } - - if (m_xMin < 0) - { - return false; - } - - const int n = 1000000; - for (int i = 0; i <= n; ++i) - { - const float x = 1.1f * (i / (float)n); - const float resOriginal = m_fn(x); - const float resTable = compute(x); - const float difference = resOriginal - resTable; - - if (fabs(difference) > maxDifferenceAllowed) - { - return false; - } - } - return true; - } - - private: - float(*m_fn)(float x); - float m_xMin; - mutable float m_table[TABLE_SIZE + 1]; - mutable bool m_initialized = false; - float m_fMaxDiff = 0.0f; - }; - - - static float GammaToLinear(float x) - { - return (x <= 0.04045f) ? x / 12.92f : powf((x + 0.055f) / 1.055f, 2.4f); - } - - static float LinearToGamma(float x) - { - return (x <= 0.0031308f) ? x * 12.92f : 1.055f * powf(x, 1.0f / 2.4f) - 0.055f; - } - - static FunctionLookupTable<1024> s_lutGammaToLinear(GammaToLinear, 0.04045f, 0.00001f); - static FunctionLookupTable<1024> s_lutLinearToGamma(LinearToGamma, 0.05f, 0.00001f); - - /////////////////////////////////////////////////////////////////////////////////// - - /////////////////////////////////////////////////////////////////////////////////// - bool ImageToProcess::GammaToLinearRGBA32F(bool bDeGamma) - { - // return immediately if there is no need to de-gamma image and the source is in the desired format - EPixelFormat srcFmt = m_img->GetPixelFormat(); - if (!bDeGamma && (srcFmt == ePixelFormat_R32G32B32A32F)) - { - return true; - } - - //convert to 32F first - if (!CPixelFormats::GetInstance().IsPixelFormatUncompressed(srcFmt)) - { - AZ_Warning("Image Processing", false, "This is not common user case with compressed format input. But it may continue"); - ConvertFormat(ePixelFormat_R32G32B32A32F); - } - - IImageObjectPtr srcImage = m_img; - EPixelFormat dstFmt = ePixelFormat_R32G32B32A32F; - IImageObjectPtr dstImage(m_img->AllocateImage(dstFmt)); - - //create pixel operation function for src and dst images - IPixelOperationPtr srcOp = CreatePixelOperation(srcFmt); - IPixelOperationPtr dstOp = CreatePixelOperation(dstFmt); - - //get count of bytes per pixel for both src and dst images - uint32 srcPixelBytes = CPixelFormats::GetInstance().GetPixelFormatInfo(srcFmt)->bitsPerBlock / 8; - uint32 dstPixelBytes = CPixelFormats::GetInstance().GetPixelFormatInfo(dstFmt)->bitsPerBlock / 8; - - const uint32 dwMips = dstImage->GetMipCount(); - float r, g, b, a; - for (uint32 dwMip = 0; dwMip < dwMips; ++dwMip) - { - uint8* srcPixelBuf; - uint32 srcPitch; - srcImage->GetImagePointer(dwMip, srcPixelBuf, srcPitch); - uint8* dstPixelBuf; - uint32 dstPitch; - dstImage->GetImagePointer(dwMip, dstPixelBuf, dstPitch); - - const uint32 pixelCount = srcImage->GetPixelCount(dwMip); - - for (uint32 i = 0; i < pixelCount; ++i, srcPixelBuf += srcPixelBytes, dstPixelBuf += dstPixelBytes) - { - srcOp->GetRGBA(srcPixelBuf, r, g, b, a); - if (bDeGamma) - { - r = s_lutGammaToLinear.compute(r); - g = s_lutGammaToLinear.compute(g); - b = s_lutGammaToLinear.compute(b); - } - - dstOp->SetRGBA(dstPixelBuf, r, g, b, a); - } - } - - m_img = dstImage; - - if (bDeGamma) - { - m_img->RemoveImageFlags(EIF_SRGBRead); - } - return true; - } - - void ImageToProcess::LinearToGamma() - { - if (Get()->HasImageFlags(EIF_SRGBRead)) - { - AZ_Assert(false, "%s: input image is already SRGB", __FUNCTION__); - return; - } - - if (!CPixelFormats::GetInstance().IsPixelFormatUncompressed(m_img->GetPixelFormat())) - { - AZ_Assert(false, "This is not common user case with compressed format input. But it may continue"); - ConvertFormat(ePixelFormat_R32G32B32A32F); - } - - EPixelFormat srcFmt = m_img->GetPixelFormat(); - IImageObjectPtr srcImage = m_img; - - IImageObjectPtr dstImage(m_img->AllocateImage(srcFmt)); - - //create pixel operation function - IPixelOperationPtr pixelOp = CreatePixelOperation(srcFmt); - - //get count of bytes per pixel for both src and dst images - uint32 pixelBytes = CPixelFormats::GetInstance().GetPixelFormatInfo(srcFmt)->bitsPerBlock / 8; - - const uint32 dwMips = srcImage->GetMipCount(); - float r, g, b, a; - for (uint32 dwMip = 0; dwMip < dwMips; ++dwMip) - { - uint8* srcPixelBuf; - uint32 srcPitch; - srcImage->GetImagePointer(dwMip, srcPixelBuf, srcPitch); - uint8* dstPixelBuf; - uint32 dstPitch; - dstImage->GetImagePointer(dwMip, dstPixelBuf, dstPitch); - - const uint32 pixelCount = srcImage->GetPixelCount(dwMip); - - for (uint32 i = 0; i < pixelCount; ++i, srcPixelBuf += pixelBytes, dstPixelBuf += pixelBytes) - { - pixelOp->GetRGBA(srcPixelBuf, r, g, b, a); - r = s_lutLinearToGamma.compute(r); - g = s_lutLinearToGamma.compute(g); - b = s_lutLinearToGamma.compute(b); - pixelOp->SetRGBA(dstPixelBuf, r, g, b, a); - } - } - - m_img = dstImage; - Get()->AddImageFlags(EIF_SRGBRead); - } - -} // namespace ImageProcessing diff --git a/Gems/ImageProcessing/Code/Source/Converters/HighPass.cpp b/Gems/ImageProcessing/Code/Source/Converters/HighPass.cpp deleted file mode 100644 index 7660d02016..0000000000 --- a/Gems/ImageProcessing/Code/Source/Converters/HighPass.cpp +++ /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. -* -*/ - -#include - -#include -#include -#include -#include -#include -#include - -namespace ImageProcessing -{ - - // higher mip level is subtracted by lower mip level when applying the [cheap] high pass filter - void ImageToProcess::CreateHighPass(AZ::u32 dwMipDown) - { - //no need to convert if mip go down 0 - if (dwMipDown == 0) - { - return; - } - - const EPixelFormat ePixelFormat = m_img->GetPixelFormat(); - - if (ePixelFormat != ePixelFormat_R32G32B32A32F) - { - AZ_Assert(false, "You need convert the orginal image to ePixelFormat_R32G32B32A32F before call this function"); - return; - } - - - AZ::u32 dwWidth, dwHeight, dwMips; - dwWidth = m_img->GetWidth(0); - dwHeight = m_img->GetHeight(0); - dwMips = m_img->GetMipCount(); - - if (dwMipDown >= dwMips) - { - AZ_Warning("Image Processing", false, "CreateHighPass can't go down %i MIP levels for high pass as there are not\ - enough MIP levels available, going down by %i instead", dwMipDown, dwMips - 1); - dwMipDown = dwMips - 1; - } - - IImageObjectPtr newImage(IImageObject::CreateImage(dwWidth, dwHeight, dwMips, ePixelFormat)); - newImage->CopyPropertiesFrom(m_img); - - IPixelOperationPtr pixelOp = CreatePixelOperation(ePixelFormat); - AZ::u32 pixelBytes = CPixelFormats::GetInstance().GetPixelFormatInfo(ePixelFormat)->bitsPerBlock / 8; - - AZ::u32 dstMips = newImage->GetMipCount(); - for (AZ::u32 dstMip = 0; dstMip < dwMipDown; ++dstMip) - { - // linear interpolation - FilterImage(MipGenType::triangle, MipGenEvalType::sum, 0.0f, 0.0f, m_img, dwMipDown, newImage, dstMip, NULL, NULL); - - const AZ::u32 pixelCountIn = m_img->GetWidth(dstMip) *m_img->GetHeight(dstMip); - const AZ::u32 pixelCountOut = newImage->GetWidth(dstMip) * newImage->GetHeight(dstMip); - - //substraction - AZ::u8* srcPixelBuf; - AZ::u32 srcPitch; - m_img->GetImagePointer(dstMip, srcPixelBuf, srcPitch); - AZ::u8* dstPixelBuf; - AZ::u32 dstPitch; - newImage->GetImagePointer(dstMip, dstPixelBuf, dstPitch); - const AZ::u32 pixelCount = newImage->GetPixelCount(dstMip); - - for (AZ::u32 i = 0; i < pixelCount; ++i, srcPixelBuf += pixelBytes, dstPixelBuf += pixelBytes) - { - float r1, g1, b1, a1, r2, g2, b2, a2; - pixelOp->GetRGBA(srcPixelBuf, r1, g1, b1, a1); - pixelOp->GetRGBA(dstPixelBuf, r2, g2, b2, a2); - - r2 = AZ::GetClamp(r1 - r2 + 0.5f, 0.0f, 1.0f); - g2 = AZ::GetClamp(g1 - g2 + 0.5f, 0.0f, 1.0f); - b2 = AZ::GetClamp(b1 - b2 + 0.5f, 0.0f, 1.0f); - a2 = AZ::GetClamp(a1 - a2 + 0.5f, 0.0f, 1.0f); - pixelOp->SetRGBA(dstPixelBuf, r2, g2, b2, a2); - } - } - - // mips below the chosen highpass mip are grey - for (AZ::u32 dstMip = dwMipDown; dstMip < dstMips; ++dstMip) - { - AZ::u8* dstPixelBuf; - AZ::u32 dstPitch; - newImage->GetImagePointer(dstMip, dstPixelBuf, dstPitch); - const AZ::u32 pixelCount = newImage->GetPixelCount(dstMip); - - for (AZ::u32 i = 0; i < pixelCount; ++i, dstPixelBuf += pixelBytes) - { - pixelOp->SetRGBA(dstPixelBuf, 0.5f, 0.5f, 0.5f, 1.0f); - } - } - - m_img = newImage; - } - -} // namespace ImageProcessing diff --git a/Gems/ImageProcessing/Code/Source/Converters/Histogram.cpp b/Gems/ImageProcessing/Code/Source/Converters/Histogram.cpp deleted file mode 100644 index 23cd836891..0000000000 --- a/Gems/ImageProcessing/Code/Source/Converters/Histogram.cpp +++ /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. -* -*/ - -#include - -#include -#include -#include -#include - -#include - -/////////////////////////////////////////////////////////////////////////////////// - -namespace ImageProcessing -{ - float GetLuminance(const float& r, const float& g, const float& b) - { - return (r * 0.30f + g * 0.59f + b * 0.11f); - } - - bool ComputeLuminanceHistogram(IImageObjectPtr imageObject, Histogram<256>& histogram) - { - EPixelFormat pixelFormat = imageObject->GetPixelFormat(); - if (!(CPixelFormats::GetInstance().IsPixelFormatUncompressed(pixelFormat))) - { - AZ_Assert(false, "%s function only works with uncompressed pixel format", __FUNCTION__); - return false; - } - - //create pixel operation function - IPixelOperationPtr pixelOp = CreatePixelOperation(pixelFormat); - - //setup histogram bin - static const size_t binCount = 256; - Histogram::Bins bins; - Histogram::clearBins(bins); - - //get count of bytes per pixel - AZ::u32 pixelBytes = CPixelFormats::GetInstance().GetPixelFormatInfo(pixelFormat)->bitsPerBlock / 8; - - const AZ::u32 mipCount = imageObject->GetMipCount(); - float color[4]; - for (uint32 mip = 0; mip < mipCount; ++mip) - { - AZ::u8* pixelBuf; - AZ::u32 pitch; - imageObject->GetImagePointer(mip, pixelBuf, pitch); - const uint32 pixelCount = imageObject->GetPixelCount(mip); - - for (uint32 i = 0; i < pixelCount; ++i, pixelBuf += pixelBytes) - { - pixelOp->GetRGBA(pixelBuf, color[0], color[1], color[2], color[3]); - - const float luminance = AZ::GetClamp(GetLuminance(color[0], color[1], color[2]), 0.0f, 1.0f); - const float f = luminance * binCount; - if (f <= 0) - { - ++bins[0]; - } - else - { - const int bin = int(f); - ++bins[(bin < binCount) ? bin : binCount - 1]; - } - } - } - - histogram.set(bins); - return true; - } -} // end namespace ImageProcessing diff --git a/Gems/ImageProcessing/Code/Source/Converters/Histogram.h b/Gems/ImageProcessing/Code/Source/Converters/Histogram.h deleted file mode 100644 index 4f73f23a74..0000000000 --- a/Gems/ImageProcessing/Code/Source/Converters/Histogram.h +++ /dev/null @@ -1,84 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#pragma once - -namespace ImageProcessing -{ - template - class Histogram - { - public: - typedef AZ::u64 Bins[BIN_COUNT]; - - public: - Histogram() - { - } - - static void clearBins(Bins& bins) - { - memset(&bins, 0, sizeof(bins)); - } - - void set(const Bins& bins) - { - m_bins[0] = bins[0]; - m_binsCumulative[0] = bins[0]; - double sum = 0.0f; - for (size_t i = 1; i < BIN_COUNT; ++i) - { - m_bins[i] = bins[i]; - m_binsCumulative[i] = m_binsCumulative[i - 1] + bins[i]; - sum += i * double(bins[i]); - } - - const AZ::u64 totalCount = getTotalSampleCount(); - m_meanBin = (totalCount <= 0) ? 0.0f : float(sum / totalCount); - } - - AZ::u64 getTotalSampleCount() const - { - return m_binsCumulative[BIN_COUNT - 1]; - } - - float getPercentage(size_t minBin, size_t maxBin) const - { - const AZ::u64 totalCount = getTotalSampleCount(); - - if ((totalCount <= 0) || (minBin > maxBin) || (maxBin < 0) || (minBin >= BIN_COUNT)) - { - return 0.0f; - } - - minBin = AZ::GetMax(minBin, size_t(0)); - maxBin = AZ::GetMin(maxBin, BIN_COUNT-1); - - const AZ::u64 count = m_binsCumulative[maxBin] - ((minBin <= 0) ? 0 : m_binsCumulative[minBin-1]); - - return float((double(count) * 100.0) / double(totalCount)); - } - - float getMeanBin() const - { - return m_meanBin; - } - - private: - Bins m_bins; - Bins m_binsCumulative; - float m_meanBin; - }; - - bool ComputeLuminanceHistogram(IImageObjectPtr imageObject, Histogram<256>& histogram); -} diff --git a/Gems/ImageProcessing/Code/Source/Converters/Normalize.cpp b/Gems/ImageProcessing/Code/Source/Converters/Normalize.cpp deleted file mode 100644 index bb41991385..0000000000 --- a/Gems/ImageProcessing/Code/Source/Converters/Normalize.cpp +++ /dev/null @@ -1,420 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS 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 - -namespace ImageProcessing -{ - template - static void AdjustScaleForQuantization(float fBaseValue, float fBaseLine, float& cScale, float& cMinColor, float& cMaxColor) - { - const int qOne = (1 << qBits) - 1; - const int qUpperBits = (8 - qBits); - const int qLowerBits = qBits - qUpperBits; - - const int v = int(floor(fBaseValue * qOne)); - - int v0 = v - (v != 0); - int v1 = v + 0; - int v2 = v + (v != qOne); - - v0 = (v0 << qUpperBits) | (v0 >> qLowerBits); - v1 = (v1 << qUpperBits) | (v1 >> qLowerBits); - v2 = (v2 << qUpperBits) | (v2 >> qLowerBits); - - const float f0 = v0 / 255.0f; - const float f1 = v1 / 255.0f; - const float f2 = v2 / 255.0f; - - float fBaseLock = -1; - - if (fabsf(f0 - fBaseValue) < fabsf(fBaseLock - fBaseValue)) - { - fBaseLock = f0; - } - if (fabsf(f1 - fBaseValue) < fabsf(fBaseLock - fBaseValue)) - { - fBaseLock = f1; - } - if (fabsf(f2 - fBaseValue) < fabsf(fBaseLock - fBaseValue)) - { - fBaseLock = f2; - } - - float lScale = (1.0f - fBaseLock) / (1.0f - fBaseLine); - float vScale = (1.0f - fBaseValue) / (1.0f - fBaseLine); - float sScale = lScale / vScale; - - float csScale = (cScale / sScale); - float csBias = cMinColor - (1.0f - sScale) * (cScale / sScale); - - if ((csBias > 0.0f) && ((csScale + csBias) < 1.0f)) - { - cMinColor = csBias; - cScale = csScale; - cMaxColor = csScale + csBias; - } - } - - /////////////////////////////////////////////////////////////////////////////////// - - void CImageObject::NormalizeImageRange(EColorNormalization eColorNorm, EAlphaNormalization eAlphaNorm, bool bMaintainBlack, int nExponentBits) - { - if (GetPixelFormat() != ePixelFormat_R32G32B32A32F) - { - AZ_Assert(false, "%s: unsupported source format", __FUNCTION__); - return; - } - - uint32 dwWidth, dwHeight, dwMips; - GetExtent(dwWidth, dwHeight, dwMips); - - // find image's range, can be negative - float cMinColor[4] = { FLT_MAX, FLT_MAX, FLT_MAX, FLT_MAX }; - float cMaxColor[4] = { -FLT_MAX, -FLT_MAX, -FLT_MAX, -FLT_MAX }; - - for (uint32 dwMip = 0; dwMip < dwMips; ++dwMip) - { - uint8* pSrcMem; - uint32 dwSrcPitch; - GetImagePointer(dwMip, pSrcMem, dwSrcPitch); - - dwHeight = GetHeight(dwMip); - dwWidth = GetWidth(dwMip); - for (uint32 dwY = 0; dwY < dwHeight; ++dwY) - { - const float* pSrcPix = (float*)&pSrcMem[dwY * dwSrcPitch]; - for (uint32 dwX = 0; dwX < dwWidth; ++dwX) - { - cMinColor[0] = AZ::GetMin(cMinColor[0], pSrcPix[0]); - cMinColor[1] = AZ::GetMin(cMinColor[1], pSrcPix[1]); - cMinColor[2] = AZ::GetMin(cMinColor[2], pSrcPix[2]); - cMinColor[3] = AZ::GetMin(cMinColor[3], pSrcPix[3]); - - cMaxColor[0] = AZ::GetMax(cMaxColor[0], pSrcPix[0]); - cMaxColor[1] = AZ::GetMax(cMaxColor[1], pSrcPix[1]); - cMaxColor[2] = AZ::GetMax(cMaxColor[2], pSrcPix[2]); - cMaxColor[3] = AZ::GetMax(cMaxColor[3], pSrcPix[3]); - - pSrcPix += 4; - } - } - } - - if (bMaintainBlack) - { - cMinColor[0] = AZ::GetMin(0.f, cMinColor[0]); - cMinColor[1] = AZ::GetMin(0.f, cMinColor[1]); - cMinColor[2] = AZ::GetMin(0.f, cMinColor[2]); - cMinColor[3] = AZ::GetMin(0.f, cMinColor[3]); - } - - AZ_Assert(cMaxColor[0] >= cMinColor[0] && cMaxColor[1] >= cMinColor[1] && - cMaxColor[2] >= cMinColor[2] && cMaxColor[3] >= cMinColor[3], "bad color range"); - - // some graceful threshold to avoid extreme cases - if (cMaxColor[0] - cMinColor[0] < (3.f / 255)) - { - cMinColor[0] = AZ::GetMax(0.f, cMinColor[0] - (2.f / 255)); - cMaxColor[0] = AZ::GetMin(1.f, cMaxColor[0] + (2.f / 255)); - } - if (cMaxColor[1] - cMinColor[1] < (3.f / 255)) - { - cMinColor[1] = AZ::GetMax(0.f, cMinColor[1] - (2.f / 255)); - cMaxColor[1] = AZ::GetMin(1.f, cMaxColor[1] + (2.f / 255)); - } - if (cMaxColor[2] - cMinColor[2] < (3.f / 255)) - { - cMinColor[2] = AZ::GetMax(0.f, cMinColor[2] - (2.f / 255)); - cMaxColor[2] = AZ::GetMin(1.f, cMaxColor[2] + (2.f / 255)); - } - if (cMaxColor[3] - cMinColor[3] < (3.f / 255)) - { - cMinColor[3] = AZ::GetMax(0.f, cMinColor[3] - (2.f / 255)); - cMaxColor[3] = AZ::GetMin(1.f, cMaxColor[3] + (2.f / 255)); - } - - // calculate range to normalize to - const float fMaxExponent = powf(2.0f, (float)nExponentBits) - 1.0f; - const float cUprValue = powf(2.0f, fMaxExponent); - - if (eColorNorm == eColorNormalization_PassThrough) - { - cMinColor[0] = cMinColor[1] = cMinColor[2] = 0.f; - cMaxColor[0] = cMaxColor[1] = cMaxColor[2] = 1.f; - } - - // don't touch alpha channel if not used - if (eAlphaNorm == eAlphaNormalization_SetToZero) - { - // Store the range explicitly into the structure for read-back. - // The formats which request range expansion don't support alpha. - cMinColor[3] = 0.f; - cMaxColor[3] = cUprValue; - } - else if (eAlphaNorm == eAlphaNormalization_PassThrough) - { - cMinColor[3] = 0.f; - cMaxColor[3] = 1.f; - } - - // get the origins of the color model's lattice for the range of values - // these values need to be encoded as precise as possible under quantization - AZ::Vector4 cBaseLines = AZ::Vector4(0.0f, 0.0f, 0.0f, 0.0f); - AZ::Vector4 cScale = AZ::Vector4(cMaxColor[0] - cMinColor[0], cMaxColor[1] - cMinColor[1], - cMaxColor[2] - cMinColor[2], cMaxColor[3] - cMinColor[3]); - -#if 0 - // NOTE: disabled for now, in the future we can turn this on to force availability - // of value to guarantee for example perfect grey-scales (using YFF) - switch (GetImageFlags() & EIF_Colormodel) - { - case EIF_Colormodel_RGB: - cBaseLines = Vec4(0.0f, 0.0f, 0.0f, 0.0f); - break; - case EIF_Colormodel_CIE: - cBaseLines = Vec4(0.0f, 1.f / 3, 1.f / 3, 0.0f); - break; - case EIF_Colormodel_IRB: - cBaseLines = Vec4(0.0f, 1.f / 2, 1.f / 2, 0.0f); - break; - case EIF_Colormodel_YCC: - case EIF_Colormodel_YFF: - cBaseLines = Vec4(1.f / 2, 0.0f, 1.f / 2, 0.0f); - break; - } - - Vec4 cBaseScale = cBaseLines; - cBaseLines = cBaseLines - cMinColor; - cBaseLines = cBaseLines / cScale; - - if ((cBaseLines.x > 0.0f) && (cBaseLines.x < 1.0f)) - { - AdjustScaleForQuantization<5>(cBaseLines.x, cBaseScale.x, cScale.x, cMinColor.x, cMaxColor.x); - } - if ((cBaseLines.y > 0.0f) && (cBaseLines.y < 1.0f)) - { - AdjustScaleForQuantization<6>(cBaseLines.y, cBaseScale.y, cScale.y, cMinColor.y, cMaxColor.y); - } - if ((cBaseLines.z > 0.0f) && (cBaseLines.z < 1.0f)) - { - AdjustScaleForQuantization<5>(cBaseLines.z, cBaseScale.z, cScale.z, cMinColor.z, cMaxColor.z); - } -#endif - - // normalize the image - AZ::Vector4 vMin = AZ::Vector4(cMinColor[0], cMinColor[1], cMinColor[2], cMinColor[3]); - for (uint32 dwMip = 0; dwMip < dwMips; ++dwMip) - { - uint8* pSrcMem; - uint32 dwSrcPitch; - GetImagePointer(dwMip, pSrcMem, dwSrcPitch); - - dwHeight = GetHeight(dwMip); - dwWidth = GetWidth(dwMip); - for (uint32 dwY = 0; dwY < dwHeight; ++dwY) - { - AZ::Vector4* pSrcPix = (AZ::Vector4*)&pSrcMem[dwY * dwSrcPitch]; - for (uint32 dwX = 0; dwX < dwWidth; ++dwX) - { - *pSrcPix = *pSrcPix - vMin; - *pSrcPix = *pSrcPix / cScale; - *pSrcPix = *pSrcPix * cUprValue; - - pSrcPix++; - } - } - } - - // set up a range - SetColorRange(AZ::Color(cMinColor[0], cMinColor[1], cMinColor[2], cMinColor[3]), - AZ::Color(cMaxColor[0], cMaxColor[1], cMaxColor[2], cMaxColor[3])); - - // set up a flag - AddImageFlags(EIF_RenormalizedTexture); - } - - void CImageObject::ExpandImageRange([[maybe_unused]] EColorNormalization eColorMode, EAlphaNormalization eAlphaMode, int nExponentBits) - { - AZ_Assert(!((eAlphaMode != eAlphaNormalization_SetToZero) && (nExponentBits != 0)), "%s: Unexpected alpha mode", __FUNCTION__); - - if (!HasImageFlags(EIF_RenormalizedTexture)) - { - return; - } - - if (GetPixelFormat() != ePixelFormat_R32G32B32A32F) - { - AZ_Assert(false, "%s: only supports source format A32B32G32R32F", __FUNCTION__); - return; - } - - uint32 dwWidth, dwHeight, dwMips; - GetExtent(dwWidth, dwHeight, dwMips); - - // calculate range to normalize to - const float fMaxExponent = powf(2.0f, (float)nExponentBits) - 1.0f; - float cUprValue = powf(2.0f, fMaxExponent); - - // find image's range, can be negative - AZ::Color cMinColor = AZ::Color(FLT_MAX, FLT_MAX, FLT_MAX, FLT_MAX); - AZ::Color cMaxColor = AZ::Color(-FLT_MAX, -FLT_MAX, -FLT_MAX, -FLT_MAX); - - GetColorRange(cMinColor, cMaxColor); - - // don't touch alpha channel if not used - if (eAlphaMode == eAlphaNormalization_SetToZero) - { - // Overwrite the range explicitly into the structure. - // The formats which request range expansion don't support alpha. - cUprValue = cMaxColor.GetA(); - - cMinColor.SetA(1.f); - cMaxColor.SetA(1.f); - } - - // expand the image - const AZ::Vector4 cScale = cMaxColor.GetAsVector4() - cMinColor.GetAsVector4(); - for (uint32 dwMip = 0; dwMip < dwMips; ++dwMip) - { - uint8* pSrcMem; - uint32 dwSrcPitch; - GetImagePointer(dwMip, pSrcMem, dwSrcPitch); - - dwHeight = GetHeight(dwMip); - dwWidth = GetWidth(dwMip); - for (uint32 dwY = 0; dwY < dwHeight; ++dwY) - { - AZ::Vector4* pSrcPix = (AZ::Vector4*)&pSrcMem[dwY * dwSrcPitch]; - for (uint32 dwX = 0; dwX < dwWidth; ++dwX) - { - *pSrcPix = *pSrcPix / cUprValue; - *pSrcPix = *pSrcPix * cScale; - *pSrcPix = *pSrcPix + cMinColor.GetAsVector4(); - - pSrcPix++; - } - } - } - - // set up a range - SetColorRange(AZ::Color(0.0f, 0.0f, 0.0f, 0.0f), AZ::Color(1.0f, 1.0f, 1.0f, 1.0f)); - - // set up a flag - RemoveImageFlags(EIF_RenormalizedTexture); - } - - /////////////////////////////////////////////////////////////////////////////////// - - void CImageObject::NormalizeVectors(AZ::u32 firstMip, AZ::u32 maxMipCount) - { - if (GetPixelFormat() != ePixelFormat_R32G32B32A32F) - { - AZ_Assert(false, "%s: only supports source format A32B32G32R32F", __FUNCTION__); - return; - } - - uint32 lastMip = AZ::GetMin(firstMip + maxMipCount, GetMipCount()); - for (uint32 mip = firstMip; mip < lastMip; ++mip) - { - const uint32 pixelCount = GetPixelCount(mip); - uint8* imageMem; - uint32 pitch; - GetImagePointer(mip, imageMem, pitch); - float* pPixels = (float*)imageMem; - - for (uint32 i = 0; i < pixelCount; ++i, pPixels += 4) - { - AZ::Vector3 vNormal = AZ::Vector3(pPixels[0] * 2.0f - 1.0f, pPixels[1] * 2.0f - 1.0f, pPixels[2] * 2.0f - 1.0f); - - // TODO: every opposing vector addition produces the zero-vector for - // normals on the entire sphere, in that case the forward vector [0,0,1] - // isn't necessarily right and we should look at the adjacent normals - // for a direction - if (vNormal.IsZero()) - { - vNormal = AZ::Vector3(1.0f, 0.0f, 0.0f); - } - else - { - vNormal.NormalizeSafe(); - } - - pPixels[0] = vNormal.GetX() * 0.5f + 0.5f; - pPixels[1] = vNormal.GetY() * 0.5f + 0.5f; - pPixels[2] = vNormal.GetZ() * 0.5f + 0.5f; - } - } - } - - /////////////////////////////////////////////////////////////////////////////////// - void CImageObject::ScaleAndBiasChannels(AZ::u32 firstMip, AZ::u32 maxMipCount, const AZ::Vector4& scale, const AZ::Vector4& bias) - { - if (GetPixelFormat() != ePixelFormat_R32G32B32A32F) - { - AZ_Assert(false, "%s: only supports source format A32B32G32R32F", __FUNCTION__); - return; - } - - const uint32 lastMip = AZ::GetMin(firstMip + maxMipCount, GetMipCount()); - for (uint32 mip = firstMip; mip < lastMip; ++mip) - { - const uint32 pixelCount = GetPixelCount(mip); - uint8* imageMem; - uint32 pitch; - GetImagePointer(mip, imageMem, pitch); - float* pPixels = (float*)imageMem; - - for (uint32 i = 0; i < pixelCount; ++i, pPixels += 4) - { - pPixels[0] = pPixels[0] * scale.GetX() + bias.GetX(); - pPixels[1] = pPixels[1] * scale.GetY() + bias.GetY(); - pPixels[2] = pPixels[2] * scale.GetZ() + bias.GetZ(); - pPixels[3] = pPixels[3] * scale.GetW() + bias.GetW(); - } - } - } - - /////////////////////////////////////////////////////////////////////////////////// - void CImageObject::ClampChannels(AZ::u32 firstMip, AZ::u32 maxMipCount, const AZ::Vector4& min, const AZ::Vector4& max) - { - if (GetPixelFormat() != ePixelFormat_R32G32B32A32F) - { - AZ_Assert(false, "%s: only supports source format A32B32G32R32F", __FUNCTION__); - return; - } - - const uint32 lastMip = AZ::GetMin(firstMip + maxMipCount, GetMipCount()); - for (uint32 mip = firstMip; mip < lastMip; ++mip) - { - - const uint32 pixelCount = GetPixelCount(mip); - uint8* imageMem; - uint32 pitch; - GetImagePointer(mip, imageMem, pitch); - float* pPixels = (float*)imageMem; - - for (uint32 i = 0; i < pixelCount; ++i, pPixels += 4) - { - pPixels[0] = AZ::GetClamp(pPixels[0], float(min.GetX()), float(max.GetX())); - pPixels[1] = AZ::GetClamp(pPixels[1], float(min.GetY()), float(max.GetY())); - pPixels[2] = AZ::GetClamp(pPixels[2], float(min.GetZ()), float(max.GetZ())); - pPixels[3] = AZ::GetClamp(pPixels[3], float(min.GetW()), float(max.GetW())); - } - } - } - -} //namespace ImageProcessing diff --git a/Gems/ImageProcessing/Code/Source/Converters/PixelOperation.cpp b/Gems/ImageProcessing/Code/Source/Converters/PixelOperation.cpp deleted file mode 100644 index 034dcdfda1..0000000000 --- a/Gems/ImageProcessing/Code/Source/Converters/PixelOperation.cpp +++ /dev/null @@ -1,487 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or 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 - -/////////////////////////////////////////////////////////////////////////////////// -//functions for maintaining alpha coverage. - -namespace ImageProcessing -{ - //convertion: all data type supported by pixel channel <=> float - float U8ToF32(uint8 in) - { - return in / 255.f; - } - - uint8 F32ToU8(float in) - { - return aznumeric_cast(round(AZ::GetClamp(in, 0.f, 1.f) * 255)); - } - - float U16ToF32(uint16 in) - { - return in / 65535.f; - } - - uint16 F32ToU16(float in) - { - return aznumeric_cast(round(AZ::GetClamp(in, 0.f, 1.f) * 65535.f)); - } - - float HalfToF32(SHalf in) - { - return in; - } - - SHalf F32ToHalf(float in) - { - return SHalf(in); - } - - //stucture for RGBE pixel format - struct RgbE - { - static const int RGB9E5_EXPONENT_BITS = 5; - static const int RGB9E5_MANTISSA_BITS = 9; - static const int RGB9E5_EXP_BIAS = 15; - static const int RGB9E5_MAX_VALID_BIASED_EXP = 31; - static const int MAX_RGB9E5_EXP = (RGB9E5_MAX_VALID_BIASED_EXP - RGB9E5_EXP_BIAS); - static const int RGB9E5_MANTISSA_VALUES = (1 << RGB9E5_MANTISSA_BITS); - static const int MAX_RGB9E5_MANTISSA = (RGB9E5_MANTISSA_VALUES - 1); - - static float MAX_RGB9E5; - - unsigned int r : 9; - unsigned int g : 9; - unsigned int b : 9; - unsigned int e : 5; - - static int log2(float x) - { - int bitfield = *((int*)(&x)); - bitfield &= ~0x80000000; - - return ((bitfield >> 23) - 127); - } - - void GetRGBF(float& outR, float& outG, float& outB) const - { - int exponent = e - RGB9E5_EXP_BIAS - RGB9E5_MANTISSA_BITS; - float scale = powf(2.0f, aznumeric_cast(exponent)); - outR = r * scale; - outG = g * scale; - outB = b * scale; - } - - void SetRGBF(const float& inR, const float& inG, const float& inB) - { - float rf = AZStd::GetMax(0.0f, AZStd::GetMin(inR, MAX_RGB9E5)); - float gf = AZStd::GetMax(0.0f, AZStd::GetMin(inG, MAX_RGB9E5)); - float bf = AZStd::GetMax(0.0f, AZStd::GetMin(inB, MAX_RGB9E5)); - float mf = AZStd::GetMax(rf, AZStd::GetMax(gf, bf)); - - e = AZStd::GetMax(0, log2(mf) + (RGB9E5_EXP_BIAS + 1)); - - int exponent = e - RGB9E5_EXP_BIAS - RGB9E5_MANTISSA_BITS; - float scale = powf(2.0f, aznumeric_cast(exponent)); - - r = AZStd::GetMin(511, (int)floorf(rf / scale + 0.5f)); - g = AZStd::GetMin(511, (int)floorf(gf / scale + 0.5f)); - b = AZStd::GetMin(511, (int)floorf(bf / scale + 0.5f)); - } - }; - - float RgbE::MAX_RGB9E5 = (((float)MAX_RGB9E5_MANTISSA) / RGB9E5_MANTISSA_VALUES * (1 << MAX_RGB9E5_EXP)); - - //ePixelFormat_R8G8B8A8 - class PixelOperationR8G8B8A8 : public IPixelOperation - { - void GetRGBA(const uint8* buf, float& r, float& g, float& b, float& a) override - { - const uint8* data = buf; - r = U8ToF32(data[0]); - g = U8ToF32(data[1]); - b = U8ToF32(data[2]); - a = U8ToF32(data[3]); - } - - void SetRGBA(uint8* buf, const float& r, const float& g, const float& b, const float& a) override - { - uint8* data = buf; - data[0] = F32ToU8(r); - data[1] = F32ToU8(g); - data[2] = F32ToU8(b); - data[3] = F32ToU8(a); - } - }; - - //ePixelFormat_R8G8B8X8 - class PixelOperationR8G8B8X8 : public IPixelOperation - { - void GetRGBA(const uint8* buf, float& r, float& g, float& b, float& a) override - { - const uint8* data = buf; - r = U8ToF32(data[0]); - g = U8ToF32(data[1]); - b = U8ToF32(data[2]); - a = 1.f; - } - - void SetRGBA(uint8* buf, const float& r, const float& g, const float& b, [[maybe_unused]] const float& a) override - { - uint8* data = buf; - data[0] = F32ToU8(r); - data[1] = F32ToU8(g); - data[2] = F32ToU8(b); - data[3] = 0xff; - } - }; - - //ePixelFormat_B8G8R8A8 - class PixelOperationB8G8R8A8 : public IPixelOperation - { - void GetRGBA(const uint8* buf, float& r, float& g, float& b, float& a) override - { - const uint8* data = buf; - r = U8ToF32(data[2]); - g = U8ToF32(data[1]); - b = U8ToF32(data[0]); - a = U8ToF32(data[3]); - } - - void SetRGBA(uint8* buf, const float& r, const float& g, const float& b, const float& a) override - { - uint8* data = buf; - data[0] = F32ToU8(b); - data[1] = F32ToU8(g); - data[2] = F32ToU8(r); - data[3] = F32ToU8(a); - } - }; - - //ePixelFormat_R8G8 - class PixelOperationR8G8 : public IPixelOperation - { - void GetRGBA(const uint8* buf, float& r, float& g, float& b, float& a) override - { - const uint8* data = buf; - r = U8ToF32(data[0]); - g = U8ToF32(data[1]); - b = 0.f; - a = 1.f; - } - - void SetRGBA(uint8* buf, const float& r, const float& g, [[maybe_unused]] const float& b, [[maybe_unused]] const float& a) override - { - uint8* data = buf; - data[0] = F32ToU8(r); - data[1] = F32ToU8(g); - } - }; - - //ePixelFormat_R8 - class PixelOperationR8 : public IPixelOperation - { - void GetRGBA(const uint8* buf, float& r, float& g, float& b, float& a) override - { - const uint8* data = buf; - r = U8ToF32(data[0]); - g = 0.f; - b = 0.f; - a = 1.f; - } - - void SetRGBA(uint8* buf, const float& r, [[maybe_unused]] const float& g, [[maybe_unused]] const float& b, [[maybe_unused]] const float& a) override - { - uint8* data = buf; - data[0] = F32ToU8(r); - } - }; - - //ePixelFormat_A8 - class PixelOperationA8 : public IPixelOperation - { - void GetRGBA(const uint8* buf, float& r, float& g, float& b, float& a) override - { - const uint8* data = buf; - a = U8ToF32(data[0]); - //save alpha information to rgb too. useful for preview. - r = a; - g = a; - b = a; - } - - void SetRGBA(uint8* buf, [[maybe_unused]] const float& r, [[maybe_unused]] const float& g, [[maybe_unused]] const float& b, const float& a) override - { - uint8* data = buf; - data[0] = F32ToU8(a); - } - }; - - //ePixelFormat_R16G16B16A16 - class PixelOperationR16G16B16A16 : public IPixelOperation - { - void GetRGBA(const uint8* buf, float& r, float& g, float& b, float& a) override - { - const uint16* data = (uint16*)(buf); - r = U16ToF32(data[0]); - g = U16ToF32(data[1]); - b = U16ToF32(data[2]); - a = U16ToF32(data[3]); - } - - void SetRGBA(uint8* buf, const float& r, const float& g, const float& b, const float& a) override - { - uint16* data = (uint16*)(buf); - data[0] = F32ToU16(r); - data[1] = F32ToU16(g); - data[2] = F32ToU16(b); - data[3] = F32ToU16(a); - } - }; - - //ePixelFormat_R16G16 - class PixelOperationR16G16 : public IPixelOperation - { - void GetRGBA(const uint8* buf, float& r, float& g, float& b, float& a) override - { - const uint16* data = (uint16*)(buf); - r = U16ToF32(data[0]); - g = U16ToF32(data[1]); - b = 0.f; - a = 1.f; - } - - void SetRGBA(uint8* buf, const float& r, const float& g, [[maybe_unused]] const float& b, [[maybe_unused]] const float& a) override - { - uint16* data = (uint16*)(buf); - data[0] = F32ToU16(r); - data[1] = F32ToU16(g); - } - }; - - //ePixelFormat_R16 - class PixelOperationR16 : public IPixelOperation - { - void GetRGBA(const uint8* buf, float& r, float& g, float& b, float& a) override - { - const uint16* data = (uint16*)(buf); - r = U16ToF32(data[0]); - g = 0.f; - b = 0.f; - a = 1.f; - } - - void SetRGBA(uint8* buf, const float& r, [[maybe_unused]] const float& g, [[maybe_unused]] const float& b, [[maybe_unused]] const float& a) override - { - uint16* data = (uint16*)(buf); - data[0] = F32ToU16(r); - } - }; - - //ePixelFormat_R9G9B9E5 - class PixelOperationR9G9B9E5 : public IPixelOperation - { - void GetRGBA(const uint8* buf, float& r, float& g, float& b, float& a) override - { - const RgbE* data = (RgbE*)(buf); - data->GetRGBF(r, g, b); - a = 1.f; - } - - void SetRGBA(uint8* buf, const float& r, const float& g, const float& b, [[maybe_unused]] const float& a) override - { - RgbE* data = (RgbE*)(buf); - data->SetRGBF(r, g, b); - } - }; - - //ePixelFormat_R32G32B32A32F - class PixelOperationR32G32B32A32F : public IPixelOperation - { - public: - void GetRGBA(const uint8* buf, float& r, float& g, float& b, float& a) override - { - const float* data = (float*)(buf); - r = data[0]; - g = data[1]; - b = data[2]; - a = data[3]; - } - - void SetRGBA(uint8* buf, const float& r, const float& g, const float& b, const float& a) override - { - float* data = (float*)(buf); - data[0] = r; - data[1] = g; - data[2] = b; - data[3] = a; - } - }; - - //ePixelFormat_R32G32F - class PixelOperationR32G32F : public IPixelOperation - { - public: - void GetRGBA(const uint8* buf, float& r, float& g, float& b, float& a) override - { - const float* data = (float*)(buf); - r = data[0]; - g = data[1]; - b = 0.f; - a = 1.f; - } - - void SetRGBA(uint8* buf, const float& r, const float& g, [[maybe_unused]] const float& b, [[maybe_unused]] const float& a) override - { - float* data = (float*)(buf); - data[0] = r; - data[1] = g; - } - }; - - //ePixelFormat_R32F - class PixelOperationR32F : public IPixelOperation - { - public: - void GetRGBA(const uint8* buf, float& r, float& g, float& b, float& a) override - { - const float* data = (float*)(buf); - r = data[0]; - g = 0.f; - b = 0.f; - a = 1.f; - } - - void SetRGBA(uint8* buf, const float& r, [[maybe_unused]] const float& g, [[maybe_unused]] const float& b, [[maybe_unused]] const float& a) override - { - float* data = (float*)(buf); - data[0] = r; - } - }; - - //ePixelFormat_R16G16B16A16F - class PixelOperationR16G16B16A16F : public IPixelOperation - { - public: - void GetRGBA(const uint8* buf, float& r, float& g, float& b, float& a) override - { - const SHalf* data = (SHalf*)(buf); - r = data[0]; - g = data[1]; - b = data[2]; - a = data[3]; - } - - void SetRGBA(uint8* buf, const float& r, const float& g, const float& b, const float& a) override - { - SHalf* data = (SHalf*)(buf); - data[0] = SHalf(r); - data[1] = SHalf(g); - data[2] = SHalf(b); - data[3] = SHalf(a); - } - }; - - //ePixelFormat_R16G16F - class PixelOperationR16G16F : public IPixelOperation - { - public: - void GetRGBA(const uint8* buf, float& r, float& g, float& b, float& a) override - { - const SHalf* data = (SHalf*)(buf); - r = data[0]; - g = data[1]; - b = 0.f; - a = 1.f; - } - - void SetRGBA(uint8* buf, const float& r, const float& g, [[maybe_unused]] const float& b, [[maybe_unused]] const float& a) override - { - SHalf* data = (SHalf*)(buf); - data[0] = SHalf(r); - data[1] = SHalf(g); - } - }; - - //ePixelFormat_R16F - class PixelOperationR16F : public IPixelOperation - { - public: - void GetRGBA(const uint8* buf, float& r, float& g, float& b, float& a) override - { - const SHalf* data = (SHalf*)(buf); - r = data[0]; - g = 0.f; - b = 0.f; - a = 1.f; - } - - void SetRGBA(uint8* buf, const float& r, [[maybe_unused]] const float& g, [[maybe_unused]] const float& b, [[maybe_unused]] const float& a) override - { - SHalf* data = (SHalf*)(buf); - data[0] = SHalf(r); - } - }; - - IPixelOperationPtr CreatePixelOperation(EPixelFormat pixelFmt) - { - switch (pixelFmt) - { - case ePixelFormat_R8G8B8A8: - return AZStd::make_shared(); - case ePixelFormat_R8G8B8X8: - return AZStd::make_shared(); - case ePixelFormat_B8G8R8A8: - return AZStd::make_shared(); - case ePixelFormat_R8G8: - return AZStd::make_shared(); - case ePixelFormat_R8: - return AZStd::make_shared(); - case ePixelFormat_A8: - return AZStd::make_shared(); - case ePixelFormat_R16G16B16A16: - return AZStd::make_shared(); - case ePixelFormat_R16G16: - return AZStd::make_shared(); - case ePixelFormat_R16: - return AZStd::make_shared(); - case ePixelFormat_R9G9B9E5: - return AZStd::make_shared(); - case ePixelFormat_R32G32B32A32F: - return AZStd::make_shared(); - case ePixelFormat_R32G32F: - return AZStd::make_shared(); - case ePixelFormat_R32F: - return AZStd::make_shared(); - case ePixelFormat_R16G16B16A16F: - return AZStd::make_shared(); - case ePixelFormat_R16G16F: - return AZStd::make_shared(); - case ePixelFormat_R16F: - return AZStd::make_shared(); - default: - AZ_Assert(false, "This function should be only called for uncompressed pixel format"); - break; - } - return nullptr; - } - -} // namespace ImageProcessing diff --git a/Gems/ImageProcessing/Code/Source/Converters/PixelOperation.h b/Gems/ImageProcessing/Code/Source/Converters/PixelOperation.h deleted file mode 100644 index 4ce8a20643..0000000000 --- a/Gems/ImageProcessing/Code/Source/Converters/PixelOperation.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. -* -*/ - -#pragma once - -#include - -namespace ImageProcessing -{ - class IPixelOperation - { - public: - virtual ~IPixelOperation() {} - - virtual void GetRGBA(const uint8* buf, float& r, float& g, float& b, float& a) = 0; - virtual void SetRGBA(uint8* buf, const float& r, const float& g, const float& b, const float& a) = 0; - }; - - typedef AZStd::shared_ptr IPixelOperationPtr; - IPixelOperationPtr CreatePixelOperation(EPixelFormat pixelFmt); - -}// namespace ImageProcessing diff --git a/Gems/ImageProcessing/Code/Source/Editor/EditorCommon.cpp b/Gems/ImageProcessing/Code/Source/Editor/EditorCommon.cpp deleted file mode 100644 index fb62bd258f..0000000000 --- a/Gems/ImageProcessing/Code/Source/Editor/EditorCommon.cpp +++ /dev/null @@ -1,386 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or 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 - -namespace ImageProcessingEditor -{ - using namespace ImageProcessing; - - bool EditorHelper::s_IsPixelFormatStringInited = false; - const char* EditorHelper::s_PixelFormatString[ImageProcessing::EPixelFormat::ePixelFormat_Count]; - - void EditorHelper::InitPixelFormatString() - { - if (!s_IsPixelFormatStringInited) - { - s_IsPixelFormatStringInited = true; - } - - CPixelFormats& pixelFormats = CPixelFormats::GetInstance(); - for (int format = 0; format < EPixelFormat::ePixelFormat_Count; format ++) - { - const PixelFormatInfo* info = pixelFormats.GetPixelFormatInfo((EPixelFormat)format); - s_PixelFormatString[(EPixelFormat)format] = ""; - if (info) - { - s_PixelFormatString[(EPixelFormat)format] = info->szName; - } - else - { - AZ_Error("Texture Editor", false, "Cannot find name of EPixelFormat %i", format); - } - } - } - - const AZStd::string EditorHelper::GetFileSizeString(AZ::u32 fileSizeInBytes) - { - AZStd::string fileSizeStr; - - static double kb = 1024.0f; - static double mb = kb * 1024.0; - static double gb = mb * 1024.0; - - static AZStd::string byteStr = "B"; - static AZStd::string kbStr = "KB"; - static AZStd::string mbStr = "MB"; - static AZStd::string gbStr = "GB"; - -#if AZ_TRAIT_IMAGEPROCESSING_USE_BASE10_BYTE_PREFIX - kb = 1000.0; - mb = kb * 1000.0; - gb = mb * 1000.0; - - kbStr = "kB"; - mbStr = "mB"; - gbStr = "gB"; -#endif // AZ_TRAIT_IMAGEPROCESSING_USE_BASE10_BYTE_PREFIX - - if (fileSizeInBytes < kb) - { - fileSizeStr = AZStd::string::format("%u%s", fileSizeInBytes, byteStr.c_str()); - } - else if (fileSizeInBytes < mb) - { - double size = fileSizeInBytes / kb; - fileSizeStr = AZStd::string::format("%.2f%s", size, kbStr.c_str()); - } - else if (fileSizeInBytes < gb) - { - double size = fileSizeInBytes / mb; - fileSizeStr = AZStd::string::format("%.2f%s", size, mbStr.c_str()); - } - else - { - double size = fileSizeInBytes / gb; - fileSizeStr = AZStd::string::format("%.2f%s", size, gbStr.c_str()); - } - return fileSizeStr; - } - - const AZStd::string EditorHelper::ToReadablePlatformString(const AZStd::string& platformRawStr) - { - AZStd::string readableString; - AZStd::string platformStrLowerCase = platformRawStr; - AZStd::to_lower(platformStrLowerCase.begin(), platformStrLowerCase.end()); - if (platformStrLowerCase == "pc") - { - readableString = "PC"; - } - else if (platformStrLowerCase == "es3") - { - readableString = "Android"; - } - else if (platformStrLowerCase == "osx_gl") - { - readableString = "macOS"; - } - else if (platformStrLowerCase == "provo") - { - readableString = "Provo"; - } - else if (platformStrLowerCase == "ios") - { - readableString = "iOS"; - } - else - { - return platformRawStr; - } - - return readableString; - } - - - EditorTextureSetting::EditorTextureSetting(const AZ::Uuid& sourceTextureId) - { - const AzToolsFramework::AssetBrowser::SourceAssetBrowserEntry* fullDetails = AzToolsFramework::AssetBrowser::SourceAssetBrowserEntry::GetSourceByUuid(sourceTextureId); - InitFromPath(fullDetails->GetFullPath()); - } - - EditorTextureSetting::EditorTextureSetting(const AZStd::string& texturePath) - { - InitFromPath(texturePath); - } - - void EditorTextureSetting::InitFromPath(const AZStd::string& texturePath) - { - m_fullPath = texturePath; - AzFramework::StringFunc::Path::GetFullFileName(texturePath.c_str(), m_textureName); - - m_img = IImageObjectPtr(LoadImageFromFile(m_fullPath)); - - if (m_img == nullptr) - { - AZ_Warning("Texture Editor", false, "%s is not a valid texture image.", texturePath.c_str()); - return; - } - - bool generatedDefaults = false; - m_settingsMap = TextureSettings::GetMultiplatformTextureSetting(m_fullPath, generatedDefaults); - - // Get the preset id from one platform. The preset id for each platform should always be same - AZ_Assert(m_settingsMap.size() > 0, "There is no platform information"); - AZ::Uuid presetId = m_settingsMap.begin()->second.m_preset; - const PresetSettings* preset = BuilderSettingManager::Instance()->GetPreset(presetId); - - if (!preset) - { - AZ_Warning("Texture Editor", false, "Cannot find preset %s! Will assign a suggested one for the texture.", presetId.ToString().c_str()); - presetId = BuilderSettingManager::Instance()->GetSuggestedPreset(m_fullPath, m_img); - - for (auto& settingIter : m_settingsMap) - { - settingIter.second.ApplyPreset(presetId); - } - } - } - - void EditorTextureSetting::SetIsOverrided() - { - for (auto& it : m_settingsMap) - { - m_overrideFromPreset = false; - TextureSettings& textureSetting = it.second; - const PresetSettings* presetSetting = BuilderSettingManager::Instance()->GetPreset(textureSetting.m_preset); - if (presetSetting != nullptr) - { - if ((textureSetting.m_sizeReduceLevel != presetSetting->m_sizeReduceLevel) || - (textureSetting.m_suppressEngineReduce != presetSetting->m_suppressEngineReduce) || - (presetSetting->m_mipmapSetting != nullptr && textureSetting.m_mipGenType != presetSetting->m_mipmapSetting->m_type)) - { - m_overrideFromPreset = true; - } - } - else - { - AZ_Error("Texture Editor", false, "Texture Preset %s is not found!", textureSetting.m_preset.ToString().c_str()); - } - } - } - - void EditorTextureSetting::SetToPreset(const AZStd::string& presetName) - { - m_overrideFromPreset = false; - - AZ::Uuid presetId = BuilderSettingManager::Instance()->GetPresetIdFromName(presetName); - if (presetId.IsNull()) - { - AZ_Error("Texture Editor", false, "Texture Preset %s has no associated UUID.", presetName.c_str()); - return; - } - - for (auto& settingIter : m_settingsMap) - { - settingIter.second.ApplyPreset(presetId); - } - } - - //Get the texture setting on certain platform - TextureSettings& EditorTextureSetting::GetMultiplatformTextureSetting(const AZStd::string& platform) - { - AZ_Assert(m_settingsMap.size() > 0, "Texture Editor", "There is no texture settings for texture %s", m_fullPath.c_str()); - PlatformName platformName = platform; - if (platform.empty()) - { - platformName = BuilderSettingManager::s_defaultPlatform; - } - if (m_settingsMap.find(platformName) != m_settingsMap.end()) - { - return m_settingsMap[platformName]; - } - else - { - AZ_Error("Texture Editor", false, "Cannot find texture setting on platform %s", platformName.c_str()); - } - return m_settingsMap.begin()->second; - } - - bool EditorTextureSetting::GetFinalInfoForTextureOnPlatform(const AZStd::string& platform, AZ::u32 wantedReduce, ResolutionInfo& outResolutionInfo) - { - if (m_settingsMap.find(platform) == m_settingsMap.end()) - { - return false; - } - - // Copy current texture setting and set to desired reduce - TextureSettings textureSetting = m_settingsMap[platform]; - wantedReduce = AZStd::min(AZStd::max(s_MinReduceLevel, wantedReduce), s_MaxReduceLevel); - textureSetting.m_sizeReduceLevel = wantedReduce; - - const PresetSettings* presetSetting = BuilderSettingManager::Instance()->GetPreset(textureSetting.m_preset, platform); - if (presetSetting) - { - EPixelFormat pixelFormat = presetSetting->m_pixelFormat; - CPixelFormats& pixelFormats = CPixelFormats::GetInstance(); - - AZ::u32 inputWidth = m_img->GetWidth(0); - AZ::u32 inputHeight = m_img->GetHeight(0); - - // Update input width and height if it's a cubemap - if (presetSetting->m_cubemapSetting != nullptr) - { - CubemapLayout *srcCubemap = CubemapLayout::CreateCubemapLayout(m_img); - if (srcCubemap == nullptr) - { - return false; - } - inputWidth = srcCubemap->GetFaceSize(); - inputHeight = inputWidth; - outResolutionInfo.arrayCount = 6; - delete srcCubemap; - } - - GetOutputExtent(inputWidth, inputHeight, outResolutionInfo.width, outResolutionInfo.height, outResolutionInfo.reduce, &textureSetting, presetSetting); - - AZ::u32 mipMapCount = pixelFormats.ComputeMaxMipCount(pixelFormat, outResolutionInfo.width, outResolutionInfo.height); - outResolutionInfo.mipCount = presetSetting->m_mipmapSetting != nullptr && textureSetting.m_enableMipmap ? mipMapCount : 1; - - return true; - } - else - { - return false; - } - } - - bool EditorTextureSetting::RefreshMipSetting(bool enableMip) - { - bool enabled = true; - for (auto& it : m_settingsMap) - { - const PresetSettings* preset = BuilderSettingManager::Instance()->GetPreset(it.second.m_preset); - if (enableMip) - { - if (preset && preset->m_mipmapSetting) - { - it.second.m_enableMipmap = true; - it.second.m_mipGenType = preset->m_mipmapSetting->m_type; - } - else - { - it.second.m_enableMipmap = false; - enabled = false; - AZ_Error("Texture Editor", false, "Preset %s does not support mipmap!", preset->m_name.c_str()); - } - } - else - { - it.second.m_enableMipmap = false; - enabled = false; - } - } - return enabled; - } - - void EditorTextureSetting::PropagateCommonSettings() - { - if (m_settingsMap.size() <= 1) - { - //Only one setting available, no need to propagate - return; - } - - TextureSettings& texSetting = GetMultiplatformTextureSetting(); - for (auto& it = ++ m_settingsMap.begin(); it != m_settingsMap.end(); ++it) - { - const PlatformName defaultPlatform = BuilderSettingManager::s_defaultPlatform; - if (it->first != defaultPlatform) - { - it->second.m_enableMipmap = texSetting.m_enableMipmap; - it->second.m_maintainAlphaCoverage = texSetting.m_maintainAlphaCoverage; - it->second.m_mipGenEval = texSetting.m_mipGenEval; - it->second.m_mipGenType = texSetting.m_mipGenType; - for (size_t i = 0; i < TextureSettings::s_MaxMipMaps; i++) - { - it->second.m_mipAlphaAdjust[i] = texSetting.m_mipAlphaAdjust[i]; - } - } - } - } - - AZStd::list EditorTextureSetting::GetResolutionInfo(AZStd::string platform, AZ::u32& minReduce, AZ::u32& maxReduce) - { - AZStd::list resolutionInfos; - // Set the min/max reduce to the global value range first - minReduce = s_MaxReduceLevel; - maxReduce = s_MinReduceLevel; - for (AZ::u32 i = s_MinReduceLevel; i <= s_MaxReduceLevel; i++) - { - ResolutionInfo resolutionInfo; - GetFinalInfoForTextureOnPlatform(platform, i, resolutionInfo); - // If actual reduce is lower than desired reduce, it reaches the limit and we can stop try lower resolution - if (i > resolutionInfo.reduce) - { - break; - } - // Finds out the final min/max reduce based on range in different platforms - minReduce = AZStd::min(resolutionInfo.reduce, minReduce); - maxReduce = AZStd::max(resolutionInfo.reduce, maxReduce); - resolutionInfos.push_back(resolutionInfo); - } - return resolutionInfos; - } - - AZStd::list EditorTextureSetting::GetResolutionInfoForMipmap(AZStd::string platform) - { - AZStd::list resolutionInfos; - unsigned int baseReduce = m_settingsMap[platform].m_sizeReduceLevel; - ResolutionInfo baseInfo; - GetFinalInfoForTextureOnPlatform(platform, baseReduce, baseInfo); - resolutionInfos.push_back(baseInfo); - for (AZ::u32 i = 1; i < baseInfo.mipCount; i++) - { - ResolutionInfo resolutionInfo = baseInfo; - resolutionInfo.width = AZStd::max(baseInfo.width >> i, 1); - resolutionInfo.height = AZStd::max(baseInfo.height >> i, 1); - resolutionInfo.reduce = baseInfo.reduce + i; - resolutionInfo.mipCount = 1; - resolutionInfos.push_back(resolutionInfo); - } - return resolutionInfos; - } - -} //namespace ImageProcessingEditor - diff --git a/Gems/ImageProcessing/Code/Source/Editor/EditorCommon.h b/Gems/ImageProcessing/Code/Source/Editor/EditorCommon.h deleted file mode 100644 index cbba723f06..0000000000 --- a/Gems/ImageProcessing/Code/Source/Editor/EditorCommon.h +++ /dev/null @@ -1,105 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ - -#pragma once - -#include -#include -#include -#include -#include -#include - -#include -namespace ImageProcessingEditor -{ - class EditorHelper - { - public: - static const char* s_PixelFormatString[ImageProcessing::EPixelFormat::ePixelFormat_Count]; - static void InitPixelFormatString(); - static const AZStd::string GetFileSizeString(AZ::u32 fileSizeInBytes); - static const AZStd::string ToReadablePlatformString(const AZStd::string& platformRawStr); - - private: - static bool s_IsPixelFormatStringInited; - }; - - struct ResolutionInfo - { - AZ::u32 width = 0; - AZ::u32 height = 0; - AZ::u32 arrayCount = 1; - AZ::u32 reduce = 0; - AZ::u32 mipCount = 0; - }; - - struct EditorTextureSetting - { - AZStd::string m_textureName = ""; - AZStd::string m_fullPath = ""; - ImageProcessing::MultiplatformTextureSettings m_settingsMap; - bool m_overrideFromPreset = false; - bool m_modified = false; - ImageProcessing::IImageObjectPtr m_img; - - EditorTextureSetting(const AZ::Uuid& sourceTextureId); - EditorTextureSetting(const AZStd::string& texturePath); - ~EditorTextureSetting() = default; - - void InitFromPath(const AZStd::string& texturePath); - - void SetIsOverrided(); - - void SetToPreset(const AZStd::string& presetName); - - //Get the texture setting on certain platform - ImageProcessing::TextureSettings& GetMultiplatformTextureSetting(const AZStd::string& platform = ""); - - //Gets the final resolution/reduce/mip count for a texture on a certain platform - //@param wantedReduce indicates the reduce level that's preferred - //@return successfully get the value or not - bool GetFinalInfoForTextureOnPlatform(const AZStd::string& platform, AZ::u32 wantedReduce, ResolutionInfo& outResolutionInfo); - - //Refresh the mip setting when the mip map setting is enabled/disabled. - //@return whether the mipmap is enabled or not. - bool RefreshMipSetting(bool enableMip); - - //Propagate non platform specific settings from the first setting to all the settings stored in m_settingsMap - void PropagateCommonSettings(); - - //Returns a list of calculated final resolution info based on different base reduce levels - AZStd::list GetResolutionInfo(AZStd::string platform, AZ::u32& minReduce, AZ::u32& maxReduce); - - //Returns a list of calculated final resolution info based on different mipmap levels - AZStd::list GetResolutionInfoForMipmap(AZStd::string platform); - }; - - - class ImageProcessingEditorInteralNotifications - : public AZ::EBusTraits - { - public: - ////////////////////////////////////////////////////////////////////////// - // EBusTraits overrides - static const AZ::EBusHandlerPolicy HandlerPolicy = AZ::EBusHandlerPolicy::Multiple; - static const AZ::EBusAddressPolicy AddressPolicy = AZ::EBusAddressPolicy::Single; - ///////////////////////////////////////////////////////////////////////// - - //! Used to inform the settings changed across widgets - virtual void OnEditorSettingsChanged(bool needRefresh, const AZStd::string& platform) = 0; - }; - - using EditorInternalNotificationBus = AZ::EBus; - -} //namespace ImageProcessingEditor - diff --git a/Gems/ImageProcessing/Code/Source/Editor/ImagePopup.cpp b/Gems/ImageProcessing/Code/Source/Editor/ImagePopup.cpp deleted file mode 100644 index c646d7adad..0000000000 --- a/Gems/ImageProcessing/Code/Source/Editor/ImagePopup.cpp +++ /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. -* -*/ - -#include -#include "ImagePopup.h" -#include -#include -#include - -namespace ImageProcessingEditor -{ - ImagePopup::ImagePopup(QImage previewImage, QWidget* parent /*= nullptr*/) - : QDialog(parent, Qt::Dialog | Qt::FramelessWindowHint | Qt::Popup) - , m_ui(new Ui::ImagePopup) - { - m_ui->setupUi(this); - m_previewImage = previewImage; - - if (!m_previewImage.isNull()) - { - int height = previewImage.height(); - int width = previewImage.width(); - - this->resize(width, height); - m_ui->imageLabel->resize(width, height); - QPixmap pixmap = QPixmap::fromImage(previewImage); - m_ui->imageLabel->setPixmap(pixmap); - - this->setFocusPolicy(Qt::FocusPolicy::NoFocus); - this->setModal(false); - } - } - - ImagePopup::~ImagePopup() - { - - } - -}//namespace ImageProcessingEditor -#include diff --git a/Gems/ImageProcessing/Code/Source/Editor/ImagePopup.ui b/Gems/ImageProcessing/Code/Source/Editor/ImagePopup.ui deleted file mode 100644 index 419812b686..0000000000 --- a/Gems/ImageProcessing/Code/Source/Editor/ImagePopup.ui +++ /dev/null @@ -1,43 +0,0 @@ - - - ImagePopup - - - Qt::WindowModal - - - - 0 - 0 - 400 - 300 - - - - - 0 - 0 - - - - - 0 - 0 - - - - Form - - - - - - - - - - - - - - diff --git a/Gems/ImageProcessing/Code/Source/Editor/MipmapSettingWidget.cpp b/Gems/ImageProcessing/Code/Source/Editor/MipmapSettingWidget.cpp deleted file mode 100644 index e0e70e30be..0000000000 --- a/Gems/ImageProcessing/Code/Source/Editor/MipmapSettingWidget.cpp +++ /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. -* -*/ - -#include -#include "MipmapSettingWidget.h" -#include - -#include -#include -#include - -#include -#include - -namespace ImageProcessingEditor -{ - using namespace ImageProcessing; - MipmapSettingWidget::MipmapSettingWidget(EditorTextureSetting& textureSetting, QWidget* parent /*= nullptr*/) - : QWidget(parent) - , m_ui(new Ui::MipmapSettingWidget) - , m_textureSetting(&textureSetting) - { - m_ui->setupUi(this); - - - AZ::SerializeContext* serializeContext = nullptr; - EBUS_EVENT_RESULT(serializeContext, AZ::ComponentApplicationBus, GetSerializeContext); - AZ_Assert(serializeContext, "Serialization context not available"); - - m_ui->propertyEditor->SetAutoResizeLabels(true); - m_ui->propertyEditor->Setup(serializeContext, this, true, 250); - - m_ui->propertyEditor->ClearInstances(); - TextureSettings* instance = &m_textureSetting->GetMultiplatformTextureSetting(); - const AZ::Uuid& classId = AZ::SerializeTypeInfo::GetUuid(instance); - m_ui->propertyEditor->AddInstance(instance, classId); - m_ui->propertyEditor->InvalidateAll(); - m_ui->propertyEditor->ExpandAll(); - - RefreshUI(); - - EditorInternalNotificationBus::Handler::BusConnect(); - } - - MipmapSettingWidget::~MipmapSettingWidget() - { - EditorInternalNotificationBus::Handler::BusDisconnect(); - } - - void MipmapSettingWidget::RefreshUI() - { - TextureSettings& texSetting = m_textureSetting->GetMultiplatformTextureSetting(); - const PresetSettings* preset = BuilderSettingManager::Instance()->GetPreset(texSetting.m_preset); - if (preset == nullptr || preset->m_mipmapSetting == nullptr) - { - m_ui->enableCheckBox->setCheckState(Qt::CheckState::Unchecked); - m_ui->enableCheckBox->setEnabled(false); - m_ui->propertyEditor->hide(); - } - else - { - bool showMipMap = texSetting.m_enableMipmap; - m_ui->enableCheckBox->setEnabled(true); - m_ui->enableCheckBox->setCheckState(showMipMap ? Qt::CheckState::Checked : Qt::CheckState::Unchecked); - QObject::connect(m_ui->enableCheckBox, &QCheckBox::clicked, this, &MipmapSettingWidget::OnCheckBoxStateChanged); - if (showMipMap) - { - m_ui->propertyEditor->show(); - this->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding); - } - else - { - m_ui->propertyEditor->hide(); - this->setSizePolicy(QSizePolicy::Minimum, QSizePolicy::Minimum); - } - } - m_ui->propertyEditor->InvalidateValues(); - } - - void MipmapSettingWidget::OnCheckBoxStateChanged(bool checked) - { - bool finalChecked = m_textureSetting->RefreshMipSetting(checked); - - if (finalChecked) - { - m_ui->propertyEditor->show(); - } - else - { - m_ui->propertyEditor->hide(); - } - EditorInternalNotificationBus::Broadcast(&EditorInternalNotificationBus::Events::OnEditorSettingsChanged, false, BuilderSettingManager::s_defaultPlatform); - } - - - void MipmapSettingWidget::AfterPropertyModified(AzToolsFramework::InstanceDataNode* /*pNode*/) - { - //Only the first texture setting reflected is changed, we need to propagate the change to every texture settings. - m_textureSetting->PropagateCommonSettings(); - m_ui->propertyEditor->InvalidateValues(); - EditorInternalNotificationBus::Broadcast(&EditorInternalNotificationBus::Events::OnEditorSettingsChanged, false, BuilderSettingManager::s_defaultPlatform); - } - - void MipmapSettingWidget::OnEditorSettingsChanged(bool needRefresh, const AZStd::string& /*platform*/) - { - if (needRefresh) - { - RefreshUI(); - } - } - -}//namespace ImageProcessingEditor -#include diff --git a/Gems/ImageProcessing/Code/Source/Editor/MipmapSettingWidget.h b/Gems/ImageProcessing/Code/Source/Editor/MipmapSettingWidget.h deleted file mode 100644 index 813c09eb77..0000000000 --- a/Gems/ImageProcessing/Code/Source/Editor/MipmapSettingWidget.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. -* -*/ - -#pragma once - -#if !defined(Q_MOC_RUN) -#include -#include -#include -#include -#endif - -namespace Ui -{ - class MipmapSettingWidget; -} - -namespace ImageProcessingEditor -{ - class MipmapSettingWidget - : public QWidget - , public AzToolsFramework::IPropertyEditorNotify - , protected EditorInternalNotificationBus::Handler - { - Q_OBJECT - public: - AZ_CLASS_ALLOCATOR(MipmapSettingWidget, AZ::SystemAllocator, 0); - explicit MipmapSettingWidget(EditorTextureSetting& textureSetting, QWidget* parent = nullptr); - ~MipmapSettingWidget(); - - //IPropertyEditorNotify Interface - void BeforePropertyModified([[maybe_unused]] AzToolsFramework::InstanceDataNode* pNode) override {} - void AfterPropertyModified(AzToolsFramework::InstanceDataNode* pNode) override; - void SetPropertyEditingActive([[maybe_unused]] AzToolsFramework::InstanceDataNode* pNode) override {} - void SetPropertyEditingComplete([[maybe_unused]] AzToolsFramework::InstanceDataNode* pNode) override {} - void SealUndoStack() override {} - - public slots: - void OnCheckBoxStateChanged(bool checked); - - protected: - //////////////////////////////////////////////////////////////////////// - //EditorInternalNotificationBus - void OnEditorSettingsChanged(bool needRefresh, const AZStd::string& platform); - //////////////////////////////////////////////////////////////////////// - - private: - void RefreshUI(); - QScopedPointer m_ui; - EditorTextureSetting* m_textureSetting; - }; -} //namespace ImageProcessingEditor - diff --git a/Gems/ImageProcessing/Code/Source/Editor/MipmapSettingWidget.ui b/Gems/ImageProcessing/Code/Source/Editor/MipmapSettingWidget.ui deleted file mode 100644 index bdab04033c..0000000000 --- a/Gems/ImageProcessing/Code/Source/Editor/MipmapSettingWidget.ui +++ /dev/null @@ -1,89 +0,0 @@ - - - MipmapSettingWidget - - - - 0 - 0 - 583 - 489 - - - - - 0 - 0 - - - - Form - - - - - - - - Mipmap Settings - - - - - - - Qt::Horizontal - - - - 40 - 20 - - - - - - - - Enable - - - - - - - - - - 0 - 0 - - - - - - - - Qt::Vertical - - - - 20 - 1 - - - - - - - - - AzToolsFramework::ReflectedPropertyEditor - QFrame -
AzToolsFramework/UI/PropertyEditor/ReflectedPropertyEditor.hxx
- 1 -
-
- - -
diff --git a/Gems/ImageProcessing/Code/Source/Editor/PresetInfoPopup.cpp b/Gems/ImageProcessing/Code/Source/Editor/PresetInfoPopup.cpp deleted file mode 100644 index e3fc2500c2..0000000000 --- a/Gems/ImageProcessing/Code/Source/Editor/PresetInfoPopup.cpp +++ /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. -* -*/ - -#include -#include "PresetInfoPopup.h" -#include -#include -#include -#include - -namespace ImageProcessingEditor -{ - using namespace ImageProcessing; - // Help functions to convert enum to strings - static const char* RGBWeightToString(RGBWeight weight) - { - static const char* RGBWeightNames[] = { "uniform", "luminance", "ciexyz" }; - AZ_Assert(weight <= RGBWeight::ciexyz, "Invalid RGBWeight!"); - return RGBWeightNames[(int)weight]; - } - - static const char* ColorSpaceToString(ColorSpace colorSpace) - { - static const char* colorSpaceNames[] = { "linear", "sRGB", "auto" }; - AZ_Assert(colorSpace <= ColorSpace::autoSelect, "Invalid ColorSpace!"); - return colorSpaceNames[(int)colorSpace]; - } - - static const char* MipGenTypeToString(MipGenType mipGenType) - { - static const char* mipGenTypeNames[] = { "point", "average", "linear" , "bilinear" , "gaussian" , "blackmanHarris", "kaiserSinc" }; - AZ_Assert(mipGenType <= MipGenType::kaiserSinc, "Invalid MipGenType!"); - return mipGenTypeNames[(int)mipGenType]; - } - - static const char* CubemapFilterTypeToString(CubemapFilterType cubemapFilterType) - { - static const char* cubemapFilterTypeNames[] = { "disc", "cone", "cosine" , "gaussian" , "cosine power" , "ggx" }; - AZ_Assert(cubemapFilterType <= CubemapFilterType::ggx, "Invalid CubemapFilterType!"); - return cubemapFilterTypeNames[(int)cubemapFilterType]; - } - - PresetInfoPopup::PresetInfoPopup(const PresetSettings* presetSettings, QWidget* parent /*= nullptr*/) - : AzQtComponents::StyledDialog(parent, Qt::Dialog | Qt::Popup) - , m_ui(new Ui::PresetInfoPopup) - { - m_ui->setupUi(this); - RefreshPresetInfoLabel(presetSettings); - } - - PresetInfoPopup::~PresetInfoPopup() - { - - } - void PresetInfoPopup::RefreshPresetInfoLabel(const PresetSettings* presetSettings) - { - - QString presetInfoText = ""; - if (!presetSettings) - { - presetInfoText = "Invalid Preset!"; - m_ui->infoLabel->setText(presetInfoText); - return; - } - - presetInfoText += QString("UUID: %1\n").arg(presetSettings->m_uuid.ToString().c_str()); - presetInfoText += QString("Name: %1\n").arg(presetSettings->m_name.c_str()); - presetInfoText += QString("RGB Weight: %1\n").arg(RGBWeightToString(presetSettings->m_rgbWeight)); - presetInfoText += QString("Source ColorSpace: %1\n").arg(ColorSpaceToString(presetSettings->m_srcColorSpace)); - presetInfoText += QString("Destination ColorSpace: %1\n").arg(ColorSpaceToString(presetSettings->m_destColorSpace)); - presetInfoText += QString("FileMasks: "); - int i = 0; - for (auto& mask : presetSettings->m_fileMasks) - { - presetInfoText += i > 0 ? ", " : ""; - presetInfoText += mask.c_str(); - i++; - } - presetInfoText += "\n"; - presetInfoText += QString("Suppress Engine Reduce: %1\n").arg(presetSettings->m_suppressEngineReduce ? "True" : "False"); - presetInfoText += QString("Discard Alpha: %1\n").arg(presetSettings->m_discardAlpha ? "True" : "False"); - presetInfoText += QString("Is Power Of 2: %1\n").arg(presetSettings->m_isPowerOf2 ? "True" : "False"); - presetInfoText += QString("Is Color Chart: %1\n").arg(presetSettings->m_isColorChart ? "True" : "False"); - presetInfoText += QString("High Pass Mip: %1\n").arg(presetSettings->m_highPassMip); - presetInfoText += QString("Gloss From Normal: %1\n").arg(presetSettings->m_glossFromNormals); - presetInfoText += QString("Use Legacy Gloss: %1\n").arg(presetSettings->m_isLegacyGloss ? "True" : "False"); - presetInfoText += QString("Mip Re-normalize: %1\n").arg(presetSettings->m_isMipRenormalize ? "True" : "False"); - presetInfoText += QString("Streamable Mips Number: %1\n").arg(presetSettings->m_numStreamableMips); - presetInfoText += QString("Swizzle: %1\n").arg(presetSettings->m_swizzle.c_str()); - if (presetSettings->m_cubemapSetting) - { - presetInfoText += QString("[Cubemap Settings]\n"); - presetInfoText += QString("Filter: %1\n").arg(CubemapFilterTypeToString(presetSettings->m_cubemapSetting->m_filter)); - presetInfoText += QString("Angle: %1\n").arg(presetSettings->m_cubemapSetting->m_angle); - presetInfoText += QString("Mip Angle: %1\n").arg(presetSettings->m_cubemapSetting->m_mipAngle); - presetInfoText += QString("Mip Slope: %1\n").arg(presetSettings->m_cubemapSetting->m_mipSlope); - presetInfoText += QString("Edge Fixup: %1\n").arg(presetSettings->m_cubemapSetting->m_edgeFixup); - presetInfoText += QString("Generate Diff: %1\n").arg(presetSettings->m_cubemapSetting->m_generateDiff ? "True" : "False"); - presetInfoText += QString("Diffuse Probe Preset: %1\n").arg(presetSettings->m_cubemapSetting->m_diffuseGenPreset.ToString().c_str()); - } - - if (presetSettings->m_mipmapSetting) - { - presetInfoText += QString("[MipMapSetting]\n"); - presetInfoText += QString("Type: %1\n").arg(MipGenTypeToString(presetSettings->m_mipmapSetting->m_type)); - } - - m_ui->infoLabel->setText(presetInfoText); - } -}//namespace ImageProcessingEditor -#include diff --git a/Gems/ImageProcessing/Code/Source/Editor/PresetInfoPopup.h b/Gems/ImageProcessing/Code/Source/Editor/PresetInfoPopup.h deleted file mode 100644 index 64fa666d25..0000000000 --- a/Gems/ImageProcessing/Code/Source/Editor/PresetInfoPopup.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 - - -#if !defined(Q_MOC_RUN) -#include -#include -#include -#endif - -namespace ImageProcessing -{ - class PresetSettings; -} -namespace Ui -{ - class PresetInfoPopup; -} - -namespace ImageProcessingEditor -{ - class PresetInfoPopup - : public AzQtComponents::StyledDialog - { - Q_OBJECT - public: - AZ_CLASS_ALLOCATOR(PresetInfoPopup, AZ::SystemAllocator, 0); - explicit PresetInfoPopup(const ImageProcessing::PresetSettings* preset, QWidget* parent = nullptr); - ~PresetInfoPopup(); - void RefreshPresetInfoLabel(const ImageProcessing::PresetSettings* presetSettings); - private: - QScopedPointer m_ui; - - - - }; -} //namespace ImageProcessingEditor - diff --git a/Gems/ImageProcessing/Code/Source/Editor/PresetInfoPopup.ui b/Gems/ImageProcessing/Code/Source/Editor/PresetInfoPopup.ui deleted file mode 100644 index fd52b34c8e..0000000000 --- a/Gems/ImageProcessing/Code/Source/Editor/PresetInfoPopup.ui +++ /dev/null @@ -1,83 +0,0 @@ - - - PresetInfoPopup - - - Qt::NonModal - - - - 0 - 0 - 300 - 400 - - - - - 0 - 0 - - - - - 0 - 0 - - - - Preset Info - - - false - - - false - - - - - - 10 - - - 10 - - - 10 - - - 10 - - - 10 - - - - - - 0 - 0 - - - - QFrame::NoFrame - - - QFrame::Plain - - - - - - Qt::AlignLeading|Qt::AlignLeft|Qt::AlignTop - - - - - - - - - - diff --git a/Gems/ImageProcessing/Code/Source/Editor/ResolutionSettingItemWidget.cpp b/Gems/ImageProcessing/Code/Source/Editor/ResolutionSettingItemWidget.cpp deleted file mode 100644 index 73340a45a7..0000000000 --- a/Gems/ImageProcessing/Code/Source/Editor/ResolutionSettingItemWidget.cpp +++ /dev/null @@ -1,145 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or 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 "ResolutionSettingItemWidget.h" -#include -#include - -#include -#include - -namespace ImageProcessingEditor -{ - using namespace ImageProcessing; - - ResolutionSettingItemWidget::ResolutionSettingItemWidget(ResoultionWidgetType type, QWidget* parent /*= nullptr*/) - : QWidget(parent) - , m_ui(new Ui::ResolutionSettingItemWidget) - { - m_ui->setupUi(this); - m_type = type; - - EditorInternalNotificationBus::Handler::BusConnect(); - } - - ResolutionSettingItemWidget::~ResolutionSettingItemWidget() - { - EditorInternalNotificationBus::Handler::BusDisconnect(); - } - - void ResolutionSettingItemWidget::Init(AZStd::string platform, EditorTextureSetting* editorTextureSetting) - { - m_platform = platform; - m_editorTextureSetting = editorTextureSetting; - m_textureSetting = &m_editorTextureSetting->m_settingsMap[m_platform]; - m_preset = BuilderSettingManager::Instance()->GetPreset(m_textureSetting->m_preset, platform); - SetupResolutionInfo(); - RefreshUI(); - if (m_type == ResoultionWidgetType::TexturePropety) - { - m_ui->formatLabel->show(); - m_ui->formatComboBox->hide(); - } - else - { - m_ui->formatLabel->hide(); - m_ui->formatComboBox->show(); - QObject::connect(m_ui->formatComboBox, static_cast(&QComboBox::currentIndexChanged), this, &ResolutionSettingItemWidget::OnChangeFormat); - } - QObject::connect(m_ui->downResSpinBox, static_cast(&QSpinBox::valueChanged), this, &ResolutionSettingItemWidget::OnChangeDownRes); - - } - - void ResolutionSettingItemWidget::RefreshUI() - { - m_ui->platformLabel->setText(EditorHelper::ToReadablePlatformString(m_platform).c_str()); - - m_ui->downResSpinBox->setRange(m_minReduce, m_maxReduce); - int clampedReduce = AZStd::min(AZStd::max(m_textureSetting->m_sizeReduceLevel, s_MinReduceLevel), s_MaxReduceLevel); - auto it = m_resolutionInfos.begin(); - it = AZStd::next(it, clampedReduce); - m_ui->downResSpinBox->setValue(it->reduce); - - QString finalResolution; - - if (it->arrayCount > 1) - { - finalResolution = QString("%1 x %2 x %3").arg(QString::number(it->width), QString::number(it->height), QString::number(it->arrayCount)); - } - else - { - finalResolution = QString("%1 x %2").arg(QString::number(it->width), QString::number(it->height)); - } - - m_ui->sizeLabel->setText(finalResolution); - - QString finalFormat = GetFinalFormat(m_textureSetting->m_preset); - if (m_type == ResoultionWidgetType::TexturePropety) - { - m_ui->formatLabel->setText(finalFormat); - } - else - { - SetupFormatComboBox(); - m_ui->formatComboBox->setCurrentText(finalFormat); - } - } - - void ResolutionSettingItemWidget::SetupResolutionInfo() - { - m_resolutionInfos = m_editorTextureSetting->GetResolutionInfo(m_platform, m_minReduce, m_maxReduce); - } - - void ResolutionSettingItemWidget::OnChangeDownRes(int downRes) - { - if ((unsigned int)downRes >= m_minReduce && (unsigned int)downRes <= m_maxReduce) - { - m_textureSetting->m_sizeReduceLevel = downRes; - RefreshUI(); - EditorInternalNotificationBus::Broadcast(&EditorInternalNotificationBus::Events::OnEditorSettingsChanged, false, m_platform); - } - } - - QString ResolutionSettingItemWidget::GetFinalFormat([[maybe_unused]] const AZ::Uuid& presetId) - { - if (m_preset && m_preset->m_pixelFormat >=0 && m_preset->m_pixelFormat < ePixelFormat_Count) - { - return EditorHelper::s_PixelFormatString[m_preset->m_pixelFormat]; - } - return QString(); - } - - - void ResolutionSettingItemWidget::SetupFormatComboBox() - { - m_ui->formatComboBox->clear(); - } - - void ResolutionSettingItemWidget::OnChangeFormat([[maybe_unused]] int index) - { - bool oldState = m_ui->formatComboBox->blockSignals(true); - m_ui->formatComboBox->blockSignals(oldState); - } - - void ResolutionSettingItemWidget::OnEditorSettingsChanged(bool needRefresh, const AZStd::string& /*platform*/) - { - if (needRefresh) - { - m_preset = BuilderSettingManager::Instance()->GetPreset(m_textureSetting->m_preset, m_platform); - SetupResolutionInfo(); - RefreshUI(); - } - } - -}//namespace ImageProcessingEditor -#include diff --git a/Gems/ImageProcessing/Code/Source/Editor/ResolutionSettingItemWidget.h b/Gems/ImageProcessing/Code/Source/Editor/ResolutionSettingItemWidget.h deleted file mode 100644 index ef86ad716e..0000000000 --- a/Gems/ImageProcessing/Code/Source/Editor/ResolutionSettingItemWidget.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. -* -*/ - -#pragma once - -#if !defined(Q_MOC_RUN) -#include -#include -#include -#endif - -namespace ImageProcessing -{ - class PresetSettings; -} -namespace Ui -{ - class ResolutionSettingItemWidget; -} - -namespace ImageProcessingEditor -{ - enum class ResoultionWidgetType - { - TexturePipeline, //Fully editable - TexturePropety, //Only DownRes is editable - }; - - class ResolutionSettingItemWidget - : public QWidget - , EditorInternalNotificationBus::Handler - { - Q_OBJECT - public: - - AZ_CLASS_ALLOCATOR(ResolutionSettingItemWidget, AZ::SystemAllocator, 0); - explicit ResolutionSettingItemWidget(ResoultionWidgetType type, QWidget* parent = nullptr); - ~ResolutionSettingItemWidget(); - void Init(AZStd::string platform, EditorTextureSetting* editorTextureSetting); - - public slots: - - void OnChangeDownRes(int downRes); - void OnChangeFormat(int index); - - protected: - //////////////////////////////////////////////////////////////////////// - //EditorInternalNotificationBus - void OnEditorSettingsChanged(bool needRefresh, const AZStd::string& platform); - //////////////////////////////////////////////////////////////////////// - - private: - - void SetupFormatComboBox(); - void SetupResolutionInfo(); - void RefreshUI(); - QString GetFinalFormat(const AZ::Uuid& presetId); - - QScopedPointer m_ui; - ResoultionWidgetType m_type; - AZStd::string m_platform; - ImageProcessing::TextureSettings* m_textureSetting; - EditorTextureSetting* m_editorTextureSetting; - const ImageProcessing::PresetSettings* m_preset; - //Cached list of calculated final resolution info based on different reduce levels - AZStd::list m_resolutionInfos; - //Final reduce level range - unsigned int m_maxReduce; - unsigned int m_minReduce; - }; -} //namespace ImageProcessingEditor - diff --git a/Gems/ImageProcessing/Code/Source/Editor/ResolutionSettingItemWidget.ui b/Gems/ImageProcessing/Code/Source/Editor/ResolutionSettingItemWidget.ui deleted file mode 100644 index 5e5055e382..0000000000 --- a/Gems/ImageProcessing/Code/Source/Editor/ResolutionSettingItemWidget.ui +++ /dev/null @@ -1,205 +0,0 @@ - - - ResolutionSettingItemWidget - - - - 0 - 0 - 400 - 20 - - - - - 0 - 0 - - - - - 400 - 0 - - - - - 400 - 20 - - - - Form - - - Qt::LeftToRight - - - - 0 - - - QLayout::SetDefaultConstraint - - - 0 - - - 0 - - - 0 - - - 0 - - - - - - 0 - 0 - - - - - 60 - 0 - - - - - 60 - 16777215 - - - - - 60 - 0 - - - - Provo - - - - - - - Qt::Horizontal - - - - 40 - 20 - - - - - - - - - 0 - 0 - - - - - 50 - 0 - - - - - 50 - 0 - - - - - - - - Qt::Horizontal - - - - 40 - 20 - - - - - - - - - 0 - 0 - - - - - 100 - 0 - - - - - 100 - 0 - - - - TextLabel - - - - - - - Qt::Horizontal - - - - 40 - 20 - - - - - - - - - 0 - 0 - - - - - 80 - 0 - - - - - 80 - 0 - - - - TextLabel - - - - - - - - - - - diff --git a/Gems/ImageProcessing/Code/Source/Editor/ResolutionSettingWidget.cpp b/Gems/ImageProcessing/Code/Source/Editor/ResolutionSettingWidget.cpp deleted file mode 100644 index 4fe8bdbb0b..0000000000 --- a/Gems/ImageProcessing/Code/Source/Editor/ResolutionSettingWidget.cpp +++ /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. -* -*/ - -#include -#include "ResolutionSettingWidget.h" -#include -#include - -namespace ImageProcessingEditor -{ - using namespace ImageProcessing; - ResolutionSettingWidget::ResolutionSettingWidget(ResoultionWidgetType type, EditorTextureSetting& textureSetting, QWidget* parent /*= nullptr*/) - : QWidget(parent) - , m_ui(new Ui::ResolutionSettingWidget) - , m_textureSetting(&textureSetting) - { - m_ui->setupUi(this); - m_type = type; - - //Put default platform in the first row - ResolutionSettingItemWidget* item = new ResolutionSettingItemWidget(ResoultionWidgetType::TexturePropety, this); - item->Init(BuilderSettingManager::s_defaultPlatform, m_textureSetting); - m_ui->listLayout->addWidget(item); - - //Add the other platforms in the list - for (auto& it : m_textureSetting->m_settingsMap) - { - AZStd::string platform = it.first; - if (platform != BuilderSettingManager::s_defaultPlatform) - { - ResolutionSettingItemWidget* item2 = new ResolutionSettingItemWidget(ResoultionWidgetType::TexturePropety, this); - item2->Init(platform, m_textureSetting); - m_ui->listLayout->addWidget(item2); - } - } - - // Tooltips - m_ui->downResLabel->setToolTip(QString("Adjust the resolution based on the target platform. \ - Use this setting to preserve the resolution of a source file even though it appears smaller in the game. \ - Select 0 to preserve the original size or 5 for the maximum reduction.")); - } - - ResolutionSettingWidget::~ResolutionSettingWidget() - { - - } - -}//namespace ImageProcessingEditor -#include diff --git a/Gems/ImageProcessing/Code/Source/Editor/ResolutionSettingWidget.h b/Gems/ImageProcessing/Code/Source/Editor/ResolutionSettingWidget.h deleted file mode 100644 index 1960130521..0000000000 --- a/Gems/ImageProcessing/Code/Source/Editor/ResolutionSettingWidget.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. -* -*/ - -#pragma once - -#if !defined(Q_MOC_RUN) -#include -#include -#include -#endif - -namespace Ui -{ - class ResolutionSettingWidget; -} - -namespace ImageProcessingEditor -{ - class ResolutionSettingWidget - : public QWidget - { - Q_OBJECT - public: - AZ_CLASS_ALLOCATOR(ResolutionSettingWidget, AZ::SystemAllocator, 0); - explicit ResolutionSettingWidget(ResoultionWidgetType type, EditorTextureSetting& texureSetting, QWidget* parent = nullptr); - ~ResolutionSettingWidget(); - - private: - QScopedPointer m_ui; - ResoultionWidgetType m_type; - EditorTextureSetting* m_textureSetting; - - }; -} //namespace ImageProcessingEditor - diff --git a/Gems/ImageProcessing/Code/Source/Editor/ResolutionSettingWidget.ui b/Gems/ImageProcessing/Code/Source/Editor/ResolutionSettingWidget.ui deleted file mode 100644 index d8987a37eb..0000000000 --- a/Gems/ImageProcessing/Code/Source/Editor/ResolutionSettingWidget.ui +++ /dev/null @@ -1,177 +0,0 @@ - - - ResolutionSettingWidget - - - - 0 - 0 - 550 - 300 - - - - - 0 - 0 - - - - - 0 - 0 - - - - Form - - - - - - 0 - - - - - 0 - - - QLayout::SetDefaultConstraint - - - - - - 0 - 0 - - - - - 60 - 0 - - - - - 60 - 16777215 - - - - - 60 - 0 - - - - Platform - - - - - - - Qt::Horizontal - - - - 40 - 20 - - - - - - - - - 0 - 0 - - - - - 50 - 0 - - - - DownRes - - - - - - - Qt::Horizontal - - - - 40 - 20 - - - - - - - - - 0 - 0 - - - - - 100 - 0 - - - - Size - - - - - - - Qt::Horizontal - - - - 40 - 20 - - - - - - - - - 0 - 0 - - - - - 80 - 0 - - - - Format - - - - - - - - - - - - diff --git a/Gems/ImageProcessing/Code/Source/Editor/TexturePresetSelectionWidget.cpp b/Gems/ImageProcessing/Code/Source/Editor/TexturePresetSelectionWidget.cpp deleted file mode 100644 index da78295c80..0000000000 --- a/Gems/ImageProcessing/Code/Source/Editor/TexturePresetSelectionWidget.cpp +++ /dev/null @@ -1,199 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or 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 "TexturePresetSelectionWidget.h" -#include - -#include -#include -#include -#include -#include - -namespace ImageProcessingEditor -{ - using namespace ImageProcessing; - TexturePresetSelectionWidget::TexturePresetSelectionWidget(EditorTextureSetting& textureSetting, QWidget* parent /*= nullptr*/) - : QWidget(parent) - , m_ui(new Ui::TexturePresetSelectionWidget) - , m_textureSetting(&textureSetting) - { - m_ui->setupUi(this); - - // Add presets into combo box - m_presetList.clear(); - auto& presetFilterMap = BuilderSettingManager::Instance()->GetPresetFilterMap(); - - AZStd::set noFilterPresetList; - - // Check if there is any filtered preset list first - for(auto& presetFilter : presetFilterMap) - { - if (presetFilter.first.empty()) - { - noFilterPresetList = presetFilter.second; - } - else if (IsMatchingWithFileMask(m_textureSetting->m_textureName, presetFilter.first)) - { - for(const AZStd::string& presetName : presetFilter.second) - { - m_presetList.insert(presetName); - } - } - } - // If no filtered preset list available or should list all presets, use non-filter list - if (m_presetList.size() == 0 || m_listAllPresets) - { - m_presetList = noFilterPresetList; - } - - foreach (const AZStd::string& presetName, m_presetList) - { - m_ui->presetComboBox->addItem(QString(presetName.c_str())); - } - - // Set current preset - const AZ::Uuid& currPreset = m_textureSetting->GetMultiplatformTextureSetting().m_preset; - const PresetSettings* presetSetting = BuilderSettingManager::Instance()->GetPreset(currPreset); - - if (presetSetting) - { - m_ui->presetComboBox->setCurrentText(presetSetting->m_name.c_str()); - QObject::connect(m_ui->presetComboBox, static_cast(&QComboBox::currentIndexChanged), this, &TexturePresetSelectionWidget::OnChangePreset); - - // Suppress engine reduction checkbox - m_ui->serCheckBox->setCheckState(m_textureSetting->GetMultiplatformTextureSetting().m_suppressEngineReduce ? Qt::CheckState::Checked : Qt::CheckState::Unchecked); - - SetCheckBoxReadOnly(m_ui->serCheckBox, presetSetting->m_suppressEngineReduce); - QObject::connect(m_ui->serCheckBox, &QCheckBox::clicked, this, &TexturePresetSelectionWidget::OnCheckBoxStateChanged); - - // Set convention label - SetPresetConvention(presetSetting); - } - - // Reset btn - QObject::connect(m_ui->resetBtn, &QPushButton::clicked, this, &TexturePresetSelectionWidget::OnRestButton); - - // PresetInfo btn - QObject::connect(m_ui->infoBtn, &QPushButton::clicked, this, &TexturePresetSelectionWidget::OnPresetInfoButton); - - // Tooltips - m_ui->activeFileConventionLabel->setToolTip(QString("Displays the supported naming convention for the selected preset.")); - m_ui->presetComboBox->setToolTip(QString("Choose a preset to update the preview and other properties.")); - m_ui->resetBtn->setToolTip(QString("Reset values to current preset defaults.")); - m_ui->serCheckBox->setToolTip(QString("Preserves the original size. Use this setting for textures that include text.")); - m_ui->infoBtn->setToolTip(QString("Show detail properties of the current preset")); - - EditorInternalNotificationBus::Handler::BusConnect(); - } - - TexturePresetSelectionWidget::~TexturePresetSelectionWidget() - { - EditorInternalNotificationBus::Handler::BusDisconnect(); - } - - void TexturePresetSelectionWidget::OnCheckBoxStateChanged(bool checked) - { - for (auto& it : m_textureSetting->m_settingsMap) - { - it.second.m_suppressEngineReduce = checked; - } - m_textureSetting->SetIsOverrided(); - EditorInternalNotificationBus::Broadcast(&EditorInternalNotificationBus::Events::OnEditorSettingsChanged, false, BuilderSettingManager::s_defaultPlatform); - } - - void TexturePresetSelectionWidget::OnRestButton() - { - m_textureSetting->SetToPreset(AZStd::string(m_ui->presetComboBox->currentText().toUtf8().data())); - EditorInternalNotificationBus::Broadcast(&EditorInternalNotificationBus::Events::OnEditorSettingsChanged, true, BuilderSettingManager::s_defaultPlatform); - } - - void TexturePresetSelectionWidget::OnChangePreset(int index) - { - QString text = m_ui->presetComboBox->itemText(index); - m_textureSetting->SetToPreset(AZStd::string(text.toUtf8().data())); - EditorInternalNotificationBus::Broadcast(&EditorInternalNotificationBus::Events::OnEditorSettingsChanged, true, BuilderSettingManager::s_defaultPlatform); - } - - void ImageProcessingEditor::TexturePresetSelectionWidget::OnPresetInfoButton() - { - const AZ::Uuid& currPreset = m_textureSetting->GetMultiplatformTextureSetting().m_preset; - const PresetSettings* presetSetting = BuilderSettingManager::Instance()->GetPreset(currPreset); - m_presetPopup.reset(new PresetInfoPopup(presetSetting, this)); - m_presetPopup->installEventFilter(this); - m_presetPopup->show(); - } - - void TexturePresetSelectionWidget::OnEditorSettingsChanged(bool needRefresh, const AZStd::string& /*platform*/) - { - if (needRefresh) - { - bool oldState = m_ui->serCheckBox->blockSignals(true); - m_ui->serCheckBox->setChecked(m_textureSetting->GetMultiplatformTextureSetting().m_suppressEngineReduce); - // If the preset's SER is true, texture setting should not override - const AZ::Uuid& currPreset = m_textureSetting->GetMultiplatformTextureSetting().m_preset; - const PresetSettings* presetSetting = BuilderSettingManager::Instance()->GetPreset(currPreset); - if (presetSetting) - { - SetCheckBoxReadOnly(m_ui->serCheckBox, presetSetting->m_suppressEngineReduce); - SetPresetConvention(presetSetting); - // If there is preset info dialog open, update the text - if (m_presetPopup && m_presetPopup->isVisible()) - { - m_presetPopup->RefreshPresetInfoLabel(presetSetting); - } - } - m_ui->serCheckBox->blockSignals(oldState); - } - } - - bool TexturePresetSelectionWidget::IsMatchingWithFileMask(const AZStd::string& filename, const AZStd::string& fileMask) - { - if (fileMask.empty()) - { - // Will not match with empty string - return false; - } - else - { - // Extract the file name and compare if it ends with file mask or not - AZStd::string filenameNoExt; - AzFramework::StringFunc::Path::GetFileName(filename.c_str(), filenameNoExt); - return filenameNoExt.length() >= fileMask.length() && filenameNoExt.compare(filenameNoExt.length() - fileMask.length(), fileMask.length(), fileMask) == 0; - } - } - - void ImageProcessingEditor::TexturePresetSelectionWidget::SetPresetConvention(const PresetSettings* presetSettings) - { - AZStd::string conventionText = ""; - if (presetSettings) - { - int i = 0; - for (const PlatformName& filemask : presetSettings->m_fileMasks) - { - conventionText += i > 0 ? " " + filemask : filemask; - i++; - } - } - m_ui->conventionLabel->setText(QString(conventionText.c_str())); - } - - void ImageProcessingEditor::TexturePresetSelectionWidget::SetCheckBoxReadOnly(QCheckBox* checkBox, bool readOnly) - { - checkBox->setAttribute(Qt::WA_TransparentForMouseEvents, readOnly); - checkBox->setFocusPolicy(readOnly ? Qt::NoFocus : Qt::StrongFocus); - checkBox->setEnabled(!readOnly); - } - -}//namespace ImageProcessingEditor -#include diff --git a/Gems/ImageProcessing/Code/Source/Editor/TexturePresetSelectionWidget.h b/Gems/ImageProcessing/Code/Source/Editor/TexturePresetSelectionWidget.h deleted file mode 100644 index c490fdbf1f..0000000000 --- a/Gems/ImageProcessing/Code/Source/Editor/TexturePresetSelectionWidget.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. -* -*/ - -#pragma once - -#if !defined(Q_MOC_RUN) -#include -#include -#include -#include -#include -#endif - -class QCheckBox; -namespace Ui -{ - class TexturePresetSelectionWidget; -} - -namespace ImageProcessingEditor -{ - class TexturePresetSelectionWidget - : public QWidget - , protected EditorInternalNotificationBus::Handler - { - Q_OBJECT - public: - AZ_CLASS_ALLOCATOR(TexturePresetSelectionWidget, AZ::SystemAllocator, 0); - explicit TexturePresetSelectionWidget(EditorTextureSetting& texureSetting, QWidget* parent = nullptr); - ~TexturePresetSelectionWidget(); - - public slots: - void OnCheckBoxStateChanged(bool checked); - void OnRestButton(); - void OnChangePreset(int index); - void OnPresetInfoButton(); - - protected: - //////////////////////////////////////////////////////////////////////// - //EditorInternalNotificationBus - void OnEditorSettingsChanged(bool needRefresh, const AZStd::string& platform); - //////////////////////////////////////////////////////////////////////// - - private: - QScopedPointer m_ui; - AZStd::set m_presetList; - EditorTextureSetting* m_textureSetting; - QScopedPointer m_presetPopup; - bool IsMatchingWithFileMask(const AZStd::string& filename, const AZStd::string& fileMask); - void SetPresetConvention(const ImageProcessing::PresetSettings* presetSettings); - void SetCheckBoxReadOnly(QCheckBox* checkBox, bool readOnly); - - bool m_listAllPresets = true; - }; -} //namespace ImageProcessingEditor - diff --git a/Gems/ImageProcessing/Code/Source/Editor/TexturePresetSelectionWidget.ui b/Gems/ImageProcessing/Code/Source/Editor/TexturePresetSelectionWidget.ui deleted file mode 100644 index 73a7741dde..0000000000 --- a/Gems/ImageProcessing/Code/Source/Editor/TexturePresetSelectionWidget.ui +++ /dev/null @@ -1,91 +0,0 @@ - - - TexturePresetSelectionWidget - - - - 0 - 0 - 624 - 118 - - - - Form - - - - - - - - - - - - - Active file conventions - - - - - - - Texture presets - - - - - - - - - - Active preset - - - - - - - - - - - :/Reset.png - - - - - - - - Suppress spec reduction - - - - - - - - - - - :/info.png - - - - - 16 - 16 - - - - - - - - - - - diff --git a/Gems/ImageProcessing/Code/Source/Editor/TexturePreviewWidget.cpp b/Gems/ImageProcessing/Code/Source/Editor/TexturePreviewWidget.cpp deleted file mode 100644 index 8a1cd3b650..0000000000 --- a/Gems/ImageProcessing/Code/Source/Editor/TexturePreviewWidget.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. -* -*/ - -#include -#include "TexturePreviewWidget.h" -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace ImageProcessingEditor -{ - using namespace ImageProcessing; - - TexturePreviewWidget::TexturePreviewWidget(EditorTextureSetting& texureSetting, QWidget* parent /*= nullptr*/) - : QWidget(parent) - , m_ui(new Ui::TexturePreviewWidget) - , m_textureSetting(&texureSetting) - { - m_ui->setupUi(this); - - m_platform = BuilderSettingManager::s_defaultPlatform; - // For now, only provide preview for default platform - m_previewConverter = AZStd::make_unique(m_textureSetting->m_fullPath, &m_textureSetting->GetMultiplatformTextureSetting()); - - m_updateTimer = new QTimer(this); - connect(m_updateTimer, &QTimer::timeout, this, &TexturePreviewWidget::UpdatePreview); - m_updateTimer->setSingleShot(false); - - m_ui->infoLayer->setAttribute(Qt::WA_NoSystemBackground); - m_ui->mipLevelLabel->setAttribute(Qt::WA_NoSystemBackground); - m_ui->imageSizeLabel->setAttribute(Qt::WA_NoSystemBackground); - m_ui->fileSizeLabel->setAttribute(Qt::WA_NoSystemBackground); - - // Setup preview mode combo box - static const QString previewModeString[] = { "RGB", - "R", - "G", - "B", - "Alpha", - "RGBA" }; - - for (int i = 0; i < (int)PreviewMode::Count; i ++) - { - m_ui->previewComboBox->addItem(previewModeString[i]); - } - - QSize size = m_ui->imageLabel->size(); - m_imageLabelSize = aznumeric_cast(size.width()); - - SetUpResolutionInfo(); - RefreshUI(true); - - QObject::connect(m_ui->previewCheckBox, &QCheckBox::clicked, this, &TexturePreviewWidget::OnTiledChanged); - QObject::connect(m_ui->nextMipBtn, &QPushButton::clicked, this, &TexturePreviewWidget::OnNextMip); - QObject::connect(m_ui->prevMipBtn, &QPushButton::clicked, this, &TexturePreviewWidget::OnPrevMip); - QObject::connect(m_ui->previewComboBox, static_cast(&QComboBox::currentIndexChanged), this, &TexturePreviewWidget::OnChangePreviewMode); - - // Set up Refresh button - m_alwaysRefreshAction = new QAction("Always refresh preview", this); - m_alwaysRefreshAction->setCheckable(true); - m_alwaysRefreshAction->setChecked(m_alwaysRefreshPreview); - QObject::connect(m_alwaysRefreshAction, &QAction::triggered, this, &TexturePreviewWidget::OnAlwaysRefresh); - - m_refreshPerClickAction = new QAction("Press to refresh preview", this); - m_refreshPerClickAction->setCheckable(true); - m_refreshPerClickAction->setChecked(!m_alwaysRefreshPreview); - QObject::connect(m_refreshPerClickAction, &QAction::triggered, this, &TexturePreviewWidget::OnRefreshPerClick); - - QMenu* menu = new QMenu(this); - menu->addAction(m_alwaysRefreshAction); - menu->addAction(m_refreshPerClickAction); - - m_ui->refreshBtn->setMenu(menu); - AzQtComponents::PushButton::applySmallIconStyle(m_ui->refreshBtn); - - QObject::connect(m_ui->refreshBtn, &QPushButton::clicked, this, &TexturePreviewWidget::OnRefreshClicked); - m_alwaysRefreshIcon.addFile(QStringLiteral(":/refresh.png"), QSize(), QIcon::Normal, QIcon::On); - m_refreshPerClickIcon.addFile(QStringLiteral(":/refresh-active.png"), QSize(), QIcon::Normal, QIcon::On); - m_ui->refreshBtn->setIcon(m_alwaysRefreshIcon); - - m_ui->busyLabel->SetBusyIconSize(16); - SetImageLabelText(QString(), false); - - // Tooltips - m_ui->previewComboBox->setToolTip(QString("Preview the texture in different channels.")); - m_ui->previewCheckBox->setToolTip(QString("Show or hide a 2x2 tiling of the texture.")); - m_ui->hotkeyLabel->setToolTip(QString("Preview different texture states with keyboard shortcuts.")); - m_ui->refreshBtn->setToolTip(QString("Provide different ways to refresh the preview. Click on the button to refresh manually.")); - - EditorInternalNotificationBus::Handler::BusConnect(); - } - - TexturePreviewWidget::~TexturePreviewWidget() - { - EditorInternalNotificationBus::Handler::BusDisconnect(); - } - - void TexturePreviewWidget::resizeEvent(QResizeEvent *event) - { - QWidget::resizeEvent(event); - - QSize size = m_ui->mainWidget->size(); - m_ui->infoLayer->resize(size); - - QSize imageSize = m_ui->imageLabel->size(); - QPoint center = m_ui->mainWidget->rect().center(); - m_ui->imageLabel->move(center - QPoint(imageSize.width() / 2, imageSize.height() / 2)); - QSize busyLabelSize = m_ui->busyLabel->size(); - m_ui->busyLabel->move(center - QPoint(busyLabelSize.width() + m_ui->imageLabel->sizeHint().width() / 2, busyLabelSize.width() / 2)); - } - - void TexturePreviewWidget::SetUpResolutionInfo() - { - m_resolutionInfos = m_textureSetting->GetResolutionInfoForMipmap(m_platform); - m_mipCount = (unsigned int)m_resolutionInfos.size(); - if (m_currentMipIndex > (int)m_mipCount) - { - m_currentMipIndex = 0; - } - } - - void TexturePreviewWidget::OnEditorSettingsChanged([[maybe_unused]] bool needRefresh, const AZStd::string& platform) - { - // Only update the preview if there is any change in current platform - if (platform == m_platform) - { - SetUpResolutionInfo(); - RefreshUI(true); - } - } - - void TexturePreviewWidget::RefreshUI(bool fullRefresh) - { - m_ui->mipLevelLabel->setText(QString("Mip %1").arg(QString::number(m_currentMipIndex))); - m_ui->previewCheckBox->setCheckState(m_previewTiled ? Qt::CheckState::Checked : Qt::CheckState::Unchecked); - - bool hasNextMip = m_currentMipIndex < (int)m_mipCount - 1; - m_ui->nextMipBtn->setVisible(hasNextMip); - - bool hasPrevMip = m_currentMipIndex > 0; - m_ui->prevMipBtn->setVisible(hasPrevMip); - - RefreshWarning(); - - if (m_currentMipIndex < m_resolutionInfos.size()) - { - auto it = AZStd::next(m_resolutionInfos.begin(), m_currentMipIndex); - QString finalResolution; - if (it->arrayCount > 1) - { - finalResolution = QString("Image Size: %1 x %2 x %3").arg(QString::number(it->width), QString::number(it->height), QString::number(it->arrayCount)); - } - else - { - finalResolution = QString("Image Size: %1 x %2").arg(QString::number(it->width), QString::number(it->height)); - } - m_ui->imageSizeLabel->setText(finalResolution); - - CPixelFormats& pixelFormats = CPixelFormats::GetInstance(); - const PresetSettings* preset = BuilderSettingManager::Instance()->GetPreset(m_textureSetting->GetMultiplatformTextureSetting().m_preset); - if (preset) - { - uint32 size = pixelFormats.EvaluateImageDataSize(preset->m_pixelFormat, it->width, it->height) * it->arrayCount; - AZStd::string fileSizeString = EditorHelper::GetFileSizeString(size); - QString finalFileSize = QString("File Size: %1").arg(fileSizeString.c_str()); - m_ui->fileSizeLabel->setText(finalFileSize); - } - - if (m_alwaysRefreshPreview) - { - RefreshPreviewImage(fullRefresh ? RefreshMode::Convert : RefreshMode::Mip); - } - - } - else - { - AZ_Error("Texture Setting", false, "Cannot find mip reduce level for mip %d", m_currentMipIndex); - } - } - - void TexturePreviewWidget::OnNextMip() - { - if (m_currentMipIndex >= (int)m_mipCount - 1) - { - return; - } - m_currentMipIndex ++; - RefreshUI(false); - } - - - void TexturePreviewWidget::OnPrevMip() - { - if (m_currentMipIndex <= 0) - { - return; - } - - m_currentMipIndex--; - RefreshUI(false); - } - - void TexturePreviewWidget::UpdatePreview() - { - if (!m_previewConverter->IsDone()) - { - float progress = m_previewConverter->GetProgress(); - SetImageLabelText(QString("Converting for preview...Progress %1%").arg(QString::number(progress * 100, 'f', 2))); - return; - } - - m_updateTimer->stop(); - m_previewImageRaw = m_previewConverter->GetOutputImage(); - - GenerateMipmap(m_currentMipIndex); - GenerateChannelImage(m_previewMode); - PaintPreviewImage(); - } - - void TexturePreviewWidget::OnAlwaysRefresh() - { - m_alwaysRefreshPreview = true; - m_alwaysRefreshAction->setChecked(true); - m_refreshPerClickAction->setChecked(false); - - m_ui->refreshBtn->setIcon(m_alwaysRefreshIcon); - } - - void TexturePreviewWidget::OnRefreshPerClick() - { - m_alwaysRefreshPreview = false; - m_alwaysRefreshAction->setChecked(false); - m_refreshPerClickAction->setChecked(true); - - m_ui->refreshBtn->setIcon(m_refreshPerClickIcon); - } - - void TexturePreviewWidget::OnRefreshClicked() - { - RefreshPreviewImage(RefreshMode::Convert); - } - - void TexturePreviewWidget::GenerateMipmap(int mip) - { - // Clear all cached preview images - for (int i = 0; i < (int)PreviewMode::Count; i++) - { - m_previewImages[i] = QImage(); - } - - if (m_previewImageRaw && (AZ::u32)mip < m_previewImageRaw->GetMipCount() ) - { - uint8* imageBuf; - uint32 pitch; - m_previewImageRaw->GetImagePointer(mip, imageBuf, pitch); - const uint32 width = m_previewImageRaw->GetWidth(mip); - const uint32 height = m_previewImageRaw->GetHeight(mip); - m_previewImages[PreviewMode::RGBA] = QImage(imageBuf, width, height, pitch, QImage::Format_RGBA8888); - } - else - { - AZ_Error("Texture Editor", false, "Cannot generate mip preview from an invalid image."); - } - - } - - void TexturePreviewWidget::GenerateChannelImage(PreviewMode channel) - { - // If there is no preview image generated, ignore this function - if (m_previewImages[PreviewMode::RGBA].isNull()) - { - AZ_Error("Texture Editor", false, "Cannot generate channel image from an invalid image."); - return; - } - - if (m_previewImages[channel].isNull()) - { - // Copy the RGBA image before changing the color - QImage previewImg = m_previewImages[PreviewMode::RGBA].copy(); - for (int x = 0; x < previewImg.width(); x++) - { - for (int y = 0; y < previewImg.height(); y++) - { - QRgb pixel = previewImg.pixel(x, y); - int r = qRed(pixel); - int g = qGreen(pixel); - int b = qBlue(pixel); - int a = qAlpha(pixel); - - switch (channel) - { - case ImageProcessingEditor::RGB: - pixel = qRgba(r, g, b, 255); - break; - case ImageProcessingEditor::RRR: - pixel = qRgba(r, r, r, 255); - break; - case ImageProcessingEditor::GGG: - pixel = qRgba(g, g, g, 255); - break; - case ImageProcessingEditor::BBB: - pixel = qRgba(b, b, b, 255); - break; - case ImageProcessingEditor::Alpha: - pixel = qRgba(a, a, a, 255); - break; - default: - break; - } - - previewImg.setPixel(x, y, pixel); - } - } - // Cache the image in current preview mode - m_previewImages[channel] = previewImg; - } - } - - void TexturePreviewWidget::RefreshPreviewImage(RefreshMode mode) - { - // Ignore any none-conversion refresh request when the image is being converted - if (m_updateTimer->isActive() && mode != RefreshMode::Convert) - { - return; - } - - switch (mode) - { - case RefreshMode::Convert: - { - // Start conversion in a AZ::Job - m_previewConverter->StartConvert(); - // Start the timer to trigger the update function - m_updateTimer->start(s_updateInterval); - SetImageLabelText(QString("Converting for preview...Progress 0.01%")); - } - break; - case RefreshMode::Mip: - { - GenerateMipmap(m_currentMipIndex); - GenerateChannelImage(m_previewMode); - PaintPreviewImage(); - } - break; - case RefreshMode::Channel: - { - GenerateChannelImage(m_previewMode); - PaintPreviewImage(); - } - break; - default: - PaintPreviewImage(); - break; - } - } - - void TexturePreviewWidget::PaintPreviewImage() - { - if (m_previewImages[m_previewMode].isNull()) - { - SetImageLabelText(QString("Conversion failed, please check console for more information."), false); - return; - } - SetImageLabelText(QString(), false); - - // Paint the image on to the image label - QPixmap pixMap = QPixmap::fromImage(m_previewImages[m_previewMode]); - QSize size = m_ui->imageLabel->size(); - QPixmap finalPix = pixMap.copy(); - finalPix.fill(Qt::transparent); - finalPix = finalPix.scaled(size, Qt::KeepAspectRatio, Qt::SmoothTransformation); - QPainter painter(&finalPix); - painter.setCompositionMode(QPainter::CompositionMode_DestinationOver); - QRect rect = finalPix.rect(); - if (m_previewTiled) - { - pixMap = pixMap.scaled(size / 2, Qt::KeepAspectRatio, Qt::SmoothTransformation); - painter.drawTiledPixmap(rect, pixMap); - } - else - { - painter.drawPixmap(rect, pixMap); - } - // Recenter the image label - float aspectRatio = static_cast(finalPix.width()) / static_cast(finalPix.height()); - QSize preferredSize; - if (aspectRatio >= 1.0f) - { - preferredSize = QSize(aznumeric_cast(m_imageLabelSize), aznumeric_cast(m_imageLabelSize / aspectRatio)); - } - else - { - preferredSize = QSize(aznumeric_cast(m_imageLabelSize * aspectRatio), aznumeric_cast(m_imageLabelSize)); - } - - m_ui->imageLabel->resize(preferredSize); - m_ui->imageLabel->setPixmap(finalPix); - - QPoint center = m_ui->mainWidget->rect().center(); - m_ui->imageLabel->move(center - QPoint(preferredSize.width() / 2, preferredSize.height() / 2)); - - } - - void TexturePreviewWidget::SetImageLabelText(const QString& text, bool busyStatus /*= true*/) - { - // Since setting pixmap will change the label size - // Need to set back to initial size and recenter before displaying text - m_ui->imageLabel->resize(QSize(aznumeric_cast(m_imageLabelSize), aznumeric_cast(m_imageLabelSize))); - QPoint center = m_ui->mainWidget->rect().center(); - m_ui->imageLabel->move(center - QPoint(aznumeric_cast(m_imageLabelSize / 2), aznumeric_cast(m_imageLabelSize / 2))); - m_ui->imageLabel->setText(text); - - // Set busy label status and position to align with the text - m_ui->busyLabel->SetIsBusy(busyStatus); - QSize size = m_ui->busyLabel->size(); - m_ui->busyLabel->move(center - QPoint(size.width() + m_ui->imageLabel->sizeHint().width() / 2, size.width() / 2)); - m_ui->busyLabel->setVisible(busyStatus); - } - - void TexturePreviewWidget::RefreshWarning() - { - int imageWidth = m_textureSetting->m_img->GetWidth(0); - int imageHeight = m_textureSetting->m_img->GetHeight(0); - AZStd::list stretchedPlatform; - - for (auto& iter: m_textureSetting->m_settingsMap) - { - PlatformName platform = iter.first; - const PresetSettings* presetSettings = BuilderSettingManager::Instance()->GetPreset(iter.second.m_preset, platform); - if (presetSettings) - { - EPixelFormat dstFmt = presetSettings->m_pixelFormat; - if (!CPixelFormats::GetInstance().IsImageSizeValid(dstFmt, imageWidth, imageHeight, false)) - { - stretchedPlatform.push_back(EditorHelper::ToReadablePlatformString(platform).c_str()); - } - } - } - - if (stretchedPlatform.size() > 0) - { - QString warningText = QString("The output image will be stretched on Platform:"); - int i = 0; - for (AZStd::string platform: stretchedPlatform) - { - warningText += i > 0 ? ", " : " "; - warningText += platform.c_str(); - i ++; - } - m_ui->warningLabel->setText(warningText); - m_ui->warningLabel->setVisible(true); - m_ui->warningIcon->setVisible(true); - } - else - { - m_ui->warningLabel->setVisible(false); - m_ui->warningIcon->setVisible(false); - } - } - - void TexturePreviewWidget::OnChangePreviewMode(int index) - { - if (index < (int)PreviewMode::Count) - { - m_previewMode = (PreviewMode)index; - - RefreshPreviewImage(RefreshMode::Channel); - } - } - - void TexturePreviewWidget::OnTiledChanged(bool checked) - { - m_previewTiled = checked; - RefreshPreviewImage(RefreshMode::Repaint); - } - - bool TexturePreviewWidget::OnQtEvent(QEvent * event) - { - if (event->type() == QEvent::KeyPress) - { - const QKeyEvent* ke = static_cast(event); - if (ke->isAutoRepeat()) - { - return false; //ignore repeat key event - } - - if (ke->key() == Qt::Key_Space) - { - if (!m_updateTimer->isActive()) // Only popup when image is not converting - { - m_previewPopup.reset(new ImagePopup(m_previewImages[m_previewMode], this)); - m_previewPopup->installEventFilter(this); - m_previewPopup->show(); - event->accept(); - return true; - } - } - else if (ke->key() == Qt::Key_Alt) - { - m_previewMode = PreviewMode::Alpha; - RefreshPreviewImage(RefreshMode::Channel); - event->accept(); - return true; - } - else if (ke->key() == Qt::Key_Shift) - { - m_previewMode = PreviewMode::RGBA; - RefreshPreviewImage(RefreshMode::Channel); - event->accept(); - return true; - } - } - else if (event->type() == QEvent::KeyRelease) - { - const QKeyEvent* ke = static_cast(event); - if (ke->isAutoRepeat()) - { - return false; //ignore repeat key event - } - if (ke->key() == Qt::Key_Space) - { - if (m_previewPopup) - { - m_previewPopup->hide(); - } - event->accept(); - return true; - } - else if (ke->key() == Qt::Key_Alt) - { - m_previewMode = (PreviewMode)m_ui->previewComboBox->currentIndex(); - RefreshPreviewImage(RefreshMode::Channel); - event->accept(); - return true; - } - else if (ke->key() == Qt::Key_Shift) - { - m_previewMode = (PreviewMode)m_ui->previewComboBox->currentIndex(); - RefreshPreviewImage(RefreshMode::Channel); - event->accept(); - return true; - } - } - else if (event->type() == QEvent::ApplicationStateChange) - { - const QApplicationStateChangeEvent* appEvent = static_cast(event); - AZ_Warning("Texture Editor", false, "app status change %d", appEvent->applicationState()); - if (appEvent->applicationState() != Qt::ApplicationState::ApplicationActive) - { - PreviewMode currPreviewMode = (PreviewMode)m_ui->previewComboBox->currentIndex(); - if (m_previewMode != currPreviewMode) - { - m_previewMode = currPreviewMode; - RefreshPreviewImage(RefreshMode::Channel); - event->accept(); - return true; - } - } - } - else if (event->type() == QEvent::ShortcutOverride) - { - // since we respond to the following things, let Qt know so that shortcuts don't override us - - QKeyEvent* kev = static_cast(event); - int key = kev->key() | kev->modifiers(); - switch (key) - { - case Qt::Key_Space: - case Qt::Key_Alt: - case Qt::Key_Shift: - event->accept(); - return true; - break; - - default: - break; - } - } - return false; - } - - bool TexturePreviewWidget::eventFilter(QObject* obj, QEvent* event) - { - if (event->type() == QEvent::KeyRelease) - { - const QKeyEvent* ke = static_cast(event); - if (ke->key() == Qt::Key_Space && !ke->isAutoRepeat()) - { - if (m_previewPopup) - { - m_previewPopup->hide(); - } - return true; - } - } - else if (event->type() == QEvent::ApplicationStateChange) - { - const QApplicationStateChangeEvent* appEvent = static_cast(event); - if (appEvent->applicationState() != Qt::ApplicationState::ApplicationActive) - { - if (m_previewPopup) - { - m_previewPopup->hide(); - } - } - return true; - } - - return QWidget::eventFilter(obj, event); - } - -}//namespace ImageProcessingEditor -#include diff --git a/Gems/ImageProcessing/Code/Source/Editor/TexturePreviewWidget.h b/Gems/ImageProcessing/Code/Source/Editor/TexturePreviewWidget.h deleted file mode 100644 index 84ef09d366..0000000000 --- a/Gems/ImageProcessing/Code/Source/Editor/TexturePreviewWidget.h +++ /dev/null @@ -1,121 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or 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 -#include - -#include -#endif - -namespace Ui -{ - class TexturePreviewWidget; -} - -namespace ImageProcessingEditor -{ - enum PreviewMode - { - RGB = 0, - RRR, - GGG, - BBB, - Alpha, - RGBA, - Count - }; - - enum class RefreshMode - { - Convert, // Convert the whole image from beginning, takes longest time - Mip, // Generate a new mip from from converted image - Channel, // Generate a new channel image from converted image - Repaint, - }; - - class TexturePreviewWidget - : public QWidget - , protected EditorInternalNotificationBus::Handler - { - Q_OBJECT - public: - AZ_CLASS_ALLOCATOR(TexturePreviewWidget, AZ::SystemAllocator, 0); - explicit TexturePreviewWidget(EditorTextureSetting& texureSetting, QWidget* parent = 0); - ~TexturePreviewWidget(); - bool OnQtEvent(QEvent* event); - - public slots: - void OnTiledChanged(bool checked); - void OnPrevMip(); - void OnNextMip(); - void OnChangePreviewMode(int index); - void UpdatePreview(); - void OnAlwaysRefresh(); - void OnRefreshPerClick(); - void OnRefreshClicked(); - - protected: - //////////////////////////////////////////////////////////////////////// - //EditorInternalNotificationBus - void OnEditorSettingsChanged(bool needRefresh, const AZStd::string& platform); - //////////////////////////////////////////////////////////////////////// - void resizeEvent(QResizeEvent *event) override; - bool eventFilter(QObject* obj, QEvent* event) override; - - private: - void SetUpResolutionInfo(); - void RefreshUI(bool fullRefresh = false); - void RefreshPreviewImage(RefreshMode mode); - void GenerateMipmap(int mip); - void GenerateChannelImage(PreviewMode channel); - void PaintPreviewImage(); - void SetImageLabelText(const QString& text, bool busyStatus = true); - void RefreshWarning(); - - AZStd::list m_resolutionInfos; - QScopedPointer m_ui; - EditorTextureSetting* m_textureSetting; - int m_currentMipIndex = 0; - bool m_previewTiled = false; - float m_imageLabelSize = 0; - AZStd::string m_platform; - unsigned int m_mipCount = 1; - - /////////////////////////////////////////// - // Preview window - PreviewMode m_previewMode = PreviewMode::RGB; - QScopedPointer m_previewPopup; - AZStd::unique_ptr m_previewConverter; - ImageProcessing::IImageObjectPtr m_previewImageRaw; - QImage m_previewImages[PreviewMode::Count]; - QTimer* m_updateTimer; - static const int s_updateInterval = 200; - //////////////////////////////////////////// - - //////////////////////////////////////////// - // Refresh button - bool m_alwaysRefreshPreview = true; - QAction* m_alwaysRefreshAction = nullptr; - QAction* m_refreshPerClickAction = nullptr; - QIcon m_refreshPerClickIcon; - QIcon m_alwaysRefreshIcon; - //////////////////////////////////////////// - }; -} //namespace ImageProcessingEditor - diff --git a/Gems/ImageProcessing/Code/Source/Editor/TexturePreviewWidget.ui b/Gems/ImageProcessing/Code/Source/Editor/TexturePreviewWidget.ui deleted file mode 100644 index 5f42fc8fd9..0000000000 --- a/Gems/ImageProcessing/Code/Source/Editor/TexturePreviewWidget.ui +++ /dev/null @@ -1,371 +0,0 @@ - - - TexturePreviewWidget - - - - 0 - 0 - 672 - 579 - - - - Form - - - - - - - - - - - Preview tiled - - - - - - - - 0 - 0 - - - - Shift: RGBA | Alt:Alpha | Space: Full-size - - - Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter - - - - - - - - - - 0 - 0 - - - - - 0 - 500 - - - - - - 0 - 0 - 171 - 185 - - - - - 0 - 0 - - - - Qt::RightToLeft - - - - - - - - - - - - - - - - 0 - 0 - - - - - 16 - 16 - - - - - 26 - 25 - - - - - - - :/warning.png - - - - - - - - - Qt::Vertical - - - - 115 - 32 - - - - - - - - - - - - - - :/Forward.png - - - - - - - - Qt::Horizontal - - - - 40 - 20 - - - - - - - - ... - - - - :/Backward.png - - - - - - - - - - Qt::Vertical - - - - 115 - 32 - - - - - - - - - - - - Mip 1 - - - Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter - - - - - - - Image size: 2048 x 2048 - - - Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter - - - - - - - File Size: 4,096 KB - - - Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter - - - - - - - - - - 0 - 0 - - - - - 16777215 - 16777215 - - - - - 0 - 0 - - - - Qt::LeftToRight - - - true - - - - - - - - - - 24 - 24 - - - - false - - - false - - - QToolButton::MenuButtonPopup - - - Qt::ToolButtonIconOnly - - - false - - - - - - - - - - - 0 - 0 - 400 - 400 - - - - - 0 - 0 - - - - - 0 - 0 - - - - - 2048 - 2048 - - - - image - - - true - - - Qt::AlignCenter - - - - - - 510 - 80 - 30 - 30 - - - - - 0 - 0 - - - - - 10 - 10 - - - - - 0 - 0 - - - - - 24 - 24 - - - - imageLabel - infoLayer - busyLabel - - - - - - - AzQtComponents::StyledBusyLabel - QWidget -
AzQtComponents/Components/StyledBusyLabel.h
- 1 -
-
- - - - -
diff --git a/Gems/ImageProcessing/Code/Source/Editor/TexturePropertyEditor.cpp b/Gems/ImageProcessing/Code/Source/Editor/TexturePropertyEditor.cpp deleted file mode 100644 index 90044a18c0..0000000000 --- a/Gems/ImageProcessing/Code/Source/Editor/TexturePropertyEditor.cpp +++ /dev/null @@ -1,217 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or 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 "TexturePropertyEditor.h" -#include - -#include -#include -#include -#include - -#include -#include -#include -#include -#include - -#include -#include - -namespace ImageProcessingEditor -{ - TexturePropertyEditor::TexturePropertyEditor(const AZ::Uuid& sourceTextureId, QWidget* parent /*= nullptr*/) - : AzQtComponents::StyledDialog(parent, Qt::Dialog | Qt::CustomizeWindowHint | Qt::WindowCloseButtonHint | Qt::WindowTitleHint) - , m_ui(new Ui::TexturePropertyEditor) - , m_textureSetting(sourceTextureId) - , m_validImage(true) - { - if (m_textureSetting.m_img == nullptr) - { - m_validImage = false; - return; - } - - m_ui->setupUi(this); - - //Initialize all the format string here - EditorHelper::InitPixelFormatString(); - - //TexturePreviewWidget will be the widget to preview mipmaps - m_previewWidget.reset(aznew TexturePreviewWidget(m_textureSetting, this)); - m_ui->mainLayout->layout()->addWidget(m_previewWidget.data()); - - //TexturePresetSelectionWidget will be the widget to select the preset for the texture - m_presetSelectionWidget.reset(aznew TexturePresetSelectionWidget(m_textureSetting, this)); - m_ui->mainLayout->layout()->addWidget(m_presetSelectionWidget.data()); - - //ResolutionSettingWidget will be the table section to display mipmap resolution for each platform - m_resolutionSettingWidget.reset(aznew ResolutionSettingWidget(ResoultionWidgetType::TexturePropety, m_textureSetting, this)); - m_ui->mainLayout->layout()->addWidget(m_resolutionSettingWidget.data()); - - //MipmapSettingWidget will be simple ReflectedProperty editor to reflect mipmap settings section - m_mipmapSettingWidget.reset(aznew MipmapSettingWidget(m_textureSetting, this)); - m_ui->mainLayout->layout()->addWidget(m_mipmapSettingWidget.data()); - - // Disable horizontal scroll - m_ui->scrollArea->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); - - QObject::connect(m_ui->saveBtn, &QPushButton::clicked, this, &TexturePropertyEditor::OnSave); - QObject::connect(m_ui->helpBtn, &QPushButton::clicked, this, &TexturePropertyEditor::OnHelp); - QObject::connect(m_ui->cancelBtn, &QPushButton::clicked, this, &QDialog::reject); - - EditorInternalNotificationBus::Handler::BusConnect(); - - // When checkbox and combobox is focused, they will intercept the space shortcut, need to disable focus on them first - // to get space shortcut pass through - QList checkBoxWidgets = QObject::findChildren(); - for (QCheckBox* widget: checkBoxWidgets) - { - widget->setFocusPolicy(Qt::NoFocus); - } - QList comboBoxWidgets = QObject::findChildren(); - for (QComboBox* widget : comboBoxWidgets) - { - widget->setFocusPolicy(Qt::NoFocus); - } - this->setFocusPolicy(Qt::StrongFocus); - - } - - TexturePropertyEditor::~TexturePropertyEditor() - { - EditorInternalNotificationBus::Handler::BusDisconnect(); - } - - bool TexturePropertyEditor::HasValidImage() - { - return m_validImage; - } - - void TexturePropertyEditor::OnEditorSettingsChanged([[maybe_unused]] bool needRefresh, const AZStd::string& /*platform*/) - { - m_textureSetting.m_modified = true; - } - - void TexturePropertyEditor::OnSave() - { - if (!m_validImage) - { - return; - } - - bool sourceControlActive = false; - AzToolsFramework::SourceControlConnectionRequestBus::BroadcastResult(sourceControlActive, &AzToolsFramework::SourceControlConnectionRequests::IsActive); - AZStd::string outputPath = m_textureSetting.m_fullPath + ImageProcessing::TextureSettings::modernExtensionName; - - if (sourceControlActive) - { - using ApplicationBus = AzToolsFramework::ToolsApplicationRequestBus; - bool checkoutResult = false; - ApplicationBus::BroadcastResult(checkoutResult, &ApplicationBus::Events::RequestEditForFileBlocking, outputPath.c_str(), "Checking out .imagesetting file", []([[maybe_unused]] int& current, [[maybe_unused]] int& max) {}); - - if (checkoutResult) - { - SaveTextureSetting(outputPath); - } - else - { - AZ_Error("Texture Editor", false, "Cannot checkout file '%s' from source control.", outputPath.c_str()); - } - } - else - { - const bool fileExisted = AZ::IO::FileIOBase::GetInstance()->Exists(outputPath.c_str()); - const bool fileReadOnly = AZ::IO::FileIOBase::GetInstance()->IsReadOnly(outputPath.c_str()); - - if (!fileExisted || !fileReadOnly) - { - SaveTextureSetting(outputPath); - } - } - } - - void TexturePropertyEditor::SaveTextureSetting(AZStd::string outputPath) - { - if (!m_validImage) - { - return; - } - - ImageProcessing::TextureSettings& baseSetting = m_textureSetting.GetMultiplatformTextureSetting(); - for (auto& it : m_textureSetting.m_settingsMap) - { - baseSetting.ApplySettings(it.second, it.first); - } - - ImageProcessing::StringOutcome outcome = ImageProcessing::TextureSettings::WriteTextureSetting(outputPath, baseSetting); - - if (outcome.IsSuccess()) - { - // Since setting is successfully saved, we can safely delete the legacy setting now - DeleteLegacySetting(); - } - else - { - AZ_Error("Texture Editor", false, "Cannot save texture settings!"); - } - } - - void TexturePropertyEditor::DeleteLegacySetting() - { - AZStd::string legacyFile = m_textureSetting.m_fullPath + ImageProcessing::TextureSettings::legacyExtensionName; - const bool fileExisted = AZ::IO::FileIOBase::GetInstance()->Exists(legacyFile.c_str()); - if (fileExisted) - { - bool sourceControlActive = false; - AzToolsFramework::SourceControlConnectionRequestBus::BroadcastResult(sourceControlActive, &AzToolsFramework::SourceControlConnectionRequests::IsActive); - - if (sourceControlActive) - { - AzToolsFramework::SourceControlCommandBus::Broadcast(&AzToolsFramework::SourceControlCommandBus::Events::RequestDelete, legacyFile.c_str(), - [](bool success, const AzToolsFramework::SourceControlFileInfo& info) - { - //Deletes the file locally if it's not tracked by source control - if (!success && !info.IsManaged()) - { - AZ::IO::FileIOBase::GetInstance()->Remove(info.m_filePath.c_str()); - } - }); - } - else - { - AZ::IO::FileIOBase::GetInstance()->Remove(legacyFile.c_str()); - } - } - } - - - void TexturePropertyEditor::OnHelp() - { - QString webLink = tr("https://docs.aws.amazon.com/console/lumberyard/texturepipeline"); - QDesktopServices::openUrl(QUrl(webLink)); - } - - - bool TexturePropertyEditor::event(QEvent* event) - { - bool needsBlocking = false; - if (m_previewWidget) - { - needsBlocking = m_previewWidget->OnQtEvent(event); - } - return needsBlocking ? true : QWidget::event(event); - } - -}//namespace ImageProcessingEditor -#include diff --git a/Gems/ImageProcessing/Code/Source/Editor/TexturePropertyEditor.h b/Gems/ImageProcessing/Code/Source/Editor/TexturePropertyEditor.h deleted file mode 100644 index 77261d820a..0000000000 --- a/Gems/ImageProcessing/Code/Source/Editor/TexturePropertyEditor.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. -* -*/ - -#pragma once - -#if !defined(Q_MOC_RUN) -#include -#include -#include -#include - -#include -#include -#include -#include -#include -#endif - -namespace Ui -{ - class TexturePropertyEditor; -} - -namespace ImageProcessingEditor -{ - class TexturePropertyEditor - : public AzQtComponents::StyledDialog - , protected EditorInternalNotificationBus::Handler - { - Q_OBJECT - public: - - AZ_CLASS_ALLOCATOR(TexturePropertyEditor, AZ::SystemAllocator, 0); - explicit TexturePropertyEditor(const AZ::Uuid& sourceTextureId, QWidget* parent = nullptr); - ~TexturePropertyEditor(); - - bool HasValidImage(); - - protected: - void OnSave(); - void OnHelp(); - - //////////////////////////////////////////////////////////////////////// - //EditorInternalNotificationBus - void OnEditorSettingsChanged(bool needRefresh, const AZStd::string& platform); - //////////////////////////////////////////////////////////////////////// - - bool event(QEvent* event) override; - - private: - QScopedPointer m_ui; - QScopedPointer m_previewWidget; - QScopedPointer m_presetSelectionWidget; - QScopedPointer m_resolutionSettingWidget; - QScopedPointer m_mipmapSettingWidget; - - EditorTextureSetting m_textureSetting; - bool m_validImage = true; - - void SaveTextureSetting(AZStd::string outputPath); - void DeleteLegacySetting(); - - }; -} //namespace ImageProcessingEditor - diff --git a/Gems/ImageProcessing/Code/Source/Editor/TexturePropertyEditor.ui b/Gems/ImageProcessing/Code/Source/Editor/TexturePropertyEditor.ui deleted file mode 100644 index 33a7fd3376..0000000000 --- a/Gems/ImageProcessing/Code/Source/Editor/TexturePropertyEditor.ui +++ /dev/null @@ -1,120 +0,0 @@ - - - TexturePropertyEditor - - - - 0 - 0 - 580 - 1100 - - - - - 580 - 800 - - - - - 580 - 1200 - - - - Texture Settings Editor - - - - - - - 0 - 0 - - - - true - - - - - 0 - 0 - 560 - 1049 - - - - - 0 - 0 - - - - - 0 - - - 0 - - - 0 - - - 0 - - - - - - - - - - - - - - ? - - - - - - - Qt::Horizontal - - - QSizePolicy::Expanding - - - - 40 - 20 - - - - - - - - Apply - - - - - - - Close - - - - - - - - - - diff --git a/Gems/ImageProcessing/Code/Source/ImageBuilderBaseType.h b/Gems/ImageProcessing/Code/Source/ImageBuilderBaseType.h deleted file mode 100644 index 962cd81668..0000000000 --- a/Gems/ImageProcessing/Code/Source/ImageBuilderBaseType.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 - -typedef AZ::s8 int8; -typedef AZ::s8 sint8; -typedef AZ::u8 uint8; - -typedef AZ::s16 int16; -typedef AZ::s16 sint16; -typedef AZ::u16 uint16; - -typedef AZ::s32 int32; -typedef AZ::s32 sint32; -typedef AZ::u32 uint32; - -typedef float f32; -typedef double f64; diff --git a/Gems/ImageProcessing/Code/Source/ImageBuilderComponent.cpp b/Gems/ImageProcessing/Code/Source/ImageBuilderComponent.cpp deleted file mode 100644 index 8c0dc0ff56..0000000000 --- a/Gems/ImageProcessing/Code/Source/ImageBuilderComponent.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. -* -*/ - -#include "ImageProcessing_precompiled.h" -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include - -#include -#include -#include - -namespace ImageProcessing -{ - BuilderPluginComponent::BuilderPluginComponent() - { - // AZ Components should only initialize their members to null and empty in constructor - // after construction, they may be deserialized from file. - } - - BuilderPluginComponent::~BuilderPluginComponent() - { - } - - void BuilderPluginComponent::Init() - { - } - - void BuilderPluginComponent::Activate() - { - // create and initialize BuilderSettingManager once since it's will be used for image conversion - BuilderSettingManager::CreateInstance(); - - auto outcome = ImageProcessing::BuilderSettingManager::Instance()->LoadBuilderSettings(); - AZ_Error("Image Processing", outcome.IsSuccess(), "Failed to load default preset settings!"); - - // Activate is where you'd perform registration with other objects and systems. - // Since we want to register our builder, we do that here: - AssetBuilderSDK::AssetBuilderDesc builderDescriptor; - builderDescriptor.m_name = "Image Worker Builder"; - builderDescriptor.m_version = 2; - builderDescriptor.m_analysisFingerprint = AZStd::string::format("%d", ImageProcessing::BuilderSettingManager::Instance()->BuilderSettingsVersion()); - - for (int i = 0; i < s_TotalSupportedImageExtensions; i++) - { - builderDescriptor.m_patterns.push_back(AssetBuilderSDK::AssetBuilderPattern(s_SupportedImageExtensions[i], AssetBuilderSDK::AssetBuilderPattern::PatternType::Wildcard)); - } - - //add ".dds" here separately since we only apply copy operation for this type of file. and there won't be export option for dds files. - builderDescriptor.m_patterns.push_back(AssetBuilderSDK::AssetBuilderPattern("*.dds", AssetBuilderSDK::AssetBuilderPattern::PatternType::Wildcard)); - builderDescriptor.m_busId = azrtti_typeid(); - builderDescriptor.m_createJobFunction = AZStd::bind(&ImageBuilderWorker::CreateJobs, &m_imageBuilder, AZStd::placeholders::_1, AZStd::placeholders::_2); - builderDescriptor.m_processJobFunction = AZStd::bind(&ImageBuilderWorker::ProcessJob, &m_imageBuilder, AZStd::placeholders::_1, AZStd::placeholders::_2); - m_imageBuilder.BusConnect(builderDescriptor.m_busId); - ImageProcessingRequestBus::Handler::BusConnect(); - AssetBuilderSDK::AssetBuilderBus::Broadcast(&AssetBuilderSDK::AssetBuilderBusTraits::RegisterBuilderInformation, builderDescriptor); - } - - void BuilderPluginComponent::Deactivate() - { - ImageProcessingRequestBus::Handler::BusDisconnect(); - m_imageBuilder.BusDisconnect(); - BuilderSettingManager::DestroyInstance(); - CPixelFormats::DestroyInstance(); - } - - void BuilderPluginComponent::Reflect(AZ::ReflectContext* context) - { - // components also get Reflect called automatically - // this is your opportunity to perform static reflection or type registration of any types you want the serializer to know about - if (AZ::SerializeContext* serialize = azrtti_cast(context)) - { - serialize->Class() - ->Version(0) - ->Attribute(AZ::Edit::Attributes::SystemComponentTags, AZStd::vector({ AssetBuilderSDK::ComponentTags::AssetBuilder })) - ; - } - - BuilderSettingManager::Reflect(context); - BuilderSettings::Reflect(context); - PresetSettings::Reflect(context); - CubemapSettings::Reflect(context); - MipmapSettings::Reflect(context); - TextureSettings::Reflect(context); - } - - void BuilderPluginComponent::GetProvidedServices(AZ::ComponentDescriptor::DependencyArrayType& provided) - { - provided.push_back(AZ_CRC("ImagerBuilderPluginService", 0x6dc0db6e)); - } - - void BuilderPluginComponent::GetIncompatibleServices(AZ::ComponentDescriptor::DependencyArrayType& incompatible) - { - incompatible.push_back(AZ_CRC("ImagerBuilderPluginService", 0x6dc0db6e)); - } - - IImageObjectPtr BuilderPluginComponent::LoadImage(const AZStd::string& filePath) - { - return IImageObjectPtr(LoadImageFromFile(filePath)); - } - - IImageObjectPtr BuilderPluginComponent::LoadImagePreview(const AZStd::string& filePath) - { - IImageObjectPtr image(LoadImageFromFile(filePath)); - if (image) - { - ImageToProcess imageToProcess(image); - imageToProcess.ConvertFormat(ePixelFormat_R8G8B8A8); - return imageToProcess.Get(); - } - return image; - } - - void ImageBuilderWorker::ShutDown() - { - // it is important to note that this will be called on a different thread than your process job thread - m_isShuttingDown = true; - } - - // this happens early on in the file scanning pass - // this function should consistently always create the same jobs, and should do no checking whether the job is up to date or not - just be consistent. - void ImageBuilderWorker::CreateJobs(const AssetBuilderSDK::CreateJobsRequest& request, AssetBuilderSDK::CreateJobsResponse& response) - { - if (m_isShuttingDown) - { - response.m_result = AssetBuilderSDK::CreateJobsResultCode::ShuttingDown; - return; - } - - // Get the extension of the file - AZStd::string ext; - AzFramework::StringFunc::Path::GetExtension(request.m_sourceFile.c_str(), ext, false); - AZStd::to_upper(ext.begin(), ext.end()); - - // We process the same file for all platforms - for (const AssetBuilderSDK::PlatformInfo& platformInfo : request.m_enabledPlatforms) - { - if (ImageProcessing::BuilderSettingManager::Instance()->DoesSupportPlatform(platformInfo.m_identifier)) - { - AssetBuilderSDK::JobDescriptor descriptor; - descriptor.m_jobKey = ext + " Compile"; - descriptor.SetPlatformIdentifier(platformInfo.m_identifier.c_str()); - descriptor.m_critical = false; - descriptor.m_additionalFingerprintInfo = AZStd::string::format("%d", ImageProcessing::BuilderSettingManager::Instance()->BuilderSettingsVersion()); - response.m_createJobOutputs.push_back(descriptor); - } - } - - response.m_result = AssetBuilderSDK::CreateJobsResultCode::Success; - return; - } - - // later on, this function will be called for jobs that actually need doing. - // the request will contain the CreateJobResponse you constructed earlier, including any keys and values you placed into the hash table - void ImageBuilderWorker::ProcessJob(const AssetBuilderSDK::ProcessJobRequest& request, AssetBuilderSDK::ProcessJobResponse& response) - { - // Before we begin, let's make sure we are not meant to abort. - AssetBuilderSDK::JobCancelListener jobCancelListener(request.m_jobId); - - AZStd::vector productFilepaths; - bool imageProcessingSuccessful = false; - bool needConversion = true; - - //if the original file is a dds file then skip conversion - if (AzFramework::StringFunc::Path::IsExtension(request.m_fullPath.c_str(), "dds", false)) - { - productFilepaths.push_back(request.m_fullPath); - imageProcessingSuccessful = true; - needConversion = false; - } - - // Do conversion and get exported file's path - if (needConversion) - { - AZ_TracePrintf(AssetBuilderSDK::InfoWindow, "Performing image conversion: %s\n", request.m_fullPath.c_str()); - ImageConvertProcess* process = CreateImageConvertProcess(request.m_fullPath, request.m_tempDirPath, - request.m_jobDescription.GetPlatformIdentifier()); - - if (process != nullptr) - { - //the process can be stopped if the job is cancelled or the worker is shutting down - while (!process->IsFinished() && !m_isShuttingDown && !jobCancelListener.IsCancelled()) - { - process->UpdateProcess(); - } - - //get process result - imageProcessingSuccessful = process->IsSucceed(); - process->GetAppendOutputFilePaths(productFilepaths); - - delete process; - } - else - { - imageProcessingSuccessful = false; - } - } - - if (imageProcessingSuccessful) - { - AZ::Outcome result = PopulateProducts(request, productFilepaths, response.m_outputProducts); - if (result.IsSuccess()) - { - response.m_resultCode = AssetBuilderSDK::ProcessJobResult_Success; - } - else - { - AZ_Error(AssetBuilderSDK::ErrorWindow, false, result.GetError().c_str()); - response.m_resultCode = AssetBuilderSDK::ProcessJobResult_Failed; - } - } - else - { - if (m_isShuttingDown) - { - AZ_TracePrintf(AssetBuilderSDK::ErrorWindow, "Cancelled job %s because shutdown was requested.\n", request.m_fullPath.c_str()); - response.m_resultCode = AssetBuilderSDK::ProcessJobResult_Cancelled; - } - else if (jobCancelListener.IsCancelled()) - { - AZ_TracePrintf(AssetBuilderSDK::ErrorWindow, "Cancelled was requested for job %s.\n", request.m_fullPath.c_str()); - response.m_resultCode = AssetBuilderSDK::ProcessJobResult_Cancelled; - } - else - { - AZ_TracePrintf(AssetBuilderSDK::ErrorWindow, "Unexpected error during processing job %s.\n", request.m_fullPath.c_str()); - response.m_resultCode = AssetBuilderSDK::ProcessJobResult_Failed; - } - } - } - - AZ::Outcome ImageBuilderWorker::PopulateProducts(const AssetBuilderSDK::ProcessJobRequest& request, const AZStd::vector& productFilepaths, AZStd::vector& jobProducts) - { - AssetBuilderSDK::JobProduct* rgbBaseJobProduct = nullptr; - AssetBuilderSDK::JobProduct* diffBaseJobProduct = nullptr; - AssetBuilderSDK::JobProduct* baseJobProduct = nullptr; - AssetBuilderSDK::JobProduct* alphaBaseJobProduct = nullptr; - // Report the image-import result (filepath to one or many '.dds') - - // This reserve is critically important to prevent resizing the vector and invalidating the pointers we need to save off - jobProducts.reserve(productFilepaths.size()); - - for (const auto& product : productFilepaths) - { - AssetBuilderSDK::JobProduct jobProduct(product); - jobProduct.m_dependenciesHandled = true; // Dependencies are handled down below. The base products will have dependencies, lod products won't - jobProducts.push_back(jobProduct); - - AZ::u32 lodLevel = AssetBuilderSDK::GetSubID_LOD(jobProduct.m_productSubID); - - if(jobProduct.m_productSubID == 0) - { - rgbBaseJobProduct = &jobProducts.back(); - } - else if((jobProduct.m_productSubID & AssetBuilderSDK::SUBID_FLAG_DIFF) && lodLevel == 0) - { - diffBaseJobProduct = &jobProducts.back(); - } - else if((jobProduct.m_productSubID & AssetBuilderSDK::SUBID_FLAG_ALPHA) && lodLevel == 0) - { - alphaBaseJobProduct = &jobProducts.back(); - } - } - - //We can have a diff and/or a rgb base. The rgb base always takes precedence when present - baseJobProduct = rgbBaseJobProduct; - - if(!baseJobProduct) - { - baseJobProduct = diffBaseJobProduct; - } - - for (AssetBuilderSDK::JobProduct& jobProduct : jobProducts) - { - AssetBuilderSDK::ProductDependency productDependency(AZ::Data::AssetId(request.m_sourceFileUUID, jobProduct.m_productSubID), 0); - - AZ::u32 lodLevel = AssetBuilderSDK::GetSubID_LOD(jobProduct.m_productSubID); - bool isAlpha = jobProduct.m_productSubID & AssetBuilderSDK::SUBID_FLAG_ALPHA; - - if (lodLevel > 0) - { - if (isAlpha) - { - if (alphaBaseJobProduct) - { - // add all alpha mips to the base alpha texture as product dependency - alphaBaseJobProduct->m_dependencies.push_back(productDependency); - } - else - { - return AZ::Failure(AZStd::string::format("Unable to add (%s) file as a product dependency of the base alpha texture file. Base alpha texture file is missing from the products list.\n", jobProduct.m_productFileName.c_str())); - } - } - else - { - if (baseJobProduct) - { - // add all rgb mips to the base rgb texture as product dependency - baseJobProduct->m_dependencies.push_back(productDependency); - } - else - { - return AZ::Failure(AZStd::string::format("Unable to add (%s) file as a product dependency of the base rgb texture file. Base rgb texture file is missing from the products list.\n", jobProduct.m_productFileName.c_str())); - } - } - } - } - - // Diffuse (_diff) is required by the base (typically for cubemaps) - if (rgbBaseJobProduct && diffBaseJobProduct) - { - AssetBuilderSDK::ProductDependency productDependency(AZ::Data::AssetId(request.m_sourceFileUUID, diffBaseJobProduct->m_productSubID), 0); - rgbBaseJobProduct->m_dependencies.push_back(productDependency); - } - - if (alphaBaseJobProduct && baseJobProduct) - { - // Add the alphaBaseTexture as a product dependency for baseTexture - AssetBuilderSDK::ProductDependency productDependency(AZ::Data::AssetId(request.m_sourceFileUUID, alphaBaseJobProduct->m_productSubID), 0); - baseJobProduct->m_dependencies.push_back(productDependency); - } - - return AZ::Success(); - } -} // namespace ImageProcessing diff --git a/Gems/ImageProcessing/Code/Source/ImageBuilderComponent.h b/Gems/ImageProcessing/Code/Source/ImageBuilderComponent.h deleted file mode 100644 index 212081ec92..0000000000 --- a/Gems/ImageProcessing/Code/Source/ImageBuilderComponent.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. -* -*/ - -#pragma once - -#include -#include -#include -#include -#include - -namespace ImageProcessing -{ - //! Builder to process images - class ImageBuilderWorker - : public AssetBuilderSDK::AssetBuilderCommandBus::Handler - { - public: - AZ_RTTI(ImageBuilderWorker, "{525422DE-05B3-4095-966F-90CD7657A7E1}"); - - ImageBuilderWorker() = default; - ~ImageBuilderWorker() = default; - - //! Asset Builder Callback Functions - void CreateJobs(const AssetBuilderSDK::CreateJobsRequest& request, AssetBuilderSDK::CreateJobsResponse& response); - void ProcessJob(const AssetBuilderSDK::ProcessJobRequest& request, AssetBuilderSDK::ProcessJobResponse& response); - - ////////////////////////////////////////////////////////////////////////// - //!AssetBuilderSDK::AssetBuilderCommandBus interface - void ShutDown() override; // if you get this you must fail all existing jobs and return. - ////////////////////////////////////////////////////////////////////////// - - //! Populates the jobProduct vector with all the entries including their product dependencies - AZ::Outcome PopulateProducts(const AssetBuilderSDK::ProcessJobRequest& request, const AZStd::vector& productFilepaths, AZStd::vector& jobProducts); - - private: - bool m_isShuttingDown = false; - }; - - //! BuilderPluginComponent is to handle the lifecycle of ImageBuilder module. - class BuilderPluginComponent - : public AZ::Component - , protected ImageProcessingRequestBus::Handler - { - public: - AZ_COMPONENT(BuilderPluginComponent, "{2F12E1BE-D8F6-47A4-AC3E-6C5527C55840}") - static void Reflect(AZ::ReflectContext* context); - - BuilderPluginComponent(); // avoid initialization here. - ~BuilderPluginComponent() override; // free memory an uninitialize yourself. - - ////////////////////////////////////////////////////////////////////////// - // AZ::Component - void Init() override; // create objects, allocate memory and initialize yourself without reaching out to the outside world - void Activate() override; // reach out to the outside world and connect up to what you need to, register things, etc. - void Deactivate() override; // unregister things, disconnect from the outside world - - static void GetProvidedServices(AZ::ComponentDescriptor::DependencyArrayType& provided); - static void GetIncompatibleServices(AZ::ComponentDescriptor::DependencyArrayType& incompatible); - ////////////////////////////////////////////////////////////////////////// - - //////////////////////////////////////////////////////////////////////// - // ImageProcessingRequestBus interface implementation - IImageObjectPtr LoadImage(const AZStd::string& filePath) override; - IImageObjectPtr LoadImagePreview(const AZStd::string& filePath) override; - //////////////////////////////////////////////////////////////////////// - - private: - ImageBuilderWorker m_imageBuilder; - }; -}// namespace ImageProcessing diff --git a/Gems/ImageProcessing/Code/Source/ImageBuilderDefaultPresets.settings b/Gems/ImageProcessing/Code/Source/ImageBuilderDefaultPresets.settings deleted file mode 100644 index 7e16a3c98f..0000000000 --- a/Gems/ImageProcessing/Code/Source/ImageBuilderDefaultPresets.settings +++ /dev/null @@ -1,8051 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/Gems/ImageProcessing/Code/Source/ImageLoader/BTImageLoader.cpp b/Gems/ImageProcessing/Code/Source/ImageLoader/BTImageLoader.cpp deleted file mode 100644 index b06ceccddc..0000000000 --- a/Gems/ImageProcessing/Code/Source/ImageLoader/BTImageLoader.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. -* -*/ - -#include "ImageProcessing_precompiled.h" - -#include "ImageLoaders.h" - -#include -#include - -#include - -namespace -{ - //--------------------------------------------------------------------------- - // Load and save the VTP Binary Terrain (BT) format, documented here: - // http://vterrain.org/Implementation/Formats/BT.html - - // This structure represents a binary layout in the file. To direct load & save it, we need to remove all structure memory padding -#pragma pack(push,1) - struct BtHeader - { - char headerTag[7]; // Should be "binterr" - char headerTagVersion[3]; // Should be "1.3" - AZ::s32 columns; // # of columns in the heightfield - AZ::s32 rows; // # of rows in the heightfield - AZ::s16 bytesPerPoint; // bytes per height value, either 2 for signed ints or 4 for floats - AZ::s16 isFloatingPointData; // 1 if height values are floats, 0 for 16-bit signed ints - AZ::s16 horizUnits; // 0 if degrees, 1 if meters, 2 if international feet, 3 if US survey feet - AZ::s16 utmZone; // UTM projection zone 1 to 60 or -1 to -60 (see https://en.wikipedia.org/wiki/Universal_Transverse_Mercator_coordinate_system ) - AZ::s16 datum; // Datum value (6001 to 6094), see http://www.epsg.org/ - double leftExtent; // left coordinate projection of the file - double rightExtent; // right coordinate projection of the file - double bottomExtent; // bottom coordinate projection of the file - double topExtent; // top coordinate projection of the file - AZ::s16 externalProjection; // 1 if projection is in an external .prj file, 0 if it's contained in the header - float scale; // vertical units in meters. 0.0 should be treated as 1.0 - char unused[190]; - }; -#pragma pack(pop) - - AZStd::vector LoadFile(const AZStd::string& fileName) - { - AZ::IO::FileIOBase* fileReader = AZ::IO::FileIOBase::GetInstance(); - - if (!fileReader) - { - return {}; - } - - // an engine compatible file reader has been attached, so use that. - AZ::IO::HandleType fileHandle = AZ::IO::InvalidHandle; - AZ::u64 fileSize = 0; - - if (!fileReader->Open(fileName.c_str(), AZ::IO::OpenMode::ModeRead | AZ::IO::OpenMode::ModeBinary, fileHandle)) - { - return {}; - } - - if ((!fileReader->Size(fileHandle, fileSize)) || (fileSize == 0)) - { - fileReader->Close(fileHandle); - return {}; - } - - AZStd::vector fileBuf(fileSize); - - if (!fileReader->Read(fileHandle, fileBuf.data(), fileSize, true)) - { - fileReader->Close(fileHandle); - return {}; - } - - fileReader->Close(fileHandle); - - return fileBuf; - } - - bool IsHeaderValid(const BtHeader* header, std::size_t fileSize) - { - bool validData = true; - - // Do some quick error-checking on the header to make sure it meets our expectations - - // Does the header have the right header tag? (binterr1.0 - binterr1.3) - validData = validData && (memcmp(header->headerTag, "binterr", sizeof(header->headerTag)) == 0); - validData = validData && (header->headerTagVersion[0] == '1') && (header->headerTagVersion[1] == '.') && (header->headerTagVersion[2] >= '0') && (header->headerTagVersion[2] <= '3'); - - // Will the grid fit into a reasonable image size? - validData = validData && (header->columns >= 0) && (header->columns < 65536); - validData = validData && (header->rows >= 0) && (header->rows < 65536); - - // Do we either have 32-bit floats or 16-bit ints? - validData = validData && (((header->isFloatingPointData == 1) && (header->bytesPerPoint == 4)) || ((header->isFloatingPointData == 0) && (header->bytesPerPoint == 2))); - - // Is the remaining data exactly the size needed to fill our image? - AZ::s32 total = header->columns * header->rows * header->bytesPerPoint; - validData = validData && ((fileSize - sizeof(BtHeader)) == total); - - return validData; - } -} - -namespace ImageProcessing -{ - bool BTLoader::IsExtensionSupported(const char* extension) - { - return strcmp(extension, "bt") == 0; - } - - /* - Most of the logic here was taken from ImageBT.cpp. Please make sure - any changes are kept in sync :) - */ - IImageObject* BTLoader::LoadImageFromBT(const AZStd::string& fileName) - { - auto fileData = LoadFile(fileName); - - if (fileData.size() < sizeof(BtHeader)) - { - return nullptr; - } - - auto header = reinterpret_cast(fileData.data()); - - if (!header || !IsHeaderValid(header, fileData.size())) - { - return nullptr; - } - - if (header->scale == 0.0f) - { - header->scale = 1.0f; - } - - // The BT format defines the data as stored in column-first order, from bottom to top. - // However, some BT files store the data in row-first order, from top to bottom. - // There isn't anything that clearly specifies which type of file it is. If you load it the wrong way, - // the data will look like a bunch of wavy stripes. - // The only difference I've found in test files is datum values above 8000, which appears to be an invalid value for datum - // (it should be 6001-6904 according to the BT definition) - constexpr AZ::s32 invalidDatumValueDenotingColumnFirstData = 8000; - bool isColumnFirstData = (header->datum >= invalidDatumValueDenotingColumnFirstData) ? true : false; - AZ::s32 imageWidth = 0; - AZ::s32 imageHeight = 0; - - if (isColumnFirstData) - { - imageWidth = header->rows; - imageHeight = header->columns; - } - else - { - imageWidth = header->columns; - imageHeight = header->rows; - } - - IImageObject* image = IImageObject::CreateImage(imageWidth, imageHeight, 1, EPixelFormat::ePixelFormat_R32F); - - AZ::u8* p = nullptr; - AZ::u32 dwPitch = 0; - image->GetImagePointer(0, p, dwPitch); - - auto dst = reinterpret_cast(p); - auto maxPixel = std::numeric_limits::lowest(); - auto minPixel = std::numeric_limits::max(); - auto terrainData = reinterpret_cast(header + 1); - - // Read in the pixel data - if (header->isFloatingPointData) - { - for (AZ::s32 y = 0; y < imageHeight; ++y) - { - for (AZ::s32 x = 0; x < imageWidth; ++x) - { - float height = *reinterpret_cast(terrainData); - terrainData += sizeof(float); - - // Scale based on what our header defines - float setVal = dst[(y * imageWidth) + x] = height * header->scale; - maxPixel = AZStd::max(maxPixel, setVal); - minPixel = AZStd::min(minPixel, setVal); - } - } - } - else - { - for (AZ::s32 y = 0; y < imageHeight; ++y) - { - for (AZ::s32 x = 0; x < imageWidth; ++x) - { - float height = static_cast(*reinterpret_cast(terrainData)); - terrainData += sizeof(AZ::s16); - - // Scale based on what our header defines - float setVal = dst[(y * imageWidth) + x] = height * header->scale; - maxPixel = AZStd::max(maxPixel, setVal); - minPixel = AZStd::min(minPixel, setVal); - } - } - } - - // Scale our range down to 0 - 1 - auto diff = maxPixel - minPixel; - if (AZ::GetAbs(diff) < std::numeric_limits::epsilon()) - { - diff = 1.0f; - } - - auto imagePixels = imageWidth * imageHeight; - for (AZ::s32 i = 0; i < imagePixels; ++i) - { - dst[i] = (dst[i] - minPixel) / diff; - } - - return image; - } -} diff --git a/Gems/ImageProcessing/Code/Source/ImageLoader/ImageLoaders.cpp b/Gems/ImageProcessing/Code/Source/ImageLoader/ImageLoaders.cpp deleted file mode 100644 index ac6b1d34d5..0000000000 --- a/Gems/ImageProcessing/Code/Source/ImageLoader/ImageLoaders.cpp +++ /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. -* -*/ - -#include - -#include -#include -#include - -namespace ImageProcessing -{ - IImageObject* LoadImageFromFile(const AZStd::string& filename) - { - QFileInfo fileInfo(filename.c_str()); - QString ext = fileInfo.suffix(); - - if (TIFFLoader::IsExtensionSupported(ext.toUtf8())) - { - return TIFFLoader::LoadImageFromTIFF(filename); - } - else if (BTLoader::IsExtensionSupported(ext.toUtf8())) - { - return BTLoader::LoadImageFromBT(filename); - } - else if (QtImageLoader::IsExtensionSupported(ext.toUtf8())) - { - return QtImageLoader::LoadImageFromFile(filename); - } - - AZ_Warning("ImageProcessing", false, "No proper image loader to load file: %s", filename.c_str()); - return nullptr; - } - - bool IsExtensionSupported(const char* extension) - { - if (TIFFLoader::IsExtensionSupported(extension)) - { - return true; - } - else if (BTLoader::IsExtensionSupported(extension)) - { - return true; - } - else if (QtImageLoader::IsExtensionSupported(extension)) - { - return true; - } - return false; - } - - const AZStd::string LoadEmbeddedSettingFromFile(const AZStd::string& filename) - { - QFileInfo fileInfo(filename.c_str()); - QString ext = fileInfo.suffix(); - - if (TIFFLoader::IsExtensionSupported(ext.toUtf8())) - { - return TIFFLoader::LoadSettingFromTIFF(filename); - } - return ""; - } - -}// namespace ImageProcessing diff --git a/Gems/ImageProcessing/Code/Source/ImageLoader/ImageLoaders.h b/Gems/ImageProcessing/Code/Source/ImageLoader/ImageLoaders.h deleted file mode 100644 index ae460b3552..0000000000 --- a/Gems/ImageProcessing/Code/Source/ImageLoader/ImageLoaders.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. -* -*/ - -#pragma once - -#include - -namespace ImageProcessing -{ - class IImageObject; - - IImageObject* LoadImageFromFile(const AZStd::string& filename); - bool IsExtensionSupported(const char* extension); - const AZStd::string LoadEmbeddedSettingFromFile(const AZStd::string& filename); - - // Tiff loader. The loader support uncompressed tiff with with 1~4 channels and 8bit and 16bit uint or 16bits and 32bits float per channel - // QImage also support tiff (tiff plugin), but it only supports 8bits uint - namespace TIFFLoader - { - bool IsExtensionSupported(const char* extension); - // Load a tiff file to an image object. - IImageObject* LoadImageFromTIFF(const AZStd::string& filename); - // Load embedded .exportsettings string from tiff which was exported by deprecated feature of CryTif plugin. - const AZStd::string LoadSettingFromTIFF(const AZStd::string& filename); - };// namespace ImageTIFF - - namespace BTLoader - { - bool IsExtensionSupported(const char* extension); - // Load a BT file to an image object. - IImageObject* LoadImageFromBT(const AZStd::string& fileName); - }// namespace BTLoader - - // Image loader through Qt's QImage with image formats supported native and through plugins - namespace QtImageLoader - { - bool IsExtensionSupported(const char* extension); - // Load image file which supported by QtImage to an image object - IImageObject* LoadImageFromFile(const AZStd::string& filename); - };// namespace QtImageLoader - -}// namespace ImageProcessing diff --git a/Gems/ImageProcessing/Code/Source/ImageLoader/QtImageLoader.cpp b/Gems/ImageProcessing/Code/Source/ImageLoader/QtImageLoader.cpp deleted file mode 100644 index dd5dd62b73..0000000000 --- a/Gems/ImageProcessing/Code/Source/ImageLoader/QtImageLoader.cpp +++ /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. -* -*/ -#include "ImageProcessing_precompiled.h" - -#include -#include - -#include -#include - -/////////////////////////////////////////////////////////////////////////////////// - -namespace ImageProcessing -{ - namespace QtImageLoader - { - IImageObject* LoadImageFromFile(const AZStd::string& filename) - { - //try to open the image - QImage qimage(filename.c_str()); - if (qimage.isNull()) - { - return NULL; - } - - //convert to format which compatiable our pixel format - if (qimage.format() != QImage::Format_RGBA8888) - { - qimage = qimage.convertToFormat(QImage::Format_RGBA8888); - } - - //create a new image object - IImageObject *pImage = IImageObject::CreateImage(qimage.width(), qimage.height(), 1, - ePixelFormat_R8G8B8A8); - - //get a pointer to the image objects pixel data - uint8* pDst; - uint32 dwPitch; - pImage->GetImagePointer(0, pDst, dwPitch); - - //copy the qImage into the image object - for (uint32 dwY = 0; dwY < (uint32)qimage.height(); ++dwY) - { - uint8* dstLine = &pDst[dwPitch * dwY]; - uchar* srcLine = qimage.scanLine(dwY); - memcpy(dstLine, srcLine, dwPitch); - } - return pImage; - } - - bool IsExtensionSupported(const char* extension) - { - QList imgFormats = QImageReader::supportedImageFormats(); - - for (int i = 0; i < imgFormats.size(); ++i) - { - if (QString::fromUtf8(imgFormats[i]).toLower() == QString(extension).toLower()) - { - return true; - } - } - - return false; - } - }//namespace QtImageLoader -} //namespace ImageProcessing - diff --git a/Gems/ImageProcessing/Code/Source/ImageLoader/TIFFLoader.cpp b/Gems/ImageProcessing/Code/Source/ImageLoader/TIFFLoader.cpp deleted file mode 100644 index 6c2881423d..0000000000 --- a/Gems/ImageProcessing/Code/Source/ImageLoader/TIFFLoader.cpp +++ /dev/null @@ -1,660 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or 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 "ImageProcessing_precompiled.h" - -#include -#include -#include -#include - -#include -#include - -#include - -#include // TIFF library - -namespace ImageProcessing -{ - namespace TIFFLoader - { - class TiffFileRead - { - public: - TiffFileRead(const AZStd::string& filename) - : m_tif(nullptr) - { - m_tif = TIFFOpen(filename.c_str(), "r");; - } - - ~TiffFileRead() - { - if (m_tif != nullptr) - { - TIFFClose(m_tif); - } - } - - TIFF *GetTiff() - { - return m_tif; - } - - private: - TIFF *m_tif; - }; - - bool IsExtensionSupported(const char* extension) - { - QString ext = QString(extension).toLower(); - // This is the list of file extensions supported by this loader - return ext == "tif" || ext == "tiff"; - } - - struct TiffData - { - AZ::u32 m_channels = 0; - AZ::u32 m_photometric = 0; - AZ::u32 m_bitsPerPixel = 0; - AZ::u16 m_format = 0; - - AZ::u32 m_width = 0; - AZ::u32 m_height = 0; - - AZ::u32 m_tileWidth = 0; - AZ::u32 m_tileHeight = 0; - bool m_isTiled = false; - AZ::u32 m_bufSize = 0; - - bool m_isGeoTiff = false; - float m_pixelValueScale = 1.0f; - - EPixelFormat m_pixelFormat = EPixelFormat::ePixelFormat_Unknown; - }; - - static void Process8BitTiff(AZ::u8* dst, const AZ::u8* src, AZ::u32 destIdx, AZ::u32 srcIdx, const TiffData& data, AZ::u8& dstMult) - { - if (data.m_channels == 1) - { - if (data.m_photometric != PHOTOMETRIC_MINISBLACK) - { - dst[destIdx] = aznumeric_cast(src[srcIdx] * data.m_pixelValueScale); - } - else - { - dst[destIdx] = aznumeric_cast(src[srcIdx] * data.m_pixelValueScale); - dst[destIdx + 1] = aznumeric_cast(src[srcIdx] * data.m_pixelValueScale); - dst[destIdx + 2] = aznumeric_cast(src[srcIdx] * data.m_pixelValueScale); - dst[destIdx + 3] = 0xFF; - - dstMult = 4; - } - } - else if (data.m_channels == 2) - { - if (data.m_photometric == PHOTOMETRIC_SEPARATED) - { - // convert CMY to RGB (PHOTOMETRIC_SEPARATED refers to inks in TIFF, the value is inverted) - dst[destIdx] = aznumeric_cast(0xFF - src[srcIdx] * data.m_pixelValueScale); - dst[destIdx + 1] = aznumeric_cast(0xFF - src[srcIdx + 1] * data.m_pixelValueScale); - dst[destIdx + 2] = 0x00; - dst[destIdx + 3] = 0xFF; - - dstMult = 4; - } - else - { - dst[destIdx] = aznumeric_cast(src[srcIdx] * data.m_pixelValueScale); - dst[destIdx + 1] = aznumeric_cast(src[srcIdx + 1] * data.m_pixelValueScale); - - dstMult = 2; - } - } - else - { - dst[destIdx] = aznumeric_cast(src[srcIdx] * data.m_pixelValueScale); - dst[destIdx + 1] = aznumeric_cast(src[srcIdx + 1] * data.m_pixelValueScale); - dst[destIdx + 2] = aznumeric_cast(src[srcIdx + 2] * data.m_pixelValueScale); - dst[destIdx + 3] = (data.m_channels == 3) ? 0xFF : aznumeric_cast(src[srcIdx + 3] * data.m_pixelValueScale); - - dstMult = 4; - } - } - - static void Process16BitHDRTiff(AZ::s16* dst, const AZ::s16* src, AZ::u32 destIdx, AZ::u32 srcIdx, const TiffData& data, AZ::u8& dstMult) - { - if (data.m_channels == 1) - { - if (data.m_photometric != PHOTOMETRIC_MINISBLACK) - { - dst[destIdx] = aznumeric_cast(src[srcIdx] * data.m_pixelValueScale); - } - else - { - dst[destIdx] = aznumeric_cast(src[srcIdx] * data.m_pixelValueScale); - dst[destIdx + 1] = aznumeric_cast(src[srcIdx] * data.m_pixelValueScale); - dst[destIdx + 2] = aznumeric_cast(src[srcIdx] * data.m_pixelValueScale); - dst[destIdx + 3] = 1; - - dstMult = 4; - } - } - else if (data.m_channels == 2) - { - if (data.m_photometric == PHOTOMETRIC_SEPARATED) - { - //but convert CMY to RGB (PHOTOMETRIC_SEPARATED refers to inks in TIFF, the value is inverted) - dst[destIdx] = uint16(1.0f - src[srcIdx] * data.m_pixelValueScale); - dst[destIdx + 1] = uint16(1.0f - src[srcIdx + 1] * data.m_pixelValueScale); - dst[destIdx + 2] = 0; - dst[destIdx + 3] = 1; - - dstMult = 4; - } - else - { - dst[destIdx] = aznumeric_cast(src[srcIdx] * data.m_pixelValueScale); - dst[destIdx + 1] = aznumeric_cast(src[srcIdx + 1] * data.m_pixelValueScale); - - dstMult = 2; - } - } - else - { - dst[destIdx] = aznumeric_cast(src[srcIdx] * data.m_pixelValueScale); - dst[destIdx + 1] = aznumeric_cast(src[srcIdx + 1] * data.m_pixelValueScale); - dst[destIdx + 2] = aznumeric_cast(src[srcIdx + 2] * data.m_pixelValueScale); - dst[destIdx + 3] = (data.m_channels == 3) ? 1 : aznumeric_cast(src[srcIdx + 3] * data.m_pixelValueScale); - - dstMult = 4; - } - } - - static void Process16BitTiff(AZ::u16* dst, const AZ::u16* src, AZ::u32 destIdx, AZ::u32 srcIdx, const TiffData& data, AZ::u8& dstMult) - { - if (data.m_channels == 1) - { - if (data.m_photometric != PHOTOMETRIC_MINISBLACK) - { - dst[destIdx] = aznumeric_cast(src[srcIdx] * data.m_pixelValueScale); - } - else - { - dst[destIdx] = aznumeric_cast(src[srcIdx] * data.m_pixelValueScale); - dst[destIdx + 1] = aznumeric_cast(src[srcIdx] * data.m_pixelValueScale); - dst[destIdx + 2] = aznumeric_cast(src[srcIdx] * data.m_pixelValueScale); - dst[destIdx + 3] = 0xFFFF; - - dstMult = 4; - } - } - else if (data.m_channels == 2) - { - if (data.m_photometric == PHOTOMETRIC_SEPARATED) - { - //convert CMY to RGB (PHOTOMETRIC_SEPARATED refers to inks in TIFF, the value is inverted) - dst[destIdx] = 0xFFFF - aznumeric_cast(src[srcIdx] * data.m_pixelValueScale); - dst[destIdx + 1] = 0xFFFF - aznumeric_cast(src[srcIdx + 1] * data.m_pixelValueScale); - dst[destIdx + 2] = 0x0000; - dst[destIdx + 3] = 0xFFFF; - - dstMult = 4; - } - else - { - dst[destIdx] = aznumeric_cast(src[srcIdx] * data.m_pixelValueScale); - dst[destIdx + 1] = aznumeric_cast(src[srcIdx + 1] * data.m_pixelValueScale); - - dstMult = 2; - } - } - else - { - dst[destIdx] = aznumeric_cast(src[srcIdx] * data.m_pixelValueScale); - dst[destIdx + 1] = aznumeric_cast(src[srcIdx + 1] * data.m_pixelValueScale); - dst[destIdx + 2] = aznumeric_cast(src[srcIdx + 2] * data.m_pixelValueScale); - dst[destIdx + 3] = (data.m_channels == 3) ? 0xFFFF : aznumeric_cast(src[srcIdx + 3] * data.m_pixelValueScale); - - dstMult = 4; - } - } - - static void Process32BitHDRTiff(float* dst, const float* src, AZ::u32 destIdx, AZ::u32 srcIdx, const TiffData& data, AZ::u8& dstMult) - { - auto getScaledOrClamped = [&data](auto val) - { - // GeoTiff doesn't clamp because negative values are legitimate when the data represents height values below sea level. - return data.m_isGeoTiff ? (val * data.m_pixelValueScale) : AZ::GetMax(val, 0.0f); - }; - - if (data.m_channels == 1) - { - if (data.m_photometric != PHOTOMETRIC_MINISBLACK) - { - // clamp negative values - const float v = getScaledOrClamped(src[srcIdx]); - dst[destIdx] = v; - } - else - { - // clamp negative values - const float v = getScaledOrClamped(src[srcIdx]); - dst[destIdx] = v; - dst[destIdx + 1] = v; - dst[destIdx + 2] = v; - dst[destIdx + 3] = 1.0f; - - dstMult = 4; - } - } - else if (data.m_channels == 2) - { - if (data.m_photometric == PHOTOMETRIC_SEPARATED) - { - //convert CMY to RGB (PHOTOMETRIC_SEPARATED refers to inks in TIFF, the value is inverted) - dst[destIdx] = 1.0f - getScaledOrClamped(src[srcIdx]); - dst[destIdx + 1] = 1.0f - getScaledOrClamped(src[srcIdx + 1]); - dst[destIdx + 2] = 0.0f; - dst[destIdx + 3] = 1.0f; - - dstMult = 4; - } - else - { - dst[destIdx] = src[srcIdx] * data.m_pixelValueScale; - dst[destIdx + 1] = src[srcIdx + 1] * data.m_pixelValueScale; - - dstMult = 2; - } - } - else - { - // clamp negative values; don't swap red and blue -> RGB(A) - dst[destIdx] = getScaledOrClamped(src[srcIdx]); - dst[destIdx + 1] = getScaledOrClamped(src[srcIdx + 1]); - dst[destIdx + 2] = getScaledOrClamped(src[srcIdx + 2]); - dst[destIdx + 3] = (data.m_channels == 3) ? 1.0f : getScaledOrClamped(src[srcIdx + 3]) * data.m_pixelValueScale; - - dstMult = 4; - } - } - - static TiffData GetTiffData(TIFF* tif) - { - TiffData data; - - TIFFGetField(tif, TIFFTAG_SAMPLESPERPIXEL, &data.m_channels); - TIFFGetField(tif, TIFFTAG_PHOTOMETRIC, &data.m_photometric); - TIFFGetField(tif, TIFFTAG_BITSPERSAMPLE, &data.m_bitsPerPixel); - TIFFGetField(tif, TIFFTAG_SAMPLEFORMAT, &data.m_format); - TIFFGetField(tif, TIFFTAG_IMAGEWIDTH, &data.m_width); - TIFFGetField(tif, TIFFTAG_IMAGELENGTH, &data.m_height); - TIFFGetField(tif, TIFFTAG_TILEWIDTH, &data.m_tileWidth); - TIFFGetField(tif, TIFFTAG_TILELENGTH, &data.m_tileHeight); - - // Check to see if this is a tiled TIFF (vs a scanline-based TIFF) - if ((data.m_tileWidth > 0) && (data.m_tileHeight > 0)) - { - // Tiled TIFF, so our buffer needs to be tile-sized - data.m_isTiled = true; - data.m_bufSize = TIFFTileSize(tif); - } - else - { - // Scanline TIFF, so our buffer needs to be scanline-sized. - data.m_bufSize = TIFFScanlineSize(tif); - - // Treat scanlines like a tile of 1 x width size. - data.m_tileHeight = 1; - data.m_tileWidth = data.m_width; - } - - // Defined in GeoTIFF format - http://web.archive.org/web/20160403164508/http://www.remotesensing.org/geotiff/spec/geotiffhome.html - // Used to get the X, Y, Z scales from a GeoTIFF file - constexpr auto GEOTIFF_MODELPIXELSCALE_TAG = 33550; - - // Check to see if it's a GeoTIFF, and if so, whether or not it has the ZScale parameter. - AZ::u32 tagCount = 0; - double* pixelScales = nullptr; - if (TIFFGetField(tif, GEOTIFF_MODELPIXELSCALE_TAG, &tagCount, &pixelScales) == 1) - { - data.m_isGeoTiff = true; - - // if there's an xyz scale, and the Z scale isn't 0, let's use it. - if ((tagCount == 3) && (pixelScales != nullptr) && (pixelScales[2] != 0.0f)) - { - data.m_pixelValueScale = static_cast(pixelScales[2]); - } - } - - // Retrieve the pixel format of the image - switch (data.m_bitsPerPixel) - { - case 8: - { - data.m_pixelFormat = ePixelFormat_R8G8B8X8; - - if (data.m_channels == 1 && data.m_photometric != PHOTOMETRIC_MINISBLACK) - { - data.m_pixelFormat = ePixelFormat_R8; - } - else if (data.m_channels == 4) - { - data.m_pixelFormat = ePixelFormat_R8G8B8A8; - } - - break; - } - - case 16: - { - if (data.m_format == SAMPLEFORMAT_IEEEFP) - { - data.m_pixelFormat = ePixelFormat_R16G16B16A16F; - - if (data.m_channels == 1 && data.m_photometric != PHOTOMETRIC_MINISBLACK) - { - data.m_pixelFormat = ePixelFormat_R16F; - } - } - else - { - data.m_pixelFormat = ePixelFormat_R16G16B16A16; - - if (data.m_channels == 1 && data.m_photometric != PHOTOMETRIC_MINISBLACK) - { - data.m_pixelFormat = ePixelFormat_R16; - } - } - - break; - } - - case 32: - { - if (data.m_format == SAMPLEFORMAT_IEEEFP) - { - data.m_pixelFormat = ePixelFormat_R32G32B32A32F; - - if (data.m_channels == 1 && data.m_photometric != PHOTOMETRIC_MINISBLACK) - { - data.m_pixelFormat = ePixelFormat_R32F; - } - } - - break; - } - - default: - break; - } - - return data; - } - - static IImageObject* LoadTIFF(TIFF* tif) - { - TiffData data = GetTiffData(tif); - AZStd::unique_ptr destImageObject; - destImageObject.reset(IImageObject::CreateImage(data.m_width, data.m_height, - 1, data.m_pixelFormat)); - - uint8* dst; - uint32 pitch; - destImageObject->GetImagePointer(0, dst, pitch); - - AZStd::vector buf(data.m_bufSize); - - AZ::u8 dstMult = 1; - - // Loop across the image height, one tile at a time - for (AZ::u32 imageY = 0; imageY < data.m_height; imageY += data.m_tileHeight) - { - // If we aren't actually tiled, we'll need to read a scanline here - if (!data.m_isTiled) - { - if (TIFFReadScanline(tif, buf.data(), imageY) == -1) - { - AZ_Error("LoadTIFF", false, "Error reading scanline."); - return nullptr; - } - } - - // Loop across the image width, one tile at a time - for (AZ::u32 imageX = 0; imageX < data.m_width; imageX += data.m_tileWidth) - { - // If we *are* tiled, read in a new tile here - if (data.m_isTiled) - { - if (TIFFReadTile(tif, buf.data(), imageX, imageY, 0, 0) == -1) - { - AZ_Error("LoadTIFF", false, "Error reading tile."); - return nullptr; - } - } - - // For each pixel in the tile buffer, read it in and convert. - for (AZ::u32 tileY = 0; tileY < data.m_tileHeight; ++tileY) - { - for (AZ::u32 tileX = 0; tileX < data.m_tileWidth; ++tileX) - { - AZ::u32 srcIdx = ((tileY * data.m_tileWidth) + tileX) * data.m_channels; - AZ::u32 destIdx = (((imageY + tileY) * data.m_width) + (imageX + tileX)) * dstMult; - - switch (data.m_bitsPerPixel) - { - case 8: - Process8BitTiff(dst, buf.data(), destIdx, srcIdx, data, dstMult); - break; - - case 16: - { - switch (data.m_format) - { - case SAMPLEFORMAT_INT: - case SAMPLEFORMAT_IEEEFP: - Process16BitHDRTiff(reinterpret_cast(dst), reinterpret_cast(buf.data()), - destIdx, srcIdx, data, dstMult); - - break; - - default: - Process16BitTiff(reinterpret_cast(dst), reinterpret_cast(buf.data()), - destIdx, srcIdx, data, dstMult); - - break; - } - - break; - } - - case 32: - if (data.m_format == SAMPLEFORMAT_IEEEFP) - { - Process32BitHDRTiff(reinterpret_cast(dst), reinterpret_cast(buf.data()), - destIdx, srcIdx, data, dstMult); - } - else - { - AZ_Error("LoadTIFF", false, "Unknown / unsupported format."); - return nullptr; - } - - break; - - default: - AZ_Error("LoadTIFF", false, "Unknown / unsupported format."); - return nullptr; - } - - } - } - } - } - - return destImageObject.release(); - } - - IImageObject* LoadImageFromTIFF(const AZStd::string& filename) - { - TiffFileRead tiffRead(filename); - TIFF* tif = tiffRead.GetTiff(); - - IImageObject* destImageObject = nullptr; - - if (!tif) - { - AZ_Warning("Image Processing", false, "%s: Open tiff failed (%s)", __FUNCTION__, filename.c_str()); - return destImageObject; - } - - uint32 bitsPerChannel = 0; - uint32 channels = 0; - uint32 format = 0; - TIFFGetField(tif, TIFFTAG_SAMPLESPERPIXEL, &channels); - TIFFGetField(tif, TIFFTAG_BITSPERSAMPLE, &bitsPerChannel); - TIFFGetField(tif, TIFFTAG_SAMPLEFORMAT, &format); - - if (channels != 1 && channels != 2 && channels != 3 && channels != 4) - { - AZ_Warning("Image Processing", false, "Unsupported TIFF pixel format (channel count: %d)", channels); - return destImageObject; - } - - uint32 width = 0; - uint32 height = 0; - TIFFGetField(tif, TIFFTAG_IMAGEWIDTH, &width); - TIFFGetField(tif, TIFFTAG_IMAGELENGTH, &height); - if (width <= 0 || height <= 0) - { - AZ_Error("Image Processing", false, "%s failed (empty image)", __FUNCTION__); - return destImageObject; - } - - destImageObject = LoadTIFF(tif); - - if (destImageObject == nullptr) - { - AZ_Error("Image Processing", false, "Failed to read TIFF pixels"); - } - - return destImageObject; - } - - const AZStd::string LoadSettingFromTIFF(const AZStd::string& filename) - { - AZStd::string setting = ""; - - TiffFileRead tiffRead(filename); - TIFF* tif = tiffRead.GetTiff(); - - if (tif == nullptr) - { - return setting; - } - - // get image metadata - const unsigned char* buffer = nullptr; - unsigned int bufferLength = 0; - - if (!TIFFGetField(tif, TIFFTAG_PHOTOSHOP, &bufferLength, &buffer)) // 34377 IPTC TAG - { - return setting; - } - - const unsigned char* const bufferEnd = buffer + bufferLength; - - // detailed structure here: - // https://www.adobe.com/devnet-apps/photoshop/fileformatashtml/#50577409_pgfId-1037504 - while (buffer < bufferEnd) - { - const unsigned char* const bufferStart = buffer; - - // sanity check - if (buffer[0] != '8' || buffer[1] != 'B' || buffer[2] != 'I' || buffer[3] != 'M') - { - AZ_Warning("Image Processing", false, "Invalid Photoshop TIFF file [%s]!", filename.c_str()); - return setting; - } - buffer += 4; - - // get image resource id - const unsigned short resourceId = (((unsigned short)buffer[0]) << 8) | (unsigned short)buffer[1]; - buffer += 2; - - // get size of pascal string - const unsigned int nameSize = (unsigned int)buffer[0]; - ++buffer; - - // get pascal string - AZStd::string szName(buffer, buffer + nameSize); - buffer += nameSize; - - // align 2 bytes - if ((buffer - bufferStart) & 1) - { - ++buffer; - } - - // get size of resource data - const unsigned int resDataSize = - (((unsigned int)buffer[0]) << 24) | - (((unsigned int)buffer[1]) << 16) | - (((unsigned int)buffer[2]) << 8) | - (unsigned int)buffer[3]; - buffer += 4; - - // IPTC-NAA record. Contains the [File Info...] information. Old RC use this section to store the setting string. - if (resourceId == 0x0404) - { - const unsigned char* const iptcBufferStart = buffer; - - // Old RC uses IPTC ApplicationRecord tags SpecialInstructions to store the setting string - // IPTC Details: https://iptc.org/std/photometadata/specification/mapping/iptc-pmd-newsmlg2.html - unsigned int iptcPos = 0; - while (iptcPos + 5 < resDataSize) - { - int marker = iptcBufferStart[iptcPos++]; - int recordNumber = iptcBufferStart[iptcPos++]; - int dataSetNumber = iptcBufferStart[iptcPos++]; - int fieldLength = (iptcBufferStart[iptcPos++] << 8); - fieldLength += iptcBufferStart[iptcPos++]; - - // Ignore fields other than SpecialInstructions - if (marker != 0x1C || recordNumber != 0x02 || dataSetNumber != 0x28 ) - { - iptcPos += fieldLength; - continue; - } - - //save the setting string before close file - setting = AZStd::string(iptcBufferStart + iptcPos, iptcBufferStart + iptcPos + fieldLength); - return setting; - } - } - - buffer += resDataSize; - - // align 2 bytes - if ((buffer - bufferStart) & 1) - { - ++buffer; - } - } - - return setting; - } - - }// namespace ImageTIFF - -} //namespace ImageProcessing diff --git a/Gems/ImageProcessing/Code/Source/ImageProcessingModule.cpp b/Gems/ImageProcessing/Code/Source/ImageProcessingModule.cpp deleted file mode 100644 index 9cd28b39fe..0000000000 --- a/Gems/ImageProcessing/Code/Source/ImageProcessingModule.cpp +++ /dev/null @@ -1,53 +0,0 @@ -/* -* All or portions of this file Copyright(c) Amazon.com, Inc.or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -*or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -*WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ - -#include "ImageProcessing_precompiled.h" -#include -#include "ImageProcessingSystemComponent.h" -#include "ImageBuilderComponent.h" -#include "AtlasBuilder/AtlasBuilderComponent.h" - -namespace ImageProcessing -{ - class ImageProcessingModule - : public AZ::Module - { - public: - AZ_RTTI(ImageProcessingModule, "{A5392495-DD0E-4719-948A-B98DBAE88197}", AZ::Module); - - ImageProcessingModule() - : AZ::Module() - { - // Push results of the components' ::CreateDescriptor() into m_descriptors here. - m_descriptors.insert(m_descriptors.end(), { - ImageProcessingSystemComponent::CreateDescriptor(), //system component for editor - BuilderPluginComponent::CreateDescriptor(), //builder component for AP - TextureAtlasBuilder::AtlasBuilderComponent::CreateDescriptor(), //builder component for texture atlas - }); - } - - /** - * Add required SystemComponents to the SystemEntity. - */ - AZ::ComponentTypeList GetRequiredSystemComponents() const override - { - return AZ::ComponentTypeList{ - azrtti_typeid(), - }; - } - }; -} - -// DO NOT MODIFY THIS LINE UNLESS YOU RENAME THE GEM -// The first parameter should be GemName_GemIdLower -// The second should be the fully qualified name of the class above -AZ_DECLARE_MODULE_CLASS(Gem_ImageProcessing, ImageProcessing::ImageProcessingModule) diff --git a/Gems/ImageProcessing/Code/Source/ImageProcessingSystemComponent.cpp b/Gems/ImageProcessing/Code/Source/ImageProcessingSystemComponent.cpp deleted file mode 100644 index 6629dc592a..0000000000 --- a/Gems/ImageProcessing/Code/Source/ImageProcessingSystemComponent.cpp +++ /dev/null @@ -1,196 +0,0 @@ -/* -* All or portions of this file Copyright(c) Amazon.com, Inc.or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -*or, if provided, by the license below or the license accompanying this file. Do not -* remove or 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 "ImageProcessing_precompiled.h" - -#include -#include - -#include -#include -#include -#include -#include -#include -#include - -#include -#include - -#include -#include -#include -#include - -#include "ImageProcessingSystemComponent.h" -#include -#include - -namespace ImageProcessing -{ - void ImageProcessingSystemComponent::Reflect(AZ::ReflectContext* context) - { - if (auto serialize = azrtti_cast(context)) - { - serialize->Class() - ->Version(0) - ; - } - } - - void ImageProcessingSystemComponent::GetProvidedServices(AZ::ComponentDescriptor::DependencyArrayType& provided) - { - provided.push_back(AZ_CRC("ImageBuilderService", 0x43c4be37)); - } - - void ImageProcessingSystemComponent::GetIncompatibleServices(AZ::ComponentDescriptor::DependencyArrayType& incompatible) - { - incompatible.push_back(AZ_CRC("ImageBuilderService", 0x43c4be37)); - } - - void ImageProcessingSystemComponent::GetRequiredServices(AZ::ComponentDescriptor::DependencyArrayType& required) - { - (void)required; - } - - void ImageProcessingSystemComponent::GetDependentServices(AZ::ComponentDescriptor::DependencyArrayType& dependent) - { - (void)dependent; - } - - void ImageProcessingSystemComponent::Init() - { - - } - - void ImageProcessingSystemComponent::Activate() - { - // Call to allocate BuilderSettingManager - BuilderSettingManager::CreateInstance(); - - ImageProcessingEditor::ImageProcessingEditorRequestBus::Handler::BusConnect(); - AzToolsFramework::AssetBrowser::AssetBrowserInteractionNotificationBus::Handler::BusConnect(); - AzToolsFramework::AssetBrowser::AssetBrowserTexturePreviewRequestsBus::Handler::BusConnect(); - ImageProcessingRequestBus::Handler::BusConnect(); - } - - void ImageProcessingSystemComponent::Deactivate() - { - ImageProcessingRequestBus::Handler::BusDisconnect(); - ImageProcessingEditor::ImageProcessingEditorRequestBus::Handler::BusDisconnect(); - AzToolsFramework::AssetBrowser::AssetBrowserInteractionNotificationBus::Handler::BusDisconnect(); - AzToolsFramework::AssetBrowser::AssetBrowserTexturePreviewRequestsBus::Handler::BusDisconnect(); - - // Deallocate BuilderSettingManager - BuilderSettingManager::DestroyInstance(); - CPixelFormats::DestroyInstance(); - } - - void ImageProcessingSystemComponent::OpenSourceTextureFile(const AZ::Uuid& textureSourceID) - { - if (textureSourceID.IsNull()) - { - QMessageBox::warning(QApplication::activeWindow(), "Warning", - "Texture source does not have a unique ID. This can occur if the source asset has not yet been processed by the Asset Processor.", - QMessageBox::Ok); - } - else - { - ImageProcessingEditor::TexturePropertyEditor editor(textureSourceID, QApplication::activeWindow()); - if (!editor.HasValidImage()) - { - QMessageBox::warning(QApplication::activeWindow(), "Warning", "Invalid texture file", QMessageBox::Ok); - return; - } - editor.exec(); - } - } - - IImageObjectPtr ImageProcessingSystemComponent::LoadImage(const AZStd::string& filePath) - { - return IImageObjectPtr(LoadImageFromFile(filePath)); - } - - IImageObjectPtr ImageProcessingSystemComponent::LoadImagePreview(const AZStd::string& filePath) - { - IImageObjectPtr image(LoadImageFromFile(filePath)); - if (image) - { - ImageToProcess imageToProcess(image); - imageToProcess.ConvertFormat(ePixelFormat_R8G8B8A8); - return imageToProcess.Get(); - } - return image; - } - - void ImageProcessingSystemComponent::AddSourceFileOpeners(const char* fullSourceFileName, [[maybe_unused]] const AZ::Uuid& sourceUUID, AzToolsFramework::AssetBrowser::SourceFileOpenerList& openers) - { - if (HandlesSource(fullSourceFileName)) - { - openers.push_back( - { - "Image_Processing_Editor", - "Edit Image Settings...", - QIcon(), - [&](const char* fullSourceFileNameInCallback, const AZ::Uuid& sourceUUID) - { - AZ_UNUSED(fullSourceFileNameInCallback); - - if (!LoadTextureSettings()) - { - return; - } - - ImageProcessingEditor::ImageProcessingEditorRequestBus::Broadcast(&ImageProcessingEditor::ImageProcessingEditorRequests::OpenSourceTextureFile, sourceUUID); - } - }); - } - } - - bool ImageProcessingSystemComponent::HandlesSource(AZStd::string_view fileName) const - { - for (int i = 0; i < s_TotalSupportedImageExtensions; i ++ ) - { - if (AZStd::wildcard_match(s_SupportedImageExtensions[i], fileName.data())) - { - return true; - } - } - - return false; - } - - bool ImageProcessingSystemComponent::GetProductTexturePreview(const char* fullProductFileName, QImage& previewImage, AZStd::string& productInfo, AZStd::string& productAlphaInfo) - { - return ImagePreview::GetProductTexturePreview(fullProductFileName, previewImage, productInfo, productAlphaInfo); - } - - bool ImageProcessingSystemComponent::LoadTextureSettings() - { - if (m_textureSettingsLoaded) - { - return true; - } - - // Load the preset settings before opening the editor - auto outcome = BuilderSettingManager::Instance()->LoadBuilderSettings(); - if (outcome.IsSuccess()) - { - m_textureSettingsLoaded = true; - return true; - } - - AZ_Error("Image Processing", false, "Failed to load default preset settings!"); - return false; - } - -} // namespace ImageProcessing diff --git a/Gems/ImageProcessing/Code/Source/ImageProcessingSystemComponent.h b/Gems/ImageProcessing/Code/Source/ImageProcessingSystemComponent.h deleted file mode 100644 index 3d6f03b295..0000000000 --- a/Gems/ImageProcessing/Code/Source/ImageProcessingSystemComponent.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. -* -*/ - -#pragma once - -#include - -#include -#include -#include -#include - -namespace ImageProcessing -{ - class ImageProcessingSystemComponent - : public AZ::Component - , protected ImageProcessingRequestBus::Handler - , protected ImageProcessingEditor::ImageProcessingEditorRequestBus::Handler - , protected AzToolsFramework::AssetBrowser::AssetBrowserInteractionNotificationBus::Handler - , protected AzToolsFramework::AssetBrowser::AssetBrowserTexturePreviewRequestsBus::Handler - { - public: - AZ_COMPONENT(ImageProcessingSystemComponent, "{13B1EB88-316F-4D44-B59C-886F023A5A58}"); - - static void Reflect(AZ::ReflectContext* context); - - static void GetProvidedServices(AZ::ComponentDescriptor::DependencyArrayType& provided); - static void GetIncompatibleServices(AZ::ComponentDescriptor::DependencyArrayType& incompatible); - static void GetRequiredServices(AZ::ComponentDescriptor::DependencyArrayType& required); - static void GetDependentServices(AZ::ComponentDescriptor::DependencyArrayType& dependent); - - protected: - //////////////////////////////////////////////////////////////////////// - // ImageProcessingEditorRequestBus interface implementation - void OpenSourceTextureFile(const AZ::Uuid& textureSourceID) override; - //////////////////////////////////////////////////////////////////////// - - //////////////////////////////////////////////////////////////////////// - // ImageProcessingRequestBus interface implementation - IImageObjectPtr LoadImage(const AZStd::string& filePath) override; - IImageObjectPtr LoadImagePreview(const AZStd::string& filePath) override; - //////////////////////////////////////////////////////////////////////// - - //////////////////////////////////////////////////////////////////////// - // AZ::Component interface implementation - void Init() override; - void Activate() override; - void Deactivate() override; - //////////////////////////////////////////////////////////////////////// - - //////////////////////////////////////////////////////////////////////// - // AzToolsFramework::AssetBrowser::AssetBrowserInteractionNotificationsBus::Handler - void AddSourceFileOpeners(const char* fullSourceFileName, const AZ::Uuid& sourceUUID, AzToolsFramework::AssetBrowser::SourceFileOpenerList& openers) override; - //////////////////////////////////////////////////////////////////////// - - //////////////////////////////////////////////////////////////////////// - // AzToolsFramework::AssetBrowser::AssetBrowserTexturePreviewRequestsBus::Handler - bool GetProductTexturePreview(const char* fullProductFileName, QImage& previewImage, AZStd::string& productInfo, AZStd::string& productAlphaInfo) override; - //////////////////////////////////////////////////////////////////////// - - private: - bool HandlesSource(AZStd::string_view fileName) const; - - bool LoadTextureSettings(); - - bool m_textureSettingsLoaded = false; - }; -} // namespace ImageProcessing diff --git a/Gems/ImageProcessing/Code/Source/ImageProcessing_precompiled.cpp b/Gems/ImageProcessing/Code/Source/ImageProcessing_precompiled.cpp deleted file mode 100644 index cb97685105..0000000000 --- a/Gems/ImageProcessing/Code/Source/ImageProcessing_precompiled.cpp +++ /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. -* -*/ - -#include "ImageProcessing_precompiled.h" diff --git a/Gems/ImageProcessing/Code/Source/ImageProcessing_precompiled.h b/Gems/ImageProcessing/Code/Source/ImageProcessing_precompiled.h deleted file mode 100644 index 2972414a1f..0000000000 --- a/Gems/ImageProcessing/Code/Source/ImageProcessing_precompiled.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. -* -*/ - -#pragma once - -///////////////////////////////////////////////////////////////////////////// -// Qt -///////////////////////////////////////////////////////////////////////////// -#include -#include -#include - -///////////////////////////////////////////////////////////////////////////// -// AZCore -///////////////////////////////////////////////////////////////////////////// -#include -#include -#include -#include - -///////////////////////////////////////////////////////////////////////////// -//Type definitions -///////////////////////////////////////////////////////////////////////////// -#include diff --git a/Gems/ImageProcessing/Code/Source/Platform/Android/ImageProcessing_Traits_Android.h b/Gems/ImageProcessing/Code/Source/Platform/Android/ImageProcessing_Traits_Android.h deleted file mode 100644 index ab7622478b..0000000000 --- a/Gems/ImageProcessing/Code/Source/Platform/Android/ImageProcessing_Traits_Android.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. -* -*/ -#pragma once - -#define AZ_TRAIT_IMAGEPROCESSING_BESSEL_FUNCTION_FIRST_ORDER j1 -#define AZ_TRAIT_IMAGEPROCESSING_DEFAULT_PLATFORM "pc" -#define AZ_TRAIT_IMAGEPROCESSING_DEFINE_DIRECT3D_CONSTANTS 0 -#define AZ_TRAIT_IMAGEPROCESSING_PVRTEXLIB_USE_WINDLL_IMPORT 0 -#define AZ_TRAIT_IMAGEPROCESSING_SQUISH_DO_NOT_USE_FASTCALL 0 -#define AZ_TRAIT_IMAGEPROCESSING_SUPPORT_TRY_CATCH 1 -#define AZ_TRAIT_IMAGEPROCESSING_USE_BASE10_BYTE_PREFIX 0 diff --git a/Gems/ImageProcessing/Code/Source/Platform/Android/ImageProcessing_Traits_Platform.h b/Gems/ImageProcessing/Code/Source/Platform/Android/ImageProcessing_Traits_Platform.h deleted file mode 100644 index db38b9f980..0000000000 --- a/Gems/ImageProcessing/Code/Source/Platform/Android/ImageProcessing_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/Gems/ImageProcessing/Code/Source/Platform/Android/platform_android.cmake b/Gems/ImageProcessing/Code/Source/Platform/Android/platform_android.cmake deleted file mode 100644 index bafe20e506..0000000000 --- a/Gems/ImageProcessing/Code/Source/Platform/Android/platform_android.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. -# - -# Platform specific cmake file for configuring target compiler/link properties -# based on the active platform -# NOTE: functions in cmake are global, therefore adding functions to this file -# is being avoided to prevent overriding functions declared in other targets platfrom -# specific cmake files diff --git a/Gems/ImageProcessing/Code/Source/Platform/Android/platform_android_files.cmake b/Gems/ImageProcessing/Code/Source/Platform/Android/platform_android_files.cmake deleted file mode 100644 index fd81e56d8d..0000000000 --- a/Gems/ImageProcessing/Code/Source/Platform/Android/platform_android_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 - ImageProcessing_Traits_Platform.h - ImageProcessing_Traits_Android.h -) diff --git a/Gems/ImageProcessing/Code/Source/Platform/Linux/ImageProcessing_Traits_Linux.h b/Gems/ImageProcessing/Code/Source/Platform/Linux/ImageProcessing_Traits_Linux.h deleted file mode 100644 index f1186391ad..0000000000 --- a/Gems/ImageProcessing/Code/Source/Platform/Linux/ImageProcessing_Traits_Linux.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. -* -*/ -#pragma once - -#define AZ_TRAIT_IMAGEPROCESSING_BESSEL_FUNCTION_FIRST_ORDER j1 -#define AZ_TRAIT_IMAGEPROCESSING_DEFAULT_PLATFORM "pc" -#define AZ_TRAIT_IMAGEPROCESSING_DEFINE_DIRECT3D_CONSTANTS 0 -#define AZ_TRAIT_IMAGEPROCESSING_PVRTEXLIB_USE_WINDLL_IMPORT 0 -#define AZ_TRAIT_IMAGEPROCESSING_SQUISH_DO_NOT_USE_FASTCALL 1 -#define AZ_TRAIT_IMAGEPROCESSING_SUPPORT_TRY_CATCH 0 -#define AZ_TRAIT_IMAGEPROCESSING_USE_BASE10_BYTE_PREFIX 0 diff --git a/Gems/ImageProcessing/Code/Source/Platform/Linux/ImageProcessing_Traits_Platform.h b/Gems/ImageProcessing/Code/Source/Platform/Linux/ImageProcessing_Traits_Platform.h deleted file mode 100644 index 4131e01743..0000000000 --- a/Gems/ImageProcessing/Code/Source/Platform/Linux/ImageProcessing_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/Gems/ImageProcessing/Code/Source/Platform/Linux/platform_linux.cmake b/Gems/ImageProcessing/Code/Source/Platform/Linux/platform_linux.cmake deleted file mode 100644 index bafe20e506..0000000000 --- a/Gems/ImageProcessing/Code/Source/Platform/Linux/platform_linux.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. -# - -# Platform specific cmake file for configuring target compiler/link properties -# based on the active platform -# NOTE: functions in cmake are global, therefore adding functions to this file -# is being avoided to prevent overriding functions declared in other targets platfrom -# specific cmake files diff --git a/Gems/ImageProcessing/Code/Source/Platform/Linux/platform_linux_files.cmake b/Gems/ImageProcessing/Code/Source/Platform/Linux/platform_linux_files.cmake deleted file mode 100644 index 5f1d5dfd84..0000000000 --- a/Gems/ImageProcessing/Code/Source/Platform/Linux/platform_linux_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 - ImageProcessing_Traits_Platform.h - ImageProcessing_Traits_Linux.h -) diff --git a/Gems/ImageProcessing/Code/Source/Platform/Mac/ImageProcessing_Traits_Mac.h b/Gems/ImageProcessing/Code/Source/Platform/Mac/ImageProcessing_Traits_Mac.h deleted file mode 100644 index b2e35a528d..0000000000 --- a/Gems/ImageProcessing/Code/Source/Platform/Mac/ImageProcessing_Traits_Mac.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. -* -*/ -#pragma once - -#define AZ_TRAIT_IMAGEPROCESSING_BESSEL_FUNCTION_FIRST_ORDER j1 -#define AZ_TRAIT_IMAGEPROCESSING_DEFAULT_PLATFORM "osx_gl" -#define AZ_TRAIT_IMAGEPROCESSING_DEFINE_DIRECT3D_CONSTANTS 1 -#define AZ_TRAIT_IMAGEPROCESSING_PVRTEXLIB_USE_WINDLL_IMPORT 0 -#define AZ_TRAIT_IMAGEPROCESSING_SQUISH_DO_NOT_USE_FASTCALL 1 -#define AZ_TRAIT_IMAGEPROCESSING_SUPPORT_TRY_CATCH 0 -#define AZ_TRAIT_IMAGEPROCESSING_USE_BASE10_BYTE_PREFIX 1 diff --git a/Gems/ImageProcessing/Code/Source/Platform/Mac/ImageProcessing_Traits_Platform.h b/Gems/ImageProcessing/Code/Source/Platform/Mac/ImageProcessing_Traits_Platform.h deleted file mode 100644 index bc9d313e91..0000000000 --- a/Gems/ImageProcessing/Code/Source/Platform/Mac/ImageProcessing_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/Gems/ImageProcessing/Code/Source/Platform/Mac/platform_mac_files.cmake b/Gems/ImageProcessing/Code/Source/Platform/Mac/platform_mac_files.cmake deleted file mode 100644 index a25ce357a8..0000000000 --- a/Gems/ImageProcessing/Code/Source/Platform/Mac/platform_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 - ImageProcessing_Traits_Platform.h - ImageProcessing_Traits_Mac.h -) diff --git a/Gems/ImageProcessing/Code/Source/Platform/Windows/ImageProcessing_Traits_Platform.h b/Gems/ImageProcessing/Code/Source/Platform/Windows/ImageProcessing_Traits_Platform.h deleted file mode 100644 index d2a32135c3..0000000000 --- a/Gems/ImageProcessing/Code/Source/Platform/Windows/ImageProcessing_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/Gems/ImageProcessing/Code/Source/Platform/Windows/ImageProcessing_Traits_Windows.h b/Gems/ImageProcessing/Code/Source/Platform/Windows/ImageProcessing_Traits_Windows.h deleted file mode 100644 index 0410a31986..0000000000 --- a/Gems/ImageProcessing/Code/Source/Platform/Windows/ImageProcessing_Traits_Windows.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. -* -*/ -#pragma once - -#define AZ_TRAIT_IMAGEPROCESSING_BESSEL_FUNCTION_FIRST_ORDER _j1 -#define AZ_TRAIT_IMAGEPROCESSING_DEFAULT_PLATFORM "pc" -#define AZ_TRAIT_IMAGEPROCESSING_DEFINE_DIRECT3D_CONSTANTS 0 -#define AZ_TRAIT_IMAGEPROCESSING_PVRTEXLIB_USE_WINDLL_IMPORT 1 -#define AZ_TRAIT_IMAGEPROCESSING_SQUISH_DO_NOT_USE_FASTCALL 0 -#define AZ_TRAIT_IMAGEPROCESSING_SUPPORT_TRY_CATCH 0 -#define AZ_TRAIT_IMAGEPROCESSING_USE_BASE10_BYTE_PREFIX 0 diff --git a/Gems/ImageProcessing/Code/Source/Platform/Windows/platform_windows.cmake b/Gems/ImageProcessing/Code/Source/Platform/Windows/platform_windows.cmake deleted file mode 100644 index bafe20e506..0000000000 --- a/Gems/ImageProcessing/Code/Source/Platform/Windows/platform_windows.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. -# - -# Platform specific cmake file for configuring target compiler/link properties -# based on the active platform -# NOTE: functions in cmake are global, therefore adding functions to this file -# is being avoided to prevent overriding functions declared in other targets platfrom -# specific cmake files diff --git a/Gems/ImageProcessing/Code/Source/Platform/Windows/platform_windows_files.cmake b/Gems/ImageProcessing/Code/Source/Platform/Windows/platform_windows_files.cmake deleted file mode 100644 index eabc30e929..0000000000 --- a/Gems/ImageProcessing/Code/Source/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 - ImageProcessing_Traits_Platform.h - ImageProcessing_Traits_Windows.h -) diff --git a/Gems/ImageProcessing/Code/Source/Platform/iOS/ImageProcessing_Traits_Platform.h b/Gems/ImageProcessing/Code/Source/Platform/iOS/ImageProcessing_Traits_Platform.h deleted file mode 100644 index 4ecfd207ca..0000000000 --- a/Gems/ImageProcessing/Code/Source/Platform/iOS/ImageProcessing_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/Gems/ImageProcessing/Code/Source/Platform/iOS/ImageProcessing_Traits_iOS.h b/Gems/ImageProcessing/Code/Source/Platform/iOS/ImageProcessing_Traits_iOS.h deleted file mode 100644 index 55b1be4d77..0000000000 --- a/Gems/ImageProcessing/Code/Source/Platform/iOS/ImageProcessing_Traits_iOS.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. -* -*/ -#pragma once - -#define AZ_TRAIT_IMAGEPROCESSING_BESSEL_FUNCTION_FIRST_ORDER j1 -#define AZ_TRAIT_IMAGEPROCESSING_DEFAULT_PLATFORM "osx_gl" -#define AZ_TRAIT_IMAGEPROCESSING_DEFINE_DIRECT3D_CONSTANTS 1 -#define AZ_TRAIT_IMAGEPROCESSING_PVRTEXLIB_USE_WINDLL_IMPORT 0 -#define AZ_TRAIT_IMAGEPROCESSING_SQUISH_DO_NOT_USE_FASTCALL 1 -#define AZ_TRAIT_IMAGEPROCESSING_SUPPORT_TRY_CATCH 1 -#define AZ_TRAIT_IMAGEPROCESSING_USE_BASE10_BYTE_PREFIX 1 diff --git a/Gems/ImageProcessing/Code/Source/Platform/iOS/platform_ios.cmake b/Gems/ImageProcessing/Code/Source/Platform/iOS/platform_ios.cmake deleted file mode 100644 index bafe20e506..0000000000 --- a/Gems/ImageProcessing/Code/Source/Platform/iOS/platform_ios.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. -# - -# Platform specific cmake file for configuring target compiler/link properties -# based on the active platform -# NOTE: functions in cmake are global, therefore adding functions to this file -# is being avoided to prevent overriding functions declared in other targets platfrom -# specific cmake files diff --git a/Gems/ImageProcessing/Code/Source/Platform/iOS/platform_ios_files.cmake b/Gems/ImageProcessing/Code/Source/Platform/iOS/platform_ios_files.cmake deleted file mode 100644 index 12d59f3933..0000000000 --- a/Gems/ImageProcessing/Code/Source/Platform/iOS/platform_ios_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 - ImageProcessing_Traits_Platform.h - ImageProcessing_Traits_iOS.h -) diff --git a/Gems/ImageProcessing/Code/Source/Processing/DDSHeader.h b/Gems/ImageProcessing/Code/Source/Processing/DDSHeader.h deleted file mode 100644 index 9fd0827e21..0000000000 --- a/Gems/ImageProcessing/Code/Source/Processing/DDSHeader.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. -* -*/ - -#pragma once -#include -#include -#include - -//! The following defines and constants are extracted from ImageExtensionHelper.h -//! Please make sure they are always synced with ImageExtensionHelper.h - -#define IMAGE_BUIDER_MAKEFOURCC(ch0, ch1, ch2, ch3) \ - ((AZ::u32)(AZ::u8)(ch0) | ((AZ::u32)(AZ::u8)(ch1) << 8) | \ - ((AZ::u32)(AZ::u8)(ch2) << 16) | ((AZ::u32)(AZ::u8)(ch3) << 24)) - -// This header defines constants and structures that are useful when parsing -// DDS files. DDS files were originally designed to use several structures -// and constants that are native to DirectDraw and are defined in ddraw.h, -// such as DDSURFACEDESC2 and DDSCAPS2. This file defines similar -// (compatible) constants and structures so that one can use DDS files -// without needing to include ddraw.h. - - -//Needed to write out DDS files on Mac -#if AZ_TRAIT_IMAGEPROCESSING_DEFINE_DIRECT3D_CONSTANTS -#define DDPF_ALPHAPIXELS 0x00000001 // Texture contains alpha data -#define DDPF_ALPHA 0x00000002 // For alpha channel only uncompressed data -#define DDPF_FOURCC 0x00000004 // Texture contains compressed RGB data -#define DDPF_RGB 0x00000040 // Texture contains uncompressed RGB data -#define DDPF_YUV 0x00000200 // For YUV uncompressed data -#define DDPF_LUMINANCE 0x00020000 // For single channel color uncompressed data - -#define DDSCAPS_COMPLEX 0x00000008 // Must be used on any file that contains more than one surface -#define DDSCAPS_MIPMAP 0x00400000 // Should be used for a mipmap -#define DDSCAPS_TEXTURE 0x00001000 // Required -#endif - -#define DDS_FOURCC 0x00000004 // DDPF_FOURCC -#define DDS_RGB 0x00000040 // DDPF_RGB -#define DDS_LUMINANCE 0x00020000 // DDPF_LUMINANCE -#define DDS_SIGNED 0x00080000 // DDPF_SIGNED -#define DDS_RGBA 0x00000041 // DDPF_RGB | DDPF_ALPHAPIXELS -#define DDS_LUMINANCEA 0x00020001 // DDS_LUMINANCE | DDPF_ALPHAPIXELS -#define DDS_A 0x00000001 // DDPF_ALPHAPIXELS -#define DDS_A_ONLY 0x00000002 // DDPF_ALPHA - -#define DDS_FOURCC_A16B16G16R16 0x00000024 // FOURCC A16B16G16R16 -#define DDS_FOURCC_V16U16 0x00000040 // FOURCC V16U16 -#define DDS_FOURCC_Q16W16V16U16 0x0000006E // FOURCC Q16W16V16U16 -#define DDS_FOURCC_R16F 0x0000006F // FOURCC R16F -#define DDS_FOURCC_G16R16F 0x00000070 // FOURCC G16R16F -#define DDS_FOURCC_A16B16G16R16F 0x00000071 // FOURCC A16B16G16R16F -#define DDS_FOURCC_R32F 0x00000072 // FOURCC R32F -#define DDS_FOURCC_G32R32F 0x00000073 // FOURCC G32R32F -#define DDS_FOURCC_A32B32G32R32F 0x00000074 // FOURCC A32B32G32R32F - -#define DDSD_CAPS 0x00000001l // default -#define DDSD_PIXELFORMAT 0x00001000l -#define DDSD_WIDTH 0x00000004l -#define DDSD_HEIGHT 0x00000002l -#define DDSD_LINEARSIZE 0x00080000l - -#define DDS_HEADER_FLAGS_TEXTURE 0x00001007 // DDSD_CAPS | DDSD_HEIGHT | DDSD_WIDTH | DDSD_PIXELFORMAT -#define DDS_HEADER_FLAGS_MIPMAP 0x00020000 // DDSD_MIPMAPCOUNT -#define DDS_HEADER_FLAGS_VOLUME 0x00800000 // DDSD_DEPTH -#define DDS_HEADER_FLAGS_PITCH 0x00000008 // DDSD_PITCH -#define DDS_HEADER_FLAGS_LINEARSIZE 0x00080000 // DDSD_LINEARSIZE - -#define DDS_SURFACE_FLAGS_TEXTURE 0x00001000 // DDSCAPS_TEXTURE -#define DDS_SURFACE_FLAGS_MIPMAP 0x00400008 // DDSCAPS_COMPLEX | DDSCAPS_MIPMAP -#define DDS_SURFACE_FLAGS_CUBEMAP 0x00000008 // DDSCAPS_COMPLEX - -#define DDS_CUBEMAP_POSITIVEX 0x00000600 // DDSCAPS2_CUBEMAP | DDSCAPS2_CUBEMAP_POSITIVEX -#define DDS_CUBEMAP_NEGATIVEX 0x00000a00 // DDSCAPS2_CUBEMAP | DDSCAPS2_CUBEMAP_NEGATIVEX -#define DDS_CUBEMAP_POSITIVEY 0x00001200 // DDSCAPS2_CUBEMAP | DDSCAPS2_CUBEMAP_POSITIVEY -#define DDS_CUBEMAP_NEGATIVEY 0x00002200 // DDSCAPS2_CUBEMAP | DDSCAPS2_CUBEMAP_NEGATIVEY -#define DDS_CUBEMAP_POSITIVEZ 0x00004200 // DDSCAPS2_CUBEMAP | DDSCAPS2_CUBEMAP_POSITIVEZ -#define DDS_CUBEMAP_NEGATIVEZ 0x00008200 // DDSCAPS2_CUBEMAP | DDSCAPS2_CUBEMAP_NEGATIVEZ - -#define DDS_CUBEMAP_ALLFACES (DDS_CUBEMAP_POSITIVEX | DDS_CUBEMAP_NEGATIVEX | \ - DDS_CUBEMAP_POSITIVEY | DDS_CUBEMAP_NEGATIVEY | \ - DDS_CUBEMAP_POSITIVEZ | DDS_CUBEMAP_NEGATIVEZ) - -#define DDS_FLAGS_VOLUME 0x00200000 // DDSCAPS2_VOLUME - -#define DDS_RESF1_NORMALMAP 0x01000000 -#define DDS_RESF1_DSDT 0x02000000 - - -namespace ImageProcessing -{ - const static AZ::u32 FOURCC_DX10 = IMAGE_BUIDER_MAKEFOURCC('D', 'X', '1', '0'); - const static AZ::u32 FOURCC_DDS = IMAGE_BUIDER_MAKEFOURCC('D', 'D', 'S', ' '); - const static AZ::u32 FOURCC_FYRC = IMAGE_BUIDER_MAKEFOURCC('F', 'Y', 'R', 'C'); - - //The values of each elements in this enum should be same as ITexture ETEX_TileMode enum. - enum DDS_TileMode : AZ::u8 - { - eTM_None = 0, - eTM_LinearPadded, - eTM_Optimal, - }; - - struct DDS_PIXELFORMAT - { - AZ::u32 dwSize; - AZ::u32 dwFlags; - AZ::u32 dwFourCC; - AZ::u32 dwRGBBitCount; - AZ::u32 dwRBitMask; - AZ::u32 dwGBitMask; - AZ::u32 dwBBitMask; - AZ::u32 dwABitMask; - - const bool operator == (const DDS_PIXELFORMAT& fmt) const - { - return dwFourCC == fmt.dwFourCC && - dwFlags == fmt.dwFlags && - dwRGBBitCount == fmt.dwRGBBitCount && - dwRBitMask == fmt.dwRBitMask && - dwGBitMask == fmt.dwGBitMask && - dwBBitMask == fmt.dwBBitMask && - dwABitMask == fmt.dwABitMask && - dwSize == fmt.dwSize; - } - - }; - - struct DDS_HEADER_DXT10 - { - // we're unable to use native enums, so we use AZ::u32 instead. - AZ::u32 /*DXGI_FORMAT*/ dxgiFormat; - AZ::u32 /*D3D10_RESOURCE_DIMENSION*/ resourceDimension; - AZ::u32 miscFlag; - AZ::u32 arraySize; - AZ::u32 reserved; - }; - - struct DDS_HEADER - { - AZ::u32 dwSize; - AZ::u32 dwHeaderFlags; - AZ::u32 dwHeight; - AZ::u32 dwWidth; - AZ::u32 dwPitchOrLinearSize; - AZ::u32 dwDepth; // only if DDS_HEADER_FLAGS_VOLUME is set in dwHeaderFlags - AZ::u32 dwMipMapCount; - AZ::u32 dwAlphaBitDepth; - AZ::u32 dwReserved1; // Crytek image flags - float fAvgBrightness; // Average top mip brightness. Could be f16/half - float cMinColor[4]; - float cMaxColor[4]; - DDS_PIXELFORMAT ddspf; - AZ::u32 dwSurfaceFlags; - AZ::u32 dwCubemapFlags; - AZ::u8 bNumPersistentMips; - AZ::u8 tileMode; //DDS_TileMode - AZ::u8 bReserved2[6]; - AZ::u32 dwTextureStage; - - - inline const bool IsValid() const { return sizeof(*this) == dwSize; } - inline const bool IsDX10Ext() const { return ddspf.dwFourCC == FOURCC_DX10; } - inline const AZ::u32 GetMipCount() const { return AZStd::GetMax(1u, (AZ::u32)dwMipMapCount); } - - inline const size_t GetFullHeaderSize() const - { - if (IsDX10Ext()) - { - return sizeof(DDS_HEADER) + sizeof(DDS_HEADER_DXT10); - } - - return sizeof(DDS_HEADER); - } - }; - - // standard description of file header - struct DDS_FILE_DESC - { - AZ::u32 dwMagic; - DDS_HEADER header; - - inline const bool IsValid() const { return dwMagic == FOURCC_DDS && header.IsValid(); } - inline const size_t GetFullHeaderSize() const { return sizeof(dwMagic) + header.GetFullHeaderSize(); } - }; - - // chunk identifier - const static AZ::u32 FOURCC_CExt = IMAGE_BUIDER_MAKEFOURCC('C', 'E', 'x', 't'); // Crytek extension start - const static AZ::u32 FOURCC_CEnd = IMAGE_BUIDER_MAKEFOURCC('C', 'E', 'n', 'd'); // Crytek extension end - const static AZ::u32 FOURCC_AttC = IMAGE_BUIDER_MAKEFOURCC('A', 't', 't', 'C'); // Chunk Attached Channel - - //Fourcc for pixel formats which aren't supported by dx10, such as astc formats, etc formats, pvrtc formats - //They are used for dwFourCC of dds header's DDS_PIXELFORMAT to identify non-dx10 pixel formats - const static AZ::u32 FOURCC_EAC_R11 = IMAGE_BUIDER_MAKEFOURCC('E', 'A', 'R', ' '); - const static AZ::u32 FOURCC_EAC_RG11 = IMAGE_BUIDER_MAKEFOURCC('E', 'A', 'R', 'G'); - const static AZ::u32 FOURCC_ETC2 = IMAGE_BUIDER_MAKEFOURCC('E', 'T', '2', ' '); - const static AZ::u32 FOURCC_ETC2A = IMAGE_BUIDER_MAKEFOURCC('E', 'T', '2', 'A'); - const static AZ::u32 FOURCC_PVRTC2 = IMAGE_BUIDER_MAKEFOURCC('P', 'V', 'R', '2'); - const static AZ::u32 FOURCC_PVRTC4 = IMAGE_BUIDER_MAKEFOURCC('P', 'V', 'R', '4'); - const static AZ::u32 FOURCC_ASTC_4x4 = IMAGE_BUIDER_MAKEFOURCC('A', 'S', '4', '4'); - const static AZ::u32 FOURCC_ASTC_5x4 = IMAGE_BUIDER_MAKEFOURCC('A', 'S', '5', '4'); - const static AZ::u32 FOURCC_ASTC_5x5 = IMAGE_BUIDER_MAKEFOURCC('A', 'S', '5', '5'); - const static AZ::u32 FOURCC_ASTC_6x5 = IMAGE_BUIDER_MAKEFOURCC('A', 'S', '6', '5'); - const static AZ::u32 FOURCC_ASTC_6x6 = IMAGE_BUIDER_MAKEFOURCC('A', 'S', '6', '6'); - const static AZ::u32 FOURCC_ASTC_8x5 = IMAGE_BUIDER_MAKEFOURCC('A', 'S', '8', '5'); - const static AZ::u32 FOURCC_ASTC_8x6 = IMAGE_BUIDER_MAKEFOURCC('A', 'S', '8', '6'); - const static AZ::u32 FOURCC_ASTC_10x5 = IMAGE_BUIDER_MAKEFOURCC('A', 'S', 'A', '5'); - const static AZ::u32 FOURCC_ASTC_10x6 = IMAGE_BUIDER_MAKEFOURCC('A', 'S', 'A', '6'); - const static AZ::u32 FOURCC_ASTC_8x8 = IMAGE_BUIDER_MAKEFOURCC('A', 'S', '8', '8'); - const static AZ::u32 FOURCC_ASTC_10x8 = IMAGE_BUIDER_MAKEFOURCC('A', 'S', 'A', '8'); - const static AZ::u32 FOURCC_ASTC_10x10 = IMAGE_BUIDER_MAKEFOURCC('A', 'S', 'A', 'A'); - const static AZ::u32 FOURCC_ASTC_12x10 = IMAGE_BUIDER_MAKEFOURCC('A', 'S', 'C', 'A'); - const static AZ::u32 FOURCC_ASTC_12x12 = IMAGE_BUIDER_MAKEFOURCC('A', 'S', 'C', 'C'); - - //legacy formats names. they are only used for load rc.exe's dds formats - const static AZ::u32 FOURCC_DXT1 = IMAGE_BUIDER_MAKEFOURCC('D', 'X', 'T', '1'); - const static AZ::u32 FOURCC_DXT3 = IMAGE_BUIDER_MAKEFOURCC('D', 'X', 'T', '3'); - const static AZ::u32 FOURCC_DXT5 = IMAGE_BUIDER_MAKEFOURCC('D', 'X', 'T', '5'); - const static AZ::u32 FOURCC_3DCP = IMAGE_BUIDER_MAKEFOURCC('A', 'T', 'I', '1'); - const static AZ::u32 FOURCC_3DC = IMAGE_BUIDER_MAKEFOURCC('A', 'T', 'I', '2'); -} diff --git a/Gems/ImageProcessing/Code/Source/Processing/ImageConvert.cpp b/Gems/ImageProcessing/Code/Source/Processing/ImageConvert.cpp deleted file mode 100644 index b5fc329a03..0000000000 --- a/Gems/ImageProcessing/Code/Source/Processing/ImageConvert.cpp +++ /dev/null @@ -1,1014 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or 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 - -//qt has convenience functions to handle file -#include -#include - -//for texture splitting -//mininum number of low level mips will be saved in the base file. -#define MinPersistantMips 3 -//mininum texture size to be splitted. A texture will only be split when the size is larger than this number -#define MinSizeToSplit 1<<5 - -#if defined(AZ_TOOLS_EXPAND_FOR_RESTRICTED_PLATFORMS) - #if defined(TOOLS_SUPPORT_JASPER) - #include AZ_RESTRICTED_FILE_EXPLICIT(ImageProcess, Jasper) - #endif - #if defined(TOOLS_SUPPORT_PROVO) - #include AZ_RESTRICTED_FILE_EXPLICIT(ImageProcess, Provo) - #endif - #if defined(TOOLS_SUPPORT_SALEM) - #include AZ_RESTRICTED_FILE_EXPLICIT(ImageProcess, Salem) - #endif -#endif - -namespace ImageProcessing -{ - - IImageObjectPtr ImageConvertProcess::GetOutputImage() - { - if (m_image) - { - return m_image->Get(); - } - return nullptr; - } - - IImageObjectPtr ImageConvertProcess::GetOutputAlphaImage() - { - return m_alphaImage; - } - - IImageObjectPtr ImageConvertProcess::GetOutputDiffCubemap() - { - return m_diffCubemapImage; - } - - void ImageConvertProcess::GetAppendOutputFilePaths(AZStd::vector& outPaths) - { - for (const auto& path : m_productFilepaths) - { - outPaths.push_back(path); - } - } - - ImageConvertProcess::ImageConvertProcess(const IImageObjectPtr inputImage, const TextureSettings& textureSetting, - const PresetSettings& presetSetting, bool isPreview, bool isStreaming, bool canOverridePreset, - const AZStd::string& outputPath, const AZStd::string& platformId) : - m_inputImage(inputImage), - m_textureSetting(textureSetting), - m_presetSetting(presetSetting), - m_canOverridePreset(canOverridePreset), - m_image(nullptr), - m_isPreview(isPreview), - m_outputPath(outputPath), - m_progressStep(0), - m_isFinished(false), - m_isSucceed(false), - m_processTime(0), - m_isStreaming(isStreaming), - m_platformId(platformId) - { - } - - ImageConvertProcess::~ImageConvertProcess() - { - delete m_image; - } - - bool ImageConvertProcess::IsConvertToCubemap() - { - return m_presetSetting.m_cubemapSetting != nullptr; - } - - void ImageConvertProcess::UpdateProcess() - { - if (m_isFinished) - { - return; - } - - switch (m_progressStep) - { - case StepValidateInput: - //validate - if (!ValidateInput()) - { - m_isSucceed = false; - break; - } - - //set start time - m_startTime = AZStd::GetTimeUTCMilliSecond(); - - //identify the alpha content of input image if gloss from normal wasn't set - m_alphaContent = m_inputImage->GetAlphaContent(); - - //create image for process - m_image = new ImageToProcess(IImageObjectPtr(m_inputImage->Clone())); - - break; - case StepGenerateColorChart: - //GenerateColorChart. - if (m_presetSetting.m_isColorChart) - { - m_image->CreateColorChart(); - } - break; - case StepConvertToLinear: - //convert to linear space and the output image pixel format should be rgba32f - ConvertToLinear(); - break; - case StepSwizzle: - //convert texture format. - if (m_presetSetting.m_swizzle.size() >= 4) - { - m_image->Get()->Swizzle(m_presetSetting.m_swizzle.substr(0, 4).c_str()); - m_alphaContent = m_image->Get()->GetAlphaContent(); - } - - //convert gloss map (alhpa channel) from legacy distribution to new one - if (m_presetSetting.m_isLegacyGloss) - { - m_image->Get()->ConvertLegacyGloss(); - } - break; - case StepOverridePreset: - if (m_canOverridePreset) - { - // Set the pixel format to BC3 if the source contains greyscale alpha and BC1 if it does not. - if (m_presetSetting.m_pixelFormat == ePixelFormat_BC1 - || m_presetSetting.m_pixelFormat == ePixelFormat_BC1a - || m_presetSetting.m_pixelFormat == ePixelFormat_BC3) - { - if (m_alphaContent == EAlphaContent::eAlphaContent_Greyscale) - { - m_presetSetting.m_pixelFormat = ePixelFormat_BC3; - } - else if (m_alphaContent == EAlphaContent::eAlphaContent_OnlyBlackAndWhite - || m_alphaContent == EAlphaContent::eAlphaContent_OnlyBlack - || m_alphaContent == EAlphaContent::eAlphaContent_OnlyWhite) - { - m_presetSetting.m_pixelFormat = ePixelFormat_BC1a; - } - else - { - m_presetSetting.m_pixelFormat = ePixelFormat_BC1; - } - } - } - break; - case StepCubemapLayout: - //convert cubemap image's layout to vertical strip used in game. - if (IsConvertToCubemap()) - { - if (!m_image->ConvertCubemapLayout(CubemapLayoutVertical)) - { - m_image->Set(nullptr); - } - } - break; - case StepPreNormalize: - //normalize base image before mipmap generation if glossfromnormals is enabled and require normalize - if (m_presetSetting.m_isMipRenormalize && m_presetSetting.m_glossFromNormals) - { - // Normalize the base mip map. This has to be done explicitly because we need to disable mip renormalization to - // preserve the normal length when deriving the normal variance - m_image->Get()->NormalizeVectors(0, 1); - } - break; - case StepDiffCubemap: - //create diffuse cubemap. We need to have better way to handle one input multiple export settings later. - CreateDiffuseCubemap(); - break; - case StepMipmap: - //generate mipmaps - if (IsConvertToCubemap()) - { - FillCubemapMipmaps(); - } - else - { - FillMipmaps(); - } - //add image flag - if (m_presetSetting.m_suppressEngineReduce || m_textureSetting.m_suppressEngineReduce) - { - m_image->Get()->AddImageFlags(EIF_SupressEngineReduce); - } - break; - case StepGlossFromNormal: - //get gloss from normal for all mipmaps and save to alpha channel - if (m_presetSetting.m_glossFromNormals) - { - bool hasAlpha = (m_alphaContent == EAlphaContent::eAlphaContent_OnlyBlack - || m_alphaContent == EAlphaContent::eAlphaContent_OnlyBlackAndWhite - || m_alphaContent == EAlphaContent::eAlphaContent_Greyscale); - - m_image->Get()->GlossFromNormals(hasAlpha); - //set alpha content so it won't be ignored later. - m_alphaContent = EAlphaContent::eAlphaContent_Greyscale; - } - break; - case StepPostNormalize: - //normalize all the other mipmaps - if (!IsConvertToCubemap() && m_presetSetting.m_isMipRenormalize) - { - if (m_presetSetting.m_glossFromNormals) - { - //normalize other mips except first mip - m_image->Get()->NormalizeVectors(1, 100); - } - else - { - //normalize all mips - m_image->Get()->NormalizeVectors(0, 100); - } - - m_image->Get()->AddImageFlags(EIF_RenormalizedTexture); - } - break; - case StepCreateHighPass: - if (m_presetSetting.m_highPassMip > 0) - { - m_image->CreateHighPass(m_presetSetting.m_highPassMip); - } - break; - case StepConvertOutputColorSpace: - //comvert image from linear space to desired output color space - ConvertToOuputColorSpace(); - break; - case StepAlphaImage: - //save alpha channel to separate image if it's needed - CreateAlphaImage(); - break; - case StepConvertPixelFormat: - //convert pixel format - ConvertPixelformat(); - break; - case StepSaveToFile: - //save to file - if (!m_isPreview) - { - m_isSucceed = SaveOutput(); - } - else - { - m_isSucceed = true; - } - break; - } - - m_progressStep++; - - if (m_image == nullptr || m_image->Get() == nullptr || m_progressStep >= StepAll) - { - m_isFinished = true; - AZStd::sys_time_t endTime = AZStd::GetTimeUTCMilliSecond(); - m_processTime = aznumeric_cast((endTime - m_startTime) / 1000); - } - - //output conversion log - if (m_isSucceed && m_isFinished) - { - const uint32 sizeTotal = m_image->Get()->GetTextureMemory(); - if (m_isPreview) - { - AZ_TracePrintf("Image Processing", "Image ( %d bytes) converted in %f seconds\n", sizeTotal, m_processTime); - } - else - { - AZ_TracePrintf("Image Processing", "Image converted and saved to %s ( %d bytes) with %f seconds\n", m_outputPath.c_str(), - sizeTotal, m_processTime); - } - } - } - - void ImageConvertProcess::ProcessAll() - { - while (!m_isFinished) - { - UpdateProcess(); - } - } - - float ImageConvertProcess::GetProgress() - { - return m_progressStep / (float)StepAll; - } - - bool ImageConvertProcess::IsFinished() - { - return m_isFinished; - } - - bool ImageConvertProcess::IsSucceed() - { - return m_isSucceed; - } - - //function to get desired output image extent - void GetOutputExtent(AZ::u32 inputWidth, AZ::u32 inputHeight, AZ::u32& outWidth, AZ::u32& outHeight, AZ::u32& outReduce, - const TextureSettings* textureSettings, const PresetSettings* presetSettings) - { - outWidth = inputWidth; - outHeight = inputHeight; - outReduce = 0; - - if (textureSettings == nullptr || presetSettings == nullptr) - { - return; - } - - //don't do any reduce for color chart - if (presetSettings->m_isColorChart) - { - return; - } - - //get suitable size for dest pixel format - CPixelFormats::GetInstance().GetSuitableImageSize(presetSettings->m_pixelFormat, inputWidth, inputHeight, - outWidth, outHeight); - - //desired reduce level. 1 means reduce one level - uint sizeReduceLevel = textureSettings->m_sizeReduceLevel; - - outReduce = 0; - - //reduce to not exceed max texture size - if (presetSettings->m_maxTextureSize > 0) - { - while (outWidth > presetSettings->m_maxTextureSize || outHeight > presetSettings->m_maxTextureSize) - { - outWidth >>= 1; - outHeight >>= 1; - outReduce++; - } - } - - //if it requires to reduce more and the result size will still larger than min texture size, then reduce - while (outReduce < sizeReduceLevel && - (outWidth >= presetSettings->m_minTextureSize * 2 && outHeight >= presetSettings->m_minTextureSize * 2)) - { - outWidth >>= 1; - outHeight >>= 1; - outReduce++; - } - } - - bool ImageConvertProcess::ConvertToLinear() - { - //de-gamma only if the input is sRGB. this will convert other uncompressed format to RGBA32F - return m_image->GammaToLinearRGBA32F(m_presetSetting.m_srcColorSpace == ColorSpace::sRGB); - } - - //mipmap generation - bool ImageConvertProcess::FillMipmaps() - { - //this function only works with pixel format rgba32f - const EPixelFormat srcPixelFormat = m_image->Get()->GetPixelFormat(); - if (srcPixelFormat != ePixelFormat_R32G32B32A32F) - { - AZ_Assert(false, "%s only works with pixel format rgba32f", __FUNCTION__); - return false; - } - - //only if the src image has one mip - if (m_image->Get()->GetMipCount() != 1) - { - AZ_Assert(false, "%s called for a mipmapped image. ", __FUNCTION__); - return false; - } - - //get output image size - uint32 outWidth; - uint32 outHeight; - uint32 outReduce = 0; - GetOutputExtent(m_image->Get()->GetWidth(0), m_image->Get()->GetHeight(0), outWidth, outHeight, outReduce, &m_textureSetting, - &m_presetSetting); - - //max mipmap count - uint32 mipCount = UINT32_MAX; - if (m_presetSetting.m_mipmapSetting == nullptr || !m_textureSetting.m_enableMipmap) - { - mipCount = 1; - } - - //create new new output image with proper side - IImageObjectPtr outImage(IImageObject::CreateImage(outWidth, outHeight, mipCount, ePixelFormat_R32G32B32A32F)); - - //filter setting for mip map generation - float blurH = 0; - float blurV = 0; - - //fill mipmap data for uncompressed output image - for (uint32 mip = 0; mip < outImage->GetMipCount(); mip++) - { - FilterImage(m_textureSetting.m_mipGenType, m_textureSetting.m_mipGenEval, blurH, blurV, m_image->Get(), 0, outImage, mip, nullptr, nullptr); - } - - //transfer alpha coverage - if (m_textureSetting.m_maintainAlphaCoverage) - { - outImage->TransferAlphaCoverage(&m_textureSetting, m_image->Get()); - } - - //set back to image - m_image->Set(outImage); - return true; - } - - void ImageConvertProcess::CreateAlphaImage() - { - //if alpha content doesn't have alpha or we need to discard alpha, skip - //we won't create alpha image for cubemap too - if (m_alphaContent == EAlphaContent::eAlphaContent_Absent - || m_alphaContent == EAlphaContent::eAlphaContent_OnlyWhite - || m_presetSetting.m_discardAlpha || IsConvertToCubemap()) - { - return; - } - - //Ensure that the PixelFormatAlpha is set otherwise no need to create m_alphaImage - if (m_presetSetting.m_pixelFormatAlpha == ePixelFormat_Unknown) - { - return; - } - - //now create alpha image - ImageToProcess alphaImage(m_image->Get()); - alphaImage.ConvertFormat(ePixelFormat_A8); - - - if(CPixelFormats::GetInstance().IsFormatSingleChannel(m_presetSetting.m_pixelFormatAlpha)) - { - alphaImage.ConvertFormat(m_presetSetting.m_pixelFormatAlpha); - } - else - { - //For PVRTC compression we need to clear out the alpha to get accurate rgb compression. - if (IsPVRTCFormat(m_presetSetting.m_pixelFormat) || IsASTCFormat(m_presetSetting.m_pixelFormat)) - { - alphaImage.ConvertFormat(ePixelFormat_R8G8B8A8); - alphaImage.Get()->Swizzle("rgb1"); - alphaImage.ConvertFormat(m_presetSetting.m_pixelFormatAlpha); - } - else - { - AZ_Assert(false, "Did you apply the correct pixel format for PixelFormatAlpha?"); - } - } - - //get final result and save it to member variable for later use - m_alphaImage = alphaImage.Get(); - - m_image->Get()->AddImageFlags(EIF_AttachedAlpha); - } - - //pixel format convertions - bool ImageConvertProcess::ConvertPixelformat() - { - - //For PVRTC compression we need to clear out the alpha to get accurate rgb compression. - if(m_alphaImage && (IsPVRTCFormat(m_presetSetting.m_pixelFormat) || IsASTCFormat(m_presetSetting.m_pixelFormat))) - { - m_image->Get()->Swizzle("rgb1"); - } - - - //set up compress option - ICompressor::EQuality quality; - if (m_isPreview) - { - quality = ICompressor::eQuality_Preview; - } - else - { - quality = ICompressor::eQuality_Normal; - } - m_image->GetCompressOption().compressQuality = quality; - m_image->GetCompressOption().rgbWeight = m_presetSetting.GetColorWeight(); - m_image->ConvertFormat(m_presetSetting.m_pixelFormat); - return true; - } - - //convert color space from linear to sRGB space if it's neccessary - bool ImageConvertProcess::ConvertToOuputColorSpace() - { - if (m_presetSetting.m_destColorSpace == ColorSpace::sRGB) - { - m_image->LinearToGamma(); - } - else if (m_presetSetting.m_destColorSpace == ColorSpace::autoSelect) - { - //convert to sRGB color space if it's dark image (converting bright images decreases image quality) - bool bThresholded = false; - { - Histogram<256> histogram; - if (ComputeLuminanceHistogram(m_image->Get(), histogram)) - { - const size_t medianBinIndex = 116; - float percentage = histogram.getPercentage(medianBinIndex, 255); - - // The image has significant amount of dark pixels, it's good to use sRGB - bThresholded = (percentage < 50.0f); - } - } - - if (bThresholded) - { - bool convertToSRGB = true; - - // if the image is BC1 compressable, additionally estimate the conversion error - // to only convert if it doesn't introduce error - if (CPixelFormats::GetInstance().IsImageSizeValid(ePixelFormat_BC1, m_image->Get()->GetWidth(0), - m_image->Get()->GetHeight(0), false)) - { - //get image in RGB space - ImageToProcess imageProcess(m_image->Get()); - imageProcess.LinearToGamma(); - - ICompressor::CompressOption option; - option.compressQuality = ICompressor::eQuality_Preview; - option.rgbWeight = m_presetSetting.GetColorWeight(); - - float errorLinearBC1; - float errorSrgbBC1; - GetBC1CompressionErrors(m_image->Get(), errorLinearBC1, errorSrgbBC1, option); - - // Don't convert if it would lower the image quality when saved as sRGB according to GetDXT1GammaCompressionError() - if (errorSrgbBC1 >= errorLinearBC1) - { - convertToSRGB = false; - } - } - - // our final conclusion: if the texture had a significant percentage of dark pixels and, - // if applicable, it was BC1 compressable and gamma compression wouldn't introduce error, - // then we convert it to sRGB - if (convertToSRGB) - { - m_image->LinearToGamma(); - } - } - } - return true; - } - - bool ImageConvertProcess::ValidateInput() - { - //valid the input image and output settings here. - uint32 dwWidth, dwHeight; - dwWidth = m_inputImage->GetWidth(0); - dwHeight = m_inputImage->GetHeight(0); - - EPixelFormat dstFmt = m_presetSetting.m_pixelFormat; - - //check if whether input image can be a cubemap - if (m_presetSetting.m_cubemapSetting) - { - if (CubemapLayout::GetCubemapLayoutInfo(m_inputImage) == nullptr) - { - AZ_Error("Image Processing", false, "Invalid image size %dx%d using as cubemap. Requires power of two with 6x1, 1x6, 4x3 or 3x4 layouts", dwWidth, dwHeight); - return false; - } - } - else if (!CPixelFormats::GetInstance().IsImageSizeValid(dstFmt, dwWidth, dwHeight, false)) - { - AZ_Warning("Image Processing", false, "Image size will be scaled for pixel format %s", CPixelFormats::GetInstance().GetPixelFormatInfo(dstFmt)->szName); - } - -#if defined(AZ_TOOLS_EXPAND_FOR_RESTRICTED_PLATFORMS) -#define AZ_RESTRICTED_PLATFORM_EXPANSION(CodeName, CODENAME, codename, PrivateName, PRIVATENAME, privatename, PublicName, PUBLICNAME, publicname, PublicAuxName1, PublicAuxName2, PublicAuxName3)\ - if (ImageProcess##PrivateName::DoesSupport(m_platformId))\ - {\ - if(!ImageProcess##PrivateName::IsPixelFormatSupported(m_presetSetting.m_pixelFormat))\ - {\ - AZ_Error("Image Processing", false, "Unsupported pixel format %s for %s",\ - CPixelFormats::GetInstance().GetPixelFormatInfo(dstFmt)->szName, m_platformId.c_str());\ - return false;\ - }\ - } - AZ_TOOLS_EXPAND_FOR_RESTRICTED_PLATFORMS -#undef AZ_RESTRICTED_PLATFORM_EXPANSION -#endif //AZ_TOOLS_EXPAND_FOR_RESTRICTED_PLATFORMS - - return true; - } - - bool ImageConvertProcess::SaveOutput() - { - //if the path wasn't specified, skip - if (m_outputPath.empty()) - { - AZ_Error("Image Processing", false, "No output path provided for saving"); - return false; - } - - //set all mips as presistent mips by default. it will be modified if the image is splitted later - m_image->Get()->SetNumPersistentMips(m_image->Get()->GetMipCount()); - - //split - if (m_isStreaming && m_presetSetting.m_numStreamableMips > 0) - { - IImageObjectPtr curImage = m_image->Get(); - - if (curImage->GetMipCount() > MinPersistantMips && (curImage->GetWidth(0) > MinSizeToSplit || - curImage->GetWidth(0) > MinSizeToSplit)) - { - //calculate final persistance mip count - AZ::u32 persistantMips = MinPersistantMips; - if (m_presetSetting.m_numStreamableMips < curImage->GetMipCount() - MinPersistantMips) - { - persistantMips = curImage->GetMipCount() - m_presetSetting.m_numStreamableMips; - } - curImage->SetNumPersistentMips(persistantMips); - curImage->AddImageFlags(EIF_Splitted); - - //add flags for alpha image too, assuming alpha image has same size as origin - if (m_alphaImage) - { - m_alphaImage->SetNumPersistentMips(persistantMips); - m_alphaImage->AddImageFlags(EIF_Splitted); - } - } - } - -#if defined(AZ_TOOLS_EXPAND_FOR_RESTRICTED_PLATFORMS) -#define AZ_RESTRICTED_PLATFORM_EXPANSION(CodeName, CODENAME, codename, PrivateName, PRIVATENAME, privatename, PublicName, PUBLICNAME, publicname, PublicAuxName1, PublicAuxName2, PublicAuxName3)\ - if (ImageProcess##PrivateName::DoesSupport(m_platformId))\ - {\ - ImageProcess##PrivateName::PrepareImageForExport(m_image->Get());\ - ImageProcess##PrivateName::PrepareImageForExport(m_alphaImage);\ - } - AZ_TOOLS_EXPAND_FOR_RESTRICTED_PLATFORMS -#undef AZ_RESTRICTED_PLATFORM_EXPANSION -#endif //AZ_TOOLS_EXPAND_FOR_RESTRICTED_PLATFORMS - - AZStd::vector outputFilePaths; - if (!m_image->Get()->SaveImage(m_outputPath.c_str(), m_alphaImage, outputFilePaths)) - { - AZ_Error("Image Processing", false, "Save image to %s failed", m_outputPath.c_str()); - return false; - } - - for (auto& path : outputFilePaths) - { - m_productFilepaths.push_back(path); - } - return true; - } - - ImageConvertProcess* CreateImageConvertProcess(const AZStd::string& imageFilePath, const AZStd::string& exportDir - , const PlatformName& platformName, AZ::SerializeContext* context) - { - AZStd::string metafilePath; - BuilderSettingManager::Instance()->MetafilePathFromImagePath(imageFilePath, metafilePath); - TextureSettings textureSettings; - - MultiplatformTextureSettings multiTextureSetting; - bool canOverridePreset = false; - - multiTextureSetting = TextureSettings::GetMultiplatformTextureSetting(imageFilePath, canOverridePreset, context); - if (multiTextureSetting.empty()) - { - AZ_Error("Image Processing", false, "Could not determine export settings for image file [%s] due to previous error(s). Skipping export...", imageFilePath.c_str()); - return nullptr; - } - - if (multiTextureSetting.find(platformName) != multiTextureSetting.end()) - { - textureSettings = multiTextureSetting[platformName]; - } - else - { - PlatformName defaultPlatform = BuilderSettingManager::s_defaultPlatform; - if (multiTextureSetting.find(defaultPlatform) != multiTextureSetting.end()) - { - textureSettings = multiTextureSetting[defaultPlatform]; - } - else - { - textureSettings = (*multiTextureSetting.begin()).second; - } - } - - //load image. Do it earlier so GetSuggestedPreset function could use the information of file to choose better preset - IImageObjectPtr srcImage(LoadImageFromFile(imageFilePath)); - if (srcImage == nullptr) - { - AZ_Error("Image Processing", false, "Load image file %s failed", imageFilePath.c_str()); - return nullptr; - } - - //if get textureSetting failed, use the default texture setting, and find suitable preset for this file - //in very rare user case, an old texture setting file may not have a preset. We fix it over here too. - if (textureSettings.m_preset.IsNull()) - { - textureSettings.m_preset = BuilderSettingManager::Instance()->GetSuggestedPreset(imageFilePath, srcImage); - } - - //get preset - const PresetSettings* preset = BuilderSettingManager::Instance()->GetPreset(textureSettings.m_preset, platformName); - - if (preset == nullptr) - { - AZStd::string uuidStr; - textureSettings.m_preset.ToString(uuidStr); - AZ_Assert(false, "%s cannot find image preset with ID %s.", imageFilePath.c_str(), uuidStr.c_str()); - return nullptr; - } - - //generate export file name - QDir dir(exportDir.c_str()); - if (!dir.exists()) - { - dir.mkpath("."); - } - AZStd::string fileName, outputPath; - AzFramework::StringFunc::Path::GetFileName(imageFilePath.c_str(), fileName); - fileName += ".dds"; - AzFramework::StringFunc::Path::Join(exportDir.c_str(), fileName.c_str(), outputPath, true, true); - - //if it need streaming - bool isStreaming = BuilderSettingManager::Instance()->GetBuilderSetting(platformName)->m_enableStreaming; - - //create convert process - ImageConvertProcess* process = new ImageConvertProcess(srcImage, textureSettings, *preset, false, isStreaming, - canOverridePreset, outputPath, platformName); - - return process; - } - - void ImageConvertProcess::CreateDiffuseCubemap() - { - //only need to convert if the diffuseGenPreset in cubemap setting is set - if (m_presetSetting.m_cubemapSetting == nullptr || m_presetSetting.m_cubemapSetting->m_diffuseGenPreset.IsNull()) - { - return; - } - - //need to create another ImageConvertProcess - //prepare preset setting and texture setting - const PresetSettings* preset = BuilderSettingManager::Instance()->GetPreset( - m_presetSetting.m_cubemapSetting->m_diffuseGenPreset, m_platformId); - - TextureSettings textureSettings = m_textureSetting; - m_textureSetting.m_preset = m_presetSetting.m_cubemapSetting->m_diffuseGenPreset; - - if (preset == nullptr) - { - AZ_Error("Image Processing", false,"Couldn't find preset for diffuse cubemap generation"); - return; - } - - //generate export file name. add "_diff" in the end of file name - AZStd::string fileName, folderName, outProductPath; - AzFramework::StringFunc::Path::GetFileName(m_outputPath.c_str(), fileName); - AzFramework::StringFunc::Path::GetFullPath(m_outputPath.c_str(), folderName); - fileName += "_diff.dds"; - AzFramework::StringFunc::Path::Join(folderName.c_str(), fileName.c_str(), outProductPath, true, true); - - //create convert process - //we might be able to use current image result for the input to save some performance. But it's more safe to use input image - bool canOverridePreset = false; - ImageConvertProcess* process = new ImageConvertProcess(m_inputImage, textureSettings, *preset, - false, m_isStreaming, canOverridePreset, outProductPath, m_platformId); - if (process) - { - process->ProcessAll(); - if (process->IsSucceed()) - { - process->GetAppendOutputFilePaths(m_productFilepaths); - m_diffCubemapImage = process->m_image->Get(); - } - else - { - AZ_Error("Image Processing", false, "Convert diffuse cubemap failed"); - } - delete process; - } - else - { - AZ_Error("Image Processing", false, "Create convert process for diffuse cubemap failed"); - } - } - - bool ConvertImageFile(const AZStd::string& imageFilePath, const AZStd::string& exportDir, - AZStd::vector& outPaths, const PlatformName& platformName, AZ::SerializeContext* context) - { - bool result = false; - ImageConvertProcess* process = CreateImageConvertProcess(imageFilePath, exportDir, platformName, context); - if (process) - { - process->ProcessAll(); - result = process->IsSucceed(); - if (result) - { - process->GetAppendOutputFilePaths(outPaths); - } - delete process; - } - return result; - } - - IImageObjectPtr MergeOutputImageForPreview(IImageObjectPtr image, IImageObjectPtr alphaImage) - { - if (!image) - { - return IImageObjectPtr(); - } - - ImageToProcess imageToProcess(image); - imageToProcess.ConvertFormat(ePixelFormat_R8G8B8A8); - IImageObjectPtr previewImage = imageToProcess.Get(); - - // If there is separate Alpha image, combine it with output - if (alphaImage) - { - // Create pixel operation function for rgb and alpha images - IPixelOperationPtr imageOp = CreatePixelOperation(ePixelFormat_R8G8B8A8); - IPixelOperationPtr alphaOp = CreatePixelOperation(ePixelFormat_A8); - - // Convert the alpha image to A8 first - ImageToProcess imageToProcess2(alphaImage); - imageToProcess2.ConvertFormat(ePixelFormat_A8); - IImageObjectPtr previewImageAlpha = imageToProcess2.Get(); - - const uint32 imageMips = previewImage->GetMipCount(); - const uint32 alphaMips = previewImageAlpha->GetMipCount(); - - // Get count of bytes per pixel for both rgb and alpha images - uint32 imagePixelBytes = CPixelFormats::GetInstance().GetPixelFormatInfo(ePixelFormat_R8G8B8A8)->bitsPerBlock / 8; - uint32 alphaPixelBytes = CPixelFormats::GetInstance().GetPixelFormatInfo(ePixelFormat_A8)->bitsPerBlock / 8; - - AZ_Assert(imageMips <= alphaMips, "Mip level of alpha image is less than origin image!"); - - // For each mip level, set the alpha value to the image - for (uint32 mipLevel = 0; mipLevel < imageMips; ++mipLevel) - { - const uint32 pixelCount = previewImage->GetPixelCount(mipLevel); - const uint32 alphaPixelCount = previewImageAlpha->GetPixelCount(mipLevel); - - AZ_Assert(pixelCount == alphaPixelCount, "Pixel count for image and alpha image at mip level %d is not equal!", mipLevel); - - uint8* imageBuf; - uint32 pitch; - previewImage->GetImagePointer(mipLevel, imageBuf, pitch); - - uint8* alphaBuf; - uint32 alphaPitch; - previewImageAlpha->GetImagePointer(mipLevel, alphaBuf, alphaPitch); - - float rAlpha, gAlpha, bAlpha, aAlpha, rImage, gImage, bImage, aImage; - - for (uint32 i = 0; i < pixelCount; ++i, imageBuf += imagePixelBytes, alphaBuf += alphaPixelBytes) - { - alphaOp->GetRGBA(alphaBuf, rAlpha, gAlpha, bAlpha, aAlpha); - imageOp->GetRGBA(imageBuf, rImage, gImage, bImage, aImage); - imageOp->SetRGBA(imageBuf, rImage, gImage, bImage, aAlpha); - } - } - } - - return previewImage; - } - - // This function will convert compressed image to RGBA32. - // Also if the image is in sRGB space will convert it to Linear space. - IImageObjectPtr GetUncompressedLinearImage(IImageObjectPtr ddsImage) - { - if (ddsImage) - { - ImageToProcess processImage(ddsImage); - if (!CPixelFormats::GetInstance().IsPixelFormatUncompressed(ddsImage->GetPixelFormat())) - { - processImage.ConvertFormat(ePixelFormat_R32G32B32A32F); - } - if (ddsImage->HasImageFlags(EIF_SRGBRead)) - { - processImage.GammaToLinearRGBA32F(true); - } - return processImage.Get(); - } - return nullptr; - } - - float GetErrorBetweenImages(IImageObjectPtr inputImage1, IImageObjectPtr inputImage2) - { - // First make sure images are in uncompressed format and linear space - // Convert them if necessary - IImageObjectPtr image1 = GetUncompressedLinearImage(inputImage1); - IImageObjectPtr image2 = GetUncompressedLinearImage(inputImage2); - - const float errorValue = FLT_MAX; - - if (!image1 || !image2) - { - AZ_Warning("Image Processing", false, "Invalid images passed into %s function", __FUNCTION__); - return errorValue; - } - - // Two images should share same size - if (image1->GetWidth(0) != image2->GetWidth(0) || image1->GetHeight(0) != image2->GetHeight(0)) - { - AZ_Warning("Image Processing", false, "%s function only can get error between two images with same size", __FUNCTION__); - return errorValue; - } - - //create pixel operation function - IPixelOperationPtr pixelOp1 = CreatePixelOperation(image1->GetPixelFormat()); - IPixelOperationPtr pixelOp2 = CreatePixelOperation(image2->GetPixelFormat()); - - //get count of bytes per pixel - AZ::u32 pixelBytes1 = CPixelFormats::GetInstance().GetPixelFormatInfo(image1->GetPixelFormat())->bitsPerBlock / 8; - AZ::u32 pixelBytes2 = CPixelFormats::GetInstance().GetPixelFormatInfo(image2->GetPixelFormat())->bitsPerBlock / 8; - - float color1[4]; - float color2[4]; - AZ::u8* mem1; - AZ::u8* mem2; - uint32 pitch1, pitch2; - - float sumDeltaSqLinear = 0; - - //only process the highest mip - image1->GetImagePointer(0, mem1, pitch1); - image2->GetImagePointer(0, mem2, pitch2); - - const uint32 pixelCount = image1->GetPixelCount(0); - - for (uint32 i = 0; i < pixelCount; ++i) - { - pixelOp1->GetRGBA(mem1, color1[0], color1[1], color1[2], color1[3]); - pixelOp2->GetRGBA(mem2, color2[0], color2[1], color2[2], color2[3]); - - sumDeltaSqLinear += (color1[0] - color2[0]) * (color1[0] - color2[0]) - + (color1[1] - color2[1]) * (color1[1] - color2[1]) - + (color1[2] - color2[2]) * (color1[2] - color2[2]); - - mem1 += pixelBytes1; - mem2 += pixelBytes2; - } - - return sumDeltaSqLinear / pixelCount; - } - - void GetBC1CompressionErrors(IImageObjectPtr originImage, float& errorLinear, float& errorSrgb, - ICompressor::CompressOption option) - { - errorLinear = 0; - errorSrgb = 0; - - if (originImage->HasImageFlags(EIF_SRGBRead)) - { - AZ_Assert(false, "The input origin image of %s function need be in linear color space", __FUNCTION__); - return; - } - - //compress and decompress in linear space - ImageToProcess processLinear(originImage); - processLinear.SetCompressOption(option); - processLinear.ConvertFormat(ePixelFormat_BC1); - processLinear.ConvertFormat(ePixelFormat_R32G32B32A32F); - - errorLinear = GetErrorBetweenImages(originImage, processLinear.Get()); - - //compress and descompress in srgb space, then convert back to linear space to compare to original image - ImageToProcess processSrgb(originImage); - processSrgb.SetCompressOption(option); - processSrgb.LinearToGamma(); - processSrgb.ConvertFormat(ePixelFormat_BC1); - processSrgb.ConvertFormat(ePixelFormat_R32G32B32A32F); - processSrgb.GammaToLinearRGBA32F(true); - - errorSrgb = GetErrorBetweenImages(originImage, processSrgb.Get()); - } - -}// namespace ImageProcessing diff --git a/Gems/ImageProcessing/Code/Source/Processing/ImageConvert.h b/Gems/ImageProcessing/Code/Source/Processing/ImageConvert.h deleted file mode 100644 index 01cd422672..0000000000 --- a/Gems/ImageProcessing/Code/Source/Processing/ImageConvert.h +++ /dev/null @@ -1,182 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ - -#pragma once - -#include - -#include -#include -#include -#include -#include - -#include -#include - -namespace ImageProcessing -{ - class IImageObject; - class ImageToProcess; - - //Convert image file with its image export setting and save to specified folder. - //this function can be useful for a cancelable job - class ImageConvertProcess* CreateImageConvertProcess(const AZStd::string& imageFilePath, - const AZStd::string& exportDir, const PlatformName& platformName, AZ::SerializeContext* context = nullptr); - - //Convert image file with its image export setting and save to specified folder. it will return when the whole conversion is done. - //Could be used for command mode or test - bool ConvertImageFile(const AZStd::string& imageFilePath, const AZStd::string& exportDir, AZStd::vector& outPaths, - const PlatformName& platformName = "", AZ::SerializeContext* context = nullptr); - - //image filter function - void FilterImage(MipGenType genType, MipGenEvalType evalType, float blurH, float blurV, const IImageObjectPtr srcImg, int srcMip, - IImageObjectPtr dstImg, int dstMip, QRect* srcRect, QRect* dstRect); - - //get compression error for an image converting to certain format - void GetBC1CompressionErrors(IImageObjectPtr originImage, float& errorLinear, float& errorSrgb, - ICompressor::CompressOption option); - - float GetErrorBetweenImages(IImageObjectPtr inputImage1, IImageObjectPtr inputImage2); - - //Combine image with alpha image if any and output as RGBA8 - IImageObjectPtr MergeOutputImageForPreview(IImageObjectPtr image, IImageObjectPtr alphaImage); - - //get output image size and mip count based on the texture setting and preset setting - - //other helper functions - //Get desired output image size based on the texture settings - void GetOutputExtent(AZ::u32 inputWidth, AZ::u32 inputHeight, AZ::u32& outWidth, AZ::u32& outHeight, AZ::u32& outReduce, - const TextureSettings* textureSettings, const PresetSettings* presetSettings); - - class ImageConvertProcess - { - public: - //constructor - ImageConvertProcess(const IImageObjectPtr inputImage, const TextureSettings& textureSetting, - const PresetSettings& presetSetting, bool isPreview, bool isStreaming, bool canOverridePreset, - const AZStd::string& outputPath, const AZStd::string& platformId); - ~ImageConvertProcess(); - - //doing image conversion, this function need to be called repeatly until the process is done - //it could used for a working thread which may need to cancel a process - void UpdateProcess(); - - //doing all conversion in one step. This function will call UpdateProcess in a while loop until it's done. - void ProcessAll(); - - //for multi-thread - //get percentage of image convertion progress - float GetProgress(); - bool IsFinished(); - bool IsSucceed(); - - //get output images - IImageObjectPtr GetOutputImage(); - IImageObjectPtr GetOutputAlphaImage(); - IImageObjectPtr GetOutputDiffCubemap(); - - //get output file paths and append the paths to the outPaths vector. - void GetAppendOutputFilePaths(AZStd::vector& outPaths); - - private: - enum ConvertStep - { - StepValidateInput = 0, - StepGenerateColorChart, - StepConvertToLinear, - StepSwizzle, - StepOverridePreset, - StepCubemapLayout, - StepPreNormalize, - StepDiffCubemap, - StepMipmap, - StepGlossFromNormal, - StepPostNormalize, - StepCreateHighPass, - StepConvertOutputColorSpace, - StepAlphaImage, - StepConvertPixelFormat, - StepSaveToFile, - StepAll - }; - - //input image and settings - const IImageObjectPtr m_inputImage; - TextureSettings m_textureSetting; - PresetSettings m_presetSetting; - bool m_canOverridePreset; - bool m_isPreview; - AZStd::string m_outputPath; - AZStd::string m_platformId; - - //some global settings from builder setting - bool m_isStreaming; - - //for alpha - //to indicate the current alpha chanenl content - EAlphaContent m_alphaContent; - //An image object to hold alpha channel in a seperate image - IImageObjectPtr m_alphaImage; - - //for cubemap - //An image object to save output result of diffuse cubemap conversion - IImageObjectPtr m_diffCubemapImage; - - //image for processing - ImageToProcess *m_image; - - //progress - uint32 m_progressStep; - bool m_isFinished; - bool m_isSucceed; - - //all the output products' paths - AZStd::vector m_productFilepaths; - - //for get processing time - AZStd::sys_time_t m_startTime; - double m_processTime; //in seconds - - private: - //validate the input image and settings - bool ValidateInput(); - - //mipmap generation - bool FillMipmaps(); - - //mipmap generation for cubemap - bool FillCubemapMipmaps(); - - //special case: create diffuse cubemap - void CreateDiffuseCubemap(); - - //convert color space to linear with pixel format rgba32f - bool ConvertToLinear(); - - //convert to output color space before compression - bool ConvertToOuputColorSpace(); - - //create alpha image if it's needed - void CreateAlphaImage(); - - //pixel format convertion/compression - bool ConvertPixelformat(); - - //save output image to a file - bool SaveOutput(); - - //if it's converting for cubemap - bool IsConvertToCubemap(); - }; - -}// namespace ImageProcessing diff --git a/Gems/ImageProcessing/Code/Source/Processing/ImageConvertJob.cpp b/Gems/ImageProcessing/Code/Source/Processing/ImageConvertJob.cpp deleted file mode 100644 index cab3918a05..0000000000 --- a/Gems/ImageProcessing/Code/Source/Processing/ImageConvertJob.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. -* -*/ - -#include - -#include -#include -#include -#include -#include -#include - -namespace ImageProcessing -{ - IImageObjectPtr ImageConvertOutput::GetOutputImage(OutputImageType type) const - { - if (type < OutputImageType::Count) - { - return m_outputImage[static_cast(type)]; - } - else - { - return IImageObjectPtr(); - } - } - - void ImageConvertOutput::SetOutputImage(IImageObjectPtr image, OutputImageType type) - { - if (type < OutputImageType::Count) - { - m_outputImage[static_cast(type)] = image; - } - else - { - AZ_Error("ImageProcess", false, "Cannot set output image to %d", type); - } - } - - void ImageConvertOutput::SetReady(bool ready) - { - m_outputReady = ready; - } - - bool ImageConvertOutput::IsReady() const - { - return m_outputReady; - } - - float ImageConvertOutput::GetProgress() const - { - return m_progress; - } - - void ImageConvertOutput::SetProgress(float progress) - { - m_progress = progress; - } - - void ImageConvertOutput::Reset() - { - for (int i = 0; i < static_cast(OutputImageType::Count); i ++ ) - { - m_outputImage[i] = nullptr; - } - m_outputReady = false; - m_progress = 0.0f; - } - - ImageConvertJob::ImageConvertJob(IImageObjectPtr image, const TextureSettings* textureSetting, - const PresetSettings* preset, bool isPreview, const AZStd::string& platformId, - ImageConvertOutput* output, bool autoDelete /*= true*/, AZ::JobContext* jobContext /*= nullptr*/) - : AZ::Job(autoDelete, jobContext) - , m_isPreview(isPreview) - , m_isCancelled(false) - , m_output(output) - { - AZ_Assert(m_output, "Needs to have an output destination for image conversion!"); - if (image && textureSetting && preset) - { - bool isStreaming = BuilderSettingManager::Instance()->GetBuilderSetting(platformId)->m_enableStreaming; - bool canOverridePreset = false; - m_process = AZStd::make_unique(image, *textureSetting, *preset, isPreview, isStreaming, canOverridePreset, "", platformId); - } - } - - void ImageConvertJob::Process() - { - if (!m_process) - { - AZ_Error("Image Processing", false, "Cannot start processing, invalid setting or image!"); - m_output->SetReady(true); - m_output->SetProgress(1.0f); - return; - } - m_output->SetReady(false); - while (!m_process->IsFinished() && !IsJobCancelled()) - { - m_process->UpdateProcess(); - if (m_isPreview) - { - m_output->SetProgress(m_process->GetProgress() / static_cast(m_previewProcessStep)); - } - else - { - m_output->SetProgress(m_process->GetProgress()); - } - } - - IImageObjectPtr outputImage = m_process->GetOutputImage(); - IImageObjectPtr outputImageAlpha = m_process->GetOutputAlphaImage(); - - m_output->SetOutputImage(outputImage, ImageConvertOutput::Base); - m_output->SetOutputImage(outputImageAlpha, ImageConvertOutput::Alpha); - - if (m_isPreview && !IsJobCancelled()) - { - // For preview, combine image output with alpha if any - m_output->SetProgress(1.0f / static_cast(m_previewProcessStep)); - IImageObjectPtr combinedImage = MergeOutputImageForPreview(outputImage, outputImageAlpha); - m_output->SetOutputImage(combinedImage, ImageConvertOutput::Preview); - } - - m_output->SetReady(true); - m_output->SetProgress(1.0f); - } - - void ImageConvertJob::Cancel() - { - m_isCancelled = true; - } - - bool ImageConvertJob::IsJobCancelled() - { - return m_isCancelled || IsCancelled(); - } - - - -}// namespace ImageProcessing diff --git a/Gems/ImageProcessing/Code/Source/Processing/ImageConvertJob.h b/Gems/ImageProcessing/Code/Source/Processing/ImageConvertJob.h deleted file mode 100644 index fb3f26af50..0000000000 --- a/Gems/ImageProcessing/Code/Source/Processing/ImageConvertJob.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. -* -*/ - -#pragma once - -#include -#include -#include -#include -#include - -namespace ImageProcessing -{ - class ImageConvertProcess; - - class ImageConvertOutput - { - public: - enum OutputImageType - { - Base = 0, // Might contains alpha or not - Alpha, // Separate alpha image - Preview, // Combine base image with alpha if any, format RGBA8 - Count - }; - - IImageObjectPtr GetOutputImage(OutputImageType type) const; - void SetOutputImage(IImageObjectPtr image, OutputImageType type); - void SetReady(bool ready); - bool IsReady() const; - float GetProgress() const; - void SetProgress(float progress); - void Reset(); - - private: - IImageObjectPtr m_outputImage[OutputImageType::Count]; - bool m_outputReady = false; - float m_progress = 0.0f; - }; - - class ImageConvertJob - : public AZ::Job - { - public: - AZ_CLASS_ALLOCATOR(ImageConvertJob, AZ::ThreadPoolAllocator, 0) - - ImageConvertJob(IImageObjectPtr image, const TextureSettings* textureSetting, const PresetSettings* preset - , bool isPreview, const AZStd::string& platformId, ImageConvertOutput* output, bool autoDelete = true - , AZ::JobContext* jobContext = nullptr); - - void Process() override; - // Cancel the job itself - void Cancel(); - // Whether the job is being cancelled or the whole job group is being cancelled - bool IsJobCancelled(); - - private: - static const int m_previewProcessStep = 2; - - AZStd::unique_ptr m_process; - bool m_isPreview; - AZStd::atomic_bool m_isCancelled; - ImageConvertOutput* m_output; - }; -}// namespace ImageProcessing diff --git a/Gems/ImageProcessing/Code/Source/Processing/ImageFlags.h b/Gems/ImageProcessing/Code/Source/Processing/ImageFlags.h deleted file mode 100644 index 2f09fbb588..0000000000 --- a/Gems/ImageProcessing/Code/Source/Processing/ImageFlags.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 - -//! The following constants are extracted from ImageExtensionHelper.h -//! Please make sure they are always synced with the same constants defined in ImageExtensionHelper.h - -namespace ImageProcessing -{ - // flags to propagate from the RC to the engine through GetImageFlags() - // 32bit bitmask, numbers should not change as engine relies on them - const static AZ::u32 EIF_Cubemap = 0x1; - const static AZ::u32 EIF_Volumetexture = 0x2; - const static AZ::u32 EIF_Decal = 0x4; // this is usually set through the preset - const static AZ::u32 EIF_Greyscale = 0x8; // hint for the engine (e.g. greyscale light beams can be applied to shadow mask), can be for DXT1 because compression artfacts don't count as color - const static AZ::u32 EIF_SupressEngineReduce = 0x10; // info for the engine: don't reduce texture resolution on this texture - const static AZ::u32 EIF_UNUSED_BIT = 0x40; // Free to use - const static AZ::u32 EIF_AttachedAlpha = 0x400; // info for the engine: it's a texture with attached alpha channel - const static AZ::u32 EIF_SRGBRead = 0x800; // info for the engine: if gamma corrected rendering is on, this texture requires SRGBRead (it's not stored in linear) - const static AZ::u32 EIF_DontResize = 0x8000; // info for the engine: for dds textures that shouldn't be resized with r_TexResolution - const static AZ::u32 EIF_RenormalizedTexture = 0x10000; // info for the engine: for dds textures that have renormalized color range - const static AZ::u32 EIF_CafeNative = 0x20000; // info for the engine: native Cafe texture format - const static AZ::u32 EIF_RestrictedPlatformONative = 0x40000; // native tiled texture for restrict platform O - const static AZ::u32 EIF_Tiled = 0x80000; // info for the engine: texture has been tiled for the platform - const static AZ::u32 EIF_RestrictedPlatformDNative = 0x100000; // native tiled texture for restrict platform D - const static AZ::u32 EIF_Splitted = 0x200000; // info for the engine: this texture is splitted - const static AZ::u32 EIF_Colormodel = 0x7000000; // info for the engine: bitmask: colormodel used in the texture - const static AZ::u32 EIF_Colormodel_RGB = 0x0000000; // info for the engine: colormodel is RGB (default) - const static AZ::u32 EIF_Colormodel_CIE = 0x1000000; // info for the engine: colormodel is CIE (used for terrain) - const static AZ::u32 EIF_Colormodel_YCC = 0x2000000; // info for the engine: colormodel is Y'CbCr (used for reflectance) - const static AZ::u32 EIF_Colormodel_YFF = 0x3000000; // info for the engine: colormodel is Y'FbFr (used for reflectance) - const static AZ::u32 EIF_Colormodel_IRB = 0x4000000; // info for the engine: colormodel is IRB (used for reflectance) -} diff --git a/Gems/ImageProcessing/Code/Source/Processing/ImageObjectImpl.cpp b/Gems/ImageProcessing/Code/Source/Processing/ImageObjectImpl.cpp deleted file mode 100644 index 7a6b1e3002..0000000000 --- a/Gems/ImageProcessing/Code/Source/Processing/ImageObjectImpl.cpp +++ /dev/null @@ -1,1417 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or 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 - -// Indicates a 2D texture is a cube-map texture. -#define DDS_RESOURCE_MISC_TEXTURECUBE 0x4 - -namespace ImageProcessing -{ - - IImageObject* IImageObject::CreateImage(AZ::u32 width, AZ::u32 height, - AZ::u32 maxMipCount, EPixelFormat pixelFormat) - { - return aznew CImageObject(width, height, maxMipCount, pixelFormat); - } - - CImageObject::CImageObject(AZ::u32 width, AZ::u32 height, AZ::u32 maxMipCount, EPixelFormat pixelFormat) - : m_pixelFormat(pixelFormat) - , m_colMinARGB(0.0f, 0.0f, 0.0f, 0.0f) - , m_colMaxARGB(1.0f, 1.0f, 1.0f, 1.0f) - , m_averageBrightness(0.63f) - , m_imageFlags(0) - , m_numPersistentMips(0) - { - ResetImage(width, height, maxMipCount, pixelFormat); - } - - EPixelFormat CImageObject::GetPixelFormat() const - { - return m_pixelFormat; - } - - AZ::u32 CImageObject::GetPixelCount(AZ::u32 mip) const - { - AZ_Assert(mip < (AZ::u32)m_mips.size() && m_mips[mip], "Mip doesn't exist: %d", mip); - - return m_mips[mip]->m_width * m_mips[mip]->m_height; - } - - AZ::u32 CImageObject::GetWidth(AZ::u32 mip) const - { - AZ_Assert(mip < (AZ::u32)m_mips.size() && m_mips[mip], "Mip doesn't exist: %d", mip); - - return m_mips[mip]->m_width; - } - - AZ::u32 CImageObject::GetHeight(AZ::u32 mip) const - { - AZ_Assert(mip < (AZ::u32)m_mips.size() && m_mips[mip], "Mip doesn't exist: %d", mip); - - return m_mips[mip]->m_height; - } - - AZ::u32 CImageObject::GetMipCount() const - { - return (AZ::u32)m_mips.size(); - } - - void CImageObject::ResetImage(AZ::u32 width, AZ::u32 height, AZ::u32 maxMipCount, EPixelFormat pixelFormat) - { - //check input - AZ_Assert(width > 0 && height > 0, "image width and height need to larger than 0. width: %d, height: %d", width, height); - AZ_Assert(maxMipCount > 0, "image mipmap count need to larger than 0. maxMipCount: %d", maxMipCount); - - //clean up mipmaps - for (AZ::u32 mip = 0; mip < AZ::u32(m_mips.size()); ++mip) - { - delete m_mips[mip]; - } - - m_pixelFormat = pixelFormat; - m_colMinARGB = AZ::Color(0.0f, 0.0f, 0.0f, 0.0f); - m_colMaxARGB = AZ::Color(1.0f, 1.0f, 1.0f, 1.0f); - m_averageBrightness = 0.0f; - m_imageFlags = 0; - m_numPersistentMips = 0; - m_mips.clear(); - - const PixelFormatInfo* const pFmt = CPixelFormats::GetInstance().GetPixelFormatInfo(m_pixelFormat); - AZ_Assert(pFmt, "can't find pixe format info for %d", m_pixelFormat); - - const AZ::u32 mipCount = AZStd::min(maxMipCount, - CPixelFormats::GetInstance().ComputeMaxMipCount(m_pixelFormat, width, height)); - - m_mips.reserve(mipCount); - - for (AZ::u32 mip = 0; mip < mipCount; ++mip) - { - MipLevel* const pEntry = aznew MipLevel; - - AZ::u32 localWidth = width >> mip; - AZ::u32 localHeight = height >> mip; - if (localWidth < 1) - { - localWidth = 1; - } - if (localHeight < 1) - { - localHeight = 1; - } - - pEntry->m_width = localWidth; - pEntry->m_height = localHeight; - - if (pFmt->bCompressed) - { - const AZ::u32 blocksInRow = (pEntry->m_width + (pFmt->blockWidth - 1)) / pFmt->blockWidth; - pEntry->m_pitch = (blocksInRow * pFmt->bitsPerBlock) / 8; - pEntry->m_rowCount = (localHeight + (pFmt->blockHeight - 1)) / pFmt->blockHeight; - } - else - { - pEntry->m_pitch = (pEntry->m_width * pFmt->bitsPerBlock) / 8; - pEntry->m_rowCount = localHeight; - } - - pEntry->Alloc(); - - m_mips.push_back(pEntry); - } - } - - bool CImageObject::CompareImage(const IImageObjectPtr otherImage) const - { - CImageObject* other = static_cast(otherImage.get()); - if (other == nullptr) - { - return false; - } - - if (m_pixelFormat == other->m_pixelFormat - && m_colMinARGB == other->m_colMinARGB - && m_colMaxARGB == other->m_colMaxARGB - && m_averageBrightness == other->m_averageBrightness - && m_imageFlags == other->m_imageFlags - && m_numPersistentMips == other->m_numPersistentMips - && m_mips.size() == other->m_mips.size()) - { - for (int mip = 0; mip < m_mips.size(); mip++) - { - if (!(*m_mips[mip] == *other->m_mips[mip])) - { - return false; - } - } - return true; - } - return false; - } - - uint CImageObject::GetTextureMemory() const - { - int totalSize = 0; - for (int mip = 0; mip < m_mips.size(); mip++) - { - totalSize += CPixelFormats::GetInstance().EvaluateImageDataSize(m_pixelFormat, - m_mips[mip]->m_width, m_mips[mip]->m_height); - } - - return totalSize; - } - - EAlphaContent CImageObject::GetAlphaContent() const - { - if (CPixelFormats::GetInstance().IsPixelFormatWithoutAlpha(m_pixelFormat)) - { - return EAlphaContent::eAlphaContent_Absent; - } - - //if it's compressed format, return indeterminate. if user really want to know the content, they may convert the format to ARGB8 first - if (!CPixelFormats::GetInstance().IsPixelFormatUncompressed(m_pixelFormat)) - { - AZ_Assert(false, "the function only works right with uncompressed formats. convert to uncompressed format if you get accurate result"); - return EAlphaContent::eAlphaContent_Indeterminate; - } - - //go though alpha channel of first mip - //create pixel operation function to access pixel data - IPixelOperationPtr pixelOp = CreatePixelOperation(m_pixelFormat); - - //get count of bytes per pixel for images - AZ::u32 pixelBytes = CPixelFormats::GetInstance().GetPixelFormatInfo(m_pixelFormat)->bitsPerBlock / 8; - - // counts of blacks and white - uint nBlacks = 0; - uint nWhites = 0; - - float r, g, b, a; - AZ::u8* pixelBuf; - AZ::u32 pitch; - GetImagePointer(0, pixelBuf, pitch); - - const AZ::u32 pixelCount = GetPixelCount(0); - - for (AZ::u32 i = 0; i < pixelCount; ++i, pixelBuf += pixelBytes) - { - pixelOp->GetRGBA(pixelBuf, r, g, b, a); - if (a == 0.0f) - { - ++nBlacks; - } - else if (a == 1.0f) - { - ++nWhites; - } - else - { - return EAlphaContent::eAlphaContent_Greyscale; - } - } - - if (nBlacks == 0) - { - return EAlphaContent::eAlphaContent_OnlyWhite; - } - - if (nWhites == 0) - { - return EAlphaContent::eAlphaContent_OnlyBlack; - } - - return EAlphaContent::eAlphaContent_OnlyBlackAndWhite; - } - - // clone this image-object's contents - IImageObject* CImageObject::Clone() const - { - const EPixelFormat srcPixelformat = GetPixelFormat(); - - IImageObject* pRet = AllocateImage(); - - AZ::u32 dwMips = pRet->GetMipCount(); - for (AZ::u32 dwMip = 0; dwMip < dwMips; ++dwMip) - { - //AZ::u32 dwLocalWidth = GetWidth(dwMip); // we get error on NVidia with this (assumes input is 4x4 as well) - AZ::u32 dwLocalHeight = GetHeight(dwMip); - - AZ::u32 dwLines = dwLocalHeight; - - if (CPixelFormats::GetInstance().IsPixelFormatUncompressed(srcPixelformat)) - { - dwLines = m_mips[dwMip]->m_rowCount; - } - - AZ::u8* pMem; - AZ::u32 dwPitch; - GetImagePointer(dwMip, pMem, dwPitch); - - AZ::u8* pDstMem; - AZ::u32 dwDstPitch; - pRet->GetImagePointer(dwMip, pDstMem, dwDstPitch); - - for (AZ::u32 dwY = 0; dwY < dwLines; ++dwY) - { - memcpy(&pDstMem[dwDstPitch * dwY], &pMem[dwPitch * dwY], AZStd::min(dwPitch, dwDstPitch)); - } - } - return pRet; - } - - void CImageObject::ClearColor(float r, float g, float b, float a) - { - //if it's compressed format, return directly - if (!CPixelFormats::GetInstance().IsPixelFormatUncompressed(m_pixelFormat)) - { - AZ_Assert(false, "The %s function only works with uncompressed formats", __FUNCTION__); - return; - } - //create pixel operation function to access pixel data - IPixelOperationPtr pixelOp = CreatePixelOperation(m_pixelFormat); - - //get count of bytes per pixel for images - AZ::u32 pixelBytes = CPixelFormats::GetInstance().GetPixelFormatInfo(m_pixelFormat)->bitsPerBlock / 8; - - AZ::u8* pixelBuf; - AZ::u32 pitch; - - AZ::u32 mips = GetMipCount(); - for (AZ::u32 mip = 0; mip < mips; ++mip) - { - GetImagePointer(mip, pixelBuf, pitch); - const AZ::u32 pixelCount = GetPixelCount(mip); - for (AZ::u32 i = 0; i < pixelCount; ++i, pixelBuf += pixelBytes) - { - pixelOp->SetRGBA(pixelBuf, r, g, b, a); - } - } - } - - // allocate an empty image with the same properties as the given image and the requested format - IImageObject* CImageObject::AllocateImage(EPixelFormat pixelFormat) const - { - AZ::u32 width = GetWidth(0); - AZ::u32 height = GetHeight(0); - - if (!CPixelFormats::GetInstance().IsImageSizeValid(pixelFormat, width, height, false)) - { - AZ_Assert(false, "Cann't allocate image with format: %d", pixelFormat); - return nullptr; - } - - CImageObject* pRet = aznew CImageObject(width, height, GetMipCount(), pixelFormat); - pRet->CopyPropertiesFrom(this); - return pRet; - } - - IImageObject* CImageObject::AllocateImage() const - { - return AllocateImage(m_pixelFormat); - } - - CImageObject::~CImageObject() - { - for (size_t i = 0; i < m_mips.size(); ++i) - { - delete m_mips[i]; - } - m_mips.clear(); - } - - //note: there are some unreasonable parts of the save files formats for cry textures. We might need to rethink about - // it for new renderer - bool CImageObject::SaveImage(const char* filename, IImageObjectPtr alphaImage, AZStd::vector& outFilePaths) const - { - AZ::IO::SystemFile file; - file.Open(filename, AZ::IO::SystemFile::SF_OPEN_CREATE | AZ::IO::SystemFile::SF_OPEN_CREATE_PATH | AZ::IO::SystemFile::SF_OPEN_WRITE_ONLY); - - AZ::IO::SystemFileStream fileSaveStream(&file, true); - if (!fileSaveStream.IsOpen()) - { - - AZ_Warning("Image Processing", false, "%s: failed to create file %s", __FUNCTION__, filename); - return false; - } - - if (alphaImage) - { - AZ_Assert(HasImageFlags(EIF_AttachedAlpha), "attached alpha image flag wasn't set"); - AZ_Assert(!alphaImage->HasImageFlags(EIF_AttachedAlpha), "alpha image shouldn't have attached alpha image flag"); - - // inherit cubemap and decal image flags to attached alpha image - alphaImage->AddImageFlags(GetImageFlags() & (EIF_Cubemap - | EIF_Decal | EIF_Splitted)); - alphaImage->SetNumPersistentMips(m_numPersistentMips); - } - - bool bOk = SaveImage(fileSaveStream); - bool hasSplitFlag = HasImageFlags(EIF_Splitted); - - //append alpha image data in the end if there is no split - if (bOk && alphaImage && !hasSplitFlag) - { - //4 bytes extension tag, 4 bytes attached alpha tag, then 4 bytes of chunk size - fileSaveStream.Write(sizeof(FOURCC_CExt), &FOURCC_CExt); // marker for the start of Crytek Extended data - fileSaveStream.Write(sizeof(FOURCC_AttC), &FOURCC_AttC); // Attached Channel chunk - - AZ::u32 size = 0; - AZ::u32 sizeBytes = sizeof(size); - fileSaveStream.Write(sizeBytes, &size); //size of attached chunk - - //save alpha image and get the size - AZ::IO::SizeType startPos = fileSaveStream.GetCurPos(); - bOk = alphaImage->SaveImage(fileSaveStream); - AZ::IO::SizeType endPos = fileSaveStream.GetCurPos(); - size = aznumeric_cast(endPos - startPos); - - //move back to beginning of chunk and write chunk size then move back to end - fileSaveStream.Seek(startPos - sizeBytes, AZ::IO::GenericStream::ST_SEEK_BEGIN); - fileSaveStream.Write(sizeBytes, &size); - fileSaveStream.Seek(endPos, AZ::IO::GenericStream::ST_SEEK_BEGIN); - - // marker for the end of Crytek Extended data - fileSaveStream.Write(sizeof(FOURCC_CEnd), &FOURCC_CEnd); - } - - if (!bOk) - { - AZ::IO::SystemFile::Delete(filename); - return false; - } - - // It's important to maintain the product output sequence. Asset Database/Browser will use the first product to determine the source type! - outFilePaths.push_back(filename); - - // save stand alone products - if (hasSplitFlag) - { - // alpha - if (alphaImage) - { - AZStd::string alphaFile = AZStd::string::format("%s.a", filename); - - AZ::IO::SystemFile outAlphaFile; - outAlphaFile.Open(alphaFile.c_str(), AZ::IO::SystemFile::SF_OPEN_CREATE | AZ::IO::SystemFile::SF_OPEN_CREATE_PATH | AZ::IO::SystemFile::SF_OPEN_WRITE_ONLY); - - AZ::IO::SystemFileStream alphaFileSaveStream(&outAlphaFile, true); - - if (alphaFileSaveStream.IsOpen()) - { - alphaImage->SaveImage(alphaFileSaveStream); - outFilePaths.push_back(alphaFile); - } - else - { - AZ_Warning("Image Processing", false, "%s: failed to create file %s", __FUNCTION__, alphaFile.c_str()); - } - } - - // mips - AZ::u32 numStreamable = GetMipCount() - m_numPersistentMips; - for (AZ::u32 mip = 0; mip < numStreamable; mip++) - { - AZ::u32 nameIdx = numStreamable - mip; - AZStd::string mipFileName = AZStd::string::format("%s.%d", filename, nameIdx); - SaveMipToFile(mip, mipFileName); - outFilePaths.push_back(mipFileName); - if (alphaImage) - { - AZStd::string mipAlphaFileName = mipFileName + "a"; - alphaImage->SaveMipToFile(mip, mipAlphaFileName); - outFilePaths.push_back(mipAlphaFileName); - } - } - } - - return bOk; - } - - bool CImageObject::SaveMipToFile(AZ::u32 mip, const AZStd::string& filename) const - { - AZ::IO::SystemFile saveFile; - saveFile.Open(filename.c_str(), AZ::IO::SystemFile::SF_OPEN_CREATE | AZ::IO::SystemFile::SF_OPEN_CREATE_PATH | AZ::IO::SystemFile::SF_OPEN_WRITE_ONLY); - - AZ::IO::SystemFileStream saveFileStream(&saveFile, true); - - if (!saveFileStream.IsOpen()) - { - AZ_Warning("Image Processing", false, "%s: failed to create file %s", __FUNCTION__, filename.c_str()); - return false; - } - - saveFileStream.Write(GetMipBufSize(mip), m_mips[mip]->m_pData); - return true; - } - - IImageObject* CreateImageFromHeader(DDS_HEADER& header, DDS_HEADER_DXT10& exthead) - { - EPixelFormat eFormat = ePixelFormat_Unknown; - AZ::u32 dwWidth, dwMips, dwHeight; - AZ::u32 imageFlags = header.dwReserved1; - AZ::Color colMinARGB, colMaxARGB; - - dwWidth = header.dwWidth; - dwHeight = header.dwHeight; - dwMips = 1; - if (header.dwHeaderFlags & DDS_HEADER_FLAGS_MIPMAP) - { - dwMips = header.dwMipMapCount; - } - if ((header.dwSurfaceFlags & DDS_SURFACE_FLAGS_CUBEMAP) && (header.dwCubemapFlags & DDS_CUBEMAP_ALLFACES)) - { - AZ_Assert(header.dwReserved1&EIF_Cubemap, "Image flag should have cubemap flag"); - dwHeight *= 6; - } - - colMinARGB = AZ::Color(header.cMinColor[0], header.cMinColor[1], header.cMinColor[2], header.cMinColor[3]); - colMaxARGB = AZ::Color(header.cMaxColor[0], header.cMaxColor[1], header.cMaxColor[2], header.cMaxColor[3]); - - //get pixel format - { - // DX10 formats - if (header.ddspf.dwFourCC == FOURCC_DX10) - { - AZ::u32 dxgiFormat = exthead.dxgiFormat; - - //remove the SRGB from dxgi format and add sRGB to image flag - if (dxgiFormat == DXGI_FORMAT_R8G8B8A8_UNORM_SRGB) - { - dxgiFormat = DXGI_FORMAT_R8G8B8A8_UNORM; - } - else if (dxgiFormat == DXGI_FORMAT_BC1_UNORM_SRGB) - { - dxgiFormat = DXGI_FORMAT_BC1_UNORM; - } - else if (dxgiFormat == DXGI_FORMAT_BC2_UNORM_SRGB) - { - dxgiFormat = DXGI_FORMAT_BC2_UNORM; - } - else if (dxgiFormat == DXGI_FORMAT_BC3_UNORM_SRGB) - { - dxgiFormat = DXGI_FORMAT_BC3_UNORM; - } - else if (dxgiFormat == DXGI_FORMAT_BC7_UNORM_SRGB) - { - dxgiFormat = DXGI_FORMAT_BC7_UNORM; - } - - //add rgb flag if the dxgiformat was changed (which means it was sRGB format) above - if (dxgiFormat != exthead.dxgiFormat) - { - AZ_Assert(imageFlags&EIF_SRGBRead, "Image flags should have SRGBRead flag"); - imageFlags |= EIF_SRGBRead; - } - - //check all the pixel formats and find matching one - if (dxgiFormat != DXGI_FORMAT_UNKNOWN) - { - int i = 0; - for (i; id3d10Format == dxgiFormat) - { - eFormat = (EPixelFormat)i; - break; - } - } - if (i == ePixelFormat_Count) - { - AZ_Error("Image Processing", false, "Unhandled d3d10 format: %d", dxgiFormat); - return nullptr; - } - } - } - else - { - //for non-dx10 formats, use fourCC to find out its pixel formats - //go through all pixel formats and find a match with the fourcc - for (AZ::u32 formatIdx = 0; formatIdx < ePixelFormat_Count; formatIdx++) - { - const PixelFormatInfo *info = CPixelFormats::GetInstance().GetPixelFormatInfo((EPixelFormat)formatIdx); - if (header.ddspf.dwFourCC == info->fourCC) - { - eFormat = (EPixelFormat)formatIdx; - break; - } - } - - //legacy formats. This section is only used for load dds files converted by RC.exe - //our save to dds file function won't use any of these fourcc - if (eFormat == ePixelFormat_Unknown) - { - if (header.ddspf.dwFourCC == FOURCC_DXT1) - { - eFormat = ePixelFormat_BC1; - } - else if (header.ddspf.dwFourCC == FOURCC_DXT5) - { - eFormat = ePixelFormat_BC3; - } - else if (header.ddspf.dwFourCC == FOURCC_3DCP) - { - eFormat = ePixelFormat_BC4; - } - else if (header.ddspf.dwFourCC == FOURCC_3DC) - { - eFormat = ePixelFormat_BC5; - } - else if (header.ddspf.dwFourCC == DDS_FOURCC_R32F) - { - eFormat = ePixelFormat_R32F; - } - else if (header.ddspf.dwFourCC == DDS_FOURCC_G32R32F) - { - eFormat = ePixelFormat_R32G32F; - } - else if (header.ddspf.dwFourCC == DDS_FOURCC_A32B32G32R32F) - { - eFormat = ePixelFormat_R32G32B32A32F; - } - else if (header.ddspf.dwFourCC == DDS_FOURCC_R16F) - { - eFormat = ePixelFormat_R16F; - } - else if (header.ddspf.dwFourCC == DDS_FOURCC_G16R16F) - { - eFormat = ePixelFormat_R16G16F; - } - else if (header.ddspf.dwFourCC == DDS_FOURCC_A16B16G16R16F) - { - eFormat = ePixelFormat_R16G16B16A16F; - } - else if (header.ddspf.dwFourCC == DDS_FOURCC_A16B16G16R16) - { - eFormat = ePixelFormat_R16G16B16A16; - } - else if ((header.ddspf.dwFlags == DDS_RGBA || header.ddspf.dwFlags == DDS_RGB) - && header.ddspf.dwRGBBitCount == 32) - { - if (header.ddspf.dwRBitMask == 0x00ff0000) - { - eFormat = ePixelFormat_B8G8R8A8; - } - else - { - eFormat = ePixelFormat_R8G8B8A8; - } - } - else if (header.ddspf.dwFlags == DDS_LUMINANCEA && header.ddspf.dwRGBBitCount == 8) - { - eFormat = ePixelFormat_R8G8; - } - else if (header.ddspf.dwFlags == DDS_LUMINANCE && header.ddspf.dwRGBBitCount == 8) - { - eFormat = ePixelFormat_A8; - } - else if ((header.ddspf.dwFlags == DDS_A || header.ddspf.dwFlags == DDS_A_ONLY || header.ddspf.dwFlags == (DDS_A | DDS_A_ONLY)) && header.ddspf.dwRGBBitCount == 8) - { - eFormat = ePixelFormat_A8; - } - } - } - } - - if (eFormat == ePixelFormat_Unknown) - { - AZ_Error("Image Processing", false, "Unhandled dds pixel format fourCC: %d, flags: %d", - header.ddspf.dwFourCC, header.ddspf.dwFlags); - return nullptr; - } - - IImageObject* newImage = IImageObject::CreateImage(dwWidth, dwHeight, dwMips, eFormat); - - if (dwMips != newImage->GetMipCount()) - { - AZ_Error("Image Processing", false, "Mipcount from image data doesn't match image size and pixelformat"); - delete newImage; - return nullptr; - } - - //set properties - newImage->SetImageFlags(imageFlags); - newImage->SetAverageBrightness(header.fAvgBrightness); - newImage->SetColorRange(colMinARGB, colMaxARGB); - newImage->SetNumPersistentMips(header.bNumPersistentMips); - - return newImage; - } - - float CImageObject::CalculateAverageBrightness() const - { - //if it's compressed format, return a default value - if (!CPixelFormats::GetInstance().IsPixelFormatUncompressed(m_pixelFormat)) - { - return 0.5f; - } - - // Accumulate pixel colors of the top mip - double avgOverall[3] = { 0.0, 0.0, 0.0 }; - - //create pixel operation function to access pixel data - IPixelOperationPtr pixelOp = CreatePixelOperation(m_pixelFormat); - - //get count of bytes per pixel for images - AZ::u32 pixelBytes = CPixelFormats::GetInstance().GetPixelFormatInfo(m_pixelFormat)->bitsPerBlock / 8; - - //only calculate mip 0 - AZ::u32 mip = 0; - float color[4]; - AZ::u8* pixelBuf; - AZ::u32 pitch; - GetImagePointer(mip, pixelBuf, pitch); - const AZ::u32 pixelCount = GetPixelCount(mip); - for (AZ::u32 i = 0; i < pixelCount; ++i, pixelBuf += pixelBytes) - { - pixelOp->GetRGBA(pixelBuf, color[0], color[1], color[2], color[3]); - avgOverall[0] += color[0]; - avgOverall[1] += color[1]; - avgOverall[2] += color[2]; - } - - const double avg = (avgOverall[0] + avgOverall[1] + avgOverall[2]) / (3 * pixelCount); - - return (float)avg; - } - - bool CImageObject::BuildSurfaceHeader(DDS_HEADER& header) const - { - AZ::u32 dwWidth, dwMips, dwHeight; - GetExtent(dwWidth, dwHeight, dwMips); - - if (dwMips <= 0) - { - AZ_Error("Image Processing", false, "%s: dwMips is %u", __FUNCTION__, (unsigned)dwMips); - return false; - } - - const EPixelFormat format = GetPixelFormat(); - if ((format < 0) || (format >= ePixelFormat_Count)) - { - AZ_Error("Image Processing", false, "%s: Bad format %d", __FUNCTION__, (int)format); - return false; - } - - const PixelFormatInfo* const pPixelFormatInfo = CPixelFormats::GetInstance().GetPixelFormatInfo(format); - - memset(&header, 0, sizeof(DDS_HEADER)); - - header.dwSize = sizeof(DDS_HEADER); - header.dwHeaderFlags = DDSD_CAPS | DDSD_PIXELFORMAT | DDSD_WIDTH | DDSD_HEIGHT; - header.dwWidth = dwWidth; - header.dwHeight = dwHeight; - - if (HasImageFlags(EIF_Cubemap)) - { - header.dwSurfaceFlags |= DDS_SURFACE_FLAGS_CUBEMAP; - header.dwCubemapFlags |= DDS_CUBEMAP_ALLFACES; - //save face size instead of image size. - header.dwHeight /= 6; - } - - header.ddspf.dwSize = sizeof(DDS_PIXELFORMAT); - header.ddspf.dwFlags = DDS_FOURCC; - - header.ddspf.dwFourCC = pPixelFormatInfo->fourCC; - - header.dwSurfaceFlags |= DDS_SURFACE_FLAGS_TEXTURE; - - if (dwMips > 1) - { - header.dwHeaderFlags |= DDS_HEADER_FLAGS_MIPMAP; - header.dwMipMapCount = dwMips; - header.dwSurfaceFlags |= DDS_SURFACE_FLAGS_MIPMAP; - } - - // non standardized way to expose some features in the header (same information is in attached chunk but then - // streaming would need to find this spot in the file) - // if this is causing problems we need to change it - header.dwTextureStage = FOURCC_FYRC; - header.dwReserved1 = GetImageFlags(); - header.bNumPersistentMips = (AZ::u8)GetNumPersistentMips(); - - //tile mode for some platform native texture - if (HasImageFlags(EIF_RestrictedPlatformDNative)) - { - header.tileMode = eTM_LinearPadded; - } - else if (HasImageFlags(EIF_RestrictedPlatformONative)) - { - header.tileMode = eTM_Optimal; - } - - // setting up min and max colors - for (int i = 0; i < 4; i ++) - { - header.cMinColor[i] = m_colMinARGB.GetElement(i); - header.cMaxColor[i] = m_colMaxARGB.GetElement(i); - } - - // set avg brightness - header.fAvgBrightness = GetAverageBrightness(); - - return true; - } - - bool CImageObject::BuildSurfaceExtendedHeader(DDS_HEADER_DXT10& exthead) const - { - const EPixelFormat format = GetPixelFormat(); - - const PixelFormatInfo* const pPixelFormatInfo = CPixelFormats::GetInstance().GetPixelFormatInfo(format); - - DXGI_FORMAT dxgiformat = pPixelFormatInfo->d3d10Format; - - // check if we hit a format which can't be stored into a DX10 DDS-file (fe. L8) - if (dxgiformat == DXGI_FORMAT_UNKNOWN) - { - AZ_Error("Image Processing", false, "%s: Format can not be stored in a DDS-file %d", __FUNCTION__, dxgiformat); - return false; - } - - //the dxgi format are different for linear space or gamma space - if (HasImageFlags(EIF_SRGBRead)) - { - switch (dxgiformat) - { - case DXGI_FORMAT_R8G8B8A8_UNORM: - dxgiformat = DXGI_FORMAT_R8G8B8A8_UNORM_SRGB; - break; - case DXGI_FORMAT_BC1_UNORM: - dxgiformat = DXGI_FORMAT_BC1_UNORM_SRGB; - break; - case DXGI_FORMAT_BC2_UNORM: - dxgiformat = DXGI_FORMAT_BC2_UNORM_SRGB; - break; - case DXGI_FORMAT_BC3_UNORM: - dxgiformat = DXGI_FORMAT_BC3_UNORM_SRGB; - break; - case DXGI_FORMAT_BC7_UNORM: - dxgiformat = DXGI_FORMAT_BC7_UNORM_SRGB; - break; - default: - break; - } - } - else - { - switch (dxgiformat) - { - case DXGI_FORMAT_R8G8B8A8_UNORM_SRGB: - dxgiformat = DXGI_FORMAT_R8G8B8A8_UNORM; - break; - case DXGI_FORMAT_BC1_UNORM_SRGB: - dxgiformat = DXGI_FORMAT_BC1_UNORM; - break; - case DXGI_FORMAT_BC2_UNORM_SRGB: - dxgiformat = DXGI_FORMAT_BC2_UNORM; - break; - case DXGI_FORMAT_BC3_UNORM_SRGB: - dxgiformat = DXGI_FORMAT_BC3_UNORM; - break; - case DXGI_FORMAT_BC7_UNORM_SRGB: - dxgiformat = DXGI_FORMAT_BC7_UNORM; - break; - default: - break; - } - } - - memset(&exthead, 0, sizeof(exthead)); - - exthead.dxgiFormat = dxgiformat; - exthead.resourceDimension = 3; //texture2d. not used - - if (HasImageFlags(EIF_Volumetexture)) - { - AZ_Assert(false, "There isn't any support for volume texture"); - } - else if (HasImageFlags(EIF_Cubemap)) - { - exthead.miscFlag = DDS_RESOURCE_MISC_TEXTURECUBE; - exthead.arraySize = 6; - } - else - { - exthead.miscFlag = 0; - exthead.arraySize = 1; - } - - return true; - } - - bool CImageObject::SaveImage(AZ::IO::SystemFileStream &saveFileStream) const - { - DDS_FILE_DESC desc; - DDS_HEADER_DXT10 exthead; - - desc.dwMagic = FOURCC_DDS; - - if (!BuildSurfaceHeader(desc.header)) - { - return false; - } - - if (desc.header.IsDX10Ext() && !BuildSurfaceExtendedHeader(exthead)) - { - return false; - } - - saveFileStream.Write(sizeof(desc), &desc); - - if (desc.header.IsDX10Ext()) - { - saveFileStream.Write(sizeof(exthead), &exthead); - } - - AZ::u32 faces = 1; - - //for cubemap. export each face and its mipmap - if (HasImageFlags(EIF_Cubemap)) - { - faces = 6; - } - - AZ::u32 mipStart = 0; - if (HasImageFlags(EIF_Splitted)) - { - if (m_numPersistentMips < m_mips.size()) - { - mipStart = (AZ::u32)m_mips.size() - m_numPersistentMips; - } - else - { - AZ_Assert(false, "numPersistentMips wasn't setup correctly"); - } - } - - for (AZ::u32 face = 0; face < faces; face++) - { - for (AZ::u32 mip = mipStart; mip < m_mips.size(); ++mip) - { - const MipLevel& level = *m_mips[mip]; - AZ::u32 faceBufSize = level.m_pitch*level.m_rowCount / faces; - saveFileStream.Write(faceBufSize, level.m_pData + faceBufSize*face); - } - } - return true; - } - - void CImageObject::GetExtent(AZ::u32& width, AZ::u32& height, AZ::u32& mipCount) const - { - mipCount = (AZ::u32)m_mips.size(); - - width = m_mips[0]->m_width; - height = m_mips[0]->m_height; - } - - AZ::u32 CImageObject::GetMipDataSize(const AZ::u32 mip) const - { - AZ_Assert(mip < m_mips.size(), "mip %d doesn't exist", mip); - - return m_mips[mip]->GetSize(); - } - - void CImageObject::GetImagePointer(const AZ::u32 mip, AZ::u8*& pMem, AZ::u32& pitch) const - { - AZ_Assert(mip < (AZ::u32)m_mips.size() && m_mips[mip], "requested mip doesn't exist"); - - pMem = m_mips[mip]->m_pData; - pitch = m_mips[mip]->m_pitch; - } - - AZ::u32 CImageObject::GetMipBufSize(AZ::u32 mip) const - { - AZ_Assert(mip < (AZ::u32)m_mips.size() && m_mips[mip], "requested mip doesn't exist"); - - return m_mips[mip]->m_rowCount * m_mips[mip]->m_pitch; - } - - - void CImageObject::SetMipData(AZ::u32 mip, AZ::u8* mipBuf, AZ::u32 bufSize, AZ::u32 pitch) - { - if (mip >= m_mips.size()) - { - return; - } - m_mips[mip]->m_pData = mipBuf; - m_mips[mip]->m_pitch = pitch; - m_mips[mip]->m_rowCount = bufSize/pitch; - AZ_Assert(bufSize == m_mips[mip]->m_rowCount * pitch, "Bad pitch size"); - } - - // ARGB - void CImageObject::GetColorRange(AZ::Color& minColor, AZ::Color& maxColor) const - { - minColor = m_colMinARGB; - maxColor = m_colMaxARGB; - } - - // ARGB - void CImageObject::SetColorRange(const AZ::Color& minColor, const AZ::Color& maxColor) - { - m_colMinARGB = minColor; - m_colMaxARGB = maxColor; - } - - float CImageObject::GetAverageBrightness() const - { - return m_averageBrightness; - } - - void CImageObject::SetAverageBrightness(const float avgBrightness) - { - m_averageBrightness = avgBrightness; - } - - AZ::u32 CImageObject::GetImageFlags() const - { - return m_imageFlags; - } - - void CImageObject::SetImageFlags(const AZ::u32 imageFlags) - { - m_imageFlags = imageFlags; - } - - void CImageObject::AddImageFlags(const AZ::u32 imageFlags) - { - m_imageFlags |= imageFlags; - } - - void CImageObject::RemoveImageFlags(const AZ::u32 imageFlags) - { - m_imageFlags &= ~imageFlags; - } - - bool CImageObject::HasImageFlags(const AZ::u32 imageFlags) const - { - return (m_imageFlags & imageFlags) != 0; - } - - AZ::u32 CImageObject::GetNumPersistentMips() const - { - return m_numPersistentMips; - } - - void CImageObject::SetNumPersistentMips(AZ::u32 nMips) - { - m_numPersistentMips = nMips; - } - - bool CImageObject::HasPowerOfTwoSizes() const - { - AZ::u32 w, h, mips; - GetExtent(w, h, mips); - return ((w&(w - 1)) == 0) && ((h&(h - 1)) == 0); - } - - // use when you convert an image to another one - void CImageObject::CopyPropertiesFrom(const IImageObjectPtr src) - { - const CImageObject *imageObj = static_cast(src.get()); - CopyPropertiesFrom(imageObj); - } - - void CImageObject::CopyPropertiesFrom(const CImageObject* src) - { - m_colMinARGB = src->m_colMinARGB; - m_colMaxARGB = src->m_colMaxARGB; - m_averageBrightness = src->m_averageBrightness; - m_imageFlags = src->GetImageFlags(); - } - - void CImageObject::Swizzle(const char channels[4]) - { - if (!(CPixelFormats::GetInstance().IsPixelFormatUncompressed(m_pixelFormat))) - { - AZ_Assert(false, "%s function only works with uncompressed pixel format", __FUNCTION__); - return; - } - - const AZ::u8 channelCnt = 4; - - enum Channel_Id - { - ChannelR = 0, - ChannelG, - ChannelB, - ChannelA, - ChannelVal0, - ChannelVal1, - ChannelTypeCount - }; - - float values[ChannelTypeCount]; - values[ChannelVal0] = 0.f; - values[ChannelVal1] = 1.f; - - AZ::u8 channelIndics[channelCnt]; - for (AZ::u8 idx = 0; idx < channelCnt; idx++) - { - switch (channels[idx]) - { - case 'a': - channelIndics[idx] = ChannelA; - break; - case 'r': - channelIndics[idx] = ChannelR; - break; - case 'g': - channelIndics[idx] = ChannelG; - break; - case 'b': - channelIndics[idx] = ChannelB; - break; - case '0': - channelIndics[idx] = ChannelVal0; - break; - case '1': - channelIndics[idx] = ChannelVal1; - break; - default: - AZ_Assert(false, "%s function only works with channel name \"rgba01\"", __FUNCTION__); - return; - } - } - - //create pixel operation function - IPixelOperationPtr pixelOp = CreatePixelOperation(m_pixelFormat); - - //get count of bytes per pixel - uint32 pixelBytes = CPixelFormats::GetInstance().GetPixelFormatInfo(m_pixelFormat)->bitsPerBlock / 8; - - const uint32 mips = (uint32)m_mips.size(); - for (uint32 mip = 0; mip < mips; ++mip) - { - uint8* pixelBuf = m_mips[mip]->m_pData; - const uint32 pixelCount = GetPixelCount(mip); - - for (uint32 i = 0; i < pixelCount; ++i, pixelBuf += pixelBytes) - { - pixelOp->GetRGBA(pixelBuf, values[ChannelR], values[ChannelG], values[ChannelB], values[ChannelA]); - pixelOp->SetRGBA(pixelBuf, values[channelIndics[0]], values[channelIndics[1]], - values[channelIndics[2]], values[channelIndics[3]]); - } - } - } - - void CImageObject::GlossFromNormals(bool hasAuthoredGloss) - { - if (!(CPixelFormats::GetInstance().IsPixelFormatUncompressed(m_pixelFormat))) - { - AZ_Assert(false, "%s function only works with uncompressed pixel format", __FUNCTION__); - return; - } - - // Derive new roughness from normal variance to preserve the bumpiness of normal map mips and to reduce specular aliasing. - // The derived roughness is combined with the artist authored roughness stored in the alpha channel of the normal map. - // The algorithm is based on the Frequency Domain Normal Mapping implementation presented by Neubelt and Pettineo at Siggraph 2013. - - //create pixel operation function - IPixelOperationPtr pixelOp = CreatePixelOperation(m_pixelFormat); - - //get count of bytes per pixel - AZ::u32 pixelBytes = CPixelFormats::GetInstance().GetPixelFormatInfo(m_pixelFormat)->bitsPerBlock / 8; - - const AZ::u32 mips = (AZ::u32)m_mips.size(); - float color[4]; - for (AZ::u32 mip = 0; mip < mips; ++mip) - { - AZ::u8* pixelBuf = m_mips[mip]->m_pData; - const AZ::u32 pixelCount = GetPixelCount(mip); - - for (AZ::u32 i = 0; i < pixelCount; ++i, pixelBuf += pixelBytes) - { - pixelOp->GetRGBA(pixelBuf, color[0], color[1], color[2], color[3]); - - // Get length of the averaged normal - AZ::Vector3 normal(color[0] * 2.0f - 1.0f, color[1] * 2.0f - 1.0f, color[2] * 2.0f - 1.0f); - - float len = AZ::GetMax(normal.GetLength(), 1.0f / (1 << 15)); - - float authoredSmoothness = hasAuthoredGloss ? color[3] : 1.0f; - float finalSmoothness = authoredSmoothness; - - if (len < 1.0f) - { - // Convert from smoothness to roughness (needs to match shader code) - float authoredRoughness = (1.0f - authoredSmoothness) * (1.0f - authoredSmoothness); - - // Derive new roughness based on normal variance - float kappa = (3.0f * len - len * len * len) / (1.0f - len * len); - float variance = 1.0f / (2.0f * kappa); - float finalRoughness = AZ::GetMin(sqrtf(authoredRoughness * authoredRoughness + variance), 1.0f); - - // Convert roughness back to smoothness - finalSmoothness = 1.0f - sqrtf(finalRoughness); - } - - pixelOp->SetRGBA(pixelBuf, color[0], color[1], color[2], finalSmoothness); - - } - } - } - - void CImageObject::ConvertLegacyGloss() - { - if (!(CPixelFormats::GetInstance().IsPixelFormatUncompressed(m_pixelFormat))) - { - AZ_Assert(false, "%s function only works with uncompressed pixel format", __FUNCTION__); - return; - } - - //create pixel operation function - IPixelOperationPtr pixelOp = CreatePixelOperation(m_pixelFormat); - - //get count of bytes per pixel - AZ::u32 pixelBytes = CPixelFormats::GetInstance().GetPixelFormatInfo(m_pixelFormat)->bitsPerBlock / 8; - - const AZ::u32 mips = (AZ::u32)m_mips.size(); - float color[4]; - for (AZ::u32 mip = 0; mip < mips; ++mip) - { - AZ::u8* pixelBuf = m_mips[mip]->m_pData; - const AZ::u32 pixelCount = GetPixelCount(mip); - - for (AZ::u32 i = 0; i < pixelCount; ++i, pixelBuf += pixelBytes) - { - pixelOp->GetRGBA(pixelBuf, color[0], color[1], color[2], color[3]); - // Convert from (1 - s * 0.7)^6 to (1 - s)^2 - color[3] = 1 - pow(1.0f - color[3] * 0.7f, 3.0f); - pixelOp->SetRGBA(pixelBuf, color[0], color[1], color[2], color[3]); - } - } - } - - IImageObject* LoadImageFromDdsFile(const AZStd::string& filename) - { - AZ::IO::SystemFile file; - file.Open(filename.c_str(), AZ::IO::SystemFile::SF_OPEN_READ_ONLY); - - AZ::IO::SystemFileStream fileLoadStream(&file, true); - if (!fileLoadStream.IsOpen()) - { - AZ_Warning("Image Processing", false, "%s: failed to open file %s", __FUNCTION__, filename.c_str()); - return nullptr; - } - - AZStd::string ext = ""; - AzFramework::StringFunc::Path::GetExtension(filename.c_str(), ext, false); - bool isAlphaImage = (ext == "a"); - - IImageObject* imageObj = LoadImageFromDdsFile(fileLoadStream); - - //load mips from seperated files if it's splitted - if (imageObj && imageObj->HasImageFlags(EIF_Splitted)) - { - AZStd::string baseName; - if (isAlphaImage) - { - baseName = filename.substr(0, filename.size() - 2); - } - else - { - baseName = filename; - } - - AZ::u32 externalMipCount = 0; - if (imageObj->GetNumPersistentMips() < imageObj->GetMipCount()) - { - externalMipCount = imageObj->GetMipCount() - imageObj->GetNumPersistentMips(); - } - //load other mips from files with number extensions - for (AZ::u32 mipIdx = 1; mipIdx <= externalMipCount; mipIdx++) - { - AZ::u32 mip = externalMipCount - mipIdx; - AZStd::string mipFileName = AZStd::string::format("%s.%d%s", baseName.c_str(), mipIdx, isAlphaImage?"a":""); - - AZ::IO::SystemFile mipFile; - mipFile.Open(mipFileName.c_str(), AZ::IO::SystemFile::SF_OPEN_READ_ONLY); - - AZ::IO::SystemFileStream mipFileLoadStream(&mipFile, true); - - if (!mipFileLoadStream.IsOpen()) - { - AZ_Warning("Image Processing", false, "%s: failed to open mip file %s", __FUNCTION__, mipFileName.c_str()); - break; - } - - AZ::u32 pitch; - AZ::u8* mem; - imageObj->GetImagePointer(mip, mem, pitch); - AZ::u32 bufSize = imageObj->GetMipBufSize(mip); - mipFileLoadStream.Read(bufSize, mem); - } - } - - return imageObj; - } - - IImageObject* LoadImageFromDdsFile(AZ::IO::SystemFileStream& fileLoadStream) - { - if (fileLoadStream.GetLength() - fileLoadStream.GetCurPos() < sizeof(DDS_FILE_DESC)) - { - AZ_Error("Image Processing", false, "%s: Trying to load a none-DDS file", __FUNCTION__); - return nullptr; - } - - DDS_FILE_DESC desc; - DDS_HEADER_DXT10 exthead; - - AZ::IO::SizeType startPos = fileLoadStream.GetCurPos(); - fileLoadStream.Read(sizeof(desc.dwMagic), &desc.dwMagic); - - if (desc.dwMagic != FOURCC_DDS) - { - desc.dwMagic = FOURCC_DDS; - //the old cry .a file doesn't have "DDS " in the beginning of the file. - //so reset to previous position - fileLoadStream.Seek(startPos, AZ::IO::GenericStream::ST_SEEK_BEGIN); - } - - fileLoadStream.Read(sizeof(desc.header), &desc.header); - - if (!desc.IsValid()) - { - AZ_Error("Image Processing", false, "%s: Trying to load a none-DDS file", __FUNCTION__); - return nullptr; - } - - if (desc.header.IsDX10Ext()) - { - fileLoadStream.Read(sizeof(exthead), &exthead); - } - - IImageObject* outImage = CreateImageFromHeader(desc.header, exthead); - - if (outImage == nullptr) - { - return nullptr; - } - - //load mip data - AZ::u32 mipStart = 0; - //There are at least three lowest mips are in the file if it was splitted. This is to load splitted dds file exported by legacy rc.exe - int numPersistentMips = outImage->GetNumPersistentMips(); - if (numPersistentMips == 0 && outImage->HasImageFlags(EIF_Splitted)) - { - outImage->SetNumPersistentMips(3); - } - - if (outImage->HasImageFlags(EIF_Splitted) - && outImage->GetMipCount() > outImage->GetNumPersistentMips()) - { - mipStart = outImage->GetMipCount() - outImage->GetNumPersistentMips(); - } - - AZ::u32 faces = 1; - if (outImage->HasImageFlags(EIF_Cubemap)) - { - faces = 6; - } - - for (AZ::u32 face = 0; face < faces; face++) - { - for (AZ::u32 mip = mipStart; mip < outImage->GetMipCount(); ++mip) - { - AZ::u32 pitch; - AZ::u8* mem; - outImage->GetImagePointer(mip, mem, pitch); - AZ::u32 faceBufSize = outImage->GetMipBufSize(mip) / faces; - fileLoadStream.Read(faceBufSize, mem + faceBufSize*face); - } - } - - return outImage; - } - - IImageObject* LoadAttachedImageFromDdsFile(const AZStd::string& filename, IImageObjectPtr originImage) - { - if (originImage == nullptr) - { - return nullptr; - } - - AZ_Assert(originImage->HasImageFlags(EIF_AttachedAlpha), - "this function should only be called for origin image loaded from same file with attached alpha flag"); - - AZ::IO::SystemFile file; - file.Open(filename.c_str(), AZ::IO::SystemFile::SF_OPEN_READ_ONLY); - - AZ::IO::SystemFileStream fileLoadStream(&file, true); - if (!fileLoadStream.IsOpen()) - { - AZ_Warning("Image Processing", false, "%s: failed to open file %s", __FUNCTION__, filename.c_str()); - return nullptr; - } - - DDS_FILE_DESC desc; - DDS_HEADER_DXT10 exthead; - - fileLoadStream.Read(sizeof(desc), &desc); - if (desc.dwMagic != FOURCC_DDS) - { - AZ_Error("Image Processing", false, "%s:Trying to load a none-DDS file", __FUNCTION__); - return nullptr; - } - - if (desc.header.IsDX10Ext()) - { - fileLoadStream.Read(sizeof(exthead), &exthead); - } - - //skip size for originImage's mip data - for (AZ::u32 mip = 0; mip < originImage->GetMipCount(); ++mip) - { - AZ::u32 bufSize = originImage->GetMipBufSize(mip); - fileLoadStream.Seek(bufSize, AZ::IO::GenericStream::ST_SEEK_CUR); - } - - IImageObject* alphaImage = nullptr; - - AZ::u32 marker = 0; - fileLoadStream.Read(4, &marker); - if (marker == FOURCC_CExt) // marker for the start of Crytek Extended data - { - fileLoadStream.Read(4, &marker); - if (FOURCC_AttC == marker) // Attached Channel chunk - { - AZ::u32 size = 0; - fileLoadStream.Read(4, &size); - - alphaImage = LoadImageFromDdsFile(fileLoadStream); - fileLoadStream.Read(4, &marker); - } - - if (FOURCC_CEnd == marker ) // marker for the end of Crytek Extended data - { - fileLoadStream.Read(4, &marker); - } - } - - return alphaImage; - } - -} // namespace ImageProcessing diff --git a/Gems/ImageProcessing/Code/Source/Processing/ImageObjectImpl.h b/Gems/ImageProcessing/Code/Source/Processing/ImageObjectImpl.h deleted file mode 100644 index e6f40dac2e..0000000000 --- a/Gems/ImageProcessing/Code/Source/Processing/ImageObjectImpl.h +++ /dev/null @@ -1,199 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or 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 ImageProcessing -{ - // ImageObject allows the abstraction of different kinds of - // images generated during conversion - class CImageObject: public IImageObject - { - public: - AZ_CLASS_ALLOCATOR(CImageObject, AZ::SystemAllocator, 0); - - public: - // Constructors - CImageObject(AZ::u32 width, AZ::u32 height, AZ::u32 maxMipCount, EPixelFormat pixelFormat); - ~CImageObject(); - - //virtual functions from IImageObject - IImageObject* AllocateImage(EPixelFormat pixelFormat) const override; - IImageObject* AllocateImage() const override; - IImageObject* Clone() const override; - EPixelFormat GetPixelFormat() const override; - AZ::u32 GetPixelCount(AZ::u32 mip) const override; - AZ::u32 GetWidth(AZ::u32 mip) const override; - AZ::u32 GetHeight(AZ::u32 mip) const override; - AZ::u32 GetMipCount() const override; - bool IsCubemap() const override - { - return false; - }; - - void GetImagePointer(AZ::u32 mip, AZ::u8*& pMem, AZ::u32& pitch) const override; - AZ::u32 GetMipBufSize(AZ::u32 mip) const override; - void SetMipData(AZ::u32 mip, AZ::u8* mipBuf, AZ::u32 bufSize, AZ::u32 pitch) override; - - AZ::u32 GetImageFlags() const override; - void SetImageFlags(AZ::u32 imageFlags) override; - void AddImageFlags(AZ::u32 imageFlags) override; - void RemoveImageFlags(AZ::u32 imageFlags) override; - bool HasImageFlags(AZ::u32 imageFlags) const override; - - //image data operations and calculations - void ScaleAndBiasChannels(AZ::u32 firstMip, AZ::u32 maxMipCount, const AZ::Vector4& scale, const AZ::Vector4& bias) override; - void ClampChannels(AZ::u32 firstMip, AZ::u32 maxMipCount, const AZ::Vector4& min, const AZ::Vector4& max) override; - - void TransferAlphaCoverage(const TextureSettings* textureSetting, const IImageObjectPtr srcImg) override; - float ComputeAlphaCoverageScaleFactor(AZ::u32 mip, float fDesiredCoverage, float fAlphaRef) const override; - float ComputeAlphaCoverage(AZ::u32 firstMip, float fAlphaRef) const override; - - bool CompareImage(const IImageObjectPtr otherImage) const override; - - bool SaveImage(const char* filename, IImageObjectPtr alphaImage, AZStd::vector& outFilePaths) const override; - bool SaveImage(AZ::IO::SystemFileStream& out) const override; - bool SaveMipToFile(AZ::u32 mip, const AZStd::string& filename) const override; - - uint GetTextureMemory() const override; - - EAlphaContent GetAlphaContent() const override; - - void NormalizeVectors(AZ::u32 firstMip, AZ::u32 maxMipCount) override; - - void CopyPropertiesFrom(const IImageObjectPtr src) override; - - void Swizzle(const char channels[4]) override; - - void GetColorRange(AZ::Color& minColor, AZ::Color& maxColor) const override; - void SetColorRange(const AZ::Color& minColor, const AZ::Color& maxColor) override; - float GetAverageBrightness() const override; - void SetAverageBrightness(float avgBrightness) override; - AZ::u32 GetNumPersistentMips() const override; - void SetNumPersistentMips(AZ::u32 nMips) override; - - void GlossFromNormals(bool hasAuthoredGloss) override; - void ConvertLegacyGloss() override; - void ClearColor(float r, float g, float b, float a) override; - //end virtual functions from IImageObject - - private: - - enum EColorNormalization - { - eColorNormalization_Normalize, - eColorNormalization_PassThrough, - }; - - enum EAlphaNormalization - { - eAlphaNormalization_SetToZero, - eAlphaNormalization_Normalize, - eAlphaNormalization_PassThrough, - }; - - private: - class MipLevel - { - public: - AZ_CLASS_ALLOCATOR(MipLevel, AZ::SystemAllocator, 0); - - AZ::u32 m_width; - AZ::u32 m_height; - AZ::u32 m_rowCount; // for compressed textures m_rowCount is usually less than m_height - AZ::u32 m_pitch; // row size in bytes - AZ::u8* m_pData; - - public: - MipLevel() - : m_width(0) - , m_height(0) - , m_rowCount(0) - , m_pitch(0) - , m_pData(0) - { - } - - ~MipLevel() - { - delete[] m_pData; - m_pData = 0; - } - - void Alloc() - { - AZ_Assert(m_pData == 0, "Mip data must be empty before Allocation!"); - m_pData = new AZ::u8[m_pitch * m_rowCount]; - } - - AZ::u32 GetSize() const - { - AZ_Assert(m_pitch, "Pitch must be greater than zero!"); - return m_pitch * m_rowCount; - } - - bool operator==(const MipLevel& other) - { - if (m_width == other.m_width && m_height == other.m_height - && m_rowCount == other.m_rowCount && m_pitch == other.m_pitch) - { - return (memcmp(m_pData, other.m_pData, m_pitch * m_rowCount) == 0); - } - return false; - } - }; - - private: - EPixelFormat m_pixelFormat; - std::vector m_mips; // stores *pointers* to avoid reallocations when elements are erase()'d - - AZ::Color m_colMinARGB; // ARGB will be added the properties of the DDS file - AZ::Color m_colMaxARGB; // ARGB will be added the properties of the DDS file - float m_averageBrightness; // will be added to the properties of the DDS file - AZ::u32 m_imageFlags; // combined from CImageExtensionHelper::EIF_Cubemap,... - AZ::u32 m_numPersistentMips; // number of mipmaps won't be splitted - - public: - //reset this image object to specified format and size - void ResetImage(AZ::u32 width, AZ::u32 height, AZ::u32 maxMipCount, EPixelFormat pixelFormat); - - //get mip count and the origin (top mip) size - void GetExtent(AZ::u32& width, AZ::u32& height, AZ::u32& mipCount) const; - - AZ::u32 GetMipDataSize(AZ::u32 mip) const; - - //! calculates the average brightness for a texture - float CalculateAverageBrightness() const; - - bool HasPowerOfTwoSizes() const override; - - void CopyPropertiesFrom(const CImageObject* src); - - // Computes the dynamically used range for the texture and expands it to use the - // full range [0,2^(2^ExponentBits-1)] for better quality. - void NormalizeImageRange(EColorNormalization eColorNorm, EAlphaNormalization eAlphaNorm, bool bMaintainBlack = false, int nExponentBits = 0); - // Brings normalized ranges back to it's original range. - void ExpandImageRange(EColorNormalization eColorNorm, EAlphaNormalization eAlphaNorm, int nExponentBits = 0); - - private: - //build image file header from this image object - bool BuildSurfaceHeader(DDS_HEADER& header) const; - bool BuildSurfaceExtendedHeader(DDS_HEADER_DXT10& exthead) const; - }; - -} // namespace ImageProcessing - - diff --git a/Gems/ImageProcessing/Code/Source/Processing/ImagePreview.cpp b/Gems/ImageProcessing/Code/Source/Processing/ImagePreview.cpp deleted file mode 100644 index 09085540a9..0000000000 --- a/Gems/ImageProcessing/Code/Source/Processing/ImagePreview.cpp +++ /dev/null @@ -1,206 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or 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 - - -namespace ImageProcessing -{ - - ImagePreview::ImagePreview(const AZStd::string& inputImageFile, TextureSettings* textureSetting) - : m_imageFileName(inputImageFile) - , m_textureSetting(textureSetting) - , m_presetSetting(nullptr) - , m_inputImage(nullptr) - { - InitializeJobSettings(); - } - - void ImagePreview::StartConvert() - { - // If there is ongoing job, cancel it - Cancel(); - m_output.Reset(); - if (m_inputImage == nullptr) - { - // Load input image - m_inputImage = IImageObjectPtr(LoadImageFromFile(m_imageFileName)); - } - // Get preset if the setting in texture is changed - if (m_presetSetting == nullptr || m_presetSetting->m_uuid != m_textureSetting->m_preset) - { - m_presetSetting = BuilderSettingManager::Instance()->GetPreset(m_textureSetting->m_preset); - } - const bool isPreview = true; - const bool autoDelete = false; - PlatformName defaultPlatform = BuilderSettingManager::s_defaultPlatform; - - m_convertJob = AZStd::make_unique(m_inputImage, m_textureSetting, m_presetSetting, - isPreview, defaultPlatform, &m_output, autoDelete, m_jobContext.get()); - m_convertJob->SetDependent(&m_doneJob); - m_convertJob->Start(); - } - - bool ImagePreview::IsDone() - { - return m_output.IsReady(); - } - - float ImagePreview::GetProgress() - { - if (!m_output.IsReady()) - { - return m_output.GetProgress(); - } - return 1.0f; - } - - void ImagePreview::Cancel() - { - if (m_convertJob) - { - m_convertJob->Cancel(); - // Block until job completes - m_doneJob.StartAndWaitForCompletion(); - - AZ_Assert(m_output.IsReady(), "Conversion job is not done yet!"); - } - m_convertJob.release(); - m_doneJob.Reset(true); - } - - IImageObjectPtr ImagePreview::GetOutputImage() - { - return m_output.GetOutputImage(ImageConvertOutput::Preview); - } - - ImagePreview::~ImagePreview() - { - Cancel(); - // Maintain the releasing order - m_jobManager.release(); - m_jobContext.release(); - m_jobCancelGroup.release(); - } - - void ImagePreview::InitializeJobSettings() - { - AZ::JobManagerDesc desc; - AZ::JobManagerThreadDesc threadDesc; - desc.m_workerThreads.push_back(threadDesc); - // Check to ensure these have not already been initialized. - AZ_Error("Image Processing", !m_jobManager && !m_jobCancelGroup && !m_jobContext, "ImagePreview::InitializeJobSettings is being called again after it has already been initialized"); - m_jobManager = AZStd::make_unique(desc); - m_jobCancelGroup = AZStd::make_unique(); - m_jobContext = AZStd::make_unique(*m_jobManager, *m_jobCancelGroup); - - new (&m_doneJob) AZ::JobCompletion(m_jobContext.get()); //re-initialize with the job context - } - - - void GetImageInfoString(IImageObjectPtr image, bool isAlpha, AZStd::string& output) - { - if (!image) - { - return; - } - - CPixelFormats& pixelFormats = CPixelFormats::GetInstance(); - EPixelFormat format = image->GetPixelFormat(); - const PixelFormatInfo* info = pixelFormats.GetPixelFormatInfo(format); - if (info) - { - output += AZStd::string::format("Format: %s\r\n", info->szName); - } - - AZ::u32 mipCount = image->GetMipCount(); - output += AZStd::string::format("Mip Count: %d\r\n", mipCount); - - AZ::u32 memSize = image->GetTextureMemory(); - AZStd::string memSizeString = ImageProcessingEditor::EditorHelper::GetFileSizeString(memSize); - output += AZStd::string::format("Memory Size: %s\r\n", memSizeString.c_str()); - - if (!isAlpha) - { - if (image->HasImageFlags(EIF_SRGBRead)) - { - output += "Color Space: sRGB\r\n"; - } - else - { - output += "Color Space: Linear\r\n"; - } - - if (image->HasImageFlags(EIF_Cubemap)) - { - output += "Cubemap\r\n"; - } - } - - AZ::u32 imageFlag = image->GetImageFlags(); - output += AZStd::string::format("Image Flag: 0x%08x\r\n", imageFlag); - } - - bool ImagePreview::GetProductTexturePreview(const char* fullProductFileName, QImage& previewImage, AZStd::string& productInfo, AZStd::string& productAlphaInfo) - { - if (!AzFramework::StringFunc::Path::IsExtension(fullProductFileName, "dds", false)) - { - return false; - } - - IImageObjectPtr originImage = IImageObjectPtr(LoadImageFromDdsFile(fullProductFileName)); - IImageObjectPtr alphaImage; - - if (originImage && originImage->HasImageFlags(EIF_AttachedAlpha)) - { - if (originImage->HasImageFlags(EIF_Splitted)) - { - AZStd::string alphaFileName = AZStd::string::format("%s.a", fullProductFileName); - alphaImage = IImageObjectPtr(LoadImageFromDdsFile(alphaFileName)); - - } - else - { - alphaImage = IImageObjectPtr(LoadAttachedImageFromDdsFile(fullProductFileName, originImage)); - } - } - - GetImageInfoString(originImage, false, productInfo); - GetImageInfoString(alphaImage, true, productAlphaInfo); - - IImageObjectPtr combinedImage = MergeOutputImageForPreview(originImage, alphaImage); - if (combinedImage) - { - AZ::u8* imageBuf; - AZ::u32 pitch; - combinedImage->GetImagePointer(0, imageBuf, pitch); - const AZ::u32 width = originImage->GetWidth(0); - const AZ::u32 height = originImage->GetHeight(0); - QImage result = QImage(imageBuf, width, height, pitch, QImage::Format_RGBA8888); - previewImage = result.copy(); // Return a deep copy here - return true; - } - - return false; - } - -}// namespace ImageProcessing diff --git a/Gems/ImageProcessing/Code/Source/Processing/ImagePreview.h b/Gems/ImageProcessing/Code/Source/Processing/ImagePreview.h deleted file mode 100644 index 25be5ed37c..0000000000 --- a/Gems/ImageProcessing/Code/Source/Processing/ImagePreview.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. -* -*/ - -#pragma once - -#include -#include - -namespace ImageProcessing -{ - // The reason to have image preview class, we should keep the source image loaded once, - // we could restart conversion and cancel the old conversion at anytime when setting changed - class ImagePreview - { - public: - ImagePreview(const AZStd::string& inputImageFile, TextureSettings* textureSetting); - ~ImagePreview(); - - void InitializeJobSettings(); - void StartConvert(); - bool IsDone(); - float GetProgress(); - void Cancel(); - IImageObjectPtr GetOutputImage(); - - // Output preview image for Asset Browser - static bool GetProductTexturePreview(const char* fullProductFileName, QImage& previewImage, AZStd::string& productInfo, AZStd::string& productAlphaInfo); - - private: - AZStd::string m_imageFileName; - IImageObjectPtr m_inputImage; - const TextureSettings* m_textureSetting; - const PresetSettings* m_presetSetting; - - IImageObjectPtr m_outputImage; - IImageObjectPtr m_outputAlphaImage; - - ImageConvertOutput m_output; - - AZStd::unique_ptr m_jobManager; - AZStd::unique_ptr m_jobCancelGroup; - AZStd::unique_ptr m_jobContext; - AZStd::unique_ptr m_convertJob; - AZ::JobCompletion m_doneJob; - }; - - // Get basic image info as string - void GetImageInfoString(IImageObjectPtr image, bool isAlpha, AZStd::string& output); - -}// namespace ImageProcessing diff --git a/Gems/ImageProcessing/Code/Source/Processing/ImageToProcess.h b/Gems/ImageProcessing/Code/Source/Processing/ImageToProcess.h deleted file mode 100644 index 080fd602e8..0000000000 --- a/Gems/ImageProcessing/Code/Source/Processing/ImageToProcess.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. -* -*/ - -#pragma once - -#include -#include -#include - -namespace ImageProcessing -{ - - //cubemap layouts - enum CubemapLayoutType - { - CubemapLayoutHorizontal = 0, //6x1 strip. with rotations. - CubemapLayoutHorizontalCross, //4x3. - CubemapLayoutVerticalCross, //3x4 - CubemapLayoutVertical, //1x6 strip. new output format. it's better because the memory is continuous for each face - CubemapLayoutTypeCount, - CubemapLayoutNone = CubemapLayoutTypeCount - }; - - class ImageToProcess - { - private: - IImageObjectPtr m_img; - ICompressor::CompressOption m_compressOption; - - private: - ImageToProcess(const ImageToProcess&); - - public: - ImageToProcess(IImageObjectPtr img) - { - m_img = img; - } - - ~ImageToProcess() - { - } - - void Set(IImageObjectPtr img) - { - m_img = img; - } - - IImageObjectPtr Get() const - { - return m_img; - } - - ICompressor::CompressOption& GetCompressOption() - { - return m_compressOption; - } - - void SetCompressOption(const ICompressor::CompressOption& compressOption) - { - m_compressOption = compressOption; - } - - public: - // --------------------------------------------------------------------------------- - //! can be used to compress, requires a preset - void ConvertFormat(EPixelFormat fmtTo); - void ConvertFormatUncompressed(EPixelFormat fmtTo); - - // --------------------------------------------------------------------------------- - // Arguments: - // bDeGamma - apply de-gamma correction - bool GammaToLinearRGBA32F(bool bDeGamma); - void LinearToGamma(); - - // --------------------------------------------------------------------------------- - // Resizers for A32B32G32R32F - - // Prerequisites: image width is even, ARGB32F only, no mips. - void DownscaleTwiceHorizontally(); - - // Prerequisites: height is even, ARGB32F only, no mips. - void DownscaleTwiceVertically(); - - // Prerequisites: width is pow of 2, ARGB32F only, no mips. - void UpscalePow2TwiceHorizontally(); - - // Prerequisites: height is pow of 2, ARGB32F only, no mips. - void UpscalePow2TwiceVertically(); - - // --------------------------------------------------------------------------------- - // Tools for A32B32G32R32F - - // input needs to be in range 0..1 - void AddNormalMap(const IImageObject* pAddBump); - - void CreateHighPass(uint32 dwMipDown); - - void CreateColorChart(); - - //convert various original cubemap layouts to new layout - bool ConvertCubemapLayout(CubemapLayoutType newLayout); - - }; -}// namespace ImageProcessing - diff --git a/Gems/ImageProcessing/Code/Source/Processing/PixelFormatInfo.cpp b/Gems/ImageProcessing/Code/Source/Processing/PixelFormatInfo.cpp deleted file mode 100644 index 3bfa371dc0..0000000000 --- a/Gems/ImageProcessing/Code/Source/Processing/PixelFormatInfo.cpp +++ /dev/null @@ -1,430 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or 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 ImageProcessing -{ - CPixelFormats* CPixelFormats::s_instance = nullptr; - - CPixelFormats& CPixelFormats::GetInstance() - { - if (s_instance == nullptr) - { - s_instance = new CPixelFormats(); - } - - return *s_instance; - } - - void CPixelFormats::DestroyInstance() - { - delete s_instance; - s_instance = nullptr; - } - - PixelFormatInfo::PixelFormatInfo( - int a_bitsPerPixel, - int a_Channels, - bool a_Alpha, - const char* a_szAlpha, - uint32 a_minWidth, - uint32 a_minHeight, - int a_blockWidth, - int a_blockHeight, - int a_bitsPerBlock, - bool a_bSquarePow2, - DXGI_FORMAT a_d3d10Format, - AZ::u32 a_fourCC, - ESampleType a_eSampleType, - const char* a_szName, - const char* a_szDescription, - bool a_bCompressed, - bool a_bSelectable) - : nChannels(a_Channels) - , bHasAlpha(a_Alpha) - , minWidth(a_minWidth) - , minHeight(a_minHeight) - , blockWidth(a_blockWidth) - , blockHeight(a_blockHeight) - , bitsPerBlock(a_bitsPerBlock) - , bSquarePow2(a_bSquarePow2) - , szAlpha(a_szAlpha) - , d3d10Format(a_d3d10Format) - , fourCC(a_fourCC) - , eSampleType(a_eSampleType) - , szName(a_szName) - , szLegacyName(a_szName) - , szDescription(a_szDescription) - , bCompressed(a_bCompressed) - , bSelectable(a_bSelectable) - { - //validate pixel format - //a_bitsPerPixel could be 0 if it's ACTC format since the actual bits per-pixel could be 6.4, 5.12 etc. - if (a_bitsPerPixel) - { - AZ_Assert(a_bitsPerPixel * blockWidth * blockHeight == bitsPerBlock, "PixelFormatInfo: Wrong block setting"); - } - - AZ_Assert(szName, "szName can't be nullptr"); - AZ_Assert(nChannels > 0 && nChannels <= 4, "unreasonable channel count %d", nChannels); - AZ_Assert(a_szDescription, "szDescription can't be nullptr"); - AZ_Assert(blockWidth > 0 && blockHeight > 0, "blcok size need to be larger than 0: %d x %d", blockWidth, blockHeight); - AZ_Assert(minWidth > 0 && minHeight > 0, "piexel required mininum image size need to be larger than 0: %d x %d", minWidth, minHeight); - if (!bCompressed) - { - AZ_Assert(blockWidth == 1 && blockHeight == 1, "Uncompressed format shouldn't have block which size > 1"); - } - } - - CPixelFormats::CPixelFormats() - { - InitPixelFormats(); - - m_removedLegacyFormats["DXT1"] = ePixelFormat_BC1; - m_removedLegacyFormats["DXT1a"] = ePixelFormat_BC1a; - m_removedLegacyFormats["DXT3"] = ePixelFormat_BC3; - m_removedLegacyFormats["DXT3t"] = ePixelFormat_BC3t; - m_removedLegacyFormats["DXT5"] = ePixelFormat_BC3; - m_removedLegacyFormats["DXT5t"] = ePixelFormat_BC3t; - m_removedLegacyFormats["3DCp"] = ePixelFormat_BC4; - m_removedLegacyFormats["3DC"] = ePixelFormat_BC5; - } - - void CPixelFormats::InitPixelFormat(EPixelFormat format, const PixelFormatInfo& formatInfo) - { - AZ_Assert((format >= 0) && (format < ePixelFormat_Count), "Unsupport pixel format: %d", format); - - if (m_pixelFormatInfo[format].szName && m_pixelFormatNameMap.find(formatInfo.szName) != m_pixelFormatNameMap.end()) - { - // double initialization - AZ_Assert(false, "Pixel format already exist: %s", m_pixelFormatInfo[format].szName); - } - m_pixelFormatNameMap[formatInfo.szName] = format; - m_pixelFormatInfo[format] = formatInfo; - } - - void CPixelFormats::InitPixelFormats() - { - // Unsigned Formats - // Data in an unsigned format must be positive. Unsigned formats use combinations of - // (R)ed, (G)reen, (B)lue, (A)lpha, (L)uminance - InitPixelFormat(ePixelFormat_R8G8B8A8, PixelFormatInfo(32, 4, true, "8", 1, 1, 1, 1, 32, false, DXGI_FORMAT_R8G8B8A8_UNORM, FOURCC_DX10, ESampleType::eSampleType_Uint8, "R8G8B8A8", "32-bit RGBA pixel format with alpha, using 8 bits per channel", false, true)); - InitPixelFormat(ePixelFormat_R8G8B8X8, PixelFormatInfo(32, 4, false, "0", 1, 1, 1, 1, 32, false, DXGI_FORMAT_R8G8B8A8_UNORM, FOURCC_DX10, ESampleType::eSampleType_Uint8, "R8G8B8X8", "32-bit RGB pixel format, where 8 bits are reserved for each color", false, true)); - InitPixelFormat(ePixelFormat_R8G8, PixelFormatInfo(16, 2, false, "0", 1, 1, 1, 1, 16, false, DXGI_FORMAT_R8G8_UNORM, FOURCC_DX10, ESampleType::eSampleType_Uint8, "R8G8", "16-bit red/green, using 8 bits per channel", false, false)); - InitPixelFormat(ePixelFormat_R8, PixelFormatInfo( 8, 1, false, "0", 1, 1, 1, 1, 8, false, DXGI_FORMAT_R8_UNORM, FOURCC_DX10, ESampleType::eSampleType_Uint8, "R8", "8-bit red only", false, false)); - InitPixelFormat(ePixelFormat_A8, PixelFormatInfo( 8, 1, true, "8", 1, 1, 1, 1, 8, false, DXGI_FORMAT_A8_UNORM, FOURCC_DX10, ESampleType::eSampleType_Uint8, "A8", "8-bit alpha only", false, true)); - InitPixelFormat(ePixelFormat_R16G16B16A16, PixelFormatInfo(64, 4, true, "16", 1, 1, 1, 1, 64, false, DXGI_FORMAT_R16G16B16A16_UNORM, FOURCC_DX10, ESampleType::eSampleType_Uint16, "R16G16B16A16", "64-bit ARGB pixel format with alpha, using 16 bits per channel", false, false)); - InitPixelFormat(ePixelFormat_R16G16, PixelFormatInfo(32, 2, false, "0", 1, 1, 1, 1, 32, false, DXGI_FORMAT_R16G16_UNORM, FOURCC_DX10, ESampleType::eSampleType_Uint16, "R16G16", "32-bit red/green, using 16 bits per channel", false, false)); - InitPixelFormat(ePixelFormat_R16, PixelFormatInfo(16, 1, false, "0", 1, 1, 1, 1, 16, false, DXGI_FORMAT_R16_UNORM, FOURCC_DX10, ESampleType::eSampleType_Uint16, "R16", "16-bit red only", false, false)); - - // Custom FourCC Formats - // Data in these FourCC formats is custom compressed data and only decodable by certain hardware. - InitPixelFormat(ePixelFormat_ASTC_4x4, PixelFormatInfo(0, 4, true, "?", 16, 16, 4, 4, 128, false, DXGI_FORMAT_UNKNOWN, FOURCC_ASTC_4x4, ESampleType::eSampleType_Compressed, "ASTC_4x4", "ASTC 4x4 compressed texture format", true, false)); - InitPixelFormat(ePixelFormat_ASTC_5x4, PixelFormatInfo(0, 4, true, "?", 16, 16, 5, 4, 128, false, DXGI_FORMAT_UNKNOWN, FOURCC_ASTC_5x4, ESampleType::eSampleType_Compressed, "ASTC_5x4", "ASTC 5x4 compressed texture format", true, false)); - InitPixelFormat(ePixelFormat_ASTC_5x5, PixelFormatInfo(0, 4, true, "?", 16, 16, 5, 5, 128, false, DXGI_FORMAT_UNKNOWN, FOURCC_ASTC_5x5, ESampleType::eSampleType_Compressed, "ASTC_5x5", "ASTC 5x5 compressed texture format", true, false)); - InitPixelFormat(ePixelFormat_ASTC_6x5, PixelFormatInfo(0, 4, true, "?", 16, 16, 6, 5, 128, false, DXGI_FORMAT_UNKNOWN, FOURCC_ASTC_6x5, ESampleType::eSampleType_Compressed, "ASTC_6x5", "ASTC 6x5 compressed texture format", true, false)); - InitPixelFormat(ePixelFormat_ASTC_6x6, PixelFormatInfo(0, 4, true, "?", 16, 16, 6, 6, 128, false, DXGI_FORMAT_UNKNOWN, FOURCC_ASTC_6x6, ESampleType::eSampleType_Compressed, "ASTC_6x6", "ASTC 6x6 compressed texture format", true, false)); - InitPixelFormat(ePixelFormat_ASTC_8x5, PixelFormatInfo(0, 4, true, "?", 16, 16, 8, 5, 128, false, DXGI_FORMAT_UNKNOWN, FOURCC_ASTC_8x5, ESampleType::eSampleType_Compressed, "ASTC_8x5", "ASTC 8x5 compressed texture format", true, false)); - InitPixelFormat(ePixelFormat_ASTC_8x6, PixelFormatInfo(0, 4, true, "?", 16, 16, 8, 6, 128, false, DXGI_FORMAT_UNKNOWN, FOURCC_ASTC_8x6, ESampleType::eSampleType_Compressed, "ASTC_8x6", "ASTC 8x6 compressed texture format", true, false)); - InitPixelFormat(ePixelFormat_ASTC_8x8, PixelFormatInfo(0, 4, true, "?", 16, 16, 8, 8, 128, false, DXGI_FORMAT_UNKNOWN, FOURCC_ASTC_8x8, ESampleType::eSampleType_Compressed, "ASTC_8x8", "ASTC 8x8 compressed texture format", true, false)); - InitPixelFormat(ePixelFormat_ASTC_10x5, PixelFormatInfo(0, 4, true, "?", 16, 16, 10, 5, 128, false, DXGI_FORMAT_UNKNOWN, FOURCC_ASTC_10x5, ESampleType::eSampleType_Compressed, "ASTC_10x5", "ASTC 10x5 compressed texture format", true, false)); - InitPixelFormat(ePixelFormat_ASTC_10x6, PixelFormatInfo(0, 4, true, "?", 16, 16, 10, 6, 128, false, DXGI_FORMAT_UNKNOWN, FOURCC_ASTC_10x6, ESampleType::eSampleType_Compressed, "ASTC_10x6", "ASTC 10x6 compressed texture format", true, false)); - InitPixelFormat(ePixelFormat_ASTC_10x8, PixelFormatInfo(0, 4, true, "?", 16, 16, 10, 8, 128, false, DXGI_FORMAT_UNKNOWN, FOURCC_ASTC_10x8, ESampleType::eSampleType_Compressed, "ASTC_10x8", "ASTC 10x8 compressed texture format", true, false)); - InitPixelFormat(ePixelFormat_ASTC_10x10, PixelFormatInfo(0, 4, true, "?", 16, 16, 10, 10, 128, false, DXGI_FORMAT_UNKNOWN, FOURCC_ASTC_10x10, ESampleType::eSampleType_Compressed, "ASTC_10x10", "ASTC 10x10 compressed texture format", true, false)); - InitPixelFormat(ePixelFormat_ASTC_12x10, PixelFormatInfo(0, 4, true, "?", 16, 16, 12, 10, 128, false, DXGI_FORMAT_UNKNOWN, FOURCC_ASTC_12x10, ESampleType::eSampleType_Compressed, "ASTC_12x10", "ASTC 12x10 compressed texture format", true, false)); - InitPixelFormat(ePixelFormat_ASTC_12x12, PixelFormatInfo(0, 4, true, "?", 16, 16, 12, 12, 128, false, DXGI_FORMAT_UNKNOWN, FOURCC_ASTC_12x12, ESampleType::eSampleType_Compressed, "ASTC_12x12", "ASTC 12x12 compressed texture format", true, false)); - InitPixelFormat(ePixelFormat_PVRTC2, PixelFormatInfo(2, 4, true, "2", 16, 16, 8, 4, 64, true, DXGI_FORMAT_UNKNOWN, FOURCC_PVRTC2, ESampleType::eSampleType_Compressed, "PVRTC2", "POWERVR 2 bpp compressed texture format", true, false)); - InitPixelFormat(ePixelFormat_PVRTC4, PixelFormatInfo(4, 4, true, "2", 8, 8, 4, 4, 64, true, DXGI_FORMAT_UNKNOWN, FOURCC_PVRTC4, ESampleType::eSampleType_Compressed, "PVRTC4", "POWERVR 4 bpp compressed texture format", true, false)); - InitPixelFormat(ePixelFormat_EAC_R11, PixelFormatInfo(4, 1, true, "4", 4, 4, 4, 4, 64, false, DXGI_FORMAT_UNKNOWN, FOURCC_EAC_R11, ESampleType::eSampleType_Compressed, "EAC_R11", "EAC 4 bpp single channel texture format", true, false)); - InitPixelFormat(ePixelFormat_EAC_RG11, PixelFormatInfo(8, 2, false, "0", 4, 4, 4, 4, 128, false, DXGI_FORMAT_UNKNOWN, FOURCC_EAC_RG11, ESampleType::eSampleType_Compressed, "EAC_RG11", "EAC 8 bpp dual channel texture format", true, false)); - InitPixelFormat(ePixelFormat_ETC2, PixelFormatInfo(4, 3, false, "0", 4, 4, 4, 4, 64, false, DXGI_FORMAT_UNKNOWN, FOURCC_ETC2, ESampleType::eSampleType_Compressed, "ETC2", "ETC2 RGB 4 bpp compressed texture format", true, false)); - InitPixelFormat(ePixelFormat_ETC2a, PixelFormatInfo(8, 4, true, "4", 4, 4, 4, 4, 128, false, DXGI_FORMAT_UNKNOWN, FOURCC_ETC2A, ESampleType::eSampleType_Compressed, "ETC2a", "ETC2 RGBA 8 bpp compressed texture format", true, false)); - - // Standardized Compressed DXGI Formats (DX10+) - // Data in these compressed formats is hardware decodable on all DX10 chips, and manageable with the DX10-API. - InitPixelFormat(ePixelFormat_BC1, PixelFormatInfo(4, 3, false, "0", 4, 4, 4, 4, 64, false, DXGI_FORMAT_BC1_UNORM, FOURCC_DX10, ESampleType::eSampleType_Compressed, "BC1", "BC1 compressed texture format", true, true)); - InitPixelFormat(ePixelFormat_BC1a, PixelFormatInfo(4, 4, true, "1", 4, 4, 4, 4, 64, false, DXGI_FORMAT_BC1_UNORM, FOURCC_DX10, ESampleType::eSampleType_Compressed, "BC1a", "BC1a compressed texture format with transparency", true, true)); - InitPixelFormat(ePixelFormat_BC3, PixelFormatInfo(8, 4, true, "3of8", 4, 4, 4, 4, 128, false, DXGI_FORMAT_BC3_UNORM, FOURCC_DX10, ESampleType::eSampleType_Compressed, "BC3", "BC3 compressed texture format", true, true)); - InitPixelFormat(ePixelFormat_BC3t, PixelFormatInfo(8, 4, true, "3of8", 4, 4, 4, 4, 128, false, DXGI_FORMAT_BC3_UNORM, FOURCC_DX10, ESampleType::eSampleType_Compressed, "BC3t", "BC3t compressed texture format with transparency", true, true)); - InitPixelFormat(ePixelFormat_BC4, PixelFormatInfo(4, 1, false, "0", 4, 4, 4, 4, 64, false, DXGI_FORMAT_BC4_UNORM, FOURCC_DX10, ESampleType::eSampleType_Compressed, "BC4", "BC4 compressed texture format for single channel maps. 3DCp", true, true)); - InitPixelFormat(ePixelFormat_BC4s, PixelFormatInfo(4, 1, false, "0", 4, 4, 4, 4, 64, false, DXGI_FORMAT_BC4_SNORM, FOURCC_DX10, ESampleType::eSampleType_Compressed, "BC4s", "BC4 compressed texture format for signed single channel maps", true, true)); - InitPixelFormat(ePixelFormat_BC5, PixelFormatInfo(8, 2, false, "0", 4, 4, 4, 4, 128, false, DXGI_FORMAT_BC5_UNORM, FOURCC_DX10, ESampleType::eSampleType_Compressed, "BC5", "BC5 compressed texture format for two channel maps or normalmaps. 3DC", true, true)); - InitPixelFormat(ePixelFormat_BC5s, PixelFormatInfo(8, 2, false, "0", 4, 4, 4, 4, 128, false, DXGI_FORMAT_BC5_SNORM, FOURCC_DX10, ESampleType::eSampleType_Compressed, "BC5s", "BC5 compressed texture format for signed two channel maps or normalmaps", true, true)); - InitPixelFormat(ePixelFormat_BC6UH, PixelFormatInfo(8, 3, false, "0", 4, 4, 4, 4, 128, false, DXGI_FORMAT_BC6H_UF16, FOURCC_DX10, ESampleType::eSampleType_Compressed, "BC6UH", "BC6 compressed texture format, unsigned half", true, true)); - InitPixelFormat(ePixelFormat_BC7, PixelFormatInfo(8, 4, true, "8", 4, 4, 4, 4, 128, false, DXGI_FORMAT_BC7_UNORM, FOURCC_DX10, ESampleType::eSampleType_Compressed, "BC7", "BC7 compressed texture format", true, true)); - InitPixelFormat(ePixelFormat_BC7t, PixelFormatInfo(8, 4, true, "8", 4, 4, 4, 4, 128, false, DXGI_FORMAT_BC7_UNORM, FOURCC_DX10, ESampleType::eSampleType_Compressed, "BC7t", "BC7t compressed texture format with transparency", true, true)); - - // Float formats - // Data in a Float format is floating point data. - InitPixelFormat(ePixelFormat_R9G9B9E5, PixelFormatInfo(32, 3, false, "0", 1, 1, 1, 1, 32, false, DXGI_FORMAT_R9G9B9E5_SHAREDEXP, FOURCC_DX10, ESampleType::eSampleType_Compressed, "R9G9B9E5", "32-bit RGB pixel format with shared exponent", false, true)); - InitPixelFormat(ePixelFormat_R32G32B32A32F, PixelFormatInfo(128, 4, true, "23", 1, 1, 1, 1, 128, false, DXGI_FORMAT_R32G32B32A32_FLOAT, FOURCC_DX10, ESampleType::eSampleType_Float, "R32G32B32A32F", "four float channels", false, false)); - InitPixelFormat(ePixelFormat_R32G32F, PixelFormatInfo(64, 2, false, "0", 1, 1, 1, 1, 64, false, DXGI_FORMAT_R32G32_FLOAT, FOURCC_DX10, ESampleType::eSampleType_Float, "R32G32F", "two float channels", false, false)); // FIXME: This should be eTF_R32G32F, but CryTek did not add that enum to ITexture.h yet - InitPixelFormat(ePixelFormat_R32F, PixelFormatInfo(32, 1, false, "0", 1, 1, 1, 1, 32, false, DXGI_FORMAT_R32_FLOAT, FOURCC_DX10, ESampleType::eSampleType_Float, "R32F", "one float channel", false, false)); - InitPixelFormat(ePixelFormat_R16G16B16A16F, PixelFormatInfo(64, 4, true, "10", 1, 1, 1, 1, 64, false, DXGI_FORMAT_R16G16B16A16_FLOAT, FOURCC_DX10, ESampleType::eSampleType_Half, "R16G16B16A16F", "four half channels", false, false)); - InitPixelFormat(ePixelFormat_R16G16F, PixelFormatInfo(32, 2, false, "0", 1, 1, 1, 1, 32, false, DXGI_FORMAT_R16G16_FLOAT, FOURCC_DX10, ESampleType::eSampleType_Half, "R16G16F", "two half channel", false, false)); - InitPixelFormat(ePixelFormat_R16F, PixelFormatInfo(16, 1, false, "0", 1, 1, 1, 1, 16, false, DXGI_FORMAT_R16_FLOAT, FOURCC_DX10, ESampleType::eSampleType_Half, "R16F", "one half channel", false, false)); - - //legacy BGRA8 - InitPixelFormat(ePixelFormat_B8G8R8A8, PixelFormatInfo(32, 4, true, "8", 1, 1, 1, 1, 32, false, DXGI_FORMAT_B8G8R8A8_UNORM, FOURCC_DX10, ESampleType::eSampleType_Uint8, "B8G8R8A8", "32-bit BGRA pixel format with alpha, using 8 bits per channel", false, true)); - - InitPixelFormat(ePixelFormat_R32, PixelFormatInfo(32, 1, false, "0", 1, 1, 1, 1, 32, false, DXGI_FORMAT_FORCE_UINT, FOURCC_DX10, ESampleType::eSampleType_Uint32, "R32", "32-bit red only", false, false)); - - //Set legacy name it can be used for convertion - m_pixelFormatInfo[ePixelFormat_R8G8B8A8].szLegacyName = "A8R8G8B8"; - m_pixelFormatInfo[ePixelFormat_R8G8B8X8].szLegacyName = "X8R8G8B8"; - m_pixelFormatInfo[ePixelFormat_R8G8].szLegacyName = "G8R8"; - m_pixelFormatInfo[ePixelFormat_R16G16B16A16].szLegacyName = "A16B16G16R16"; - m_pixelFormatInfo[ePixelFormat_R16G16].szLegacyName = "G16R16"; - m_pixelFormatInfo[ePixelFormat_R32G32B32A32F].szLegacyName = "A32B32G32R32F"; - m_pixelFormatInfo[ePixelFormat_R32G32F].szLegacyName = "G32R32F"; - m_pixelFormatInfo[ePixelFormat_R16G16B16A16F].szLegacyName = "A16B16G16R16F"; - m_pixelFormatInfo[ePixelFormat_R16G16F].szLegacyName = "G16R16F"; - - //validate all pixel formats are proper initialized - for (int i = 0; i < ePixelFormat_Count; ++i) - { - if (m_pixelFormatInfo[i].szName == 0) - { - // Uninitialized entry. Should never happen. But, if it happened: make sure that entries from - // the EPixelFormat enum and InitPixelFormat() calls match. - AZ_Assert(false, "InitPixelFormats error: not all pixel formats have an implementation."); - } - } - } - - - EPixelFormat CPixelFormats::FindPixelFormatByName(const char* name) - { - if (m_pixelFormatNameMap.find(name) != m_pixelFormatNameMap.end()) - { - return m_pixelFormatNameMap[name]; - } - return ePixelFormat_Unknown; - } - - EPixelFormat CPixelFormats::FindPixelFormatByLegacyName(const char* name) - { - if (m_removedLegacyFormats.find(name) != m_removedLegacyFormats.end()) - { - return m_removedLegacyFormats[name]; - } - - for (int i = 0; i < ePixelFormat_Count; ++i) - { - if (azstricmp(m_pixelFormatInfo[i].szLegacyName, name) == 0) - { - return (EPixelFormat)i; - } - } - return ePixelFormat_Unknown; - } - - const PixelFormatInfo* CPixelFormats::GetPixelFormatInfo(EPixelFormat format) - { - AZ_Assert((format >= 0) && (format < ePixelFormat_Count), "Unsupport pixel format: %d", format); - return &m_pixelFormatInfo[format]; - } - - bool CPixelFormats::IsPixelFormatUncompressed(EPixelFormat format) - { - AZ_Assert((format >= 0) && (format < ePixelFormat_Count), "Unsupport pixel format: %d", format); - return !m_pixelFormatInfo[format].bCompressed; - } - - bool CPixelFormats::IsPixelFormatWithoutAlpha(EPixelFormat format) - { - AZ_Assert((format >= 0) && (format < ePixelFormat_Count), "Unsupport pixel format: %d", format); - return !m_pixelFormatInfo[format].bHasAlpha; - } - - uint32 CPixelFormats::ComputeMaxMipCount(EPixelFormat format, uint32 width, uint32 height) - { - const PixelFormatInfo* const pFormatInfo = GetPixelFormatInfo(format); - - AZ_Assert(pFormatInfo != nullptr, "ComputeMaxMipCount: unsupport pixel format %d", format); - - uint32 tmpWidth = width; - uint32 tmpHeight = height; - - bool bIgnoreBlockSize = CanImageSizeIgnoreBlockSize(format); - - uint32 mipCountW = 0; - while ((tmpWidth >= pFormatInfo->minWidth) && (bIgnoreBlockSize || (tmpWidth % pFormatInfo->blockWidth == 0))) - { - ++mipCountW; - tmpWidth >>= 1; - } - - uint32 mipCountH = 0; - while ((tmpHeight >= pFormatInfo->minHeight) && (bIgnoreBlockSize || (tmpHeight % pFormatInfo->blockHeight == 0))) - { - ++mipCountH; - tmpHeight >>= 1; - } - - //for compressed image, use minmum mip out of W and H because any size below won't be compressed properly - //for non-compressed image. use maximum mip count. for example the lowest two mips of 128x64 would be 2x1 and 1x1 - const uint32 mipCount = (pFormatInfo->bCompressed) - ? AZStd::min(mipCountW, mipCountH) - : AZStd::max(mipCountW, mipCountH); - - // In some cases, user may call this function for image size which is qualified for this pixel format, - // the mipCount could be 0 for those cases. Round it to 1 if it happend. - return AZStd::max((uint32)1, mipCount); - } - - bool CPixelFormats::CanImageSizeIgnoreBlockSize(EPixelFormat format) - { - // ASTC is a kind of block compression but it doesn't need the image size to be interger mutiples of block size. - // reference: https://www.khronos.org/registry/OpenGL/extensions/KHR/KHR_texture_compression_astc_hdr.txt - //"For images which are not an integer multiple of the block size, additional texels are added to the edges - // with maximum X and Y.These texels may be any color, as they will not be accessed." - bool bIgnoreBlockSize = IsASTCFormat(format); - - return bIgnoreBlockSize; - } - - bool CPixelFormats::IsImageSizeValid(EPixelFormat format, uint32 imageWidth, uint32 imageHeight, [[maybe_unused]] bool logWarning) - { - const PixelFormatInfo* const pFormatInfo = GetPixelFormatInfo(format); - AZ_Assert(pFormatInfo != nullptr, "IsImageSizeValid: unsupport pixel format %d", format); - - //if the format requires image to be sqaure and power of 2 - if (pFormatInfo->bSquarePow2 && ((imageWidth != imageHeight) || (imageWidth & (imageWidth - 1)) != 0)) - { - AZ_Warning("ImageBuilder", !logWarning, "Image size need to be square and power of 2 for pixel format %s", - pFormatInfo->szName); - return false; - } - - // minimum size required by the pixel format - if (imageWidth < pFormatInfo->minWidth || imageHeight < pFormatInfo->minHeight) - { - AZ_Warning("ImageBuilder", !logWarning, "The image size (%dx%d) is smaller than minimum size (%dx%d) for pixel format %s", - imageWidth, imageHeight, pFormatInfo->minWidth, pFormatInfo->minHeight, pFormatInfo->szName); - return false; - } - - //check image size againest block size - if (!CanImageSizeIgnoreBlockSize(format)) - { - if (imageWidth % pFormatInfo->blockWidth != 0 || imageHeight % pFormatInfo->blockHeight != 0) - { - AZ_Warning("ImageBuilder", !logWarning, "Image size (%dx%d) need to be integer multiplier of compression block size (%dx%d) for pixel format %s", - imageWidth, imageHeight, pFormatInfo->minWidth, pFormatInfo->minHeight, pFormatInfo->szName); - return false; - } - } - - return true; - } - - AZ::u32 NextPowOf2(AZ::u32 value) - { - value--; - value |= value >> 1; - value |= value >> 2; - value |= value >> 4; - value |= value >> 8; - value |= value >> 16; - value++; - return value; - } - - void CPixelFormats::GetSuitableImageSize(EPixelFormat format, AZ::u32 imageWidth, AZ::u32 imageHeight, - AZ::u32& outWidth, AZ::u32& outHeight) - { - const PixelFormatInfo* const pFormatInfo = GetPixelFormatInfo(format); - AZ_Assert(pFormatInfo != nullptr, "IsImageSizeValid: unsupport pixel format %d", format); - - outWidth = imageWidth; - outHeight = imageHeight; - - // minimum size required by the pixel format - if (outWidth < pFormatInfo->minWidth) - { - outWidth = pFormatInfo->minWidth; - } - if (outHeight < pFormatInfo->minHeight) - { - outHeight = pFormatInfo->minHeight; - } - - if (pFormatInfo->bSquarePow2 && ((outWidth != outHeight) || (outWidth & (outWidth - 1)) != 0)) - { - AZ::u32 sideSide = AZ::GetMax(outWidth, outHeight); - outWidth = NextPowOf2(sideSide); - outHeight = outWidth; - } - - //check image size againest block size - //if the format requires square and power of 2. we can skip this step - if (!CanImageSizeIgnoreBlockSize(format) && !pFormatInfo->bSquarePow2) - { - if (outWidth % pFormatInfo->blockWidth != 0) - { - outWidth = ((outWidth + pFormatInfo->blockWidth -1) / pFormatInfo->blockWidth) * pFormatInfo->blockWidth; - } - if (outHeight % pFormatInfo->blockHeight != 0) - { - outHeight = ((outHeight + pFormatInfo->blockHeight - 1) / pFormatInfo->blockHeight) * pFormatInfo->blockHeight; - } - } - - } - - uint32 CPixelFormats::EvaluateImageDataSize(EPixelFormat format, uint32 imageWidth, uint32 imageHeight) - { - const PixelFormatInfo* const pFormatInfo = GetPixelFormatInfo(format); - AZ_Assert(pFormatInfo != nullptr, "IsImageSizeValid: unsupport pixel format %d", format); - - //the image should pass IsImageSizeValid test to be eavluated correctly - if (!IsImageSizeValid(format, imageWidth, imageHeight, false)) - { - return 0; - } - - // get number of blocks (ceiling round up for block count) and multiply with bits per block. Divided by 8 to get - // final byte size - return (((imageWidth + pFormatInfo->blockWidth -1) / pFormatInfo->blockWidth) * - ((imageHeight + pFormatInfo->blockHeight - 1) / pFormatInfo->blockHeight) * pFormatInfo->bitsPerBlock) / 8; - } - - bool CPixelFormats::IsFormatSingleChannel(EPixelFormat fmt) - { - return (m_pixelFormatInfo[fmt].nChannels == 1); - } - - bool CPixelFormats::IsFormatSigned(EPixelFormat fmt) - { - // all these formats contain signed data, the FP-formats contain scale & biased unsigned data - return (fmt == ePixelFormat_BC4s || fmt == ePixelFormat_BC5s /*|| fmt == ePixelFormat_BC6SH*/); - } - - bool CPixelFormats::IsFormatFloatingPoint(EPixelFormat fmt, bool bFullPrecision) - { - // all these formats contain floating point data - if (!bFullPrecision) - { - return ((fmt == ePixelFormat_R16F || fmt == ePixelFormat_R16G16F || - fmt == ePixelFormat_R16G16B16A16F) || (fmt == ePixelFormat_BC6UH || fmt == ePixelFormat_R9G9B9E5)); - } - else - { - return ((fmt == ePixelFormat_R32F || fmt == ePixelFormat_R32G32F || fmt == ePixelFormat_R32G32B32A32F)); - } - } -} // namespace ImageProcessing diff --git a/Gems/ImageProcessing/Code/Source/Processing/PixelFormatInfo.h b/Gems/ImageProcessing/Code/Source/Processing/PixelFormatInfo.h deleted file mode 100644 index aee61d1a9f..0000000000 --- a/Gems/ImageProcessing/Code/Source/Processing/PixelFormatInfo.h +++ /dev/null @@ -1,222 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or 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 // DX10+ formats. DXGI_FORMAT - -#include - -#include -#include - -namespace ImageProcessing -{ - //The original implementation was from cryhalf's CryConvertFloatToHalf and CryConvertHalfToFloat function - struct SHalf - { - explicit SHalf(float floatValue) - { - AZ::u32 Result; - - AZ::u32 intValue = ((AZ::u32*)(&floatValue))[0]; - AZ::u32 Sign = (intValue & 0x80000000U) >> 16U; - intValue = intValue & 0x7FFFFFFFU; - - if (intValue > 0x47FFEFFFU) - { - // The number is too large to be represented as a half. Saturate to infinity. - Result = 0x7FFFU; - } - else - { - if (intValue < 0x38800000U) - { - // The number is too small to be represented as a normalized half. - // Convert it to a denormalized value. - AZ::u32 Shift = 113U - (intValue >> 23U); - intValue = (0x800000U | (intValue & 0x7FFFFFU)) >> Shift; - } - else - { - // Rebias the exponent to represent the value as a normalized half. - intValue += 0xC8000000U; - } - - Result = ((intValue + 0x0FFFU + ((intValue >> 13U) & 1U)) >> 13U) & 0x7FFFU; - } - h = (Result | Sign); - } - - operator float() const - { - AZ::u32 Mantissa; - AZ::u32 Exponent; - AZ::u32 Result; - - Mantissa = h & 0x03FF; - - if ((h & 0x7C00) != 0) // The value is normalized - { - Exponent = ((h >> 10) & 0x1F); - } - else if (Mantissa != 0) // The value is denormalized - { - // Normalize the value in the resulting float - Exponent = 1; - - do - { - Exponent--; - Mantissa <<= 1; - } while ((Mantissa & 0x0400) == 0); - - Mantissa &= 0x03FF; - } - else // The value is zero - { - Exponent = -112; - } - - Result = ((h & 0x8000) << 16) | // Sign - ((Exponent + 112) << 23) | // Exponent - (Mantissa << 13); // Mantissa - - return *(float*)&Result; - } - - private: - AZ::u16 h; - }; - - enum class ESampleType - { - eSampleType_Uint8, - eSampleType_Uint16, - eSampleType_Uint32, - eSampleType_Half, - eSampleType_Float, - eSampleType_Compressed, - }; - - struct PixelFormatInfo - { - - int nChannels; // channel count per pixel - bool bHasAlpha; // has alpha channel or not - const char* szAlpha; // a string of bits of alpha channel used to show brief of the pixel format - uint32 minWidth; // minimum width required for image using this pixel format - uint32 minHeight; // minimum height required for image using this pixel format - int blockWidth; // width of the block for block based compressing - int blockHeight; // Height of the block for block based compressing - int bitsPerBlock; // bits per pixel before uncompressed - bool bSquarePow2; // whether the pixel format requires image size be square and power of 2. - DXGI_FORMAT d3d10Format; // the mapping d3d10 pixel format - ESampleType eSampleType; // the data type used to present pixel - const char* szLegacyName; // name used for cryEngine - const char* szName; // name for showing in editors - const char* szDescription; // description for showing in editors - bool bCompressed; // if it's a compressed format - bool bSelectable; // shows up in the list of usable destination pixel formats in the dialog window - AZ::u32 fourCC; // fourCC to identify a none d3d10 format - - PixelFormatInfo() - : szAlpha(0) - , bitsPerBlock(-1) - , d3d10Format(DXGI_FORMAT_UNKNOWN) - , szName(0) - , szDescription(0) - , fourCC(0) - { - } - - PixelFormatInfo( - int a_bitsPerPixel, - int a_Channels, - bool a_Alpha, - const char* a_szAlpha, - uint32 a_minWidth, - uint32 a_minHeight, - int a_blockWidth, - int a_blockHeight, - int a_bitsPerBlock, - bool a_bSquarePow2, - DXGI_FORMAT a_d3d10Format, - AZ::u32 a_fourCC, - ESampleType a_eSampleType, - const char* a_szName, - const char* a_szDescription, - bool a_bCompressed, - bool a_bSelectable); - }; - - class CPixelFormats - { - public: - //singleton - static CPixelFormats& GetInstance(); - static void DestroyInstance(); - - const PixelFormatInfo* GetPixelFormatInfo(EPixelFormat format); - - bool IsPixelFormatWithoutAlpha(EPixelFormat format); - bool IsPixelFormatUncompressed(EPixelFormat format); - - //functions seems only used for BC compressions. need re-evaluate later - bool IsFormatSingleChannel(EPixelFormat fmt); - bool IsFormatSigned(EPixelFormat fmt); - bool IsFormatFloatingPoint(EPixelFormat fmt, bool bFullPrecision); - - //find the pixel format for name used by Cry's RC.ini - //returns ePixelFormat_Unknown if the name was not found in registed format list - EPixelFormat FindPixelFormatByLegacyName(const char* name); - - //find pixel format by its name - EPixelFormat FindPixelFormatByName(const char* name); - - //returns maximum lod levels for image which has certain pixel format, width and height. - uint32 ComputeMaxMipCount(EPixelFormat format, uint32 imageWidth, uint32 imageHeight); - - //check if the input image size work with the pixel format. Some compression formats have requirements with the input image size. - bool IsImageSizeValid(EPixelFormat format, uint32 imageWidth, uint32 imageHeight, bool logWarning); - - //get suitable new size for an image with certain width, height and pixel format - void GetSuitableImageSize(EPixelFormat format, AZ::u32 imageWidth, AZ::u32 imageHeight, - AZ::u32& outWidth, AZ::u32& outHeight); - - //check if the image size of the specified pixel format need to be integer mutiple of block size - bool CanImageSizeIgnoreBlockSize(EPixelFormat format); - - //eavluate image data size. it doesn't include mips - uint32 EvaluateImageDataSize(EPixelFormat format, uint32 imageWidth, uint32 imageHeight); - - private: - CPixelFormats(); - void InitPixelFormats(); - void InitPixelFormat(EPixelFormat format, const PixelFormatInfo& formatInfo); - - private: - static CPixelFormats *s_instance; - - PixelFormatInfo m_pixelFormatInfo[ePixelFormat_Count]; - - //pixel format name to pixel format enum - AZStd::map m_pixelFormatNameMap; - - // some formats from cryEngine were removed. using this name-pixelFormat mapping to look for new format - AZStd::map m_removedLegacyFormats; - }; - - template - bool IsPowerOfTwo(TInteger x); - -} // namespace ImageProcessing diff --git a/Gems/ImageProcessing/Code/Tests/AtlasBuilderTest.cpp b/Gems/ImageProcessing/Code/Tests/AtlasBuilderTest.cpp deleted file mode 100644 index 61462475a7..0000000000 --- a/Gems/ImageProcessing/Code/Tests/AtlasBuilderTest.cpp +++ /dev/null @@ -1,186 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or 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 "ImageProcessing_precompiled.h" -#include "Source/AtlasBuilder/AtlasBuilderWorker.h" -#include "Source/ImageBuilderComponent.h" - -#include -#include - -#include -#include -#include -#include -#include - -#include - -using namespace TextureAtlasBuilder; -using namespace ImageProcessing; - -#if defined(AZ_PLATFORM_APPLE_OSX) -# define AZ_ROOT_TEST_FOLDER "./" -#else -# define AZ_ROOT_TEST_FOLDER "" -#endif - -namespace UnitTest -{ - class AtlasBuilderTest - : public ::testing::Test - , public AzToolsFramework::AssetSystemRequestBus::Handler - { - protected: - void SetUp() override - { - AZ::AllocatorInstance::Create(); - - m_app.reset(aznew AZ::ComponentApplication()); - AZ::ComponentApplication::Descriptor desc; - desc.m_useExistingAllocator = true; - m_app->Create(desc); - - BuilderSettingManager::CreateInstance(); - - m_context = AZStd::make_unique(); - BuilderPluginComponent::Reflect(m_context.get()); - - //load qt plugins for some image file formats support - int argc = 0; - char** argv = nullptr; - m_coreApplication.reset(new QCoreApplication(argc, argv)); - - m_engineRoot.reset(new AZStd::string(AZ::Test::GetEngineRootPath())); - - // Startup default local FileIO (hits OSAllocator) if not already setup. - if (AZ::IO::FileIOBase::GetInstance() == nullptr) - { - AZ::IO::FileIOBase::SetInstance(aznew AZ::IO::LocalFileIO()); - } - - AzToolsFramework::AssetSystemRequestBus::Handler::BusConnect(); - } - - void TearDown() override - { - AzToolsFramework::AssetSystemRequestBus::Handler::BusDisconnect(); - - delete AZ::IO::FileIOBase::GetInstance(); - AZ::IO::FileIOBase::SetInstance(nullptr); - - m_app->Destroy(); - m_app = nullptr; - - m_context.release(); - BuilderSettingManager::DestroyInstance(); - CPixelFormats::DestroyInstance(); - - m_engineRoot.reset(); - m_coreApplication.reset(); - - AZ::AllocatorInstance::Destroy(); - } - - AZStd::string GetFullPath(AZStd::string_view fileName) - { - const AZStd::string testsFolder = *m_engineRoot + "/Gems/ImageProcessing/Code/Tests/"; - return AZStd::string::format("%s%.*s", testsFolder.c_str(), aznumeric_cast(fileName.size()), fileName.data()); - } - - AZStd::unique_ptr m_context; - AZStd::unique_ptr m_app; - AZStd::unique_ptr m_coreApplication; // required by engine root and IsExtensionSupported - AZStd::unique_ptr m_engineRoot; - - public: - AssetBuilderSDK::ProcessJobRequest CreateTestJobRequest( - const AZStd::string& testFileName, - const AZStd::string& watchFolder, - const AZStd::string& tempDirPath, - [[maybe_unused]] bool critical, - QString platform, - AZ::s64 jobId = 0) - { - AZStd::string fullPath; - AzFramework::StringFunc::Path::Join( - watchFolder.c_str(), testFileName.c_str(), fullPath, true, true); - - bool valid = true; - AtlasBuilderInput testInput = AtlasBuilderInput::ReadFromFile(fullPath, watchFolder, valid); - - AssetBuilderSDK::ProcessJobRequest request; - request.m_sourceFile = testFileName; - request.m_fullPath = fullPath; - request.m_tempDirPath = tempDirPath; - request.m_jobId = jobId; - request.m_platformInfo.m_identifier = platform.toUtf8().constData(); - request.m_jobDescription = AtlasBuilderWorker::GetJobDescriptor(testFileName, testInput); - - return request; - } - - AZStd::string GetTestFolderPath() - { - return AZ_ROOT_TEST_FOLDER; - } - - ////////////////////////////////////////////////////////////////////////// - // AssetSystemRequestBus - bool GetAbsoluteAssetDatabaseLocation([[maybe_unused]] AZStd::string& result) override { return false; }; - const char* GetAbsoluteDevGameFolderPath() override { return ""; }; - const char* GetAbsoluteDevRootFolderPath() override { return ""; }; - bool GetRelativeProductPathFromFullSourceOrProductPath([[maybe_unused]] const AZStd::string& fullPath, [[maybe_unused]] AZStd::string& outputPath) override { return false; }; - bool GetFullSourcePathFromRelativeProductPath([[maybe_unused]] const AZStd::string& relPath, [[maybe_unused]] AZStd::string& fullPath) override { return false; }; - bool GetAssetInfoById([[maybe_unused]] const AZ::Data::AssetId& assetId, [[maybe_unused]] const AZ::Data::AssetType& assetType, [[maybe_unused]] const AZStd::string& platformName, [[maybe_unused]] AZ::Data::AssetInfo& assetInfo, [[maybe_unused]] AZStd::string& rootFilePath) override { return false; }; - bool GetSourceInfoBySourcePath(const char* sourcePath, AZ::Data::AssetInfo& assetInfo, AZStd::string& watchFolder) override - { - assetInfo.m_relativePath = sourcePath; - watchFolder = GetFullPath("TestAssets"); - return true; - }; - bool GetSourceInfoBySourceUUID([[maybe_unused]] const AZ::Uuid& sourceUuid, [[maybe_unused]] AZ::Data::AssetInfo& assetInfo, [[maybe_unused]] AZStd::string& watchFolder) override { return false; }; - bool GetScanFolders([[maybe_unused]] AZStd::vector& scanFolders) override { return false; }; - bool GetAssetSafeFolders([[maybe_unused]] AZStd::vector& assetSafeFolders) override { return false; }; - bool IsAssetPlatformEnabled([[maybe_unused]] const char* platform) override { return false; }; - int GetPendingAssetsForPlatform([[maybe_unused]] const char* platform) override { return -1; }; - bool GetAssetsProducedBySourceUUID([[maybe_unused]] const AZ::Uuid& sourceUuid, [[maybe_unused]] AZStd::vector& productsAssetInfo) override { return false; }; - }; - - TEST_F(AtlasBuilderTest, ProcessJob_ProcessValidTextureAtlas_OutputProductDependencies) - { - AZStd::string builderSetting(*m_engineRoot + "/Gems/ImageProcessing/Code/Source/ImageBuilderDefaultPresets.settings"); - auto outcome = BuilderSettingManager::Instance()->LoadBuilderSettings(builderSetting, m_context.get()); - - // create the test job - AssetBuilderSDK::ProcessJobRequest request = CreateTestJobRequest( - "TextureAtlasTest.texatlas", GetFullPath("TestAssets"), GetTestFolderPath(), false, BuilderSettingManager::s_defaultPlatform.c_str(), 1); - - AssetBuilderSDK::ProcessJobResponse response; - - AtlasBuilderWorker testBuilder; - testBuilder.ProcessJob(request, response); - - ASSERT_EQ(response.m_resultCode, AssetBuilderSDK::ProcessJobResultCode::ProcessJobResult_Success); - - // texture atlas builder only has two output products - ASSERT_EQ(response.m_outputProducts.size(), 2); - - // textureatlasidx depends on dds its paired with, but not the other way around - AZ::Data::AssetId ddsProductAssetId(request.m_sourceFileUUID, response.m_outputProducts[static_cast(Product::DdsProduct)].m_productSubID); - AZStd::vector textureatlasidxProductDependencies = response.m_outputProducts[static_cast(Product::TexatlasidxProduct)].m_dependencies; - ASSERT_EQ(textureatlasidxProductDependencies.size(), 1); - ASSERT_EQ(textureatlasidxProductDependencies[0].m_dependencyId, ddsProductAssetId); - - AZStd::vector ddsProductDependencies = response.m_outputProducts[static_cast(Product::DdsProduct)].m_dependencies; - ASSERT_EQ(ddsProductDependencies.size(), 0); - } -} diff --git a/Gems/ImageProcessing/Code/Tests/ImageProcessing_Test.cpp b/Gems/ImageProcessing/Code/Tests/ImageProcessing_Test.cpp deleted file mode 100644 index 0eaa4df4c6..0000000000 --- a/Gems/ImageProcessing/Code/Tests/ImageProcessing_Test.cpp +++ /dev/null @@ -1,1540 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or 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 -#include -#include -#include - -#include -#include -#include -#include - -#include -#include - -//Enable generate image files for result of some tests. -//This is slow and only useful for debugging. This should be disabled for unit test -//#define DEBUG_OUTPUT_IMAGES - -//There are some test functions in this test which are DISABLED. They were mainly for programming tests. -//It's only recommended to enable them for programming test purpose. - -#include -#include -#include "../Source/ImageBuilderComponent.h" - -using namespace ImageProcessing; - -namespace UnitTest -{ - -class ImageProcessingTest - : public ScopedAllocatorSetupFixture - // Only used to provide the serialize context - , public AZ::ComponentApplicationBus::Handler -{ -protected: - AZStd::unique_ptr m_coreApplication; // required by engine root and IsExtensionSupported - AZStd::unique_ptr m_context; - AZStd::string m_engineRoot; - - void SetUp() override - { - BuilderSettingManager::CreateInstance(); - - //prepare reflection - m_context = AZStd::make_unique(); - BuilderPluginComponent::Reflect(m_context.get()); - AZ::DataPatch::Reflect(m_context.get()); - - // Startup default local FileIO (hits OSAllocator) if not already setup. - if (AZ::IO::FileIOBase::GetInstance() == nullptr) - { - AZ::IO::FileIOBase::SetInstance(aznew AZ::IO::LocalFileIO()); - } - - // Adding this handler to allow utility functions access the serialize context - AZ::ComponentApplicationBus::Handler::BusConnect(); - AZ::Interface::Register(this); - - //load qt plugins for some image file formats support - int argc = 0; - char** argv = nullptr; - m_coreApplication.reset(new QCoreApplication(argc, argv)); - m_engineRoot = AZ::Test::GetEngineRootPath(); - - InitialImageFilenames(); - - ImageProcessingEditor::EditorHelper::InitPixelFormatString(); - } - - - void TearDown() override - { - delete AZ::IO::FileIOBase::GetInstance(); - AZ::IO::FileIOBase::SetInstance(nullptr); - - m_context.reset(); - BuilderSettingManager::DestroyInstance(); - CPixelFormats::DestroyInstance(); - - AZ::Interface::Unregister(this); - AZ::ComponentApplicationBus::Handler::BusDisconnect(); - - m_coreApplication.reset(); - } - - // ComponentApplicationMessages overrides... - AZ::ComponentApplication* GetApplication() override { return nullptr; } - void RegisterComponentDescriptor(const AZ::ComponentDescriptor*) override { } - void UnregisterComponentDescriptor(const AZ::ComponentDescriptor*) override { } - void RegisterEntityAddedEventHandler(AZ::EntityAddedEvent::Handler&) override { } - void RegisterEntityRemovedEventHandler(AZ::EntityRemovedEvent::Handler&) override { } - bool AddEntity(AZ::Entity*) override { return false; } - bool RemoveEntity(AZ::Entity*) override { return false; } - bool DeleteEntity(const AZ::EntityId&) override { return false; } - AZ::Entity* FindEntity(const AZ::EntityId&) override { return nullptr; } - AZ::BehaviorContext* GetBehaviorContext() override { return nullptr; } - AZ::JsonRegistrationContext* GetJsonRegistrationContext() override { return nullptr; } - const char* GetAppRoot() const override { return nullptr; } - const char* GetEngineRoot() const override { return nullptr; } - const char* GetExecutableFolder() const override { return nullptr; } - AZ::Debug::DrillerManager* GetDrillerManager() override { return nullptr; } - void EnumerateEntities(const EntityCallback& /*callback*/) override {} - void QueryApplicationType(AZ::ApplicationTypeQuery& /*appType*/) const override {} - // The only one function we need to implement. - AZ::SerializeContext* GetSerializeContext() override - { - return m_context.get(); - } - - //enum names for Images with specific identification - enum ImageFeature - { - Image_20X16_RGBA8_Png = 0, - Image_32X32_16bit_F_Tif, - Image_32X32_32bit_F_Tif, - Image_200X200_RGB8_Jpg, - Image_512X288_RGB8_Tga, - Image_1024X1024_RGB8_Tif, - Image_UpperCase_Tga, - Image_512x512_Normal_Tga, - Image_128x128_Transparent_Tga, - Image_237x177_RGB_Jpg, - Image_GreyScale_Png, - Image_BlackWhite_Png, - Image_TerrainHeightmap_Bt - }; - - //image file names for testing - AZStd::map m_imagFileNameMap; - - //intialial image file names for testing - void InitialImageFilenames() - { - const AZStd::string fileFolder = m_engineRoot + "/Gems/ImageProcessing/Code/Tests/TestAssets/"; - - m_imagFileNameMap[Image_20X16_RGBA8_Png] = fileFolder + AZStd::string("20x16_32bit.png"); - m_imagFileNameMap[Image_32X32_16bit_F_Tif] = fileFolder + AZStd::string("32x32_16bit_f.tif"); - m_imagFileNameMap[Image_32X32_32bit_F_Tif] = fileFolder + AZStd::string("32x32_32bit_f.tif"); - m_imagFileNameMap[Image_200X200_RGB8_Jpg] = fileFolder + AZStd::string("200x200_24bit.jpg"); - m_imagFileNameMap[Image_512X288_RGB8_Tga] = fileFolder + AZStd::string("512x288_24bit.tga"); - m_imagFileNameMap[Image_1024X1024_RGB8_Tif] = fileFolder + AZStd::string("1024x1024_24bit.tif"); - m_imagFileNameMap[Image_UpperCase_Tga] = fileFolder + AZStd::string("uppercase.TGA"); - m_imagFileNameMap[Image_512x512_Normal_Tga] = fileFolder + AZStd::string("512x512_RGB_N.tga"); - m_imagFileNameMap[Image_128x128_Transparent_Tga] = fileFolder + AZStd::string("128x128_RGBA8.tga"); - m_imagFileNameMap[Image_237x177_RGB_Jpg] = fileFolder + AZStd::string("237x177_RGB.jpg"); - m_imagFileNameMap[Image_GreyScale_Png] = fileFolder + AZStd::string("greyscale.png"); - m_imagFileNameMap[Image_BlackWhite_Png] = fileFolder + AZStd::string("BlackWhite.png"); - m_imagFileNameMap[Image_TerrainHeightmap_Bt] = fileFolder + AZStd::string("TerrainHeightmap.bt"); - } - -public: - //helper function to save an image object to a file through QtImage - static void SaveImageToFile(const IImageObjectPtr imageObject, const AZStd::string imageName, AZ::u32 maxMipCnt = 100) - { -#ifndef DEBUG_OUTPUT_IMAGES - return; -#endif - if (imageObject == nullptr) - { - return; - } - - //create the directory if it's not exist - const AZStd::string outputDir = AZ::Test::GetEngineRootPath() + "/Gems/ImageProcessing/Code/Tests/TestAssets/Output/"; - QDir dir(outputDir.c_str()); - if (!dir.exists()) - { - dir.mkpath("."); - } - - //save origin file pixel format so we could use it to generate name later - EPixelFormat originPixelFormat = imageObject->GetPixelFormat(); - - //convert to RGBA8 before can be exported. - ImageToProcess imageToProcess(imageObject); - imageToProcess.ConvertFormat(ePixelFormat_R8G8B8A8); - - IImageObjectPtr finalImage = imageToProcess.Get(); - - //for each mipmap - for (uint32 mip = 0; mip < finalImage->GetMipCount() && mip < maxMipCnt; mip++) - { - uint8* imageBuf; - uint32 pitch; - finalImage->GetImagePointer(mip, imageBuf, pitch); - uint32 width = finalImage->GetWidth(mip); - uint32 height = finalImage->GetHeight(mip); - - //generate file name - char filePath[2048]; - azsprintf(filePath, "%s%s_%s_mip%d_%dx%d.png", outputDir.c_str(), imageName.c_str() - , CPixelFormats::GetInstance().GetPixelFormatInfo(originPixelFormat)->szName - , mip, width, height); - - QImage qimage(imageBuf, width, height, pitch, QImage::Format_RGBA8888); - qimage.save(filePath); - } - } - - static bool GetComparisonResult(IImageObjectPtr image1, IImageObjectPtr image2, QString& output) - { - bool isImageLoaded = true; - bool isDifferent = false; - - if (image1 == nullptr) - { - isImageLoaded = false; - output += ",Image 1 does not exist. "; - } - - if (image2 == nullptr) - { - isImageLoaded = false; - output += ",Image 2 does not exist. "; - } - - if (!isImageLoaded) - { - return (!image1 && !image2) ? false: true; - } - - // Mip - int mip1 = image1->GetMipCount(); - int mip2 = image2->GetMipCount(); - int mipDiff = abs(mip1 - mip2); - - isDifferent |= mipDiff != 0; - - // Format - EPixelFormat format1 = image1->GetPixelFormat(); - EPixelFormat format2 = image2->GetPixelFormat(); - - isDifferent |= (format1 != format2); - - // Flag - AZ::u32 flag1 = image1->GetImageFlags(); - AZ::u32 flag2 = image2->GetImageFlags(); - - isDifferent |= (flag1 != flag2); - - // Size - int memSize1 = image1->GetTextureMemory(); - int memSize2 = image2->GetTextureMemory(); - int memDiff = abs(memSize1 - memSize2); - - isDifferent |= memDiff != 0; - - // Error - float error = GetErrorBetweenImages(image1, image2); - - static float EPSILON = 0.000001f; - isDifferent |= abs(error) >= EPSILON; - - output += QString(",%1/%2,%3,%4/%5,%6/%7,").arg(QString::number(mip1,'f',1), QString::number(mip2,'f',1), QString::number(mipDiff), - QString(ImageProcessingEditor::EditorHelper::s_PixelFormatString[format1]), - QString(ImageProcessingEditor::EditorHelper::s_PixelFormatString[format2]), - QString::number(flag1, 16), QString::number(flag2, 16)); - - output += QString("%1/%2,%3,%4").arg(QString(ImageProcessingEditor::EditorHelper::GetFileSizeString(memSize1).c_str()), - QString(ImageProcessingEditor::EditorHelper::GetFileSizeString(memSize2).c_str()), - QString(ImageProcessingEditor::EditorHelper::GetFileSizeString(memDiff).c_str()), - QString::number(error, 'f', 8)); - - - return isDifferent; - } - - - static bool CompareDDSImage(const QString& imagePath1, const QString& imagePath2, QString& output) - { - IImageObjectPtr image1, alphaImage1, image2, alphaImage2; - - - image1 = IImageObjectPtr(LoadImageFromDdsFile(imagePath1.toUtf8().constData())); - if (image1 && image1->HasImageFlags(EIF_AttachedAlpha)) - { - if (image1->HasImageFlags(EIF_Splitted)) - { - alphaImage1 = IImageObjectPtr(LoadImageFromDdsFile(QString(imagePath1 + ".a").toUtf8().constData())); - } - else - { - alphaImage1 = IImageObjectPtr(LoadAttachedImageFromDdsFile(imagePath1.toUtf8().constData(), image1)); - } - } - - image2 = IImageObjectPtr(LoadImageFromDdsFile(imagePath2.toUtf8().constData())); - if (image2 && image2->HasImageFlags(EIF_AttachedAlpha)) - { - if (image2->HasImageFlags(EIF_Splitted)) - { - alphaImage2 = IImageObjectPtr(LoadImageFromDdsFile(QString(imagePath2 + ".a").toUtf8().constData())); - } - else - { - alphaImage2 = IImageObjectPtr(LoadAttachedImageFromDdsFile(imagePath2.toUtf8().constData(), image2)); - } - } - - if (!image1 && !image2) - { - output += "Cannot load both image file! "; - return false; - } - bool isDifferent = false; - - isDifferent = GetComparisonResult(image1, image2, output); - - - QFileInfo fi(imagePath1); - AZStd::string imageName = fi.baseName().toUtf8().constData(); - SaveImageToFile(image1, imageName + "_new"); - SaveImageToFile(image2, imageName + "_old"); - - if (alphaImage1 || alphaImage2) - { - isDifferent |= GetComparisonResult(alphaImage1, alphaImage2, output); - } - - return isDifferent; - } -}; - -// test CPixelFormats related functions -TEST_F(ImageProcessingTest, TestPixelFormats) -{ - CPixelFormats& pixelFormats = CPixelFormats::GetInstance(); - - //verify names which was used for legacy rc.ini - ASSERT_TRUE(pixelFormats.FindPixelFormatByLegacyName("BC7t") == ePixelFormat_BC7t); - ASSERT_TRUE(pixelFormats.FindPixelFormatByLegacyName("ETC2A") == ePixelFormat_ETC2a); - ASSERT_TRUE(pixelFormats.FindPixelFormatByLegacyName("PVRTC4") == ePixelFormat_PVRTC4); - ASSERT_TRUE(pixelFormats.FindPixelFormatByLegacyName("BC1") == ePixelFormat_BC1); - ASSERT_TRUE(pixelFormats.FindPixelFormatByLegacyName("ETC2") == ePixelFormat_ETC2); - ASSERT_TRUE(pixelFormats.FindPixelFormatByLegacyName("BC1a") == ePixelFormat_BC1a); - ASSERT_TRUE(pixelFormats.FindPixelFormatByLegacyName("BC3") == ePixelFormat_BC3); - ASSERT_TRUE(pixelFormats.FindPixelFormatByLegacyName("BC7") == ePixelFormat_BC7); - ASSERT_TRUE(pixelFormats.FindPixelFormatByLegacyName("BC5s") == ePixelFormat_BC5s); - ASSERT_TRUE(pixelFormats.FindPixelFormatByLegacyName("EAC_RG11") == ePixelFormat_EAC_RG11); - ASSERT_TRUE(pixelFormats.FindPixelFormatByLegacyName("BC4") == ePixelFormat_BC4); - ASSERT_TRUE(pixelFormats.FindPixelFormatByLegacyName("EAC_R11") == ePixelFormat_EAC_R11); - ASSERT_TRUE(pixelFormats.FindPixelFormatByLegacyName("A8R8G8B8") == ePixelFormat_R8G8B8A8); - ASSERT_TRUE(pixelFormats.FindPixelFormatByLegacyName("BC6UH") == ePixelFormat_BC6UH); - ASSERT_TRUE(pixelFormats.FindPixelFormatByLegacyName("R9G9B9E5") == ePixelFormat_R9G9B9E5); - ASSERT_TRUE(pixelFormats.FindPixelFormatByLegacyName("X8R8G8B8") == ePixelFormat_R8G8B8X8); - ASSERT_TRUE(pixelFormats.FindPixelFormatByLegacyName("A16B16G16R16F") == ePixelFormat_R16G16B16A16F); - ASSERT_TRUE(pixelFormats.FindPixelFormatByLegacyName("G8R8") == ePixelFormat_R8G8); - ASSERT_TRUE(pixelFormats.FindPixelFormatByLegacyName("G16R16") == ePixelFormat_R16G16); - ASSERT_TRUE(pixelFormats.FindPixelFormatByLegacyName("G16R16F") == ePixelFormat_R16G16F); - - //some legacy format need to be mapping to new format. - ASSERT_TRUE(pixelFormats.FindPixelFormatByLegacyName("DXT1") == ePixelFormat_BC1); - ASSERT_TRUE(pixelFormats.FindPixelFormatByLegacyName("DXT5") == ePixelFormat_BC3); - - //calculate mipmap count. no cubemap support at this moment - - //for all the non-compressed textures, if there minimum required texture size is 1x1 - for (uint32 i = 0; i < ePixelFormat_Count; i++) - { - EPixelFormat pixelFormat = (EPixelFormat)i; - if (pixelFormats.IsPixelFormatUncompressed(pixelFormat)) - { - //square, power of 2 sizes for uncompressed format which minimum required size is 1x1 - ASSERT_TRUE(pixelFormats.ComputeMaxMipCount(pixelFormat, 128, 128) == 8); - ASSERT_TRUE(pixelFormats.ComputeMaxMipCount(pixelFormat, 64, 64) == 7); - ASSERT_TRUE(pixelFormats.ComputeMaxMipCount(pixelFormat, 4, 4) == 3); - ASSERT_TRUE(pixelFormats.ComputeMaxMipCount(pixelFormat, 2, 2) == 2); - ASSERT_TRUE(pixelFormats.ComputeMaxMipCount(pixelFormat, 1, 1) == 1); - - //non-square, power of 2 sizes for uncompressed format which minimum required size is 1x1 - ASSERT_TRUE(pixelFormats.ComputeMaxMipCount(pixelFormat, 128, 64) == 8); - ASSERT_TRUE(pixelFormats.ComputeMaxMipCount(pixelFormat, 128, 32) == 8); - ASSERT_TRUE(pixelFormats.ComputeMaxMipCount(pixelFormat, 32, 2) == 6); - ASSERT_TRUE(pixelFormats.ComputeMaxMipCount(pixelFormat, 2, 1) == 2); - - //Non power of 2 sizes for uncompressed format which minimum required size is 1x1 - ASSERT_TRUE(pixelFormats.ComputeMaxMipCount(pixelFormat, 128, 64) == 8); - ASSERT_TRUE(pixelFormats.ComputeMaxMipCount(pixelFormat, 128, 32) == 8); - ASSERT_TRUE(pixelFormats.ComputeMaxMipCount(pixelFormat, 32, 2) == 6); - ASSERT_TRUE(pixelFormats.ComputeMaxMipCount(pixelFormat, 2, 1) == 2); - } - } - - //check function IsImageSizeValid && EvaluateImageDataSize function - ASSERT_TRUE(pixelFormats.IsImageSizeValid(ePixelFormat_PVRTC4, 2, 1, false) == false); - ASSERT_TRUE(pixelFormats.IsImageSizeValid(ePixelFormat_PVRTC4, 4, 4, false) == false); - ASSERT_TRUE(pixelFormats.IsImageSizeValid(ePixelFormat_PVRTC4, 16, 16, false) == true); - ASSERT_TRUE(pixelFormats.IsImageSizeValid(ePixelFormat_PVRTC4, 16, 32, false) == false); - ASSERT_TRUE(pixelFormats.IsImageSizeValid(ePixelFormat_PVRTC4, 34, 34, false) == false); - ASSERT_TRUE(pixelFormats.IsImageSizeValid(ePixelFormat_PVRTC4, 256, 256, false) == true); - - ASSERT_TRUE(pixelFormats.IsImageSizeValid(ePixelFormat_BC1, 2, 1, false) == false); - ASSERT_TRUE(pixelFormats.IsImageSizeValid(ePixelFormat_BC1, 16, 16, false) == true); - ASSERT_TRUE(pixelFormats.IsImageSizeValid(ePixelFormat_BC1, 16, 32, false) == true); - ASSERT_TRUE(pixelFormats.IsImageSizeValid(ePixelFormat_BC1, 34, 34, false) == false); - ASSERT_TRUE(pixelFormats.IsImageSizeValid(ePixelFormat_BC1, 256, 256, false) == true); - - ASSERT_TRUE(pixelFormats.IsImageSizeValid(ePixelFormat_ASTC_4x4, 2, 1, false) == false); - ASSERT_TRUE(pixelFormats.IsImageSizeValid(ePixelFormat_ASTC_4x4, 16, 16, false) == true); - ASSERT_TRUE(pixelFormats.IsImageSizeValid(ePixelFormat_ASTC_4x4, 16, 32, false) == true); - ASSERT_TRUE(pixelFormats.IsImageSizeValid(ePixelFormat_ASTC_4x4, 34, 34, false) == true); - ASSERT_TRUE(pixelFormats.IsImageSizeValid(ePixelFormat_ASTC_4x4, 256, 256, false) == true); - - ASSERT_TRUE(pixelFormats.IsImageSizeValid(ePixelFormat_A8, 2, 1, false) == true); - ASSERT_TRUE(pixelFormats.IsImageSizeValid(ePixelFormat_A8, 16, 16, false) == true); - ASSERT_TRUE(pixelFormats.IsImageSizeValid(ePixelFormat_A8, 16, 32, false) == true); - ASSERT_TRUE(pixelFormats.IsImageSizeValid(ePixelFormat_A8, 34, 34, false) == true); - ASSERT_TRUE(pixelFormats.IsImageSizeValid(ePixelFormat_A8, 256, 256, false) == true); -} - -// test image file loading -TEST_F(ImageProcessingTest, TestImageLoaders) -{ - //file extention support for different loader - ASSERT_TRUE(IsExtensionSupported("jpg") == true); - ASSERT_TRUE(IsExtensionSupported("JPG") == true); - ASSERT_TRUE(IsExtensionSupported(".JPG") == false); - ASSERT_TRUE(IsExtensionSupported("tga") == true); - ASSERT_TRUE(IsExtensionSupported("TGA") == true); - ASSERT_TRUE(IsExtensionSupported("tif") == true); - ASSERT_TRUE(IsExtensionSupported("tiff") == true); - ASSERT_TRUE(IsExtensionSupported("bt") == true); - - IImageObjectPtr img; - img = IImageObjectPtr(LoadImageFromFile(m_imagFileNameMap[Image_1024X1024_RGB8_Tif])); - - ASSERT_TRUE(img != nullptr); - ASSERT_TRUE(img->GetWidth(0) == 1024); - ASSERT_TRUE(img->GetHeight(0) == 1024); - ASSERT_TRUE(img->GetMipCount() == 1); - ASSERT_TRUE(img->GetPixelFormat() == ePixelFormat_R8G8B8X8); - - //load png - img = IImageObjectPtr(LoadImageFromFile(m_imagFileNameMap[Image_20X16_RGBA8_Png])); - ASSERT_TRUE(img != nullptr); - ASSERT_TRUE(img->GetWidth(0) == 20); - ASSERT_TRUE(img->GetHeight(0) == 16); - ASSERT_TRUE(img->GetMipCount() == 1); - ASSERT_TRUE(img->GetPixelFormat() == ePixelFormat_R8G8B8A8); - - //load jpg - img = IImageObjectPtr(LoadImageFromFile(m_imagFileNameMap[Image_200X200_RGB8_Jpg])); - ASSERT_TRUE(img->GetWidth(0) == 200); - ASSERT_TRUE(img->GetHeight(0) == 200); - ASSERT_TRUE(img->GetMipCount() == 1); - ASSERT_TRUE(img->GetPixelFormat() == ePixelFormat_R8G8B8A8); - - //tga - img = IImageObjectPtr(LoadImageFromFile(m_imagFileNameMap[Image_512X288_RGB8_Tga])); - ASSERT_TRUE(img->GetWidth(0) == 512); - ASSERT_TRUE(img->GetHeight(0) == 288); - ASSERT_TRUE(img->GetMipCount() == 1); - ASSERT_TRUE(img->GetPixelFormat() == ePixelFormat_R8G8B8A8); - - //image with upper case extension - img = IImageObjectPtr(LoadImageFromFile(m_imagFileNameMap[Image_UpperCase_Tga])); - ASSERT_TRUE(img->GetPixelFormat() == ePixelFormat_R8G8B8A8); - - //16bits float tif - img = IImageObjectPtr(LoadImageFromFile(m_imagFileNameMap[Image_32X32_16bit_F_Tif])); - ASSERT_TRUE(img->GetPixelFormat() == ePixelFormat_R16G16B16A16F); - - //32bits float tif - img = IImageObjectPtr(LoadImageFromFile(m_imagFileNameMap[Image_32X32_32bit_F_Tif])); - ASSERT_TRUE(img->GetPixelFormat() == ePixelFormat_R32G32B32A32F); - - //BT - img = IImageObjectPtr(LoadImageFromFile(m_imagFileNameMap[Image_TerrainHeightmap_Bt])); - ASSERT_TRUE(img != nullptr); - EXPECT_EQ(img->GetWidth(0), 128); - EXPECT_EQ(img->GetHeight(0), 128); - EXPECT_EQ(img->GetMipCount(), 1); - EXPECT_EQ(img->GetPixelFormat(), ePixelFormat_R32F); -} - -TEST_F(ImageProcessingTest, PresetSettingCopyAssignmentOperatorOverload_WithDynamicallyAllocatedSettings_ReturnsTwoSeparateAllocations) -{ - PresetSettings presetSetting; - presetSetting.m_mipmapSetting = AZStd::unique_ptr(new MipmapSettings()); - presetSetting.m_cubemapSetting = AZStd::unique_ptr(new CubemapSettings()); - - // Explicit invoke assignment operator by splitting the operation into two lines. - PresetSettings otherPresetSetting; - otherPresetSetting = presetSetting; - - EXPECT_NE(otherPresetSetting.m_cubemapSetting, presetSetting.m_cubemapSetting); - EXPECT_NE(otherPresetSetting.m_mipmapSetting, presetSetting.m_mipmapSetting); -} - -TEST_F(ImageProcessingTest, PresetSettingCopyConstructor_WithDynamicallyAllocatedSettings_ReturnsTwoSeparateAllocations) -{ - PresetSettings presetSetting; - presetSetting.m_mipmapSetting = AZStd::unique_ptr(new MipmapSettings()); - presetSetting.m_cubemapSetting = AZStd::unique_ptr(new CubemapSettings()); - - PresetSettings otherPresetSetting(presetSetting); - - EXPECT_NE(otherPresetSetting.m_cubemapSetting, presetSetting.m_cubemapSetting); - EXPECT_NE(otherPresetSetting.m_mipmapSetting, presetSetting.m_mipmapSetting); -} - -TEST_F(ImageProcessingTest, PresetSettingEqualityOperatorOverload_WithIdenticalSettings_ReturnsEquivalent) -{ - PresetSettings presetSetting; - PresetSettings otherPresetSetting(presetSetting); - - EXPECT_TRUE(otherPresetSetting == presetSetting); -} - -TEST_F(ImageProcessingTest, PresetSettingEqualityOperatorOverload_WithDifferingDynamicallyAllocatedSettings_ReturnsUnequivalent) -{ - PresetSettings presetSetting; - presetSetting.m_mipmapSetting = AZStd::unique_ptr(new MipmapSettings()); - presetSetting.m_mipmapSetting->m_type = MipGenType::gaussian; - - PresetSettings otherPresetSetting(presetSetting); - otherPresetSetting.m_mipmapSetting = AZStd::unique_ptr(new MipmapSettings()); - otherPresetSetting.m_mipmapSetting->m_type = MipGenType::blackmanHarris; - - EXPECT_FALSE(otherPresetSetting == presetSetting); - -} - -//this test is to test image data won't be lost between uncompressed formats (for low to high precision or same precision) -TEST_F(ImageProcessingTest, TestConvertFormatUncompressed) -{ - //source image - IImageObjectPtr srcImage(LoadImageFromFile(m_imagFileNameMap[Image_200X200_RGB8_Jpg])); - ImageToProcess imageToProcess(srcImage); - - //image pointers to hold precessed images for comparison - IImageObjectPtr dstImage1, dstImage2, dstImage3, dstImage4, dstImage5; - - //compare four channels pixel formats - //we will convert to target format then convert back to RGBX8 so they can compare to easy other - imageToProcess.ConvertFormatUncompressed(ePixelFormat_R8G8B8A8); - dstImage1 = imageToProcess.Get(); - - imageToProcess.Set(srcImage); - imageToProcess.ConvertFormatUncompressed(ePixelFormat_R16G16B16A16); - ASSERT_FALSE(srcImage->CompareImage(imageToProcess.Get())); //this is different than source image - imageToProcess.ConvertFormatUncompressed(ePixelFormat_R8G8B8A8); - dstImage2 = imageToProcess.Get(); - - imageToProcess.Set(srcImage); - imageToProcess.ConvertFormatUncompressed(ePixelFormat_R16G16B16A16F); - imageToProcess.ConvertFormatUncompressed(ePixelFormat_R8G8B8A8); - dstImage3 = imageToProcess.Get(); - - imageToProcess.Set(srcImage); - imageToProcess.ConvertFormatUncompressed(ePixelFormat_R32G32B32A32F); - imageToProcess.ConvertFormatUncompressed(ePixelFormat_R8G8B8A8); - dstImage4 = imageToProcess.Get(); - - ASSERT_TRUE(dstImage2->CompareImage(dstImage1)); - ASSERT_TRUE(dstImage3->CompareImage(dstImage1)); - ASSERT_TRUE(dstImage4->CompareImage(dstImage1)); - - // three channels formats - imageToProcess.Set(srcImage); - imageToProcess.ConvertFormatUncompressed(ePixelFormat_R8G8B8X8); - dstImage1 = imageToProcess.Get(); - - imageToProcess.Set(srcImage); - imageToProcess.ConvertFormatUncompressed(ePixelFormat_R9G9B9E5); - imageToProcess.ConvertFormatUncompressed(ePixelFormat_R8G8B8X8); - dstImage2 = imageToProcess.Get(); - - ASSERT_TRUE(dstImage2->CompareImage(dstImage1)); - - //convert image to all one channel formats then convert them back to RGBX8 for comparison - imageToProcess.Set(srcImage); - imageToProcess.ConvertFormatUncompressed(ePixelFormat_R8); - imageToProcess.ConvertFormatUncompressed(ePixelFormat_R8G8B8X8); - dstImage1 = imageToProcess.Get(); - - imageToProcess.Set(srcImage); - imageToProcess.ConvertFormatUncompressed(ePixelFormat_R16); - imageToProcess.ConvertFormatUncompressed(ePixelFormat_R8G8B8X8); - dstImage2 = imageToProcess.Get(); - - imageToProcess.Set(srcImage); - imageToProcess.ConvertFormatUncompressed(ePixelFormat_R16F); - imageToProcess.ConvertFormatUncompressed(ePixelFormat_R8G8B8X8); - dstImage3 = imageToProcess.Get(); - - imageToProcess.Set(srcImage); - imageToProcess.ConvertFormatUncompressed(ePixelFormat_R32F); - imageToProcess.ConvertFormatUncompressed(ePixelFormat_R8G8B8X8); - dstImage4 = imageToProcess.Get(); - - ASSERT_TRUE(dstImage2->CompareImage(dstImage1)); - ASSERT_TRUE(dstImage3->CompareImage(dstImage1)); - ASSERT_TRUE(dstImage4->CompareImage(dstImage1)); - - //convert image to all two channels formats then convert them back to RGBX8 for comparison - imageToProcess.Set(srcImage); - imageToProcess.ConvertFormatUncompressed(ePixelFormat_R8G8); - imageToProcess.ConvertFormatUncompressed(ePixelFormat_R8G8B8X8); - dstImage1 = imageToProcess.Get(); - - imageToProcess.Set(srcImage); - imageToProcess.ConvertFormatUncompressed(ePixelFormat_R16G16); - imageToProcess.ConvertFormatUncompressed(ePixelFormat_R8G8B8X8); - dstImage2 = imageToProcess.Get(); - - imageToProcess.Set(srcImage); - imageToProcess.ConvertFormatUncompressed(ePixelFormat_R16G16F); - imageToProcess.ConvertFormatUncompressed(ePixelFormat_R8G8B8X8); - dstImage3 = imageToProcess.Get(); - - ASSERT_TRUE(dstImage2->CompareImage(dstImage1)); - ASSERT_TRUE(dstImage3->CompareImage(dstImage1)); -} - -TEST_F(ImageProcessingTest, DISABLED_TestConvertPVRTC) -{ - //load builder presets - AZStd::string buiderSetting = m_engineRoot + "/Gems/ImageProcessing/Code/Source/ImageBuilderDefaultPresets.settings"; - auto outcome = BuilderSettingManager::Instance()->LoadBuilderSettings(buiderSetting, m_context.get()); - - AZStd::vector outPaths; - AZStd::string inputFile = m_engineRoot + "/Gems/ImageProcessing/Code/Tests/TestAssets/normalSmoothness_ddna.tif"; - const AZStd::string outputFolder = m_engineRoot + "/Gems/ImageProcessing/Code/Tests/TestAssets/temp/"; - ImageConvertProcess* process = CreateImageConvertProcess(inputFile, outputFolder, "ios", m_context.get()); - if (process != nullptr) - { - //the process can be stopped if the job is cancelled or the worker is shutting down - int step = 0; - while (!process->IsFinished()) - { - process->UpdateProcess(); - step++; - } - - //get process result - ASSERT_TRUE(process->IsSucceed()); - - SaveImageToFile(process->GetOutputImage(), "rgb", 10); - SaveImageToFile(process->GetOutputAlphaImage(), "alpha", 10); - - process->GetAppendOutputFilePaths(outPaths); - delete process; - } - - //ASSERT_TRUE(ConvertImageFile(inputFile, outputFolder, outPaths, "ios", m_context.get())); - -} - -TEST_F(ImageProcessingTest, DISABLED_TestConvertFormat) -{ - EPixelFormat pixelFormat; - IImageObjectPtr srcImage; - - //images to be tested - static const int imageCount = 5; - ImageFeature images[imageCount] = { - Image_20X16_RGBA8_Png, - Image_32X32_16bit_F_Tif, - Image_32X32_32bit_F_Tif , - Image_512x512_Normal_Tga , - Image_128x128_Transparent_Tga }; - - for (int imageIdx = 0; imageIdx < imageCount; imageIdx++) - { - //get image's name and it will be used for output file name - QFileInfo fi(m_imagFileNameMap[images[imageIdx]].c_str()); - AZStd::string imageName = fi.baseName().toUtf8().constData(); - - srcImage = IImageObjectPtr(LoadImageFromFile(m_imagFileNameMap[images[imageIdx]])); - ImageToProcess imageToProcess(srcImage); - - //test ConvertFormat functions againest all the pixel formats - for (pixelFormat = ePixelFormat_R8G8B8A8; pixelFormat < ePixelFormat_Unknown;) - { - imageToProcess.Set(srcImage); - imageToProcess.ConvertFormat(pixelFormat); - - ASSERT_TRUE(imageToProcess.Get()); - - //if the format is compressed and there is no compressor for it, it won't be converted to the expected format - if (ICompressor::FindCompressor(pixelFormat, true) == nullptr - && !CPixelFormats::GetInstance().IsPixelFormatUncompressed(pixelFormat)) - { - ASSERT_TRUE(imageToProcess.Get()->GetPixelFormat() != pixelFormat); - } - else - { - //validate the size and it may not working for some uncompressed format - if (!CPixelFormats::GetInstance().IsImageSizeValid( - pixelFormat, srcImage->GetWidth(0), srcImage->GetHeight(0), false)) - { - ASSERT_TRUE(imageToProcess.Get()->GetPixelFormat() != pixelFormat); - } - else - { - ASSERT_TRUE(imageToProcess.Get()->GetPixelFormat() == pixelFormat); - - //save the image to a file so we can check the visual result - SaveImageToFile(imageToProcess.Get(), imageName, 1); - - //convert back to an uncompressed format and expect it will be successful - imageToProcess.ConvertFormat(ePixelFormat_R8G8B8A8); - ASSERT_TRUE(imageToProcess.Get()->GetPixelFormat() == ePixelFormat_R8G8B8A8); - - } - } - - //next pixel format - pixelFormat = EPixelFormat(pixelFormat + 1); - } - } -} - -TEST_F(ImageProcessingTest, DISABLED_TestImageFilter) -{ - AZStd::string testImageFile = m_imagFileNameMap[Image_1024X1024_RGB8_Tif]; - IImageObjectPtr srcImage, dstImage; - - QFileInfo fi(testImageFile.c_str()); - AZStd::string imageName = fi.baseName().toUtf8().constData(); - - //load src image and convert it to RGBA32F - srcImage = IImageObjectPtr(LoadImageFromFile(testImageFile)); - ImageToProcess imageToProcess(srcImage); - imageToProcess.ConvertFormat(ePixelFormat_R32G32B32A32F); - srcImage = imageToProcess.Get(); - - //create dst image with same size and mipmaps - dstImage = IImageObjectPtr( - IImageObject::CreateImage(srcImage->GetWidth(0), srcImage->GetHeight(0), 3, - ePixelFormat_R32G32B32A32F)); - - //for each filters - const std::array, 7> allFilters = - { - { - {MipGenType::point, "point"}, - {MipGenType::box, "box" }, - { MipGenType::triangle, "triangle" }, - { MipGenType::quadratic, "Quadratic" }, - { MipGenType::blackmanHarris, "blackmanHarris" }, - { MipGenType::kaiserSinc, "kaiserSinc" } - } - }; - - for (std::pair filter : allFilters) - { - for (uint mip = 0; mip < dstImage->GetMipCount(); mip++) - { - FilterImage(filter.first, MipGenEvalType::sum, - 0, 0, imageToProcess.Get(), 0, dstImage, mip, nullptr, nullptr); - } - SaveImageToFile(dstImage, imageName + "_" + filter.second); - } -} - -TEST_F(ImageProcessingTest, TestColorSpaceConversion) -{ - IImageObjectPtr srcImage(LoadImageFromFile(m_imagFileNameMap[Image_GreyScale_Png])); - - ImageToProcess imageToProcess(srcImage); - imageToProcess.GammaToLinearRGBA32F(true); - SaveImageToFile(imageToProcess.Get(), "GammaTolinear_DeGamma", 1); - imageToProcess.LinearToGamma(); - SaveImageToFile(imageToProcess.Get(), "LinearToGamma_DeGamma", 1); -} - -//This function can be used to modify some value in the builder setting and keep all presets uuid then save back to setting file -//It will only change the file if the file was checked out -TEST_F(ImageProcessingTest, DISABLED_ModifyBuilderSetting) -{ - AZStd::string buiderSetting = m_engineRoot + "/Gems/ImageProcessing/Code/Source/ImageBuilderDefaultPresets.settings"; - QFileInfo fileInfo(buiderSetting.c_str()); - if (fileInfo.isWritable()) - { - auto outcome = BuilderSettingManager::Instance()->LoadBuilderSettings(buiderSetting, m_context.get()); - BuilderSettingManager::Instance()->WriteBuilderSettings(buiderSetting, m_context.get()); - } -} - -TEST_F(ImageProcessingTest, VerifyRestrictedPlatform) -{ - AZStd::string buiderSetting = m_engineRoot + "/Gems/ImageProcessing/Code/Source/ImageBuilderDefaultPresets.settings"; - auto outcome = BuilderSettingManager::Instance()->LoadBuilderSettings(buiderSetting, m_context.get()); - PlatformNameList platforms = BuilderSettingManager::Instance()->GetPlatformList(); - -#ifndef AZ_TOOLS_EXPAND_FOR_RESTRICTED_PLATFORMS - ASSERT_TRUE(platforms.size() == 4); -#endif //AZ_TOOLS_EXPAND_FOR_RESTRICTED_PLATFORMS -} - -TEST_F(ImageProcessingTest, DISABLED_TestCubemap) -{ - //load builder presets - AZStd::string buiderSetting = m_engineRoot + "/Gems/ImageProcessing/Code/Source/ImageBuilderDefaultPresets.settings"; - auto outcome = BuilderSettingManager::Instance()->LoadBuilderSettings(buiderSetting, m_context.get()); - - const AZStd::string outputFolder = m_engineRoot + "/Gems/ImageProcessing/Code/Tests/TestAssets/temp/"; - AZStd::string inputFile; - AZStd::vector outPaths; - - inputFile = m_engineRoot + "/Assets/Engine/EngineAssets/Shading/defaultProbe_cm.tif"; - - IImageObjectPtr srcImage(LoadImageFromFile(inputFile)); - ImageToProcess imageToProcess(srcImage); - imageToProcess.ConvertCubemapLayout(CubemapLayoutVertical); - SaveImageToFile(imageToProcess.Get(), "Vertical", 100); - imageToProcess.ConvertCubemapLayout(CubemapLayoutHorizontalCross); - SaveImageToFile(imageToProcess.Get(), "HorizontalCross", 100); - imageToProcess.ConvertCubemapLayout(CubemapLayoutVerticalCross); - SaveImageToFile(imageToProcess.Get(), "VerticalCross", 100); - imageToProcess.ConvertCubemapLayout(CubemapLayoutHorizontal); - SaveImageToFile(imageToProcess.Get(), "VerticalHorizontal", 100); - - ImageConvertProcess* process = CreateImageConvertProcess(inputFile, outputFolder, "pc"); - - if (process != nullptr) - { - int step = 0; - while (!process->IsFinished()) - { - process->UpdateProcess(); - step++; - char name[100]; - azsprintf(name, "cubemap_%d", step); - //SaveImageToFile(process->GetOutputImage(), name, 1); - } - - //get process result - ASSERT_TRUE(process->IsSucceed()); - - SaveImageToFile(process->GetOutputImage(), "cubemap", 100); - SaveImageToFile(process->GetOutputDiffCubemap(), "diffCubemap", 100); - SaveImageToFile(process->GetOutputAlphaImage(), "alpha", 1); - process->GetAppendOutputFilePaths(outPaths); - - delete process; - } -} - -//test image conversion for builder -TEST_F(ImageProcessingTest, DISABLED_TestBuilderImageConvertor) -{ - AZStd::string oldCacheFolder = "E:/Javelin_old_tex_cache/textures"; - AZStd::string srcFolder = "E:/Javelin_NWLYDev/dev/Assets/Textures"; - - //load builder presets - AZStd::string buiderSetting = m_engineRoot + "/Gems/ImageProcessing/Code/Source/ImageBuilderDefaultPresets.settings"; - auto outcome = BuilderSettingManager::Instance()->LoadBuilderSettings(buiderSetting, m_context.get()); - - const AZStd::string outputFolder = m_engineRoot + "/Gems/ImageProcessing/Code/Tests/TestAssets/temp/"; - AZStd::string inputFile; - AZStd::vector outPaths; - - inputFile = srcFolder + "/terrain/cry/detail/grass_with_stones_displ.tif"; - inputFile = m_imagFileNameMap[Image_128x128_Transparent_Tga]; - AZStd::string oldFile = oldCacheFolder + "/terrain/cry/detail/grass_with_stones_displ.dds"; - ImageConvertProcess* process = CreateImageConvertProcess(inputFile, outputFolder, "pc", m_context.get()); - - if (process != nullptr) - { - //the process can be stopped if the job is cancelled or the worker is shutting down - int step = 0; - while (!process->IsFinished() ) - { - process->UpdateProcess(); - step++; - } - - //get process result - ASSERT_TRUE(process->IsSucceed()); - - SaveImageToFile(process->GetOutputImage(), "rgb", 10); - SaveImageToFile(process->GetOutputAlphaImage(), "alpha", 10); - - process->GetAppendOutputFilePaths(outPaths); - - QString output; - //CompareDDSImage(outPaths[0].c_str(), oldFile.c_str(), output); - delete process; - } - - - -/* //test cases for different presets - //ddna - inputFile = "../AutomatedTesting/Objects/ParticleAssets/ShowRoom/showroom_pipe_blue_001_m_ddna.tif"; - ASSERT_TRUE(ConvertImageFile(inputFile, outputFolder, outPaths, m_context.get())); - //cubemap - inputFile = "../AutomatedTesting/Levels/Samples/Camera_Sample/Cubemaps/noon_cm.tif"; - ASSERT_TRUE(ConvertImageFile(inputFile, outputFolder, outPaths, m_context.get())); - //albedo - inputFile = "../AutomatedTesting/Objects/ParticleAssets/ShowRoom/showroom_steel_brushed_001_diff.tif"; - ASSERT_TRUE(ConvertImageFile(inputFile, outputFolder, outPaths, m_context.get())); - inputFile = "../AutomatedTesting/materials/pbs_reference/light_leather_diff.tif"; - ASSERT_TRUE(ConvertImageFile(inputFile, outputFolder, outPaths, m_context.get())); - inputFile = "../Gems/PBSreferenceMaterials/Assets/materials/pbs_reference/brushed_steel.tif"; - ASSERT_TRUE(ConvertImageFile(inputFile, outputFolder, outPaths, m_context.get())); - //ui ReferenceImage auto preset - inputFile = "../Bems/UiBasics/Assets/UI/Textures/Prefab/textinput_normal.tif"; - ASSERT_TRUE(ConvertImageFile(inputFile, outputFolder, outPaths, m_context.get())); - //albedo with generic alpha auto preset - inputFile = "../AutomatedTesting/textures/GettingStartedTextures/LY_Logo_Beaver.tif"; - ASSERT_TRUE(ConvertImageFile(inputFile, outputFolder, outPaths, m_context.get())); - //color chart - inputFile = "../Gems/PBSreferenceMaterials/Assets/materials/pbs_reference/colorcharts/debug_contrast_low_cch.tif"; - ASSERT_TRUE(ConvertImageFile(inputFile, outputFolder, outPaths, m_context.get())); -*/ -} - - -//test image loading function for output dds files -TEST_F(ImageProcessingTest, DISABLED_TestLoadDdsImage) -{ - IImageObjectPtr originImage, alphaImage; - AZStd::string inputFolder = m_engineRoot + "/Cache/AutomatedTesting/pc/automatedtesting/engineassets/texturemsg/"; - AZStd::string inputFile; - - inputFile = "E:/Javelin_NWLYDev/dev/Cache/Assets/pc/assets/textures/blend_maps/moss/jav_moss_ddn.dds"; - - IImageObjectPtr newImage = IImageObjectPtr(LoadImageFromDdsFile(inputFile)); - if (newImage->HasImageFlags(EIF_AttachedAlpha)) - { - if (newImage->HasImageFlags(EIF_Splitted)) - { - alphaImage = IImageObjectPtr(LoadImageFromDdsFile(inputFile+".a")); - - } - else - { - alphaImage = IImageObjectPtr(LoadAttachedImageFromDdsFile(inputFile, newImage)); - } - } - - SaveImageToFile(newImage, "jav_moss_ddn", 10); -} - -TEST_F(ImageProcessingTest, DISABLED_CompareOutputImage) -{ - AZStd::string curretTextureFolder = m_engineRoot + "/TestAssets/TextureAssets/assets_new/textures"; - AZStd::string oldTextureFolder = m_engineRoot + "/TestAssets/TextureAssets/assets_old/textures"; - bool outputOnlyDifferent = false; - QDirIterator it(curretTextureFolder.c_str(), QStringList() << "*.dds", QDir::Files, QDirIterator::Subdirectories); - QFile f("../texture_comparison_output.csv"); - f.open(QIODevice::ReadWrite | QIODevice::Truncate); - // Write a header for csv file - f.write("Texture Name, Path, Mip new/old, MipDiff, Format new/old, Flag new/old, MemSize new/old, MemDiff, Error, AlphaMip new/old, AlphaMipDiff, AlphaFormat new/old, AlphaFlag new/old, AlphaMemSize new/old, AlphaMemDiff, AlphaError\r\n"); - int i = 0; - while (it.hasNext()) - { - i++; - it.next(); - - QString fileName = it.fileName(); - QString newFilePath = it.filePath(); - QString sharedPath = QString(newFilePath).remove(curretTextureFolder.c_str()); - QString oldFilePath = QString(oldTextureFolder.c_str()) + sharedPath; - QString output; - if (QFile::exists(oldFilePath)) - { - bool isDifferent = CompareDDSImage(newFilePath, oldFilePath, output); - if (outputOnlyDifferent && !isDifferent) - { - continue; - } - else - { - f.write(fileName.toUtf8().constData()); - f.write(","); - f.write(sharedPath.toUtf8().constData()); - f.write(output.toUtf8().constData()); - } - } - else - { - f.write(fileName.toUtf8().constData()); - f.write(","); - f.write(sharedPath.toUtf8().constData()); - output += ",No old file for comparison!"; - f.write(output.toUtf8().constData()); - } - f.write("\r\n"); - } - f.close(); -} - - -TEST_F(ImageProcessingTest, EditorTextureSettingTest) -{ - AZStd::string buiderSetting = m_engineRoot + "/Gems/ImageProcessing/Code/Source/ImageBuilderDefaultPresets.settings"; - auto outcome = BuilderSettingManager::Instance()->LoadBuilderSettings(buiderSetting, m_context.get()); - - auto TestFunc = [](const AZStd::string& textureFilepath, bool isCubemap) { - - ImageProcessingEditor::EditorTextureSetting setting(textureFilepath); - const TextureSettings& textSettings = setting.m_settingsMap["pc"]; - auto& presetId = textSettings.m_preset; - const PresetSettings* preset = BuilderSettingManager::Instance()->GetPreset(presetId); - AZ::u32 arrayCount = 1; - AZ::u32 originalWidth = setting.m_img->GetWidth(0); - AZ::u32 originalHeight = setting.m_img->GetHeight(0); - - if (isCubemap) - { - ASSERT_TRUE(preset->m_cubemapSetting != nullptr); - CubemapLayout *srcCubemap = CubemapLayout::CreateCubemapLayout(setting.m_img); - ASSERT_TRUE(srcCubemap != nullptr); - - originalWidth = srcCubemap->GetFaceSize(); - originalHeight = srcCubemap->GetFaceSize(); - arrayCount = 6; - - delete srcCubemap; - } - - // Test GetFinalInfoForTextureOnPlatform function - { - for (AZ::u32 reduce = 0; reduce < 15; reduce++) - { - ImageProcessingEditor::ResolutionInfo info; - if (setting.GetFinalInfoForTextureOnPlatform("pc", reduce, info)) - { - ASSERT_TRUE(info.reduce <= reduce); - ASSERT_TRUE(info.arrayCount == arrayCount); - ASSERT_TRUE(info.width == AZStd::max(originalWidth >> info.reduce, 1)); - ASSERT_TRUE(info.height == AZStd::max(originalHeight >> info.reduce, 1)); - if (preset->m_maxTextureSize > 0) - { - ASSERT_TRUE(info.width <= preset->m_maxTextureSize); - ASSERT_TRUE(info.height <= preset->m_maxTextureSize); - } - if (preset->m_minTextureSize > 0) - { - ASSERT_TRUE(info.width >= preset->m_minTextureSize); - ASSERT_TRUE(info.height >= preset->m_minTextureSize); - } - } - } - } - - // Test GetResolutionInfo function - { - AZ::u32 minReduce, maxReduce; - auto resolutions = setting.GetResolutionInfo("pc", minReduce, maxReduce); - ASSERT_TRUE(resolutions.size() > 0); - ASSERT_TRUE(resolutions.size() == maxReduce - minReduce + 1); - for (auto& info : resolutions) - { - ASSERT_TRUE(info.reduce >= minReduce); - ASSERT_TRUE(info.reduce <= maxReduce); - ASSERT_TRUE(info.arrayCount == arrayCount); - ASSERT_TRUE(info.width == AZStd::max(originalWidth >> info.reduce, 1)); - ASSERT_TRUE(info.height == AZStd::max(originalHeight >> info.reduce, 1)); - ASSERT_TRUE(info.width >= 1); - ASSERT_TRUE(info.height >= 1); - } - } - - // Test GetResolutionInfo function - { - auto resolutions = setting.GetResolutionInfoForMipmap("pc"); - for (auto& info : resolutions) - { - ASSERT_TRUE(info.arrayCount == arrayCount); - ASSERT_TRUE(info.width == AZStd::max(originalWidth >> info.reduce, 1)); - ASSERT_TRUE(info.height == AZStd::max(originalHeight >> info.reduce, 1)); - ASSERT_TRUE(info.width >= 1); - ASSERT_TRUE(info.height >= 1); - } - setting.m_settingsMap["pc"].m_sizeReduceLevel += 1; - auto reducedResolutions = setting.GetResolutionInfoForMipmap("pc"); - ASSERT_TRUE(resolutions.size() >= reducedResolutions.size()); - } - }; - - // For cubemap texture - AZStd::string textureFilePath = m_engineRoot + "/Gems/ImageProcessing/Code/Tests/TestAssets/noon_cm.tif"; - TestFunc(textureFilePath, true); - - // For albedo texture - textureFilePath = m_engineRoot + "/Gems/ImageProcessing/Code/Tests/TestAssets/1024x1024_24bit.tif"; - TestFunc(textureFilePath, false); -} - -class ImageProcessingSerializationTest - : public ScopedAllocatorSetupFixture -{ -protected: - AZStd::unique_ptr m_context; - AZStd::string m_engineRoot; - - void SetUp() override - { - BuilderSettingManager::CreateInstance(); - - m_context = AZStd::make_unique(); - BuilderPluginComponent::Reflect(m_context.get()); - AZ::DataPatch::Reflect(m_context.get()); - - // Startup default local FileIO (hits OSAllocator) if not already setup. - if (AZ::IO::FileIOBase::GetInstance() == nullptr) - { - AZ::IO::FileIOBase::SetInstance(aznew AZ::IO::LocalFileIO()); - } - { - int argc = 0; - char** argv = nullptr; - QCoreApplication app(argc, argv); - m_engineRoot = AZ::Test::GetEngineRootPath(); - } - } - - void TearDown() override - { - delete AZ::IO::FileIOBase::GetInstance(); - AZ::IO::FileIOBase::SetInstance(nullptr); - - m_context.reset(); - BuilderSettingManager::DestroyInstance(); - CPixelFormats::DestroyInstance(); - } -}; - -TEST_F(ImageProcessingSerializationTest, DISABLED_LoadBuilderSettingsFromRC_SerializingLegacyDataIn_InvalidFiles) -{ - AZStd::string filepath = m_engineRoot + "/Gems/ImageProcessing/Code/Tests/TestAssets/rc.ini_Missing"; - ASSERT_FALSE(BuilderSettingManager::Instance()->LoadBuilderSettingsFromRC(filepath).IsSuccess()); - - filepath = m_engineRoot + "/Code/Tools/RC/Config/rc/rc.ini"; - auto outcome = BuilderSettingManager::Instance()->LoadBuilderSettingsFromRC(filepath); - ASSERT_TRUE(outcome.IsSuccess()); - - AZ::IO::HandleType fileHandle = AZ::IO::InvalidHandle; - - // Load legacy texture settings from file that not exists - TextureSettings legacyTextureSetting; - AZStd::string notExistingFile = m_engineRoot + "/Gems/ImageProcessing/Code/Tests/TestAssets/NotExistingFile"; - auto legacyLoadOutcome = TextureSettings::LoadLegacyTextureSettingFromFile("", notExistingFile, legacyTextureSetting, m_context.get()); - EXPECT_FALSE(legacyLoadOutcome.IsSuccess()); - - // Load legacy texture settings from file whose format is wrong - - // Wrong override data - AZStd::string wrongFormatFile = m_engineRoot + "/Gems/ImageProcessing/Code/Tests/TestAssets/invalid.exportsettings"; - AZStd::string wrongFormatContent = "/autooptimizefile=0 /preset=Diffuse_highQ /reduce=\"es3:0,randomdata,ios:3,osx_gl:0,pc:4\" /ser=0"; - if (AZ::IO::FileIOBase::GetInstance()->Open(wrongFormatFile.c_str(), AZ::IO::OpenMode::ModeWrite, fileHandle)) - { - AZ::IO::FileIOBase::GetInstance()->Write(fileHandle, wrongFormatContent.c_str(), wrongFormatContent.size()); - AZ::IO::FileIOBase::GetInstance()->Close(fileHandle); - } - else - { - EXPECT_TRUE(false); - } - legacyLoadOutcome = TextureSettings::LoadLegacyTextureSettingFromFile("", wrongFormatFile, legacyTextureSetting, m_context.get()); - EXPECT_FALSE(legacyLoadOutcome.IsSuccess()); - - // Wrong format data - wrongFormatContent = "//// ,&*&#$@#/preset=Diffuse_highQ / //reduce=0 /ser=0"; - if (AZ::IO::FileIOBase::GetInstance()->Open(wrongFormatFile.c_str(), AZ::IO::OpenMode::ModeWrite, fileHandle)) - { - AZ::IO::FileIOBase::GetInstance()->Write(fileHandle, wrongFormatContent.c_str(), wrongFormatContent.size()); - AZ::IO::FileIOBase::GetInstance()->Close(fileHandle); - } - legacyLoadOutcome = TextureSettings::LoadLegacyTextureSettingFromFile("", wrongFormatFile, legacyTextureSetting, m_context.get()); - EXPECT_FALSE(legacyLoadOutcome.IsSuccess()); - - AZ::IO::FileIOBase::GetInstance()->Remove(wrongFormatFile.c_str()); -} - - -TEST_F(ImageProcessingSerializationTest, TextureSettingReflect_SerializingLegacyDataIn_EmbeddedSetting) -{ - AZStd::string buiderSetting(m_engineRoot + "/Gems/ImageProcessing/Code/Source/ImageBuilderDefaultPresets.settings"); - auto outcome = BuilderSettingManager::Instance()->LoadBuilderSettings(buiderSetting, m_context.get()); - - // Load legacy texture settings - TextureSettings legacyTextureSetting; - AZStd::string textureFilepath = m_engineRoot + "/Gems/ImageProcessing/Code/Tests/TestAssets/Lenstexture_dirtyglass.tif"; - AZStd::string textureSetting = LoadEmbeddedSettingFromFile(textureFilepath); - EXPECT_FALSE(textureSetting.empty()); - - auto legacyLoadOutcome = TextureSettings::LoadLegacyTextureSetting(textureFilepath, textureSetting, legacyTextureSetting, m_context.get()); - // Ensure we loaded and parsed the texture settings correctly. - EXPECT_TRUE(legacyLoadOutcome.IsSuccess()); - EXPECT_EQ(legacyTextureSetting.m_preset, BuilderSettingManager::Instance()->GetPresetIdFromName("LensOptics")); -} - -TEST_F(ImageProcessingSerializationTest, TextureSettingReflect_SerializingLegacyDataIn_CommonAndPlatformSpecificSettingsAreSerializedCorrectly) -{ - AZStd::string buiderSetting(m_engineRoot + "/Gems/ImageProcessing/Code/Source/ImageBuilderDefaultPresets.settings"); - auto outcome = BuilderSettingManager::Instance()->LoadBuilderSettings(buiderSetting, m_context.get()); - - // Load legacy texture settings - TextureSettings legacyTextureSetting; - AZStd::string textureFilepath = m_engineRoot + "/Gems/ImageProcessing/Code/Tests/TestAssets/1024x1024_24bit.tif"; - auto legacyLoadOutcome = TextureSettings::LoadLegacyTextureSettingFromFile(textureFilepath, - textureFilepath + TextureSettings::legacyExtensionName, legacyTextureSetting, m_context.get()); - - // Ensure we loaded and parsed the texture settings correctly. - EXPECT_TRUE(legacyLoadOutcome.IsSuccess()); - EXPECT_EQ(legacyTextureSetting.m_mipGenType, MipGenType::kaiserSinc); - EXPECT_EQ(legacyTextureSetting.m_preset, BuilderSettingManager::Instance()->GetPresetIdFromName("Albedo")); - EXPECT_EQ(legacyTextureSetting.m_mipAlphaAdjust[0], 62); - EXPECT_EQ(legacyTextureSetting.m_suppressEngineReduce, false); - - // Ensure overrides are properly parsed as well. - { - TextureSettings iosTextureSettings; - auto iosOutcome = TextureSettings::GetPlatformSpecificTextureSetting("ios", legacyTextureSetting, iosTextureSettings, m_context.get()); - EXPECT_TRUE(iosOutcome.IsSuccess()); - EXPECT_EQ(iosTextureSettings.m_sizeReduceLevel, 3); - } -} - -TEST_F(ImageProcessingSerializationTest, TextureSettingReflect_SerializingModernDataOutThenIn_PreSerializedAndPostSerializedDataIsEquivalent) -{ - AZStd::string buiderSetting(m_engineRoot + "/Gems/ImageProcessing/Code/Source/ImageBuilderDefaultPresets.settings"); - auto outcome = BuilderSettingManager::Instance()->LoadBuilderSettings(buiderSetting, m_context.get()); - - // Load legacy texture settings - TextureSettings legacyTextureSetting; - AZStd::string textureFilepath = m_engineRoot + "/Gems/ImageProcessing/Code/Tests/TestAssets/1024x1024_24bit.tif"; - auto legacyLoadOutcome = TextureSettings::LoadLegacyTextureSettingFromFile(textureFilepath, - textureFilepath+TextureSettings::legacyExtensionName, legacyTextureSetting, m_context.get()); - - // Let's make modifications to the loaded texture setting - // Modification1: Set reduce level for common settings. - // Modification2: Set reduce level for iOS-override settings. - legacyTextureSetting.m_sizeReduceLevel = 1337; - TextureSettings iosOverride = legacyTextureSetting; - iosOverride.m_sizeReduceLevel = 0xDAD; - legacyTextureSetting.ApplySettings(iosOverride, "ios", m_context.get()); - - // Write the modified texture settings to file, using AZ::Serialization. - AZStd::string modernMetafilePath = textureFilepath + TextureSettings::modernExtensionName; - auto writeOutcome = TextureSettings::WriteTextureSetting(modernMetafilePath, legacyTextureSetting, m_context.get()); - EXPECT_TRUE(writeOutcome.IsSuccess()); - - // Load the modified settings back to memory, using AZ::Serialization - TextureSettings modernTextureSetting; - auto modernLoadOutcome = TextureSettings::LoadTextureSetting(modernMetafilePath, modernTextureSetting, m_context.get()); - - // Ensure what we just serialized-in is identical to what we serialized-out. - // The comparison operator also compares overrides. - EXPECT_TRUE(modernLoadOutcome.IsSuccess()); - EXPECT_TRUE(modernTextureSetting.Equals(legacyTextureSetting, m_context.get())); - - // Remove the temp file that was written out. - AZ::IO::FileIOBase::GetInstance()->Remove(modernMetafilePath.c_str()); -} - -TEST_F(ImageProcessingSerializationTest, TextureSettingReflect_SerializingModernDataInAndOut_WritesAndParsesFileAccurately) -{ - AZStd::string filepath = "test.xml"; - - // Fill-in structure with test data - TextureSettings fakeTextureSettings; - fakeTextureSettings.m_preset = AZ::Uuid::CreateRandom(); - fakeTextureSettings.m_sizeReduceLevel = 0; - fakeTextureSettings.m_suppressEngineReduce = true; - fakeTextureSettings.m_enableMipmap = false; - fakeTextureSettings.m_maintainAlphaCoverage = true; - fakeTextureSettings.m_mipAlphaAdjust = { 0xDEAD, 0xBADBEEF, 0xBADC0DE, 0xFEEFEE, 0xBADF00D, 0xC0FFEE }; - fakeTextureSettings.m_mipGenEval = MipGenEvalType::max; - fakeTextureSettings.m_mipGenType = MipGenType::quadratic; - - // Write test data to file - auto writeOutcome = TextureSettings::WriteTextureSetting(filepath, fakeTextureSettings, m_context.get()); - EXPECT_TRUE(writeOutcome.IsSuccess()); - - // Parse test data to file - TextureSettings parsedFakeTextureSettings; - auto readOutcome = TextureSettings::LoadTextureSetting(filepath, parsedFakeTextureSettings, m_context.get()); - EXPECT_TRUE(readOutcome.IsSuccess()); - EXPECT_TRUE(parsedFakeTextureSettings.Equals(fakeTextureSettings, m_context.get())); - - // Delete temp data - AZ::IO::FileIOBase::GetInstance()->Remove(filepath.c_str()); -} - -TEST_F(ImageProcessingSerializationTest, DISABLED_BuilderSettingsReflect_SerializingDataInAndOut_WritesAndParsesFileAccurately) -{ - AZStd::string buildSettingsFilepath = m_engineRoot + "/Gems/ImageProcessing/Code/Tests/TestAssets/tempPresets.settings"; - AZStd::string rcFilePath = m_engineRoot + "/Code/Tools/RC/Config/rc/rc.ini"; - - auto loadOutcome = BuilderSettingManager::Instance()->LoadBuilderSettingsFromRC(rcFilePath); - ASSERT_TRUE(loadOutcome.IsSuccess()); - - //Save the preset loaded from rc.ini for later comparison - AZ::Uuid oldPresetSettingsUuid = BuilderSettingManager::Instance()->GetPresetIdFromName("NormalsFromDisplacement"); - const PresetSettings oldPresetSetting = *BuilderSettingManager::Instance()->GetPreset(oldPresetSettingsUuid, "pc"); - - //Save builder settings to new file format - auto writeOutcome = BuilderSettingManager::Instance()->WriteBuilderSettings(buildSettingsFilepath, m_context.get()); - ASSERT_TRUE(writeOutcome.IsSuccess()); - - //Re-load Builder Settings - auto reloadOutcome = BuilderSettingManager::Instance()->LoadBuilderSettings(buildSettingsFilepath, m_context.get()); - ASSERT_TRUE(reloadOutcome.IsSuccess()); - - //Find the same preset - AZ::Uuid newPresetSettingsUuid = BuilderSettingManager::Instance()->GetPresetIdFromName("NormalsFromDisplacement"); - const PresetSettings newPresetSetting = *BuilderSettingManager::Instance()->GetPreset(newPresetSettingsUuid, "pc"); - - // Delete temp data - AZ::IO::FileIOBase::GetInstance()->Remove(buildSettingsFilepath.c_str()); - - //make sure the preset loaded from RC.ini is same as the preset loaded from builder setting - ASSERT_EQ(oldPresetSetting, newPresetSetting); -} - -class ProductDependencyTest - : public AllocatorsTestFixture -{ -public: - void SetUp() override - { - AllocatorsTestFixture::SetUp(); - m_data = AZStd::make_unique(); - m_data->m_request.m_sourceFileUUID = AZ::Uuid::CreateRandom(); - m_data->m_rgbBaseFilePath = AZStd::string("Foo/test.dds"); - m_data->m_alphaBaseFilePath = AZStd::string("Foo/test.dds.a"); - m_data->m_diffBaseFilePath = "Foo/test_diff.dds"; - - for (int idx = 1; idx < NumOfMips; idx++) - { - m_data->m_rgbMipsFilePath.push_back(AZStd::string::format("Foo/test.dds.%d", idx)); - m_data->m_alphaMipsFilePath.push_back(AZStd::string::format("Foo/test.dds.%da", idx)); - } - } - - void TearDown() override - { - m_data.reset(); - AllocatorsTestFixture::TearDown(); - } - - - bool ValidateResult(const AZStd::vector& productFilePaths, const AZStd::unordered_map& productDependencyMap) - { - AZStd::vector jobProducts; - m_data->m_imageBuilderWorker.PopulateProducts(m_data->m_request, productFilePaths, jobProducts); - - EXPECT_EQ(productFilePaths.size(), jobProducts.size()); - - for (const AssetBuilderSDK::JobProduct& jobProduct : jobProducts) - { - auto found = productDependencyMap.find(jobProduct.m_productFileName); - if (found != productDependencyMap.end()) - { - EXPECT_EQ(jobProduct.m_dependencies.size(), found->second); - - if (jobProduct.m_dependencies.size() != found->second) - { - return false; - } - } - } - - return true; - } -protected: - - struct StaticData - { - AssetBuilderSDK::ProcessJobRequest m_request; - AZStd::string m_rgbBaseFilePath; - AZStd::vector m_rgbMipsFilePath; - AZStd::string m_alphaBaseFilePath; - AZStd::vector m_alphaMipsFilePath; - AZStd::string m_diffBaseFilePath; - ImageProcessing::ImageBuilderWorker m_imageBuilderWorker; - }; - - AZStd::unique_ptr m_data; - static const int NumOfMips = 5; -}; - -TEST_F(ProductDependencyTest, ProductDependencyBaseRGBFile_Emit_None) -{ - AZStd::vector productFilePaths; - productFilePaths.push_back(m_data->m_rgbBaseFilePath); - - AZStd::unordered_map productDependencyMap; - - productDependencyMap[m_data->m_rgbBaseFilePath] = 0; - productDependencyMap[m_data->m_alphaBaseFilePath] = 0; - EXPECT_TRUE(ValidateResult(productFilePaths, productDependencyMap)); -} - -TEST_F(ProductDependencyTest, ProductDependencyBaseRGBFileAndMips_Emit_All) -{ - AZStd::vector productFilePaths; - productFilePaths.push_back(m_data->m_rgbBaseFilePath); - productFilePaths.insert(productFilePaths.end(), m_data->m_rgbMipsFilePath.begin(), m_data->m_rgbMipsFilePath.end()); - - AZStd::unordered_map productDependencyMap; - - productDependencyMap[m_data->m_rgbBaseFilePath] = m_data->m_rgbMipsFilePath.size(); - productDependencyMap[m_data->m_alphaBaseFilePath] = 0; - EXPECT_TRUE(ValidateResult(productFilePaths, productDependencyMap)); -} - -TEST_F(ProductDependencyTest, ProductDependencyBaseRGBFileAndBaseAlpha_Emit_ALL) -{ - AZStd::vector productFilePaths; - productFilePaths.push_back(m_data->m_rgbBaseFilePath); - productFilePaths.push_back(m_data->m_alphaBaseFilePath); - - AZStd::unordered_map productDependencyMap; - - productDependencyMap[m_data->m_rgbBaseFilePath] = 1; // one for the alphaBaseFile - productDependencyMap[m_data->m_alphaBaseFilePath] = 0; - EXPECT_TRUE(ValidateResult(productFilePaths, productDependencyMap)); -} - -TEST_F(ProductDependencyTest, ProductDependencyBaseRGBFile_Emit_ALL) -{ - AZStd::vector productFilePaths; - productFilePaths.push_back(m_data->m_rgbBaseFilePath); - productFilePaths.push_back(m_data->m_alphaBaseFilePath); - productFilePaths.insert(productFilePaths.end(), m_data->m_rgbMipsFilePath.begin(), m_data->m_rgbMipsFilePath.end()); - productFilePaths.insert(productFilePaths.end(), m_data->m_alphaMipsFilePath.begin(), m_data->m_alphaMipsFilePath.end()); - - AZStd::unordered_map productDependencyMap; - - productDependencyMap[m_data->m_rgbBaseFilePath] = m_data->m_rgbMipsFilePath.size() + 1; // adding one for the alphaBaseFile - productDependencyMap[m_data->m_alphaBaseFilePath] = m_data->m_alphaMipsFilePath.size(); - EXPECT_TRUE(ValidateResult(productFilePaths, productDependencyMap)); -} - -TEST_F(ProductDependencyTest, ProductDependency_Rgb_Diff_EmitALL) -{ - AZStd::vector productFilePaths; - productFilePaths.push_back(m_data->m_rgbBaseFilePath); - productFilePaths.push_back(m_data->m_diffBaseFilePath); - productFilePaths.insert(productFilePaths.end(), m_data->m_rgbMipsFilePath.begin(), m_data->m_rgbMipsFilePath.end()); - - AZStd::unordered_map productDependencyMap; - - productDependencyMap[m_data->m_rgbBaseFilePath] = m_data->m_rgbMipsFilePath.size() + 1; // adding one for the diffBaseFile - productDependencyMap[m_data->m_alphaBaseFilePath] = 0; - productDependencyMap[m_data->m_diffBaseFilePath] = 0; - EXPECT_TRUE(ValidateResult(productFilePaths, productDependencyMap)); -} - -TEST_F(ProductDependencyTest, ProductDependency_Diff_Alpha_EmitALL) -{ - AZStd::vector productFilePaths; - productFilePaths.push_back(m_data->m_diffBaseFilePath); - productFilePaths.push_back(m_data->m_alphaBaseFilePath); - productFilePaths.insert(productFilePaths.end(), m_data->m_rgbMipsFilePath.begin(), m_data->m_rgbMipsFilePath.end()); - productFilePaths.insert(productFilePaths.end(), m_data->m_alphaMipsFilePath.begin(), m_data->m_alphaMipsFilePath.end()); - - AZStd::unordered_map productDependencyMap; - - productDependencyMap[m_data->m_rgbBaseFilePath] = 0; - productDependencyMap[m_data->m_alphaBaseFilePath] = m_data->m_alphaMipsFilePath.size(); - productDependencyMap[m_data->m_diffBaseFilePath] = m_data->m_rgbMipsFilePath.size() + 1; // adding one for the alphaBaseFile - EXPECT_TRUE(ValidateResult(productFilePaths, productDependencyMap)); -} - -TEST_F(ProductDependencyTest, ProductDependency_Rgb_Diff_Alpha_EmitALL) -{ - AZStd::vector productFilePaths; - productFilePaths.push_back(m_data->m_rgbBaseFilePath); - productFilePaths.push_back(m_data->m_diffBaseFilePath); - productFilePaths.push_back(m_data->m_alphaBaseFilePath); - productFilePaths.insert(productFilePaths.end(), m_data->m_rgbMipsFilePath.begin(), m_data->m_rgbMipsFilePath.end()); - productFilePaths.insert(productFilePaths.end(), m_data->m_alphaMipsFilePath.begin(), m_data->m_alphaMipsFilePath.end()); - - AZStd::unordered_map productDependencyMap; - - productDependencyMap[m_data->m_rgbBaseFilePath] = m_data->m_rgbMipsFilePath.size() + 2; // adding one for the alphaBaseFile and one for diffBaseFile - productDependencyMap[m_data->m_alphaBaseFilePath] = m_data->m_alphaMipsFilePath.size(); - productDependencyMap[m_data->m_diffBaseFilePath] = 0; - EXPECT_TRUE(ValidateResult(productFilePaths, productDependencyMap)); -} - -TEST_F(ProductDependencyTest, ProductDependencyBaseRGBMissing_Error_OK) -{ - AZStd::vector productFilePaths; - productFilePaths.insert(productFilePaths.end(), m_data->m_rgbMipsFilePath.begin(), m_data->m_rgbMipsFilePath.end()); - AZStd::vector jobProducts; - AZ::Outcome result = m_data->m_imageBuilderWorker.PopulateProducts(m_data->m_request, productFilePaths, jobProducts); - - EXPECT_FALSE(result.IsSuccess()); -} - -TEST_F(ProductDependencyTest, ProductDependencyBaseAlphaMissing_Error_OK) -{ - AZStd::vector productFilePaths; - productFilePaths.insert(productFilePaths.end(), m_data->m_alphaMipsFilePath.begin(), m_data->m_alphaMipsFilePath.end()); - AZStd::vector jobProducts; - AZ::Outcome result = m_data->m_imageBuilderWorker.PopulateProducts(m_data->m_request, productFilePaths, jobProducts); - - EXPECT_FALSE(result.IsSuccess()); -} - -} - -AZ_UNIT_TEST_HOOK(DEFAULT_UNIT_TEST_ENV); diff --git a/Gems/ImageProcessing/Code/Tests/TestAssets/1024x1024_24bit.tif b/Gems/ImageProcessing/Code/Tests/TestAssets/1024x1024_24bit.tif deleted file mode 100644 index 0a03a3f231..0000000000 --- a/Gems/ImageProcessing/Code/Tests/TestAssets/1024x1024_24bit.tif +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:db3450a2e68b0ac5d88e82ed01c897ed4ea60a502bf1f44760c6f63ce4970816 -size 3157396 diff --git a/Gems/ImageProcessing/Code/Tests/TestAssets/1024x1024_24bit.tif.exportsettings b/Gems/ImageProcessing/Code/Tests/TestAssets/1024x1024_24bit.tif.exportsettings deleted file mode 100644 index 0417122033..0000000000 --- a/Gems/ImageProcessing/Code/Tests/TestAssets/1024x1024_24bit.tif.exportsettings +++ /dev/null @@ -1 +0,0 @@ -/autooptimizefile=0 /bumptype=none /M=62,18,32,83,50,50 /preset=Diffuse_highQ /mipgentype=kaiser /reduce="es3:0,ios:3,osx_gl:0,pc:4,provo:1" /ser=0 diff --git a/Gems/ImageProcessing/Code/Tests/TestAssets/128x128_RGBA8.tga b/Gems/ImageProcessing/Code/Tests/TestAssets/128x128_RGBA8.tga deleted file mode 100644 index b94d39d838..0000000000 --- a/Gems/ImageProcessing/Code/Tests/TestAssets/128x128_RGBA8.tga +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:116cd9a554235a0a2bf1b2ebbc7fdc38f50aafad7910cad01a7373bbfda3f562 -size 65580 diff --git a/Gems/ImageProcessing/Code/Tests/TestAssets/200x200_24bit.jpg b/Gems/ImageProcessing/Code/Tests/TestAssets/200x200_24bit.jpg deleted file mode 100644 index d682456d63..0000000000 --- a/Gems/ImageProcessing/Code/Tests/TestAssets/200x200_24bit.jpg +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:588e3bca4304823fdf795fd96a640d3b1e31cc8e82dc1cb1835071aa96f2eb22 -size 34658 diff --git a/Gems/ImageProcessing/Code/Tests/TestAssets/20x16_32bit.png b/Gems/ImageProcessing/Code/Tests/TestAssets/20x16_32bit.png deleted file mode 100644 index a7f48148f1..0000000000 --- a/Gems/ImageProcessing/Code/Tests/TestAssets/20x16_32bit.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:bd5106eebb6cf264fdac5f3568977fc8f944df4a4d4de6b0e9f35b3a001a3001 -size 206 diff --git a/Gems/ImageProcessing/Code/Tests/TestAssets/237x177_RGB.jpg b/Gems/ImageProcessing/Code/Tests/TestAssets/237x177_RGB.jpg deleted file mode 100644 index 637ce7a86a..0000000000 --- a/Gems/ImageProcessing/Code/Tests/TestAssets/237x177_RGB.jpg +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:af31ad61e58d030ef5406685fbccf67f83054fd81cf840aa308e513940f68645 -size 22767 diff --git a/Gems/ImageProcessing/Code/Tests/TestAssets/32x32_16bit_f.tif b/Gems/ImageProcessing/Code/Tests/TestAssets/32x32_16bit_f.tif deleted file mode 100644 index cfe2389ab5..0000000000 --- a/Gems/ImageProcessing/Code/Tests/TestAssets/32x32_16bit_f.tif +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:dfa0e2bbe4691b2fc98e8456298fc05d771cf2b30c61bba992b340abd2bacd91 -size 23944 diff --git a/Gems/ImageProcessing/Code/Tests/TestAssets/32x32_32bit_f.tif b/Gems/ImageProcessing/Code/Tests/TestAssets/32x32_32bit_f.tif deleted file mode 100644 index 7fb71acf75..0000000000 --- a/Gems/ImageProcessing/Code/Tests/TestAssets/32x32_32bit_f.tif +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:fee58c41e2306ad03870b517963f353f9be30378fbbe61e596007f4c3ac4b2cd -size 30088 diff --git a/Gems/ImageProcessing/Code/Tests/TestAssets/512x288_24bit.tga b/Gems/ImageProcessing/Code/Tests/TestAssets/512x288_24bit.tga deleted file mode 100644 index 7f2daece10..0000000000 --- a/Gems/ImageProcessing/Code/Tests/TestAssets/512x288_24bit.tga +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:2f0098e9308e50755484b9bc7205422a54106c593d5d36073bbdbd822c9d459d -size 366890 diff --git a/Gems/ImageProcessing/Code/Tests/TestAssets/512x512_RGB_N.tga b/Gems/ImageProcessing/Code/Tests/TestAssets/512x512_RGB_N.tga deleted file mode 100644 index d47f00912a..0000000000 --- a/Gems/ImageProcessing/Code/Tests/TestAssets/512x512_RGB_N.tga +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:646a9a9035cc3f4dfd57babc0055710d2f5bb8aee0a792f2b65d69b4fd6a94b3 -size 786450 diff --git a/Gems/ImageProcessing/Code/Tests/TestAssets/BlackWhite.png b/Gems/ImageProcessing/Code/Tests/TestAssets/BlackWhite.png deleted file mode 100644 index dfe856790a..0000000000 --- a/Gems/ImageProcessing/Code/Tests/TestAssets/BlackWhite.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:969c6597a6346c5ff8ae24b4ae143bacbeed2944dd139ddef9b440483dbe4c02 -size 8866921 diff --git a/Gems/ImageProcessing/Code/Tests/TestAssets/Lenstexture_dirtyglass.tif b/Gems/ImageProcessing/Code/Tests/TestAssets/Lenstexture_dirtyglass.tif deleted file mode 100644 index 090991ec7a..0000000000 --- a/Gems/ImageProcessing/Code/Tests/TestAssets/Lenstexture_dirtyglass.tif +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:265ae231486dc6d5d61aa2416b0010ea743722f7238660faeed9edacd46e8a6b -size 6303186 diff --git a/Gems/ImageProcessing/Code/Tests/TestAssets/TerrainHeightmap.bt b/Gems/ImageProcessing/Code/Tests/TestAssets/TerrainHeightmap.bt deleted file mode 100644 index d79577ea18..0000000000 Binary files a/Gems/ImageProcessing/Code/Tests/TestAssets/TerrainHeightmap.bt and /dev/null differ diff --git a/Gems/ImageProcessing/Code/Tests/TestAssets/TextureAtlasTest.texatlas b/Gems/ImageProcessing/Code/Tests/TestAssets/TextureAtlasTest.texatlas deleted file mode 100644 index 5cd9287208..0000000000 --- a/Gems/ImageProcessing/Code/Tests/TestAssets/TextureAtlasTest.texatlas +++ /dev/null @@ -1,50 +0,0 @@ -TextureAtlasTest/button.tif -TextureAtlasTest/buttonPressed.tif -TextureAtlasTest/buttonSlider.tif -TextureAtlasTest/checkbox_spritesheet.tif -TextureAtlasTest/checkered3.tif -TextureAtlasTest/Circle_Shadow.tif -TextureAtlasTest/CircleFrame.tif -TextureAtlasTest/CircleGradient.png -TextureAtlasTest/CircleMask.tif -TextureAtlasTest/empty_icon.tif -TextureAtlasTest/fixed_image.tif -TextureAtlasTest/flipbook_walking.tif -TextureAtlasTest/mask.tif -TextureAtlasTest/outline.tif -TextureAtlasTest/outlineRounded.tif -TextureAtlasTest/panelBkgd.tif -TextureAtlasTest/ParticleGlow.tif -TextureAtlasTest/pattern02.tif -TextureAtlasTest/pattern02_big.tif -TextureAtlasTest/pattern02vertical.tif -TextureAtlasTest/pattern02vertical_big.tif -TextureAtlasTest/pattern03.tif -TextureAtlasTest/pattern03_big.tif -TextureAtlasTest/scroll_box_icon_1.tif -TextureAtlasTest/scroll_box_icon_2.tif -TextureAtlasTest/scroll_box_icon_3.tif -TextureAtlasTest/scroll_box_icon_4.tif -TextureAtlasTest/scroll_box_icon_5.tif -TextureAtlasTest/scroll_box_icon_6.tif -TextureAtlasTest/scroll_box_icon_7.tif -TextureAtlasTest/scroll_box_icon_8.tif -TextureAtlasTest/scroll_box_icon_9.tif -TextureAtlasTest/scroll_box_icon_10.tif -TextureAtlasTest/scroll_box_map.tif -TextureAtlasTest/selected.tif -TextureAtlasTest/shadowInside2.tif -TextureAtlasTest/shadowInsideSquare.tif -TextureAtlasTest/imagesequence/flipbook_walking_00.png -TextureAtlasTest/imagesequence/flipbook_walking_01.png -TextureAtlasTest/imagesequence/flipbook_walking_02.png -TextureAtlasTest/imagesequence/flipbook_walking_03.png -TextureAtlasTest/imagesequence/flipbook_walking_04.png -TextureAtlasTest/imagesequence/flipbook_walking_05.png -TextureAtlasTest/imagesequence/flipbook_walking_06.png -TextureAtlasTest/imagesequence/flipbook_walking_07.png -TextureAtlasTest/imagesequence/flipbook_walking_08.png -TextureAtlasTest/imagesequence/flipbook_walking_09.png -TextureAtlasTest/imagesequence/flipbook_walking_10.png -TextureAtlasTest/imagesequence/flipbook_walking_11.png - diff --git a/Gems/ImageProcessing/Code/Tests/TestAssets/TextureAtlasTest/CircleFrame.tif b/Gems/ImageProcessing/Code/Tests/TestAssets/TextureAtlasTest/CircleFrame.tif deleted file mode 100644 index 392119bd62..0000000000 --- a/Gems/ImageProcessing/Code/Tests/TestAssets/TextureAtlasTest/CircleFrame.tif +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:839defde93893bced650c3aae365da2492ed5d3a36833f0d23b842a64459a73a -size 1069744 diff --git a/Gems/ImageProcessing/Code/Tests/TestAssets/TextureAtlasTest/CircleGradient.png b/Gems/ImageProcessing/Code/Tests/TestAssets/TextureAtlasTest/CircleGradient.png deleted file mode 100644 index ab4a88134e..0000000000 --- a/Gems/ImageProcessing/Code/Tests/TestAssets/TextureAtlasTest/CircleGradient.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:9a1ada36ae4b3ef01744ab9041f6b822470c2c7595934a05d9eae8dbf4312e90 -size 38112 diff --git a/Gems/ImageProcessing/Code/Tests/TestAssets/TextureAtlasTest/CircleMask.tif b/Gems/ImageProcessing/Code/Tests/TestAssets/TextureAtlasTest/CircleMask.tif deleted file mode 100644 index fd29516609..0000000000 --- a/Gems/ImageProcessing/Code/Tests/TestAssets/TextureAtlasTest/CircleMask.tif +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:8474b897fe02f70ed8d0e5c47cae8c816c832a7a5739b8c32317737fd275774f -size 1069752 diff --git a/Gems/ImageProcessing/Code/Tests/TestAssets/TextureAtlasTest/Circle_Shadow.tif b/Gems/ImageProcessing/Code/Tests/TestAssets/TextureAtlasTest/Circle_Shadow.tif deleted file mode 100644 index a9e9885ee0..0000000000 --- a/Gems/ImageProcessing/Code/Tests/TestAssets/TextureAtlasTest/Circle_Shadow.tif +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:65145dca27e8ddf865019947659956bae3cec4ff069bc0ff6dc4d87379fbd6fe -size 1070868 diff --git a/Gems/ImageProcessing/Code/Tests/TestAssets/TextureAtlasTest/ParticleGlow.tif b/Gems/ImageProcessing/Code/Tests/TestAssets/TextureAtlasTest/ParticleGlow.tif deleted file mode 100644 index 50fd39d881..0000000000 --- a/Gems/ImageProcessing/Code/Tests/TestAssets/TextureAtlasTest/ParticleGlow.tif +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:4633d813a6111cfe518853737897925b60616ad73f99fc47a4342c5fd2d5134b -size 267526 diff --git a/Gems/ImageProcessing/Code/Tests/TestAssets/TextureAtlasTest/button.tif b/Gems/ImageProcessing/Code/Tests/TestAssets/TextureAtlasTest/button.tif deleted file mode 100644 index d43f5383ec..0000000000 --- a/Gems/ImageProcessing/Code/Tests/TestAssets/TextureAtlasTest/button.tif +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:4c5e07103351b9c8a05056c00abc44370c39cfb9480f5e99d1612ae9ad45cfc5 -size 37780 diff --git a/Gems/ImageProcessing/Code/Tests/TestAssets/TextureAtlasTest/buttonPressed.tif b/Gems/ImageProcessing/Code/Tests/TestAssets/TextureAtlasTest/buttonPressed.tif deleted file mode 100644 index eec732a736..0000000000 --- a/Gems/ImageProcessing/Code/Tests/TestAssets/TextureAtlasTest/buttonPressed.tif +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:c10511cc5898f3edd24c24099d3dc569ebe9f014af01a523b708d74523209189 -size 37804 diff --git a/Gems/ImageProcessing/Code/Tests/TestAssets/TextureAtlasTest/buttonSlider.tif b/Gems/ImageProcessing/Code/Tests/TestAssets/TextureAtlasTest/buttonSlider.tif deleted file mode 100644 index 59fdd32998..0000000000 --- a/Gems/ImageProcessing/Code/Tests/TestAssets/TextureAtlasTest/buttonSlider.tif +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:75a0174a65eb945fdb579816968c42de002ec6210f75add6d4c2829bd1cb8c5a -size 37980 diff --git a/Gems/ImageProcessing/Code/Tests/TestAssets/TextureAtlasTest/checkbox_spritesheet.tif b/Gems/ImageProcessing/Code/Tests/TestAssets/TextureAtlasTest/checkbox_spritesheet.tif deleted file mode 100644 index 6e2b74b486..0000000000 --- a/Gems/ImageProcessing/Code/Tests/TestAssets/TextureAtlasTest/checkbox_spritesheet.tif +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:40a03c12c1a0123a1fcfaa3f44d343d4318917a9b5851748c74accaa33efda56 -size 17765 diff --git a/Gems/ImageProcessing/Code/Tests/TestAssets/TextureAtlasTest/checkered3.tif b/Gems/ImageProcessing/Code/Tests/TestAssets/TextureAtlasTest/checkered3.tif deleted file mode 100644 index c1530d4b81..0000000000 --- a/Gems/ImageProcessing/Code/Tests/TestAssets/TextureAtlasTest/checkered3.tif +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:6546cc22a1030d2207cd98f8b9afa18abccd24e8b603770c8af6f2c08a769ff0 -size 22360 diff --git a/Gems/ImageProcessing/Code/Tests/TestAssets/TextureAtlasTest/empty_icon.tif b/Gems/ImageProcessing/Code/Tests/TestAssets/TextureAtlasTest/empty_icon.tif deleted file mode 100644 index 34a317e80e..0000000000 --- a/Gems/ImageProcessing/Code/Tests/TestAssets/TextureAtlasTest/empty_icon.tif +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:23a048ecd54699e9f243f33e9d73b8d8611100357da3f7bcb56a5e1fed08b463 -size 362 diff --git a/Gems/ImageProcessing/Code/Tests/TestAssets/TextureAtlasTest/fixed_image.tif b/Gems/ImageProcessing/Code/Tests/TestAssets/TextureAtlasTest/fixed_image.tif deleted file mode 100644 index e1c6d3ad0e..0000000000 --- a/Gems/ImageProcessing/Code/Tests/TestAssets/TextureAtlasTest/fixed_image.tif +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:cced003316fae3dec3244be8967b7e28a9168d6184362bd0eb65828ac8a0b53b -size 25642 diff --git a/Gems/ImageProcessing/Code/Tests/TestAssets/TextureAtlasTest/flipbook_walking.tif b/Gems/ImageProcessing/Code/Tests/TestAssets/TextureAtlasTest/flipbook_walking.tif deleted file mode 100644 index 9a0f604003..0000000000 --- a/Gems/ImageProcessing/Code/Tests/TestAssets/TextureAtlasTest/flipbook_walking.tif +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:91e7ffe470fddde4459e54eb889b2074dc26e8a1c705238c70672b5b3563098a -size 2303404 diff --git a/Gems/ImageProcessing/Code/Tests/TestAssets/TextureAtlasTest/imagesequence/flipbook_walking_00.png b/Gems/ImageProcessing/Code/Tests/TestAssets/TextureAtlasTest/imagesequence/flipbook_walking_00.png deleted file mode 100644 index 770d3c724f..0000000000 --- a/Gems/ImageProcessing/Code/Tests/TestAssets/TextureAtlasTest/imagesequence/flipbook_walking_00.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:356ad2eaf78f24ff44f9a136fa22a17f7114052fff3061b417a48ae6b2767ab0 -size 8742 diff --git a/Gems/ImageProcessing/Code/Tests/TestAssets/TextureAtlasTest/imagesequence/flipbook_walking_01.png b/Gems/ImageProcessing/Code/Tests/TestAssets/TextureAtlasTest/imagesequence/flipbook_walking_01.png deleted file mode 100644 index f0624bcdf6..0000000000 --- a/Gems/ImageProcessing/Code/Tests/TestAssets/TextureAtlasTest/imagesequence/flipbook_walking_01.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:f5eab5cb57ba50dc1d08abb610599ae6cd8e486dfb8bef1492e01a372ad5b31f -size 7979 diff --git a/Gems/ImageProcessing/Code/Tests/TestAssets/TextureAtlasTest/imagesequence/flipbook_walking_02.png b/Gems/ImageProcessing/Code/Tests/TestAssets/TextureAtlasTest/imagesequence/flipbook_walking_02.png deleted file mode 100644 index 36e2450e1b..0000000000 --- a/Gems/ImageProcessing/Code/Tests/TestAssets/TextureAtlasTest/imagesequence/flipbook_walking_02.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:969a99c99f596f36a51893b14f2f70976809bc7a2ffb1794d0ebca0d5ad20604 -size 7575 diff --git a/Gems/ImageProcessing/Code/Tests/TestAssets/TextureAtlasTest/imagesequence/flipbook_walking_03.png b/Gems/ImageProcessing/Code/Tests/TestAssets/TextureAtlasTest/imagesequence/flipbook_walking_03.png deleted file mode 100644 index e18a46d1d6..0000000000 --- a/Gems/ImageProcessing/Code/Tests/TestAssets/TextureAtlasTest/imagesequence/flipbook_walking_03.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:73a6871305f9ee31ae35d78634cd88bb13d4da5273fce11ae5f353460d43e3c9 -size 5923 diff --git a/Gems/ImageProcessing/Code/Tests/TestAssets/TextureAtlasTest/imagesequence/flipbook_walking_04.png b/Gems/ImageProcessing/Code/Tests/TestAssets/TextureAtlasTest/imagesequence/flipbook_walking_04.png deleted file mode 100644 index e6235daabd..0000000000 --- a/Gems/ImageProcessing/Code/Tests/TestAssets/TextureAtlasTest/imagesequence/flipbook_walking_04.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:b28de207784be22c7f501e6ada59e9f9174446f43dba9929633627429e8e0ce3 -size 7076 diff --git a/Gems/ImageProcessing/Code/Tests/TestAssets/TextureAtlasTest/imagesequence/flipbook_walking_05.png b/Gems/ImageProcessing/Code/Tests/TestAssets/TextureAtlasTest/imagesequence/flipbook_walking_05.png deleted file mode 100644 index 65f5792ac9..0000000000 --- a/Gems/ImageProcessing/Code/Tests/TestAssets/TextureAtlasTest/imagesequence/flipbook_walking_05.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:4b74237f5e285dd4eab6d1936b639aa1b87f285e5473b3514f9c1713eef39813 -size 8163 diff --git a/Gems/ImageProcessing/Code/Tests/TestAssets/TextureAtlasTest/imagesequence/flipbook_walking_06.png b/Gems/ImageProcessing/Code/Tests/TestAssets/TextureAtlasTest/imagesequence/flipbook_walking_06.png deleted file mode 100644 index 61e547151f..0000000000 --- a/Gems/ImageProcessing/Code/Tests/TestAssets/TextureAtlasTest/imagesequence/flipbook_walking_06.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:ad6946b610769ba6d2ccc4269cfae24c5e4f30964fd499442108f8bf17c2e8cd -size 8846 diff --git a/Gems/ImageProcessing/Code/Tests/TestAssets/TextureAtlasTest/imagesequence/flipbook_walking_07.png b/Gems/ImageProcessing/Code/Tests/TestAssets/TextureAtlasTest/imagesequence/flipbook_walking_07.png deleted file mode 100644 index d3e1aa0ef6..0000000000 --- a/Gems/ImageProcessing/Code/Tests/TestAssets/TextureAtlasTest/imagesequence/flipbook_walking_07.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:dddff30e20fc4e2f36bedaaca14606d44c9085e8c73841f339ed0a9bc08f26bd -size 7927 diff --git a/Gems/ImageProcessing/Code/Tests/TestAssets/TextureAtlasTest/imagesequence/flipbook_walking_08.png b/Gems/ImageProcessing/Code/Tests/TestAssets/TextureAtlasTest/imagesequence/flipbook_walking_08.png deleted file mode 100644 index bdf29b4777..0000000000 --- a/Gems/ImageProcessing/Code/Tests/TestAssets/TextureAtlasTest/imagesequence/flipbook_walking_08.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:d52afab812c6fc8e9c0916c71dc2ea8d957f4326ff9a0ce71658aae06f9d07e5 -size 7459 diff --git a/Gems/ImageProcessing/Code/Tests/TestAssets/TextureAtlasTest/imagesequence/flipbook_walking_09.png b/Gems/ImageProcessing/Code/Tests/TestAssets/TextureAtlasTest/imagesequence/flipbook_walking_09.png deleted file mode 100644 index 26fd687534..0000000000 --- a/Gems/ImageProcessing/Code/Tests/TestAssets/TextureAtlasTest/imagesequence/flipbook_walking_09.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:1dad7ebe7690cc9318838dd63bfcace0fad67e14f8f1916dca2fb6ebd267a26c -size 6123 diff --git a/Gems/ImageProcessing/Code/Tests/TestAssets/TextureAtlasTest/imagesequence/flipbook_walking_10.png b/Gems/ImageProcessing/Code/Tests/TestAssets/TextureAtlasTest/imagesequence/flipbook_walking_10.png deleted file mode 100644 index dae9568f47..0000000000 --- a/Gems/ImageProcessing/Code/Tests/TestAssets/TextureAtlasTest/imagesequence/flipbook_walking_10.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:a91f9d4be1e432e7b4fa998722ecea178e38ae63ca9f521bb04e5ce2e5159e0f -size 7619 diff --git a/Gems/ImageProcessing/Code/Tests/TestAssets/TextureAtlasTest/imagesequence/flipbook_walking_11.png b/Gems/ImageProcessing/Code/Tests/TestAssets/TextureAtlasTest/imagesequence/flipbook_walking_11.png deleted file mode 100644 index 60f52297c5..0000000000 --- a/Gems/ImageProcessing/Code/Tests/TestAssets/TextureAtlasTest/imagesequence/flipbook_walking_11.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:2979e15676720eb2b81d792880360f8ea26e17322253800b4432f84541d7da7b -size 8245 diff --git a/Gems/ImageProcessing/Code/Tests/TestAssets/TextureAtlasTest/mask.tif b/Gems/ImageProcessing/Code/Tests/TestAssets/TextureAtlasTest/mask.tif deleted file mode 100644 index 5e3cd778b4..0000000000 --- a/Gems/ImageProcessing/Code/Tests/TestAssets/TextureAtlasTest/mask.tif +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:764d622d9c589f89f164f4a23d0b66270c25d34c2ecb687640c4ea3e2da55035 -size 36812 diff --git a/Gems/ImageProcessing/Code/Tests/TestAssets/TextureAtlasTest/outline.tif b/Gems/ImageProcessing/Code/Tests/TestAssets/TextureAtlasTest/outline.tif deleted file mode 100644 index 79bdc27a73..0000000000 --- a/Gems/ImageProcessing/Code/Tests/TestAssets/TextureAtlasTest/outline.tif +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:e502b7ad23409df89c713c9ce43e1df159d4a634f35fec220a7cf8b5e6c2807f -size 56428 diff --git a/Gems/ImageProcessing/Code/Tests/TestAssets/TextureAtlasTest/outlineRounded.tif b/Gems/ImageProcessing/Code/Tests/TestAssets/TextureAtlasTest/outlineRounded.tif deleted file mode 100644 index e48f6108e7..0000000000 --- a/Gems/ImageProcessing/Code/Tests/TestAssets/TextureAtlasTest/outlineRounded.tif +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:fb9616528ac43a6c46c8f3b4802cbc7cea51ccc0f86dbc5d156fe0806f34edf0 -size 66024 diff --git a/Gems/ImageProcessing/Code/Tests/TestAssets/TextureAtlasTest/panelBkgd.tif b/Gems/ImageProcessing/Code/Tests/TestAssets/TextureAtlasTest/panelBkgd.tif deleted file mode 100644 index b9ad540ce0..0000000000 --- a/Gems/ImageProcessing/Code/Tests/TestAssets/TextureAtlasTest/panelBkgd.tif +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:5abfb3bfd5eb8044ec3fde65c65d515a43179c87734b1813dc71c07050841b9f -size 27704 diff --git a/Gems/ImageProcessing/Code/Tests/TestAssets/TextureAtlasTest/pattern02.tif b/Gems/ImageProcessing/Code/Tests/TestAssets/TextureAtlasTest/pattern02.tif deleted file mode 100644 index c9895b73b3..0000000000 --- a/Gems/ImageProcessing/Code/Tests/TestAssets/TextureAtlasTest/pattern02.tif +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:739955d9e61a89f732316876e1d1ae0503a6296f946324d7d0305b71e12c9f9e -size 23776 diff --git a/Gems/ImageProcessing/Code/Tests/TestAssets/TextureAtlasTest/pattern02_big.tif b/Gems/ImageProcessing/Code/Tests/TestAssets/TextureAtlasTest/pattern02_big.tif deleted file mode 100644 index 50b056d4ef..0000000000 --- a/Gems/ImageProcessing/Code/Tests/TestAssets/TextureAtlasTest/pattern02_big.tif +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:ed7bdcd8572fda83219564e8a92cc6f3d4d15e40e8c5950bf1412f74a799edd9 -size 24824 diff --git a/Gems/ImageProcessing/Code/Tests/TestAssets/TextureAtlasTest/pattern02vertical.tif b/Gems/ImageProcessing/Code/Tests/TestAssets/TextureAtlasTest/pattern02vertical.tif deleted file mode 100644 index f8f2fd578c..0000000000 --- a/Gems/ImageProcessing/Code/Tests/TestAssets/TextureAtlasTest/pattern02vertical.tif +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:290a417825baaed85811bcc29d91fd0ba436463dadc1648f669c5042234f96c1 -size 23948 diff --git a/Gems/ImageProcessing/Code/Tests/TestAssets/TextureAtlasTest/pattern02vertical_big.tif b/Gems/ImageProcessing/Code/Tests/TestAssets/TextureAtlasTest/pattern02vertical_big.tif deleted file mode 100644 index afebca233e..0000000000 --- a/Gems/ImageProcessing/Code/Tests/TestAssets/TextureAtlasTest/pattern02vertical_big.tif +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:005b9d7623d9ea1e4a470f6fee67f1eb5f38d7a1ad4e357e0036ce81850c6d5f -size 26032 diff --git a/Gems/ImageProcessing/Code/Tests/TestAssets/TextureAtlasTest/pattern03.tif b/Gems/ImageProcessing/Code/Tests/TestAssets/TextureAtlasTest/pattern03.tif deleted file mode 100644 index 7a13c37c36..0000000000 --- a/Gems/ImageProcessing/Code/Tests/TestAssets/TextureAtlasTest/pattern03.tif +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:6730661ad80d0d9b94c2c05b9cb321e5e5646a99b267d1680cf8fa9b8d62fb42 -size 23792 diff --git a/Gems/ImageProcessing/Code/Tests/TestAssets/TextureAtlasTest/pattern03_big.tif b/Gems/ImageProcessing/Code/Tests/TestAssets/TextureAtlasTest/pattern03_big.tif deleted file mode 100644 index 0098f2ce53..0000000000 --- a/Gems/ImageProcessing/Code/Tests/TestAssets/TextureAtlasTest/pattern03_big.tif +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:2ba16a432f64432c6de9b52703faa1dc413c880e284c8719b3e56c737af6d4a0 -size 26720 diff --git a/Gems/ImageProcessing/Code/Tests/TestAssets/TextureAtlasTest/scroll_box_icon_1.tif b/Gems/ImageProcessing/Code/Tests/TestAssets/TextureAtlasTest/scroll_box_icon_1.tif deleted file mode 100644 index a21d2aaaa3..0000000000 --- a/Gems/ImageProcessing/Code/Tests/TestAssets/TextureAtlasTest/scroll_box_icon_1.tif +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:0426d9b043f9033967a31a3392b80651871af1d4e60eada2d17e445c19105e32 -size 284432 diff --git a/Gems/ImageProcessing/Code/Tests/TestAssets/TextureAtlasTest/scroll_box_icon_10.tif b/Gems/ImageProcessing/Code/Tests/TestAssets/TextureAtlasTest/scroll_box_icon_10.tif deleted file mode 100644 index 54ea437920..0000000000 --- a/Gems/ImageProcessing/Code/Tests/TestAssets/TextureAtlasTest/scroll_box_icon_10.tif +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:4eef390a93715bd46f196dc0c7ca311300ae7aca33b8163555b6429e91450497 -size 283492 diff --git a/Gems/ImageProcessing/Code/Tests/TestAssets/TextureAtlasTest/scroll_box_icon_2.tif b/Gems/ImageProcessing/Code/Tests/TestAssets/TextureAtlasTest/scroll_box_icon_2.tif deleted file mode 100644 index 9f7ba47daa..0000000000 --- a/Gems/ImageProcessing/Code/Tests/TestAssets/TextureAtlasTest/scroll_box_icon_2.tif +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:a3d0845d8cc9c75a51ad2c812e6c72ca8147bae2ce12a7ea80e07f579bead937 -size 284884 diff --git a/Gems/ImageProcessing/Code/Tests/TestAssets/TextureAtlasTest/scroll_box_icon_3.tif b/Gems/ImageProcessing/Code/Tests/TestAssets/TextureAtlasTest/scroll_box_icon_3.tif deleted file mode 100644 index 4dc54a1950..0000000000 --- a/Gems/ImageProcessing/Code/Tests/TestAssets/TextureAtlasTest/scroll_box_icon_3.tif +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:4ee3d82984650486f6d2cf4488b60b1723f143134fdb763e390a7fc7c52ace18 -size 284872 diff --git a/Gems/ImageProcessing/Code/Tests/TestAssets/TextureAtlasTest/scroll_box_icon_4.tif b/Gems/ImageProcessing/Code/Tests/TestAssets/TextureAtlasTest/scroll_box_icon_4.tif deleted file mode 100644 index 54433305f8..0000000000 --- a/Gems/ImageProcessing/Code/Tests/TestAssets/TextureAtlasTest/scroll_box_icon_4.tif +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:becdab2a389207a942895017511cf453fe059c275dce25c1f5efd41ef13c9d38 -size 285396 diff --git a/Gems/ImageProcessing/Code/Tests/TestAssets/TextureAtlasTest/scroll_box_icon_5.tif b/Gems/ImageProcessing/Code/Tests/TestAssets/TextureAtlasTest/scroll_box_icon_5.tif deleted file mode 100644 index 5eae045870..0000000000 --- a/Gems/ImageProcessing/Code/Tests/TestAssets/TextureAtlasTest/scroll_box_icon_5.tif +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:da0222316fcabd92da0908d1750122296e11f7b3e2669e4cbfed3e8c15f08cb0 -size 285076 diff --git a/Gems/ImageProcessing/Code/Tests/TestAssets/TextureAtlasTest/scroll_box_icon_6.tif b/Gems/ImageProcessing/Code/Tests/TestAssets/TextureAtlasTest/scroll_box_icon_6.tif deleted file mode 100644 index 54611d8187..0000000000 --- a/Gems/ImageProcessing/Code/Tests/TestAssets/TextureAtlasTest/scroll_box_icon_6.tif +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:3d0414c7d73a2ec33a50225af455819abb41f8d35077d3b3ec6bff8cabc3ff6b -size 283664 diff --git a/Gems/ImageProcessing/Code/Tests/TestAssets/TextureAtlasTest/scroll_box_icon_7.tif b/Gems/ImageProcessing/Code/Tests/TestAssets/TextureAtlasTest/scroll_box_icon_7.tif deleted file mode 100644 index 2da7dba224..0000000000 --- a/Gems/ImageProcessing/Code/Tests/TestAssets/TextureAtlasTest/scroll_box_icon_7.tif +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:05490310ee718b472efe4b8272077a88e2edf2992c253f46930c9ff1eb52a1e2 -size 283072 diff --git a/Gems/ImageProcessing/Code/Tests/TestAssets/TextureAtlasTest/scroll_box_icon_8.tif b/Gems/ImageProcessing/Code/Tests/TestAssets/TextureAtlasTest/scroll_box_icon_8.tif deleted file mode 100644 index 7115f20b1d..0000000000 --- a/Gems/ImageProcessing/Code/Tests/TestAssets/TextureAtlasTest/scroll_box_icon_8.tif +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:ba9fb34b4769374304e50d54cd34d1b971a5ec975cdae60ac33aa672c738e245 -size 283216 diff --git a/Gems/ImageProcessing/Code/Tests/TestAssets/TextureAtlasTest/scroll_box_icon_9.tif b/Gems/ImageProcessing/Code/Tests/TestAssets/TextureAtlasTest/scroll_box_icon_9.tif deleted file mode 100644 index c4f9f70332..0000000000 --- a/Gems/ImageProcessing/Code/Tests/TestAssets/TextureAtlasTest/scroll_box_icon_9.tif +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:0d96c5874954efba8c1c164fe5395a3a73647c09c887fe41d74d3a0f7b109ea8 -size 283488 diff --git a/Gems/ImageProcessing/Code/Tests/TestAssets/TextureAtlasTest/scroll_box_map.tif b/Gems/ImageProcessing/Code/Tests/TestAssets/TextureAtlasTest/scroll_box_map.tif deleted file mode 100644 index 8235c16cfc..0000000000 --- a/Gems/ImageProcessing/Code/Tests/TestAssets/TextureAtlasTest/scroll_box_map.tif +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:98b4c4ee5937d1211a4cf9deca85291bbe1419753cd80d97726839aaacd37699 -size 1597872 diff --git a/Gems/ImageProcessing/Code/Tests/TestAssets/TextureAtlasTest/selected.tif b/Gems/ImageProcessing/Code/Tests/TestAssets/TextureAtlasTest/selected.tif deleted file mode 100644 index 6d97b05566..0000000000 --- a/Gems/ImageProcessing/Code/Tests/TestAssets/TextureAtlasTest/selected.tif +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:fae0b4d2b33ec478d440fdfdb495a36a3980254087291ffdb5557abd66ffbb6e -size 37124 diff --git a/Gems/ImageProcessing/Code/Tests/TestAssets/TextureAtlasTest/shadowInside2.tif b/Gems/ImageProcessing/Code/Tests/TestAssets/TextureAtlasTest/shadowInside2.tif deleted file mode 100644 index ed0a235b5c..0000000000 --- a/Gems/ImageProcessing/Code/Tests/TestAssets/TextureAtlasTest/shadowInside2.tif +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:ea15986ef41dafe27f642ca91cccbc89e58247bee6b3f8e7e95bf7e5748c29d4 -size 36848 diff --git a/Gems/ImageProcessing/Code/Tests/TestAssets/TextureAtlasTest/shadowInsideSquare.tif b/Gems/ImageProcessing/Code/Tests/TestAssets/TextureAtlasTest/shadowInsideSquare.tif deleted file mode 100644 index 26c13cf93b..0000000000 --- a/Gems/ImageProcessing/Code/Tests/TestAssets/TextureAtlasTest/shadowInsideSquare.tif +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:095c764409002b30048579c50c552e63b1578acc473a0bce4a646fdc0748df64 -size 37312 diff --git a/Gems/ImageProcessing/Code/Tests/TestAssets/greyscale.png b/Gems/ImageProcessing/Code/Tests/TestAssets/greyscale.png deleted file mode 100644 index 6df643605a..0000000000 --- a/Gems/ImageProcessing/Code/Tests/TestAssets/greyscale.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:0c0bcbed46bceef7e0686b9b42027d28d98f637c9f7d0d1370eb9911921ba531 -size 1518 diff --git a/Gems/ImageProcessing/Code/Tests/TestAssets/noon_cm.tif b/Gems/ImageProcessing/Code/Tests/TestAssets/noon_cm.tif deleted file mode 100644 index 5c3c4c7a6f..0000000000 --- a/Gems/ImageProcessing/Code/Tests/TestAssets/noon_cm.tif +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:461580d9bdd4919b72d1703284f53667378d7345ea57f4c52272ef17603a91c1 -size 3148003 diff --git a/Gems/ImageProcessing/Code/Tests/TestAssets/normalSmoothness_ddna.tif b/Gems/ImageProcessing/Code/Tests/TestAssets/normalSmoothness_ddna.tif deleted file mode 100644 index 4fb9dce719..0000000000 --- a/Gems/ImageProcessing/Code/Tests/TestAssets/normalSmoothness_ddna.tif +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:cd619f19b99ea234c44c79a39413faa18e85a4817a57674c27ebf050edad5515 -size 3776022 diff --git a/Gems/ImageProcessing/Code/Tests/TestAssets/red.png b/Gems/ImageProcessing/Code/Tests/TestAssets/red.png deleted file mode 100644 index 800faddee4..0000000000 --- a/Gems/ImageProcessing/Code/Tests/TestAssets/red.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:37d146db3de179add861ee86d2316ef1dd413cdb0b02448b3b95bf0023f44bae -size 613 diff --git a/Gems/ImageProcessing/Code/Tests/TestAssets/uppercase.TGA b/Gems/ImageProcessing/Code/Tests/TestAssets/uppercase.TGA deleted file mode 100644 index d3808cdbce..0000000000 --- a/Gems/ImageProcessing/Code/Tests/TestAssets/uppercase.TGA +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:a6b6c1bf24dd39159e38c880071abad7b7315c8667192ff2495501dd0b1dec9c -size 85419 diff --git a/Gems/ImageProcessing/Code/imageprocessing_files.cmake b/Gems/ImageProcessing/Code/imageprocessing_files.cmake deleted file mode 100644 index 98aa870b46..0000000000 --- a/Gems/ImageProcessing/Code/imageprocessing_files.cmake +++ /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. -# - -set(FILES - ../Assets/Editor/Resources.qrc - ../Assets/Editor/Backward.png - ../Assets/Editor/Forward.png - ../Assets/Editor/reset.png - Source/ImageProcessingModule.cpp -) diff --git a/Gems/ImageProcessing/Code/imageprocessing_static_files.cmake b/Gems/ImageProcessing/Code/imageprocessing_static_files.cmake deleted file mode 100644 index 07bf2ad375..0000000000 --- a/Gems/ImageProcessing/Code/imageprocessing_static_files.cmake +++ /dev/null @@ -1,133 +0,0 @@ -# -# All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -# its licensors. -# -# For complete copyright and license terms please see the LICENSE at the root of this -# distribution (the "License"). All use of this software is governed by the License, -# or, if provided, by the license below or the license accompanying this file. Do not -# remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# - -set(FILES - Source/ImageProcessing_precompiled.cpp - Source/ImageProcessing_precompiled.h - Source/Compressors/CryTextureSquisher/CryTextureSquisher.cpp - Source/Compressors/CryTextureSquisher/CryTextureSquisher.h - Include/ImageProcessing/ImageProcessingBus.h - Include/ImageProcessing/ImageProcessingEditorBus.h - Include/ImageProcessing/PixelFormats.h - Include/ImageProcessing/ImageObject.h - Source/ImageProcessingSystemComponent.cpp - Source/ImageProcessingSystemComponent.h - Source/ImageBuilderComponent.cpp - Source/ImageBuilderComponent.h - Source/ImageBuilderBaseType.h - Source/BuilderSettings/MipmapSettings.h - Source/BuilderSettings/MipmapSettings.cpp - Source/BuilderSettings/CubemapSettings.h - Source/BuilderSettings/CubemapSettings.cpp - Source/BuilderSettings/PresetSettings.h - Source/BuilderSettings/PresetSettings.cpp - Source/BuilderSettings/TextureSettings.h - Source/BuilderSettings/TextureSettings.cpp - Source/BuilderSettings/BuilderSettings.cpp - Source/BuilderSettings/BuilderSettings.h - Source/BuilderSettings/BuilderSettingManager.cpp - Source/BuilderSettings/BuilderSettingManager.h - Source/BuilderSettings/ImageProcessingDefines.h - Source/BuilderSettings/PlatformSettings.h - Source/Processing/ImageObjectImpl.h - Source/Processing/ImageObjectImpl.cpp - Source/Processing/PixelFormatInfo.h - Source/Processing/PixelFormatInfo.cpp - Source/Processing/ImageConvert.h - Source/Processing/ImageConvert.cpp - Source/Processing/ImageConvertJob.h - Source/Processing/ImageConvertJob.cpp - Source/Processing/ImagePreview.h - Source/Processing/ImagePreview.cpp - Source/Processing/ImageToProcess.h - Source/Processing/ImageFlags.h - Source/Processing/DDSHeader.h - Source/ImageLoader/ImageLoaders.h - Source/ImageLoader/ImageLoaders.cpp - Source/ImageLoader/QtImageLoader.cpp - Source/ImageLoader/TIFFLoader.cpp - Source/ImageLoader/BTImageLoader.cpp - Source/Editor/EditorCommon.h - Source/Editor/EditorCommon.cpp - Source/Editor/TexturePropertyEditor.cpp - Source/Editor/TexturePropertyEditor.h - Source/Editor/TexturePropertyEditor.ui - Source/Editor/MipmapSettingWidget.cpp - Source/Editor/MipmapSettingWidget.h - Source/Editor/MipmapSettingWidget.ui - Source/Editor/ResolutionSettingWidget.cpp - Source/Editor/ResolutionSettingWidget.h - Source/Editor/ResolutionSettingWidget.ui - Source/Editor/ResolutionSettingItemWidget.cpp - Source/Editor/ResolutionSettingItemWidget.h - Source/Editor/ResolutionSettingItemWidget.ui - Source/Editor/TexturePresetSelectionWidget.cpp - Source/Editor/TexturePresetSelectionWidget.h - Source/Editor/TexturePresetSelectionWidget.ui - Source/Editor/TexturePreviewWidget.cpp - Source/Editor/TexturePreviewWidget.h - Source/Editor/TexturePreviewWidget.ui - Source/Editor/ImagePopup.cpp - Source/Editor/ImagePopup.h - Source/Editor/ImagePopup.ui - Source/Editor/PresetInfoPopup.cpp - Source/Editor/PresetInfoPopup.h - Source/Editor/PresetInfoPopup.ui - Source/Converters/Gamma.cpp - Source/Converters/FIR-Filter.cpp - Source/Converters/FIR-Windows.h - Source/Converters/FIR-Weights.h - Source/Converters/FIR-Weights.cpp - Source/Converters/AlphaCoverage.cpp - Source/Converters/PixelOperation.h - Source/Converters/PixelOperation.cpp - Source/Converters/Normalize.cpp - Source/Converters/ConvertPixelFormat.cpp - Source/Converters/Cubemap.h - Source/Converters/Cubemap.cpp - Source/Converters/ColorChart.cpp - Source/Converters/HighPass.cpp - Source/Converters/Histogram.cpp - Source/Converters/Histogram.h - ../External/CubeMapGen/CBBoxInt32.cpp - ../External/CubeMapGen/CBBoxInt32.h - ../External/CubeMapGen/CCubeMapProcessor.cpp - ../External/CubeMapGen/CCubeMapProcessor.h - ../External/CubeMapGen/CImageSurface.cpp - ../External/CubeMapGen/CImageSurface.h - ../External/CubeMapGen/VectorMacros.h - Source/Compressors/Compressor.h - Source/Compressors/Compressor.cpp - Source/Compressors/CTSquisher.h - Source/Compressors/CTSquisher.cpp - Source/Compressors/PVRTC.cpp - Source/Compressors/PVRTC.h - Source/Compressors/ETC2.cpp - Source/Compressors/ETC2.h - Source/Compressors/CryTextureSquisher/ColorBlockRGBA4x4f.cpp - Source/Compressors/CryTextureSquisher/ColorBlockRGBA4x4s.cpp - Source/Compressors/CryTextureSquisher/ColorBlockRGBA4x4c.cpp - Source/Compressors/CryTextureSquisher/ColorBlockRGBA4x4f.h - Source/Compressors/CryTextureSquisher/ColorBlockRGBA4x4s.h - Source/Compressors/CryTextureSquisher/ColorBlockRGBA4x4c.h - Source/Compressors/CryTextureSquisher/ColorTypes.h - Source/AtlasBuilder/AtlasBuilderComponent.h - Source/AtlasBuilder/AtlasBuilderComponent.cpp - Source/AtlasBuilder/AtlasBuilderWorker.h - Source/AtlasBuilder/AtlasBuilderWorker.cpp -) - -set(SKIP_UNITY_BUILD_INCLUSION_FILES - Source/Compressors/PVRTC.cpp - Source/Compressors/PVRTC.h -) - - diff --git a/Gems/ImageProcessing/Code/imageprocessing_tests_files.cmake b/Gems/ImageProcessing/Code/imageprocessing_tests_files.cmake deleted file mode 100644 index 290f00104a..0000000000 --- a/Gems/ImageProcessing/Code/imageprocessing_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 - Tests/ImageProcessing_Test.cpp - Tests/AtlasBuilderTest.cpp -) diff --git a/Gems/ImageProcessing/External/CubeMapGen/CBBoxInt32.cpp b/Gems/ImageProcessing/External/CubeMapGen/CBBoxInt32.cpp deleted file mode 100644 index 5e80267f56..0000000000 --- a/Gems/ImageProcessing/External/CubeMapGen/CBBoxInt32.cpp +++ /dev/null @@ -1,129 +0,0 @@ - -//============================================================================= -//CBBoxInt32 -// 3D bounding box with int32 coordinates -// -//============================================================================= -// (C) 2005 ATI Research, Inc., All rights reserved. -//============================================================================= -// modifications by Crytek GmbH -// modifications by Amazon - -#include - -#include "CBBoxInt32.h" - -#define CP_MIN_INT32 0x80000000 -#define CP_MAX_INT32 0x7fffffff -#define CP_MIN(a, b) (((a) < (b)) ? (a) : (b)) -#define CP_MAX(a, b) (((a) > (b)) ? (a) : (b)) - - -namespace ImageProcessing -{ - //-------------------------------------------------------------------------------------- - // CBBoxInt32 - //-------------------------------------------------------------------------------------- - CBBoxInt32::CBBoxInt32(void) - { - Clear(); - } - - - //-------------------------------------------------------------------------------------- - // Text to see if CBBoxInt32 is empty or not - //-------------------------------------------------------------------------------------- - bool CBBoxInt32::Empty(void) - { - if ((m_minCoord[0] > m_maxCoord[0]) || - (m_minCoord[1] > m_maxCoord[1]) || - (m_minCoord[2] > m_maxCoord[2])) - { - return true; - } - else - { - return false; - } - } - - - //-------------------------------------------------------------------------------------- - // Clear bounding box extents - //-------------------------------------------------------------------------------------- - void CBBoxInt32::Clear(void) - { - m_minCoord[0] = CP_MAX_INT32; - m_minCoord[1] = CP_MAX_INT32; - m_minCoord[2] = CP_MAX_INT32; - m_maxCoord[0] = CP_MIN_INT32; - m_maxCoord[1] = CP_MIN_INT32; - m_maxCoord[2] = CP_MIN_INT32; - } - - - //-------------------------------------------------------------------------------------- - // Augment bounding box extents by specifying point to include in bounding box - //-------------------------------------------------------------------------------------- - void CBBoxInt32::Augment(int32 aX, int32 aY, int32 aZ) - { - m_minCoord[0] = CP_MIN(m_minCoord[0], aX); - m_minCoord[1] = CP_MIN(m_minCoord[1], aY); - m_minCoord[2] = CP_MIN(m_minCoord[2], aZ); - m_maxCoord[0] = CP_MAX(m_maxCoord[0], aX); - m_maxCoord[1] = CP_MAX(m_maxCoord[1], aY); - m_maxCoord[2] = CP_MAX(m_maxCoord[2], aZ); - } - - - //-------------------------------------------------------------------------------------- - // Augment bounding box extents by specifying x coordinate to include in bounding box - //-------------------------------------------------------------------------------------- - void CBBoxInt32::AugmentX(int32 aX) - { - m_minCoord[0] = CP_MIN(m_minCoord[0], aX); - m_maxCoord[0] = CP_MAX(m_maxCoord[0], aX); - } - - - //-------------------------------------------------------------------------------------- - // Augment bounding box extents by specifying x coordinate to include in bounding box - //-------------------------------------------------------------------------------------- - void CBBoxInt32::AugmentY(int32 aY) - { - m_minCoord[1] = CP_MIN(m_minCoord[1], aY); - m_maxCoord[1] = CP_MAX(m_maxCoord[1], aY); - } - - - //-------------------------------------------------------------------------------------- - // Augment bounding box extents by specifying x coordinate to include in bounding box - //-------------------------------------------------------------------------------------- - void CBBoxInt32::AugmentZ(int32 aZ) - { - m_minCoord[2] = CP_MIN(m_minCoord[2], aZ); - m_maxCoord[2] = CP_MAX(m_maxCoord[2], aZ); - } - - - //-------------------------------------------------------------------------------------- - // Clamp minimum values in bbox to be no larger than aX, aY, aZ - //-------------------------------------------------------------------------------------- - void CBBoxInt32::ClampMin(int32 aX, int32 aY, int32 aZ) - { - m_minCoord[0] = CP_MAX(m_minCoord[0], aX); - m_minCoord[1] = CP_MAX(m_minCoord[1], aY); - m_minCoord[2] = CP_MAX(m_minCoord[2], aZ); - } - - - //-------------------------------------------------------------------------------------- - // Clamp maximum values in bbox to be no larger than aX, aY, aZ - //-------------------------------------------------------------------------------------- - void CBBoxInt32::ClampMax(int32 aX, int32 aY, int32 aZ) - { - m_maxCoord[0] = CP_MIN(m_maxCoord[0], aX); - m_maxCoord[1] = CP_MIN(m_maxCoord[1], aY); - m_maxCoord[2] = CP_MIN(m_maxCoord[2], aZ); - } -} //namespace ImageProcessing diff --git a/Gems/ImageProcessing/External/CubeMapGen/CBBoxInt32.h b/Gems/ImageProcessing/External/CubeMapGen/CBBoxInt32.h deleted file mode 100644 index a6bbe0c327..0000000000 --- a/Gems/ImageProcessing/External/CubeMapGen/CBBoxInt32.h +++ /dev/null @@ -1,32 +0,0 @@ -//============================================================================= -//CBBoxInt32 -// 3D bounding box with int32 coordinates -// -//============================================================================= -// (C) 2005 ATI Research, Inc., All rights reserved. -//============================================================================= -// modifications by Crytek GmbH -// modifications by Amazon - -#pragma once - -namespace ImageProcessing -{ - //bounding box class with coords specified as int32 - class CBBoxInt32 - { - public: - int32 m_minCoord[3]; //upper left back corner - int32 m_maxCoord[3]; //lower right front corner - - CBBoxInt32(); - bool Empty(void); - void Clear(void); - void Augment(int32 a_X, int32 a_Y, int32 a_Z); - void AugmentX(int32 a_X); - void AugmentY(int32 a_Y); - void AugmentZ(int32 a_Z); - void ClampMin(int32 a_X, int32 a_Y, int32 a_Z); - void ClampMax(int32 a_X, int32 a_Y, int32 a_Z); - }; -} //namespace ImageProcessing diff --git a/Gems/ImageProcessing/External/CubeMapGen/CCubeMapProcessor.cpp b/Gems/ImageProcessing/External/CubeMapGen/CCubeMapProcessor.cpp deleted file mode 100644 index 794e860f28..0000000000 --- a/Gems/ImageProcessing/External/CubeMapGen/CCubeMapProcessor.cpp +++ /dev/null @@ -1,2237 +0,0 @@ -//============================================================================= -// (C) 2005 ATI Research, Inc., All rights reserved. -//============================================================================= -// modifications by Crytek GmbH -// modifications by Amazon - -#include -#include "CCubeMapProcessor.h" - -#include - -#define CP_PI 3.14159265358979323846 - - -namespace ImageProcessing -{ - - //------------------------------------------------------------------------------ - // D3D cube map face specification - // mapping from 3D x,y,z cube map lookup coordinates - // to 2D within face u,v coordinates - // - // --------------------> U direction - // | (within-face texture space) - // | _____ - // | | | - // | | +Y | - // | _____|_____|_____ _____ - // | | | | | | - // | | -X | +Z | +X | -Z | - // | |_____|_____|_____|_____| - // | | | - // | | -Y | - // | |_____| - // | - // v V direction - // (within-face texture space) - //------------------------------------------------------------------------------ - - //Information about neighbors and how texture coorrdinates change across faces - // in ORDER of left, right, top, bottom (e.g. edges corresponding to u=0, - // u=1, v=0, v=1 in the 2D coordinate system of the particular face. - //Note this currently assumes the D3D cube face ordering and orientation - CPCubeMapNeighbor sg_CubeNgh[6][4] = - { - //XPOS face - {{CP_FACE_Z_POS, CP_EDGE_RIGHT }, - {CP_FACE_Z_NEG, CP_EDGE_LEFT }, - {CP_FACE_Y_POS, CP_EDGE_RIGHT }, - {CP_FACE_Y_NEG, CP_EDGE_RIGHT }}, - //XNEG face - {{CP_FACE_Z_NEG, CP_EDGE_RIGHT }, - {CP_FACE_Z_POS, CP_EDGE_LEFT }, - {CP_FACE_Y_POS, CP_EDGE_LEFT }, - {CP_FACE_Y_NEG, CP_EDGE_LEFT }}, - //YPOS face - {{CP_FACE_X_NEG, CP_EDGE_TOP }, - {CP_FACE_X_POS, CP_EDGE_TOP }, - {CP_FACE_Z_NEG, CP_EDGE_TOP }, - {CP_FACE_Z_POS, CP_EDGE_TOP }}, - //YNEG face - {{CP_FACE_X_NEG, CP_EDGE_BOTTOM}, - {CP_FACE_X_POS, CP_EDGE_BOTTOM}, - {CP_FACE_Z_POS, CP_EDGE_BOTTOM}, - {CP_FACE_Z_NEG, CP_EDGE_BOTTOM}}, - //ZPOS face - {{CP_FACE_X_NEG, CP_EDGE_RIGHT }, - {CP_FACE_X_POS, CP_EDGE_LEFT }, - {CP_FACE_Y_POS, CP_EDGE_BOTTOM }, - {CP_FACE_Y_NEG, CP_EDGE_TOP }}, - //ZNEG face - {{CP_FACE_X_POS, CP_EDGE_RIGHT }, - {CP_FACE_X_NEG, CP_EDGE_LEFT }, - {CP_FACE_Y_POS, CP_EDGE_TOP }, - {CP_FACE_Y_NEG, CP_EDGE_BOTTOM }} - }; - - - //3x2 matrices that map cube map indexing vectors in 3d - // (after face selection and divide through by the - // _ABSOLUTE VALUE_ of the max coord) - // into NVC space - //Note this currently assumes the D3D cube face ordering and orientation - #define CP_UDIR 0 - #define CP_VDIR 1 - #define CP_FACEAXIS 2 - - float sgFace2DMapping[6][3][3] = { - //XPOS face - {{ 0, 0, -1}, //u towards negative Z - { 0, -1, 0}, //v towards negative Y - {1, 0, 0}}, //pos X axis - //XNEG face - {{0, 0, 1}, //u towards positive Z - {0, -1, 0}, //v towards negative Y - {-1, 0, 0}}, //neg X axis - //YPOS face - {{1, 0, 0}, //u towards positive X - {0, 0, 1}, //v towards positive Z - {0, 1 , 0}}, //pos Y axis - //YNEG face - {{1, 0, 0}, //u towards positive X - {0, 0 , -1}, //v towards negative Z - {0, -1 , 0}}, //neg Y axis - //ZPOS face - {{1, 0, 0}, //u towards positive X - {0, -1, 0}, //v towards negative Y - {0, 0, 1}}, //pos Z axis - //ZNEG face - {{-1, 0, 0}, //u towards negative X - {0, -1, 0}, //v towards negative Y - {0, 0, -1}}, //neg Z axis - }; - - - //The 12 edges of the cubemap, (entries are used to index into the neighbor table) - // this table is used to average over the edges. - int32 sg_CubeEdgeList[12][2] = { - {CP_FACE_X_POS, CP_EDGE_LEFT}, - {CP_FACE_X_POS, CP_EDGE_RIGHT}, - {CP_FACE_X_POS, CP_EDGE_TOP}, - {CP_FACE_X_POS, CP_EDGE_BOTTOM}, - - {CP_FACE_X_NEG, CP_EDGE_LEFT}, - {CP_FACE_X_NEG, CP_EDGE_RIGHT}, - {CP_FACE_X_NEG, CP_EDGE_TOP}, - {CP_FACE_X_NEG, CP_EDGE_BOTTOM}, - - {CP_FACE_Z_POS, CP_EDGE_TOP}, - {CP_FACE_Z_POS, CP_EDGE_BOTTOM}, - {CP_FACE_Z_NEG, CP_EDGE_TOP}, - {CP_FACE_Z_NEG, CP_EDGE_BOTTOM} - }; - - - //Information about which of the 8 cube corners are correspond to the - // the 4 corners in each cube face - // the order is upper left, upper right, lower left, lower right - int32 sg_CubeCornerList[6][4] = { - { CP_CORNER_PPP, CP_CORNER_PPN, CP_CORNER_PNP, CP_CORNER_PNN }, // XPOS face - { CP_CORNER_NPN, CP_CORNER_NPP, CP_CORNER_NNN, CP_CORNER_NNP }, // XNEG face - { CP_CORNER_NPN, CP_CORNER_PPN, CP_CORNER_NPP, CP_CORNER_PPP }, // YPOS face - { CP_CORNER_NNP, CP_CORNER_PNP, CP_CORNER_NNN, CP_CORNER_PNN }, // YNEG face - { CP_CORNER_NPP, CP_CORNER_PPP, CP_CORNER_NNP, CP_CORNER_PNP }, // ZPOS face - { CP_CORNER_PPN, CP_CORNER_NPN, CP_CORNER_PNN, CP_CORNER_NNN } // ZNEG face - }; - - - //-------------------------------------------------------------------------------------- - // Convert cubemap face texel coordinates and face idx to 3D vector - // note the U and V coords are integer coords and range from 0 to size-1 - // this routine can be used to generate a normalizer cube map - //-------------------------------------------------------------------------------------- - void TexelCoordToVect(int32 a_FaceIdx, float a_U, float a_V, int32 a_Size, float *a_XYZ) - { - float nvcU, nvcV; - float tempVec[3]; - - //scale up to [-1, 1] range (inclusive) - nvcU = (2.0f * ((float)a_U + 0.5f) / a_Size ) - 1.0f; - nvcV = (2.0f * ((float)a_V + 0.5f) / a_Size ) - 1.0f; - - //generate x,y,z vector (xform 2d NVC coord to 3D vector) - //U contribution - VM_SCALE3(a_XYZ, sgFace2DMapping[a_FaceIdx][CP_UDIR], nvcU); - //V contribution - VM_SCALE3(tempVec, sgFace2DMapping[a_FaceIdx][CP_VDIR], nvcV); - VM_ADD3(a_XYZ, tempVec, a_XYZ); - //add face axis - VM_ADD3(a_XYZ, sgFace2DMapping[a_FaceIdx][CP_FACEAXIS], a_XYZ); - - //normalize vector - VM_NORM3(a_XYZ, a_XYZ); - } - - - //-------------------------------------------------------------------------------------- - // Convert 3D vector to cubemap face texel coordinates and face idx - // note the U and V coords are integer coords and range from 0 to size-1 - // this routine can be used to generate a normalizer cube map - // - // returns face IDX and texel coords - //-------------------------------------------------------------------------------------- - void VectToTexelCoord(float *a_XYZ, int32 a_Size, int32 *a_FaceIdx, int32 *a_U, int32 *a_V ) - { - float nvcU, nvcV; - float absXYZ[3]; - float maxCoord; - float onFaceXYZ[3]; - int32 faceIdx; - int32 u, v; - - //absolute value 3 - VM_ABS3(absXYZ, a_XYZ); - - if( (absXYZ[0] >= absXYZ[1]) && (absXYZ[0] >= absXYZ[2]) ) - { - maxCoord = absXYZ[0]; - - if(a_XYZ[0] >= 0) //face = XPOS - { - faceIdx = CP_FACE_X_POS; - } - else - { - faceIdx = CP_FACE_X_NEG; - } - } - else if ( (absXYZ[1] >= absXYZ[0]) && (absXYZ[1] >= absXYZ[2]) ) - { - maxCoord = absXYZ[1]; - - if(a_XYZ[1] >= 0) //face = XPOS - { - faceIdx = CP_FACE_Y_POS; - } - else - { - faceIdx = CP_FACE_Y_NEG; - } - } - else // if( (absXYZ[2] > absXYZ[0]) && (absXYZ[2] > absXYZ[1]) ) - { - maxCoord = absXYZ[2]; - - if(a_XYZ[2] >= 0) //face = XPOS - { - faceIdx = CP_FACE_Z_POS; - } - else - { - faceIdx = CP_FACE_Z_NEG; - } - } - - //divide through by max coord so face vector lies on cube face - VM_SCALE3(onFaceXYZ, a_XYZ, 1.0f/maxCoord); - nvcU = VM_DOTPROD3(sgFace2DMapping[ faceIdx ][CP_UDIR], onFaceXYZ ); - nvcV = VM_DOTPROD3(sgFace2DMapping[ faceIdx ][CP_VDIR], onFaceXYZ ); - - u = (int32)floor( a_Size * 0.5f * (nvcU + 1.0f) ); - v = (int32)floor( a_Size * 0.5f * (nvcV + 1.0f) ); - - *a_FaceIdx = faceIdx; - *a_U = u; - *a_V = v; - } - - - //-------------------------------------------------------------------------------------- - // gets texel ptr in a cube map given a direction vector, and an array of - // CImageSurfaces that represent the cube faces. - // - //-------------------------------------------------------------------------------------- - CP_ITYPE *GetCubeMapTexelPtr(float *a_XYZ, CImageSurface *a_Surface) - { - int32 u, v, faceIdx; - - //get face idx and u, v texel coordinate in face - VectToTexelCoord(a_XYZ, a_Surface[0].m_Width, &faceIdx, &u, &v ); - - u = VM_MIN(u, a_Surface[0].m_Width - 1); - v = VM_MIN(v, a_Surface[0].m_Width - 1); - - return( a_Surface[faceIdx].GetSurfaceTexelPtr(u, v) ); - } - - - //-------------------------------------------------------------------------------------- - // Compute solid angle of given texel in cubemap face for weighting taps in the - // kernel by the area they project to on the unit sphere. - // - // Note that this code uses an approximation to the solid angle, by treating the - // two triangles that make up the quad comprising the texel as planar. If more - // accuracy is required, the solid angle per triangle lying on the sphere can be - // computed using the sum of the interior angles - PI. - // - //-------------------------------------------------------------------------------------- - float TexelCoordSolidAngle(int32 a_FaceIdx, float a_U, float a_V, int32 a_Size) - { - float cornerVect[4][3]; - double cornerVect64[4][3]; - - float halfTexelStep = 0.5f; //note u, and v are in texel coords (where each texel is one unit) - double edgeVect0[3]; - double edgeVect1[3]; - double xProdVect[3]; - double texelArea; - - //compute 4 corner vectors of texel - TexelCoordToVect(a_FaceIdx, a_U - halfTexelStep, a_V - halfTexelStep, a_Size, cornerVect[0] ); - TexelCoordToVect(a_FaceIdx, a_U - halfTexelStep, a_V + halfTexelStep, a_Size, cornerVect[1] ); - TexelCoordToVect(a_FaceIdx, a_U + halfTexelStep, a_V - halfTexelStep, a_Size, cornerVect[2] ); - TexelCoordToVect(a_FaceIdx, a_U + halfTexelStep, a_V + halfTexelStep, a_Size, cornerVect[3] ); - - VM_NORM3_UNTYPED(cornerVect64[0], cornerVect[0] ); - VM_NORM3_UNTYPED(cornerVect64[1], cornerVect[1] ); - VM_NORM3_UNTYPED(cornerVect64[2], cornerVect[2] ); - VM_NORM3_UNTYPED(cornerVect64[3], cornerVect[3] ); - - //area of triangle defined by corners 0, 1, and 2 - VM_SUB3_UNTYPED(edgeVect0, cornerVect64[1], cornerVect64[0] ); - VM_SUB3_UNTYPED(edgeVect1, cornerVect64[2], cornerVect64[0] ); - VM_XPROD3_UNTYPED(xProdVect, edgeVect0, edgeVect1 ); - texelArea = 0.5f * sqrt( VM_DOTPROD3_UNTYPED(xProdVect, xProdVect ) ); - - //area of triangle defined by corners 1, 2, and 3 - VM_SUB3_UNTYPED(edgeVect0, cornerVect64[2], cornerVect64[1] ); - VM_SUB3_UNTYPED(edgeVect1, cornerVect64[3], cornerVect64[1] ); - VM_XPROD3_UNTYPED(xProdVect, edgeVect0, edgeVect1 ); - texelArea += 0.5f * sqrt( VM_DOTPROD3_UNTYPED(xProdVect, xProdVect ) ); - - return texelArea; - } - - - - //-------------------------------------------------------------------------------------- - //Builds a normalizer cubemap - // - // Takes in a cube face size, and an array of 6 surfaces to write the cube faces into - // - // Note that this normalizer cube map stores the vectors in unbiased -1 to 1 range. - // if _bx2 style scaled and biased vectors are needed, uncomment the SCALE and BIAS - // below - //-------------------------------------------------------------------------------------- - void CCubeMapProcessor::BuildNormalizerCubemap(int32 a_Size, CImageSurface *a_Surface ) - { - int32 iCubeFace, u, v; - - //iterate over cube faces - for(iCubeFace=0; iCubeFace<6; iCubeFace++) - { - a_Surface[iCubeFace].Clear(); - a_Surface[iCubeFace].Init(a_Size, a_Size, 3); - - //fast texture walk, build normalizer cube map - CP_ITYPE *texelPtr = a_Surface[iCubeFace].m_ImgData; - - for(v=0; v < a_Surface[iCubeFace].m_Height; v++) - { - for(u=0; u < a_Surface[iCubeFace].m_Width; u++) - { - TexelCoordToVect(iCubeFace, (float)u, (float)v, a_Size, texelPtr); - - //VM_SCALE3(texelPtr, texelPtr, 0.5f); - //VM_BIAS3(texelPtr, texelPtr, 0.5f); - - texelPtr += a_Surface[iCubeFace].m_NumChannels; - } - } - } - } - - - //-------------------------------------------------------------------------------------- - //Builds a normalizer cubemap, with the texels solid angle stored in the fourth component - // - //Takes in a cube face size, and an array of 6 surfaces to write the cube faces into - // - //Note that this normalizer cube map stores the vectors in unbiased -1 to 1 range. - // if _bx2 style scaled and biased vectors are needed, uncomment the SCALE and BIAS - // below - //-------------------------------------------------------------------------------------- - void CCubeMapProcessor::BuildNormalizerSolidAngleCubemap(int32 a_Size, CImageSurface *a_Surface ) - { - //iterate over cube faces - for(int32 iCubeFace=0; iCubeFace<6; iCubeFace++) - { - a_Surface[iCubeFace].Clear(); - a_Surface[iCubeFace].Init(a_Size, a_Size, 4); //First three channels for norm cube, and last channel for solid angle - } - - //iterate over cube faces - for(int32 iCubeFace=0; iCubeFace<6; iCubeFace++) - { - const int32 height = a_Surface[iCubeFace].m_Height; - const int32 width = a_Surface[iCubeFace].m_Width; - - for(int32 v=0; v 0) - { - neighborFace = sg_CubeNgh[faceIdx][i].m_Face; - neighborEdge = sg_CubeNgh[faceIdx][i].m_Edge; - - //For certain types of edge abutments, the bleedOverBBoxMin, and bleedOverBBoxMax need to - // be flipped: the cases are - // if a left edge mates with a left or bottom edge on the neighbor - // if a top edge mates with a top or right edge on the neighbor - // if a right edge mates with a right or top edge on the neighbor - // if a bottom edge mates with a bottom or left edge on the neighbor - //Seeing as the edges are enumerated as follows - // left =0 - // right =1 - // top =2 - // bottom =3 - // - // so if the edge enums are the same, or the sum of the enums == 3, - // the bbox needs to be flipped - if( (i == neighborEdge) || ((i+neighborEdge) == 3) ) - { - bleedOverBBoxMin[i] = (a_SrcSize-1) - bleedOverBBoxMin[i]; - bleedOverBBoxMax[i] = (a_SrcSize-1) - bleedOverBBoxMax[i]; - } - - - //The way the bounding box is extended onto the neighboring face - // depends on which edge of neighboring face abuts with this one - switch(sg_CubeNgh[faceIdx][i].m_Edge) - { - case CP_EDGE_LEFT: - a_FilterExtents[neighborFace].Augment(0, bleedOverBBoxMin[i], 0); - a_FilterExtents[neighborFace].Augment(bleedOverAmount[i], bleedOverBBoxMax[i], 0); - break; - case CP_EDGE_RIGHT: - a_FilterExtents[neighborFace].Augment( (a_SrcSize-1), bleedOverBBoxMin[i], 0); - a_FilterExtents[neighborFace].Augment( (a_SrcSize-1) - bleedOverAmount[i], bleedOverBBoxMax[i], 0); - break; - case CP_EDGE_TOP: - a_FilterExtents[neighborFace].Augment(bleedOverBBoxMin[i], 0, 0); - a_FilterExtents[neighborFace].Augment(bleedOverBBoxMax[i], bleedOverAmount[i], 0); - break; - case CP_EDGE_BOTTOM: - a_FilterExtents[neighborFace].Augment(bleedOverBBoxMin[i], (a_SrcSize-1), 0); - a_FilterExtents[neighborFace].Augment(bleedOverBBoxMax[i], (a_SrcSize-1) - bleedOverAmount[i], 0); - break; - } - - //clamp filter extents in non-center tap faces to remain within surface - a_FilterExtents[neighborFace].ClampMin(0, 0, 0); - a_FilterExtents[neighborFace].ClampMax(a_SrcSize-1, a_SrcSize-1, 0); - } - - //If the bleed over amount bleeds past the adjacent face onto the opposite face - // from the center tap face, then process the opposite face entirely for now. - //Note that the cases in which this happens, what usually happens is that - // more than one edge bleeds onto the opposite face, and the bounding box - // encompasses the entire cube map face. - if(bleedOverAmount[i] > a_SrcSize) - { - uint32 oppositeFaceIdx; - - //determine opposite face - switch(faceIdx) - { - case CP_FACE_X_POS: - oppositeFaceIdx = CP_FACE_X_NEG; - break; - case CP_FACE_X_NEG: - oppositeFaceIdx = CP_FACE_X_POS; - break; - case CP_FACE_Y_POS: - oppositeFaceIdx = CP_FACE_Y_NEG; - break; - case CP_FACE_Y_NEG: - oppositeFaceIdx = CP_FACE_Y_POS; - break; - case CP_FACE_Z_POS: - oppositeFaceIdx = CP_FACE_Z_NEG; - break; - default: // CP_FACE_Z_NEG: - oppositeFaceIdx = CP_FACE_Z_POS; - break; - } - - //just encompass entire face for now - a_FilterExtents[oppositeFaceIdx].Augment(0, 0, 0); - a_FilterExtents[oppositeFaceIdx].Augment((a_SrcSize-1), (a_SrcSize-1), 0); - } - } - - minV=minV; - } - - - //-------------------------------------------------------------------------------------- - //ProcessFilterExtents - // Process bounding box in each cube face - // - //-------------------------------------------------------------------------------------- - void CCubeMapProcessor::ProcessFilterExtents(float *a_CenterTapDir, float a_DotProdThresh, - CBBoxInt32 *a_FilterExtents, CImageSurface *a_NormCubeMap, CImageSurface *a_SrcCubeMap, - CP_ITYPE *a_DstVal, uint32 a_FilterType, bool a_bUseSolidAngleWeighting, float a_SpecularPower) - { - //accumulators are 64-bit floats in order to have the precision needed - // over a summation of a large number of pixels - double dstAccumFace[6][4]; - double weightAccumFace[6]; - - const int32 nSrcChannels = a_SrcCubeMap[0].m_NumChannels; - - //norm cube map and srcCubeMap have same face width - const int32 faceWidth = a_NormCubeMap[0].m_Width; - - //amount to add to pointer to move to next scanline in images - const int32 normCubePitch = faceWidth * a_NormCubeMap[0].m_NumChannels; - const int32 srcCubePitch = faceWidth * a_SrcCubeMap[0].m_NumChannels; - - //iterate over cubefaces - for(int32 iFaceIdx=0; iFaceIdx<6; iFaceIdx++ ) - { - //dest accum - for(int32 k=0; k= a_DotProdThresh ) - { - CP_ITYPE weight; - - //for now just weight all taps equally, but ideally - // weight should be proportional to the solid angle of the tap - if(a_bUseSolidAngleWeighting == true) - { //solid angle stored in 4th channel of normalizer/solid angle cube map - weight = *(texelVect+3); - } - else - { //all taps equally weighted - weight = 1.0f; - } - - switch(a_FilterType) - { - case CP_FILTER_TYPE_COSINE_POWER: - { - if(tapDotProd > 0.0f) - { - weight *= pow(tapDotProd, a_SpecularPower) * tapDotProd; - } - else - { - weight = 0; - } - } - break; - case CP_FILTER_TYPE_CONE: - case CP_FILTER_TYPE_ANGULAR_GAUSSIAN: - { - //weights are in same lookup table for both of these filter types - weight *= m_FilterLUT[(int32)(tapDotProd * (m_NumFilterLUTEntries - 1))]; - } - break; - case CP_FILTER_TYPE_COSINE: - { - if(tapDotProd > 0.0f) - { - weight *= tapDotProd; - } - else - { - weight = 0.0f; - } - } - break; - case CP_FILTER_TYPE_DISC: - default: - break; - } - - //iterate over channels - for(int32 k=0; k>= 1; - - m_NumMipLevels++; - - //terminate if mip chain becomes too small - if(mipLevelSize == 0) - { - return; - } - } - } - - - //-------------------------------------------------------------------------------------- - //Copy and convert cube map face data from an external image/surface into this object - // - // a_FaceIdx = a value 0 to 5 speciying which face to copy into (one of the CP_FACE_? ) - // a_Level = mip level to copy into - // a_SrcType = data type of image being copyed from (one of the CP_TYPE_? types) - // a_SrcNumChannels = number of channels of the image being copied from (usually 1 to 4) - // a_SrcPitch = number of bytes per row of the source image being copied from - // a_SrcDataPtr = pointer to the image data to copy from - // a_Degamma = original gamma level of input image to undo by degamma - // a_Scale = scale to apply to pixel values after degamma (in linear space) - //-------------------------------------------------------------------------------------- - void CCubeMapProcessor::SetInputFaceData(int32 a_FaceIdx, int32 a_SrcType, int32 a_SrcNumChannels, - int32 a_SrcPitch, void *a_SrcDataPtr, float a_MaxClamp, float a_Degamma, float a_Scale) - { - //since input is being modified, terminate any active filtering threads - TerminateActiveThreads(); - - m_InputSurface[a_FaceIdx].SetImageDataClampDegammaScale( a_SrcType, a_SrcNumChannels, a_SrcPitch, - a_SrcDataPtr, a_MaxClamp, a_Degamma, a_Scale ); - } - - - //-------------------------------------------------------------------------------------- - //Copy and convert cube map face data from this object into an external image/surface - // - // a_FaceIdx = a value 0 to 5 speciying which face to copy into (one of the CP_FACE_? ) - // a_Level = mip level to copy into - // a_DstType = data type of image to copy to (one of the CP_TYPE_? types) - // a_DstNumChannels = number of channels of the image to copy to (usually 1 to 4) - // a_DstPitch = number of bytes per row of the dest image to copy to - // a_DstDataPtr = pointer to the image data to copy to - // a_Scale = scale to apply to pixel values (in linear space) before gamma for output - // a_Gamma = gamma level to apply to pixels after scaling - //-------------------------------------------------------------------------------------- - void CCubeMapProcessor::GetInputFaceData(int32 a_FaceIdx, int32 a_DstType, int32 a_DstNumChannels, - int32 a_DstPitch, void *a_DstDataPtr, float a_Scale, float a_Gamma) - { - m_InputSurface[a_FaceIdx].GetImageDataScaleGamma( a_DstType, a_DstNumChannels, a_DstPitch, - a_DstDataPtr, a_Scale, a_Gamma ); - } - - - //-------------------------------------------------------------------------------------- - //ChannelSwapInputFaceData - // swizzle data in first 4 channels for input faces - // - //-------------------------------------------------------------------------------------- - void CCubeMapProcessor::ChannelSwapInputFaceData(int32 a_Channel0Src, int32 a_Channel1Src, - int32 a_Channel2Src, int32 a_Channel3Src ) - { - int32 iFace, u, v, k; - int32 size; - CP_ITYPE texelData[4]; - int32 channelSrcArray[4]; - - //since input is being modified, terminate any active filtering threads - TerminateActiveThreads(); - - size = m_InputSize; - - channelSrcArray[0] = a_Channel0Src; - channelSrcArray[1] = a_Channel1Src; - channelSrcArray[2] = a_Channel2Src; - channelSrcArray[3] = a_Channel3Src; - - //Iterate over faces for input images - for(iFace=0; iFace<6; iFace++) - { - for(v=0; v> 16u); - bits = ((bits & 0x55555555u) << 1u) | ((bits & 0xAAAAAAAAu) >> 1u); - bits = ((bits & 0x33333333u) << 2u) | ((bits & 0xCCCCCCCCu) >> 2u); - bits = ((bits & 0x0F0F0F0Fu) << 4u) | ((bits & 0xF0F0F0F0u) >> 4u); - bits = ((bits & 0x00FF00FFu) << 8u) | ((bits & 0xFF00FF00u) >> 8u); - - return float(bits) * 2.3283064365386963e-10; // float(bits) * 2^-32 - } - - inline void HammersleySequence(uint32 sampleIndex, uint32 sampleCount, float* vXi) - { - vXi[0] = float(sampleIndex) / float(sampleCount); - vXi[1] = RadicalInverse2(sampleIndex); - } - - void ImportanceSampleGGX(float* vXi, float roughness, float* vNormal, float* vOut) - { - float phi = 2 * CP_PI * vXi[0]; - float cosTheta = sqrtf((1 - vXi[1]) / ( 1 + (roughness * roughness - 1) * vXi[1])); - float sinTheta = sqrtf(1 - cosTheta * cosTheta); - - float vH[3]; - vH[0] = sinTheta * cosf(phi); - vH[1] = sinTheta * sinf(phi); - vH[2] = cosTheta; - - float vUpVectorX[3] = {1, 0, 0}; - float vUpVectorZ[3] = {0, 0, 1}; - float vTangentX[3]; - float vTangentY[3]; - float vTempVec[3]; - - // Build local frame - VM_XPROD3(vTempVec, fabs(vNormal[2]) < 0.999f ? vUpVectorZ : vUpVectorX, vNormal); - VM_NORM3(vTangentX, vTempVec); - VM_XPROD3(vTangentY, vNormal, vTangentX); - - // Convert from tangent to world space - vOut[0] = vTangentX[0] * vH[0] + vTangentY[0] * vH[1] + vNormal[0] * vH[2]; - vOut[1] = vTangentX[1] * vH[0] + vTangentY[1] * vH[1] + vNormal[1] * vH[2]; - vOut[2] = vTangentX[2] * vH[0] + vTangentY[2] * vH[1] + vNormal[2] * vH[2]; - } - - - void CCubeMapProcessor::FilterCubeSurfacesGGX(CImageSurface *a_SrcCubeMap, CImageSurface *a_DstCubeMap, int32 a_SampleCount, float a_Roughness, - int32 a_FaceIdxStart, int32 a_FaceIdxEnd, int32 a_ThreadIdx) - { - const uint32 numChannels = VM_MIN(m_NumChannels, 4); - const int32 dstSize = a_DstCubeMap[0].m_Width; - - //thread progress - m_ThreadProgress[a_ThreadIdx].m_StartFace = a_FaceIdxStart; - m_ThreadProgress[a_ThreadIdx].m_EndFace = a_FaceIdxEnd; - - //process required faces - for(int32 iCubeFace = a_FaceIdxStart; iCubeFace <= a_FaceIdxEnd && !m_shutdownWorkerThreadSignal; iCubeFace++) - { - //iterate over dst cube map face texel - for(int32 v = 0; v < dstSize && !m_shutdownWorkerThreadSignal; v++) - { - CP_ITYPE *texelPtr = a_DstCubeMap[iCubeFace].m_ImgData + v * a_DstCubeMap[iCubeFace].m_NumChannels * dstSize; - - m_ThreadProgress[a_ThreadIdx].m_CurrentFace = iCubeFace; - m_ThreadProgress[a_ThreadIdx].m_CurrentRow = v; - - for (int32 u = 0; u < dstSize && !m_shutdownWorkerThreadSignal; u++) - { - float color[4] = { 0 }; - float totalWeight = 0; - float vH[3]; - float vL[3]; - - // Assume normal and view vector to be vCenterTapDir - float vCenterTapDir[3]; - TexelCoordToVect(iCubeFace, (float)u, (float)v, dstSize, vCenterTapDir); - - for (uint32 i = 0; i < (uint32)a_SampleCount && !m_shutdownWorkerThreadSignal; i++) - { - float vXi[2]; - HammersleySequence(i, a_SampleCount, vXi); - ImportanceSampleGGX(vXi, a_Roughness, vCenterTapDir, vH); - - float fVdotH = VM_DOTPROD3(vCenterTapDir, vH); - vL[0] = 2 * fVdotH * vH[0] - vCenterTapDir[0]; - vL[1] = 2 * fVdotH * vH[1] - vCenterTapDir[1]; - vL[2] = 2 * fVdotH * vH[2] - vCenterTapDir[2]; - - float fNdotL = VM_DOTPROD3(vCenterTapDir, vL); - if (fNdotL > 0) - { - CP_ITYPE *sourceTexel = GetCubeMapTexelPtr(vL, a_SrcCubeMap); - for (uint32 k = 0; k < numChannels; k++) - { - color[k] += sourceTexel[k] * fNdotL; - } - - totalWeight += fNdotL; - } - } - - for (uint32 k = 0; k < numChannels; k++) - { - texelPtr[k] = color[k] / totalWeight; - } - - texelPtr += a_DstCubeMap[iCubeFace].m_NumChannels; - } - } - } - } - - - void CCubeMapProcessor::FilterCubeMapMipChain(float a_BaseFilterAngle, float a_InitialMipAngle, float a_MipAnglePerLevelScale, - int32 a_FilterType, int32 a_FixupType, int32 a_FixupWidth, bool a_bUseSolidAngle, float a_GlossScale, float a_GlossBias, - int32 a_SampleCountGGX) - { - int32 i; - float coneAngle; - - if(a_FilterType == CP_FILTER_TYPE_COSINE_POWER || a_FilterType == CP_FILTER_TYPE_GGX) - { - // Don't filter top mipmap - a_BaseFilterAngle = 0; - } - - //Build filter lookup tables based on the source miplevel size - PrecomputeFilterLookupTables(a_FilterType, m_InputSurface[0].m_Width, a_BaseFilterAngle); - - //initialize thread progress - m_ThreadProgress[0].m_CurrentMipLevel = 0; - m_ThreadProgress[0].m_CurrentRow = 0; - m_ThreadProgress[0].m_CurrentFace = 0; - - //Filter the top mip level (initial filtering used for diffuse or blurred specular lighting ) - FilterCubeSurfaces(m_InputSurface, m_OutputSurface[0], a_BaseFilterAngle, a_FilterType, a_bUseSolidAngle, - 0, //start at face 0 - 5, //end at face 5 - 0); //thread 0 is processing - - m_ThreadProgress[0].m_CurrentMipLevel = 1; - m_ThreadProgress[0].m_CurrentRow = 0; - m_ThreadProgress[0].m_CurrentFace = 0; - - - FixupCubeEdges(m_OutputSurface[0], a_FixupType, a_FixupWidth); - - //Cone angle start (for generating subsequent mip levels) - coneAngle = a_InitialMipAngle; - - //generate subsequent mip levels - for(i=0; i<(m_NumMipLevels-1) && !m_shutdownWorkerThreadSignal; i++) - { - m_ThreadProgress[0].m_CurrentMipLevel = i+1; - m_ThreadProgress[0].m_CurrentRow = 0; - m_ThreadProgress[0].m_CurrentFace = 0; - - CImageSurface* srcCubeImage = m_OutputSurface[i]; - - if (a_FilterType == CP_FILTER_TYPE_GGX) - { - uint32 numUsableMips = m_NumMipLevels - 2; // Lowest used mip is 4x4 - float smoothness = VM_MAX(1.0f - (float)(i + 1) / (float)(numUsableMips - 1), 0.0f); - - // Convert smoothness to roughness (needs to match shader code) - float roughness = (1.0f - smoothness) * (1.0f - smoothness); - - FilterCubeSurfacesGGX(srcCubeImage, m_OutputSurface[i+1], a_SampleCountGGX, roughness, - 0, //start at face 0 - 5, //end at face 5 - 0 //thread 0 is processing - ); - } - else - { - float specPow = 1.0f; - - if(a_FilterType == CP_FILTER_TYPE_COSINE_POWER) - { - uint32 numMipsForGloss = m_NumMipLevels - 2; // Lowest used mip is 4x4 - float gloss = VM_MAX(1.0f - (float)(i + 1) / (float)(numMipsForGloss - 1), 0.0f); - - // Compute specular power (this must match shader code) - specPow = pow(2.0f, a_GlossScale * gloss + a_GlossBias); - - // Blinn to Phong approximation: (R.E)^p == (N.H)^(4*p) - specPow /= 4.0f; - - coneAngle = ComputeBaseFilterAngle(specPow); - srcCubeImage = m_InputSurface; - } - - //Build filter lookup tables based on the source miplevel size - PrecomputeFilterLookupTables(a_FilterType, srcCubeImage->m_Width, coneAngle); - - //filter cube surfaces - FilterCubeSurfaces(srcCubeImage, m_OutputSurface[i+1], coneAngle, a_FilterType, a_bUseSolidAngle, - 0, //start at face 0 - 5, //end at face 5 - 0, //thread 0 is processing - specPow); - } - - m_ThreadProgress[0].m_CurrentMipLevel = i+2; - m_ThreadProgress[0].m_CurrentRow = 0; - m_ThreadProgress[0].m_CurrentFace = 0; - - FixupCubeEdges(m_OutputSurface[i+1], a_FixupType, a_FixupWidth); - - coneAngle = coneAngle * a_MipAnglePerLevelScale; - } - - m_Status = CP_STATUS_FILTER_COMPLETED; - } - - - //-------------------------------------------------------------------------------------- - //Builds the following lookup tables prior to filtering: - // -normalizer cube map - // -tap weight lookup table - // - //-------------------------------------------------------------------------------------- - void CCubeMapProcessor::PrecomputeFilterLookupTables(uint32 a_FilterType, int32 a_SrcCubeMapWidth, float a_FilterConeAngle) - { - float srcTexelAngle; - int32 iCubeFace; - - //angle about center tap that defines filter cone - float filterAngle; - - //min angle a src texel can cover (in degrees) - srcTexelAngle = (180.0f / (float)CP_PI) * atan2f(1.0f, (float)a_SrcCubeMapWidth); - - //filter angle is 1/2 the cone angle - filterAngle = a_FilterConeAngle / 2.0f; - - //ensure filter angle is larger than a texel - if(filterAngle < srcTexelAngle) - { - filterAngle = srcTexelAngle; - } - - //ensure filter cone is always smaller than the hemisphere - if(filterAngle > 90.0f) - { - filterAngle = 90.0f; - } - - //build lookup table for tap weights based on angle between current tap and center tap - BuildAngleWeightLUT(a_SrcCubeMapWidth * 2, a_FilterType, filterAngle); - - //clear pre-existing normalizer cube map - for(iCubeFace=0; iCubeFace<6; iCubeFace++) - { - m_NormCubeMap[iCubeFace].Clear(); - } - - //Normalized vectors per cubeface and per-texel solid angle - BuildNormalizerSolidAngleCubemap(a_SrcCubeMapWidth, m_NormCubeMap); - - } - - //-------------------------------------------------------------------------------------- - //The key to the speed of these filtering routines is to quickly define a per-face - // bounding box of pixels which enclose all the taps in the filter kernel efficiently. - // Later these pixels are selectively processed based on their dot products to see if - // they reside within the filtering cone. - // - //This is done by computing the smallest per-texel angle to get a conservative estimate - // of the number of texels needed to be covered in width and height order to filter the - // region. the bounding box for the center taps face is defined first, and if the - // filtereing region bleeds onto the other faces, bounding boxes for the other faces are - // defined next - //-------------------------------------------------------------------------------------- - void CCubeMapProcessor::FilterCubeSurfaces(CImageSurface *a_SrcCubeMap, CImageSurface *a_DstCubeMap, - float a_FilterConeAngle, int32 a_FilterType, bool a_bUseSolidAngle, int32 a_FaceIdxStart, - int32 a_FaceIdxEnd, int32 a_ThreadIdx, float a_SpecularPower) - { - const int32 srcSize = a_SrcCubeMap[0].m_Width; - const int32 dstSize = a_DstCubeMap[0].m_Width; - - //min angle a src texel can cover (in degrees) - const float srcTexelAngle = (180.0f / (float)CP_PI) * atan2f(1.0f, (float)srcSize); - - //angle about center tap to define filter cone - float filterAngle; - - //filter angle is 1/2 the cone angle - filterAngle = a_FilterConeAngle / 2.0f; - - //ensure filter angle is larger than a texel - if(filterAngle < srcTexelAngle) - { - filterAngle = srcTexelAngle; - } - - //ensure filter cone is always smaller than the hemisphere - if(filterAngle > 90.0f) - { - filterAngle = 90.0f; - } - - //the maximum number of texels in 1D the filter cone angle will cover - // used to determine bounding box size for filter extents - //ensure conservative region always covers at least one texel - const int32 filterSize = AZ::GetMax((int32)ceil(filterAngle / srcTexelAngle), 1); - - //dotProdThresh threshold based on cone angle to determine whether or not taps - // reside within the cone angle - const float dotProdThresh = cosf( ((float)CP_PI / 180.0f) * filterAngle ); - - //thread progress - m_ThreadProgress[a_ThreadIdx].m_StartFace = a_FaceIdxStart; - m_ThreadProgress[a_ThreadIdx].m_EndFace = a_FaceIdxEnd; - - //process required faces - for(int32 iCubeFace = a_FaceIdxStart; iCubeFace <= a_FaceIdxEnd && !m_shutdownWorkerThreadSignal; iCubeFace++) - { - //iterate over dst cube map face texel - for(int32 v = 0; v < dstSize && !m_shutdownWorkerThreadSignal; v++) - { - CP_ITYPE *texelPtr = a_DstCubeMap[iCubeFace].m_ImgData + v * a_DstCubeMap[iCubeFace].m_NumChannels * dstSize; - - m_ThreadProgress[a_ThreadIdx].m_CurrentFace = iCubeFace; - m_ThreadProgress[a_ThreadIdx].m_CurrentRow = v; - - for(int32 u=0; u 0.0f) - { - totalMipComputation = pow(m_InputSize * m_BaseFilterAngle , 2.0f) * (m_OutputSize * m_OutputSize); - } - else - { - totalMipComputation = pow(m_InputSize * 0.01f , 2.0f) * (m_OutputSize * m_OutputSize); - } - - progressMipComputation = 0.0f; - if(a_FilterProgress->m_CurrentMipLevel > 0) - { - progressMipComputation = totalMipComputation; - } - - //filtering angle for this miplevel - filterAngle = m_InitialMipAngle; - dstSize = m_OutputSize; - - //computation for entire base mip level (if current level is base level) - if(a_FilterProgress->m_CurrentMipLevel == 0) - { - currentMipComputation = totalMipComputation; - currentMipSize = dstSize; - } - - //compuatation to generate subsequent mip levels - for(i=1; i 180) - { - filterAngle = 180; - } - - //note src size is dstSize*2 since miplevels are generated from the subsequent level - computation = pow(dstSize * 2 * filterAngle, 2.0f) * (dstSize * dstSize); - - totalMipComputation += computation; - - //accumulate computation for completed mip levels - if(a_FilterProgress->m_CurrentMipLevel > i) - { - progressMipComputation = totalMipComputation; - } - - //computation for entire current mip level - if(a_FilterProgress->m_CurrentMipLevel == i) - { - currentMipComputation = computation; - currentMipSize = dstSize; - } - } - - //fraction of compuation time processing the entire current mip level will take - currentMipComputation /= totalMipComputation; - progressMipComputation /= totalMipComputation; - - progressFaceComputation = currentMipComputation * - (float)(a_FilterProgress->m_CurrentFace - a_FilterProgress->m_StartFace) / - (float)(1 + a_FilterProgress->m_EndFace - a_FilterProgress->m_StartFace); - - currentFaceComputation = currentMipComputation * - 1.0f / - (1 + a_FilterProgress->m_EndFace - a_FilterProgress->m_StartFace); - - progressRowComputation = currentFaceComputation * - ((float)a_FilterProgress->m_CurrentRow / (float)currentMipSize); - - //progress completed - a_FilterProgress->m_FractionCompleted = - progressMipComputation + - progressFaceComputation + - progressRowComputation; - - - if( a_FilterProgress->m_CurrentFace < 0) - { - a_FilterProgress->m_CurrentFace = 0; - } - - if( a_FilterProgress->m_CurrentMipLevel < 0) - { - a_FilterProgress->m_CurrentMipLevel = 0; - } - - if( a_FilterProgress->m_CurrentRow < 0) - { - a_FilterProgress->m_CurrentRow = 0; - } - - } - - - //-------------------------------------------------------------------------------------- - // Return string describing the current status of the cubemap processing threads - // - //-------------------------------------------------------------------------------------- - WCHAR *CCubeMapProcessor::GetFilterProgressString(void) - { - WCHAR threadProgressString[CP_MAX_FILTER_THREADS][CP_MAX_PROGRESS_STRING]; - int32 i; - - for(i=0; i -#include -#include -#include - -#include "VectorMacros.h" -#include "CBBoxInt32.h" -#include "CImageSurface.h" - -//has routines for saving .rgbe files -#define CG_RGBE_SUPPORT - - -#ifndef WCHAR -#define WCHAR wchar_t -#endif //WCHAR - - -//used to index cube faces -#define CP_FACE_X_POS 0 -#define CP_FACE_X_NEG 1 -#define CP_FACE_Y_POS 2 -#define CP_FACE_Y_NEG 3 -#define CP_FACE_Z_POS 4 -#define CP_FACE_Z_NEG 5 - - -//used to index image edges -// NOTE.. the actual number corresponding to the edge is important -// do not change these, or the code will break -// -// CP_EDGE_LEFT is u = 0 -// CP_EDGE_RIGHT is u = width-1 -// CP_EDGE_TOP is v = 0 -// CP_EDGE_BOTTOM is v = height-1 -#define CP_EDGE_LEFT 0 -#define CP_EDGE_RIGHT 1 -#define CP_EDGE_TOP 2 -#define CP_EDGE_BOTTOM 3 - -//corners of CUBE map (P or N specifys if it corresponds to the -// positive or negative direction each of X, Y, and Z -#define CP_CORNER_NNN 0 -#define CP_CORNER_NNP 1 -#define CP_CORNER_NPN 2 -#define CP_CORNER_NPP 3 -#define CP_CORNER_PNN 4 -#define CP_CORNER_PNP 5 -#define CP_CORNER_PPN 6 -#define CP_CORNER_PPP 7 - -//data types processed by cube map processor -// note that UNORM data types use the full range -// of the unsigned integer to represent the range [0, 1] inclusive -// the float16 datatype is stored as D3Ds S10E5 representation -#define CP_VAL_UNORM8 0 -#define CP_VAL_UNORM8_BGRA 1 -#define CP_VAL_UNORM16 10 -#define CP_VAL_FLOAT16 20 -#define CP_VAL_FLOAT32 30 - - -//return codes for thread execution -// warning STILL_ACTIVE maps to 259, so the number 259 is reserved in this case -// and should only be used for STILL_ACTIVE -#define CP_THREAD_COMPLETED 0 -#define CP_THREAD_TERMINATED 15 -#define CP_THREAD_STILL_ACTIVE STILL_ACTIVE - -#define CP_MAX_PROGRESS_STRING 1024 - -// Type of data used internally by cube map processor -// just in case for any reason more preecision is needed, -// this type can be changed down the road -#define CP_ITYPE float - -// Filter type -#define CP_FILTER_TYPE_DISC 0 -#define CP_FILTER_TYPE_CONE 1 -#define CP_FILTER_TYPE_COSINE 2 -#define CP_FILTER_TYPE_ANGULAR_GAUSSIAN 3 -#define CP_FILTER_TYPE_COSINE_POWER 4 -#define CP_FILTER_TYPE_GGX 5 - - -// Edge fixup type (how to perform smoothing near edge region) -#define CP_FIXUP_NONE 0 -#define CP_FIXUP_PULL_LINEAR 1 -#define CP_FIXUP_PULL_HERMITE 2 -#define CP_FIXUP_AVERAGE_LINEAR 3 -#define CP_FIXUP_AVERAGE_HERMITE 4 - - -// Max potential cubemap size is limited to 65k (2^16 texels) on a side -#define CP_MAX_MIPLEVELS 16 - -//maximum number of threads running for cubemap processor is 2 -#define CP_MAX_FILTER_THREADS 2 - -//initial number of filtering threads for cubemap processor -#define CP_INITIAL_NUM_FILTER_THREADS 1 - - -//current status of cubemap processor -#define CP_STATUS_READY 0 -#define CP_STATUS_PROCESSING 1 -#define CP_STATUS_FILTER_TERMINATED 2 -#define CP_STATUS_FILTER_COMPLETED 3 - - -#define CP_SAFE_DELETE(p) { if(p) { delete (p); (p)=NULL; } } -#define CP_SAFE_DELETE_ARRAY(p) { if(p) { delete[] (p); (p)=NULL; } } - -namespace ImageProcessing -{ - - - //information about cube maps neighboring face after traversing - // across an edge - struct CPCubeMapNeighbor - { - uint8 m_Face; //index of neighboring face - uint8 m_Edge; //edge in neighboring face that abuts this face - }; - - - //-------------------------------------------------------------------------------------------------- - //structure used to store current progress of the filtering - //-------------------------------------------------------------------------------------------------- - struct SFilterProgress - { - //status of current cube map processing - int32 m_CurrentFace; - int32 m_CurrentRow; - int32 m_CurrentMipLevel; - - int32 m_StartFace; - int32 m_EndFace; - - float m_FractionCompleted; //Approximate fraction of work completed for this thread - }; - - - //-------------------------------------------------------------------------------------------------- - //structure used to pass filtering parameters for Thread 0 - //-------------------------------------------------------------------------------------------------- - struct SThreadOptionsThread0 - { - class CCubeMapProcessor *m_cmProc; - float m_BaseFilterAngle; - float m_InitialMipAngle; - float m_MipAnglePerLevelScale; - float m_GlossScale; - float m_GlossBias; - int32 m_FilterType; - int32 m_FixupType; - int32 m_FixupWidth; - int32 m_SampleCountGGX; - bool m_bUseSolidAngle; - }; - - - //-------------------------------------------------------------------------------------------------- - //structure used to pass filtering parameters to the process for Thread 1 (if used) - //-------------------------------------------------------------------------------------------------- - struct SThreadOptionsThread1 - { - class CCubeMapProcessor *m_cmProc; - CImageSurface *m_SrcCubeMap; - CImageSurface *m_DstCubeMap; - float m_FilterConeAngle; - int32 m_FilterType; - bool m_bUseSolidAngle; - int32 m_FaceIdxStart; - int32 m_FaceIdxEnd; - int32 m_ThreadIdx; - }; - - - //-------------------------------------------------------------------------------------------------- - //Class to filter, perform edge fixup, and build a mip chain for a cubemap - //-------------------------------------------------------------------------------------------------- - class CCubeMapProcessor - { - public: - - //cubemap processor status - int32 m_Status; - - //information about threads actively processing the cubemap - int32 m_NumFilterThreads; - bool m_bThreadInitialized[CP_MAX_FILTER_THREADS]; - - AZStd::thread m_ThreadHandle[CP_MAX_FILTER_THREADS]; - - AZ::u32 m_ThreadID[CP_MAX_FILTER_THREADS]; - SFilterProgress m_ThreadProgress[CP_MAX_FILTER_THREADS]; - WCHAR m_ProgressString[CP_MAX_PROGRESS_STRING]; - - //filtering parameters last used for filtering - float m_BaseFilterAngle; - float m_InitialMipAngle; - float m_MipAnglePerLevelScale; - - int32 m_InputSize; //input cubemap size (e.g. face width and height of topmost mip level) - int32 m_OutputSize; //output cubemap size (e.g. face width and height of topmost mip level) - int32 m_NumMipLevels; //number of output mip levels - int32 m_NumChannels; //number of channels in cube map processor - - CP_ITYPE *m_FilterLUT; //filter weight lookup table (scale dot product 0-1 range to index into it) - int32 m_NumFilterLUTEntries; //number of filter lookup table entries - - CImageSurface m_NormCubeMap[6]; //normalizer cube map and solid angle lookup table - - CImageSurface m_InputSurface[6]; //input faces for topmost mip level - - CImageSurface m_OutputSurface[CP_MAX_MIPLEVELS][6]; //output faces for all mip levels - - private: - //========================================================================================================== - //BuildNormalizerCubemap(int32 a_Size, CImageSurface *a_Surface ); - // Builds a normalizer cubemap of size a_Size. This routine deallocates the CImageSurfaces passed - // into the the function and reallocates them with the correct size and 3 channels to store the - // normalized vector for each texel. - // - // a_Size [in] size of normalizer cubemap - // a_Surface [out] Pointer to array of 6 CImageSurfaces where normalizer cube faces will be stored - // - //========================================================================================================== - void BuildNormalizerCubemap(int32 a_Size, CImageSurface *a_Surface); - - //========================================================================================================== - //void BuildNormalizerSolidAngleCubemap(int32 a_Size, CImageSurface *a_Surface ); - // Builds a normalizer|solid angle cubemap of size a_Size. This routine deallocates the CImageSurfaces - // passed into the the function and reallocates them with the correct size and 4 channels to store the - // normalized vector, and solid angle for each texel. - // - // a_Size [in] - // a_Surface [out] Pointer to array of 6 CImageSurfaces where normalizer cube faces will be stored - // - //========================================================================================================== - void BuildNormalizerSolidAngleCubemap(int32 a_Size, CImageSurface *a_Surface); - - //========================================================================================================== - //Clears filter extent bounding boxes for each face of the cubemap - // - // a_FilterExtents [in] Array of 6 bounding boxes (corresponding to the 6 cubemap faces) to clear - //========================================================================================================== - void ClearFilterExtents(CBBoxInt32 *a_FilterExtents); - - //========================================================================================================== - //void DetermineFilterExtents(float *a_CenterTapDir, int32 a_SrcSize, int32 a_BBoxSize, - // CBBoxInt32 *a_FilterExtents); - // - //Determines bounding boxes for each cube face for a single kernels angular extent - // a_CenterTapDir [in] Vector of 3 float32s specifying the center tap direction - // a_SrcSize [in] Source cubemap size (for the miplevel used as input to the filtering) - // a_BBoxSize [in] Maximum length in texels of the bbox extent derived from the filtering - // cone angle - // a_FilterExtents [out] Array of 6 bounding boxes (corresponding to the 6 cubemap faces) to clear - //========================================================================================================== - void DetermineFilterExtents(float *a_CenterTapDir, int32 a_SrcSize, int32 a_BBoxSize, CBBoxInt32 *a_FilterExtents); - - //========================================================================================================== - //void ProcessFilterExtents(float *a_CenterTapDir, float a_DotProdThresh, CBBoxInt32 *a_FilterExtents, - // CImageSurface *a_NormCubeMap, CImageSurface *a_SrcCubeMap, CP_ITYPE *a_DstVal, uint32 a_FilterType, - // bool a_bUseSolidAngle ); - // - //Processes all the texels within the bounding boxes in order to accumulate all the weighted taps to - // compute a single fitered texel value. - // - //a_CenterTapDir [in] Center tap directions - //a_DotProdThresh [in] Threshhold on dot product between center tap and - //a_FilterExtents [in] array of 6 bounding boxes describing rough filter extents for each face - //a_NormCubeMap [in] normalizer|solid angle cubemap - //a_SrcCubeMap [in] array of 6 faces comprising the miplevel of the source cubemap the filter is - // generated from - //a_DstVal [out] resulting filtered texel color - //a_FilterType [in] filter type: Choose one of the following options: CP_FILTER_TYPE_DISC, - // CP_FILTER_TYPE_CONE, CP_FILTER_TYPE_COSINE, CP_FILTER_TYPE_ANGULAR_GAUSSIAN - //a_bUseSolidAngle [in] Set this to true in order to incorporate the solid angle subtended - // each texel in the filter kernel in the filtering. - // - //========================================================================================================== - void ProcessFilterExtents(float *a_CenterTapDir, float a_DotProdThresh, CBBoxInt32 *a_FilterExtents, - CImageSurface *a_NormCubeMap, CImageSurface *a_SrcCubeMap, CP_ITYPE *a_DstVal, uint32 a_FilterType, - bool a_bUseSolidAngle, float a_SpecularPower); - - //========================================================================================================== - //void FixupCubeEdges(CImageSurface *a_CubeMap, int32 a_FixupType, int32 a_FixupWidth); - // - //Apply edge fixup to a cubemap mip level. - // - //a_CubeMap [in/out] Array of 6 images comprising cubemap miplevel to apply edge fixup to. - //a_FixupType [in] Specifies the technique used for edge fixup. Choose one of the following, - // CP_FIXUP_NONE, CP_FIXUP_PULL_LINEAR, CP_FIXUP_PULL_HERMITE, CP_FIXUP_AVERAGE_LINEAR, - // CP_FIXUP_AVERAGE_HERMITE - //a_FixupWidth [in] Fixup width in texels - // - //========================================================================================================== - void FixupCubeEdges(CImageSurface *a_CubeMap, int32 a_FixupType, int32 a_FixupWidth); - - //========================================================================================================== - //void BuildAngleWeightLUT(int32 a_NumFilterLUTEntries, int32 a_FilterType, float a_FilterAngle); - // - // Builds filter weight lookup table in order to quickly evaluate the weight of a particular texel - // for the Cone and Angular Gaussian fiter types. This lookup table is quickly indexed using the - // same dot product between the center tap and current texel that is used to determine whether a - // texel is inside or outside the filtering kernel. - // - //a_NumFilterLUTEntries [in] Number of entries in filter weight lookup table - //a_FilterType [in] Filter type - //a_FilterAngle [in] Filtering half cone angle - //========================================================================================================== - void BuildAngleWeightLUT(int32 a_NumFilterLUTEntries, int32 a_FilterType, float a_FilterAngle); - - //========================================================================================================== - //void PrecomputeFilterLookupTables(uint32 a_FilterType, int32 a_SrcCubeMapWidth, float a_FilterConeAngle); - // - // Builds the following lookup tables prior to filtering: - // -normalizer cube map - // -filter weight lookup table - // - //a_FilterType [in] Filter type - //a_SrcCubeMapWidth [in] source cubemap size - //a_FilterConeAngle [in] Filtering half cone angle - //========================================================================================================== - void PrecomputeFilterLookupTables(uint32 a_FilterType, int32 a_SrcCubeMapWidth, float a_FilterConeAngle); - - //========================================================================================================== - //void EstimateFilterThreadProgress(SFilterProgress *a_FilterProgress); - // - // Estimates percentage complete for a filtering thread for the current tap that is being filtered - // - //a_FilterProgress [in/out] Information about the filtereing thread's current position, and range of faces - // that it will process. - //========================================================================================================== - void EstimateFilterThreadProgress(SFilterProgress *a_FilterProgress); - - public: - //========================================================================================================== - //note that these functions are only public so that they can be called from within the global scope - // from the thread starting point functions. These should not be called by any other functions external - // to the class. - //========================================================================================================== - void FilterCubeMapMipChain(float a_BaseFilterAngle, float a_InitialMipAngle, float a_MipAnglePerLevelScale, - int32 a_FilterType, int32 a_FixupType, int32 a_FixupWidth, bool a_bUseSolidAngle, float a_GlossScale, float a_GlossBias, - int32 a_SampleCountGGX); - void FilterCubeSurfaces(CImageSurface *a_SrcCubeMap, CImageSurface *a_DstCubeMap, float a_FilterConeAngle, - int32 a_FilterType, bool a_bUseSolidAngle, int32 a_FaceIdxStart, int32 a_FaceIdxEnd, int32 aThreadIdx, - float a_SpecularPower = 1.0f); - void FilterCubeSurfacesGGX(CImageSurface *a_SrcCubeMap, CImageSurface *a_DstCubeMap, int32 a_SampleCount, float a_Roughness, - int32 a_FaceIdxStart, int32 a_FaceIdxEnd, int32 aThreadIdx); - - public: - CCubeMapProcessor(void); - ~CCubeMapProcessor(); - - //========================================================================================================== - // void Init(int32 a_InputSize, int32 a_OutputSize, int32 a_NumMipLevels, int32 a_NumChannels); - // - // Initializes cube map processor class - // - // a_InputSize [in] Size of the input cubemap - // a_OutputSize [in] Size of the input cubemap - // a_NumMipLevels [in] Number of miplevels in the output cubemap - // a_NumChannels [in] Number of color channels (internally) in the input and output cubemap - //========================================================================================================== - void Init(int32 a_InputSize, int32 a_OutputSize, int32 a_NumMipLevels, int32 a_NumChannels); - - - //========================================================================================================== - // void GetInputFaceData(int32 a_FaceIdx, int32 a_DstType, int32 a_DstNumChannels, int32 a_DstPitch, - // void *a_DstDataPtr, float a_Scale, float a_Gamma); - // - // Copies image data from the input cube map into a destination image. These routine describe the output - // image layout using a pitch and a pointer so that the image can be copied from a subrect of a locked - // D3D surface easily. Note that when reading out the image data, the intensity scale is applied first, - // and then degamma. - // - // a_FaceIdx [in] Index (0-5) of the input cubemap cube face to read the image data from. - // a_DstType [in] Data type for the image data being copied out the input cube map. - // choose one of the following: CP_VAL_UNORM8, CP_VAL_UNORM8_BGRA, CP_VAL_UNORM16 - // CP_VAL_FLOAT16, CP_VAL_FLOAT32. - // a_DstNumChannels [in] Number of channels in the destination image. - // a_DstPitch [in] Pitch in bytes of the destination image. - // a_DstDataPtr [in] Pointer to the top-left pixel in the destination image. - // a_Scale [in] Scale factor to apply to intensities. - // a_Gamma [in] Degamma to apply to intensities. - // - //========================================================================================================== - void GetInputFaceData(int32 a_FaceIdx, int32 a_DstType, int32 a_DstNumChannels, int32 a_DstPitch, - void *a_DstDataPtr, float a_Scale, float a_Gamma); - - - //========================================================================================================== - // void SetInputFaceData(int32 a_FaceIdx, int32 a_SrcType, int32 a_SrcNumChannels, int32 a_SrcPitch, - // void *a_SrcDataPtr, float a_MaxClamp, float a_Scale, float a_Gamma ); - // - // Copies image data from a source image into one of the faces in the input cubemap in the cubemap. - // processor. These routines describe the output image layout using a pitch and a pointer so that the image - // can be copied from a subrect of a locked D3D surface easily. Note that the clamping is applied first, - // followed by the scale and then gamma. - // - // a_FaceIdx [in] Index (0-5) of the input cubemap cube face to write the image data into - // a_SrcType [in] Data type for the image data being copied into the cube map processor. - // choose one of the following: CP_VAL_UNORM8, CP_VAL_UNORM8_BGRA, CP_VAL_UNORM16 - // CP_VAL_FLOAT16, CP_VAL_FLOAT32. - // a_SrcNumChannels [in] Number of channels in the source image. - // a_SrcPitch [in] Pitch in bytes of the source image. - // a_SrcDataPtr [in] Pointer to the top-left pixel in the source image. - // a_MaxClamp [in] Max value to clamp the input intensity values to. - // a_Degamma [in] Degamma to apply to input intensities. - // a_Scale [in] Scale factor to apply to input intensities. - // - //========================================================================================================== - void SetInputFaceData(int32 a_FaceIdx, int32 a_SrcType, int32 a_SrcNumChannels, int32 a_SrcPitch, - void *a_SrcDataPtr, float a_MaxClamp, float a_Degamma, float a_Scale); - - - //========================================================================================================== - // void GetOutputFaceData(int32 a_FaceIdx, int32 a_Level, int32 a_DstType, int32 a_DstNumChannels, int32 a_DstPitch, - // void *a_DstDataPtr, float a_Scale, float a_Gamma ); - // - // a_FaceIdx [in] Index (0-5) of the output cubemap cube face to read the image data from. - // a_Level [in] Miplevel of the output cubemap to read from - // a_DstType [in] Data type for the image data being copied out the input cube map. - // choose one of the following: CP_VAL_UNORM8, CP_VAL_UNORM8_BGRA, CP_VAL_UNORM16 - // CP_VAL_FLOAT16, CP_VAL_FLOAT32 - // a_DstNumChannels [in] Number of channels in the destination image. - // a_DstPitch [in] Pitch in bytes of the destination image. - // a_DstDataPtr [in] Pointer to the top-left pixel in the destination image. - // a_Scale [in] Scale factor to apply to intensities. - // a_Gamma [in] Degamma to apply to intensities. - // - //========================================================================================================== - void GetOutputFaceData(int32 a_FaceIdx, int32 a_Level, int32 a_DstType, int32 a_DstNumChannels, int32 a_DstPitch, - void *a_DstDataPtr, float a_Scale, float a_Gamma); - - - //========================================================================================================== - //void InitiateFiltering(float a_BaseFilterAngle, float a_InitialMipAngle, float a_MipAnglePerLevelScale, - // int32 a_FilterType, int32 a_FixupType, int32 a_FixupWidth, bool a_bUseSolidAngle ); - // - // Starts filtering the cubemap. - // If the number of filter threads is zero, the function does not return until the filtering is complete - // If the number of filter threads is non-zero, a filtering thread (or multiple threads) are started and - // the function returns immediately, with the threads running in the background. - // - // The cube map filtereing is specified using a number of parameters: - // Filtering per miplevel is specified using 2D cone angle (in degrees) that - // indicates the region of the hemisphere to filter over for each tap. - // - // Note that the top mip level is also a filtered version of the original input images - // as well in order to create mip chains for diffuse environment illumination. - // The cone angle for the top level is specified by a_BaseAngle. This can be used to - // generate mipchains used to store the results of preintegration across the hemisphere. - // - // The angle for the subsequent levels of the mip chain are specified by their parents - // filtering angle and a per-level scale and bias - // newAngle = oldAngle * a_MipAnglePerLevelScale; - // - // a_BaseFilterAngle [in] Base filter angle - // a_InitialMipAngle [in] Mip angle used to generate the next level of the mip chain from the base level - // a_MipAnglePerLevelScale [in] Scale factor to iteratively apply to the filtering angle to filter subsequent - // mip-levels. - // a_FilterType [in] Specifies the filtering type for angular extent filtering. Choose one of the - // following options: CP_FILTER_TYPE_DISC, CP_FILTER_TYPE_CONE, - // CP_FILTER_TYPE_COSINE, CP_FILTER_TYPE_ANGULAR_GAUSSIAN - // a_FixupType [in] Specifies the technique used for edge fixup. Choose one of the following, - // CP_FIXUP_NONE, CP_FIXUP_PULL_LINEAR, CP_FIXUP_PULL_HERMITE, - // CP_FIXUP_AVERAGE_LINEAR, CP_FIXUP_AVERAGE_HERMITE - // a_FixupWidth [in] Width in texels of the fixup region. - // a_bUseSolidAngle [in] Set this to true in order to incorporate the solid angle subtended - // each texel in the filter kernel in the filtering. - //========================================================================================================== - void InitiateFiltering(float a_BaseFilterAngle, float a_InitialMipAngle, float a_MipAnglePerLevelScale, - int32 a_FilterType, int32 a_FixupType, int32 a_FixupWidth, bool a_bUseSolidAngle, - float a_GlossScale, float a_GlossBias, int32 a_SampleCountGGX); - - //========================================================================================================== - // void WriteMipLevelIntoAlpha(void) - // - // Encodes the miplevel in the alpha channel of the output cubemap. - // The miplevel is encoded as (miplevel * 16.0f / 255.0f) so that the miplevel has an exact encoding in an - // 8-bit or 16-bit UNORM representation. - // - //========================================================================================================== - void WriteMipLevelIntoAlpha(void); - - - //========================================================================================================== - // Horizontally flips all the faces in the input cubemap - // - //========================================================================================================== - void FlipInputCubemapFaces(void); - - //========================================================================================================== - // Horizontally flips all the faces in the output cubemap - // - //========================================================================================================== - void FlipOutputCubemapFaces(void); - - - //========================================================================================================== - // Allows for in-place color channel swapping of the input cubemap. This routine can be useful for - // converting RGBA format data to BGRA format data. - // - // a_Channel0Src [in] Index of the color channel used as the source for the new channel 0 - // a_Channel1Src [in] Index of the color channel used as the source for the new channel 1 - // a_Channel2Src [in] Index of the color channel used as the source for the new channel 0 - // a_Channel3Src [in] Index of the color channel used as the source for the new channel 1 - // - //========================================================================================================== - void ChannelSwapInputFaceData(int32 a_Channel0Src, int32 a_Channel1Src, int32 a_Channel2Src, int32 a_Channel3Src); - - - //========================================================================================================== - // Allows for in-place color channel swapping of the output cubemap. This routine can be useful for - // converting RGBA format data to BGRA format data. - // - // a_Channel0Src [in] Index of the color channel used as the source for the new channel 0 - // a_Channel1Src [in] Index of the color channel used as the source for the new channel 1 - // a_Channel2Src [in] Index of the color channel used as the source for the new channel 0 - // a_Channel3Src [in] Index of the color channel used as the source for the new channel 1 - //========================================================================================================== - void ChannelSwapOutputFaceData(int32 a_Channel0Src, int32 a_Channel1Src, int32 a_Channel2Src, int32 a_Channel3Src); - - - //========================================================================================================== - // Resets the current cubemap processor, and deallocates the input and output cubemaps. - // - // This function is automatically called by destructor. - //========================================================================================================== - void Clear(void); - - - //========================================================================================================== - // Terminates any active filtering threads. This stops the filtering of the current cubemap. - // - //========================================================================================================== - void TerminateActiveThreads(void); - - - //========================================================================================================== - // Gets the current filtering progress string - // - //========================================================================================================== - WCHAR *GetFilterProgressString(void); - - - //========================================================================================================== - // Checks to see if either of the filtering threads is active - // - //========================================================================================================== - bool IsFilterThreadActive(uint32 a_ThreadIdx); - - //========================================================================================================== - // Gets the current status of the cubemap processing threads. The possible return values and their - // associated meanings are: - // - // CP_STATUS_READY: The cubemap processor is currently ready to change settings, and to load a - // new input cubemap. - // CP_STATUS_PROCESSING: The cubemap processor is currently filtering a cubemap - // CP_STATUS_FILTER_TERMINATED: The cubemap processor was terminated before the filtering was completed. - // CP_STATUS_FILTER_COMPLETED: The cubemap processor fully completed filtering the cubemap. - // - //========================================================================================================== - int32 GetStatus(void); - - - //========================================================================================================== - // This signifies to the cubemap processor that you have acknowledged a - // CP_STATUS_FILTER_TERMINATED or CP_STATUS_FILTER_COMPLETED status code, and would like to - // reset the cubemap processor to CP_STATUS_READY. - //========================================================================================================== - void RefreshStatus(void); - - AZStd::atomic_bool m_shutdownWorkerThreadSignal; ///< Signals the worker threads to stop. - }; - -} // namespace ImageProcessing diff --git a/Gems/ImageProcessing/External/CubeMapGen/CImageSurface.cpp b/Gems/ImageProcessing/External/CubeMapGen/CImageSurface.cpp deleted file mode 100644 index 62daa2b4d7..0000000000 --- a/Gems/ImageProcessing/External/CubeMapGen/CImageSurface.cpp +++ /dev/null @@ -1,695 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ - -//-------------------------------------------------------------------------------------- -//CImageSurface -// Class for storing, manipulating, and copying image data to and from D3D Surfaces -// -//-------------------------------------------------------------------------------------- -// (C) 2005 ATI Research, Inc., All rights reserved. -//-------------------------------------------------------------------------------------- -// modifications by Crytek GmbH -// modifications by Amazon - -#include - -#include "CImageSurface.h" - - -namespace ImageProcessing -{ - //-------------------------------------------------------------------------------------- - // convert D3D 16 bit float to standard 32 bit float - // Format: - // - // 1 sign bit in MSB, (s) - // 5 bits of biased exponent, (e) - // 10 bits of fraction, (f), with an additional hidden bit - // A float16 value, v, made from the format above takes the following meaning: - // - // (a) if e == 31 and f != 0, then v is NaN regardless of s - // (b) if e == 31 and f == 0, then v = (-1)^s * infinity (signed infinity) - // (c) if 0 < e < 31, then v = (-1)^s * 2^(e-15) * (1.f) - // (d) if e == 0 and f != 0, then v = (-1)^s * 2^(e-14) * (0.f) (denormalized numbers) - // (e) if e == 0 and f == 0, then v = (-1)^s *0 (signed zero) - // - //-------------------------------------------------------------------------------------- - float CPf16Tof32(uint16 aVal) - { - uint32 signVal = (aVal >> 15); //sign bit in MSB - uint32 exponent = ((aVal >> 10) & 0x01f); //next 5 bits after signbit - uint32 mantissa = (aVal & 0x03ff); //lower 10 bits - uint32 rawFloat32Data; //raw binary float data - - //convert s10e5 5-bit exponent to IEEE754 s23e8 8-bit exponent - if (exponent == 31) - { // infinity or Nan depending on mantissa - exponent = 255; - } - else if (exponent == 0) - { // denormalized floats mantissa is treated as = 0.f - exponent = 0; - } - else - { //change 15base exponent to 127base exponent - //normalized floats mantissa is treated as = 1.f - exponent += (127 - 15); - } - - //convert 10-bit mantissa to 23-bit mantissa - mantissa <<= (23 - 10); - - //assemble s23e8 number using logical operations - rawFloat32Data = (signVal << 31) | (exponent << 23) | mantissa; - - //treat raw data as a 32 bit float - return *((float *)&rawFloat32Data); - } - - - //-------------------------------------------------------------------------------------- - // convert standard 32 bit float to D3D 16 bit float - // - // 16-bit float format: - // - // 1 sign bit in MSB, (s) - // 5 bits of biased exponent, (e) - // 10 bits of fraction, (f), with an additional hidden bit - // A float16 value, v, made from the format above takes the following meaning: - // - // (a) if e == 31 and f != 0, then v is NaN regardless of s - // (b) if e == 31 and f == 0, then v = (-1)s*infinity (signed infinity) - // (c) if 0 < e < 31, then v = (-1)s*2(e-15)*(1.f) - // (d) if e == 0 and f != 0, then v = (-1)s*2(e-14)*(0.f) (denormalized numbers) - // (e) if e == 0 and f == 0, then v = (-1)s*0 (signed zero) - //-------------------------------------------------------------------------------------- - uint16 CPf32Tof16(float aVal) - { - uint32 rawf32Data = *((uint32 *)&aVal); //raw binary float data - - uint32 signVal = (rawf32Data >> 31); //sign bit in MSB - uint32 exponent = ((rawf32Data >> 23) & 0xff); //next 8 bits after signbit - uint32 mantissa = (rawf32Data & 0x7fffff); //mantissa = lower 23 bits - - uint16 rawf16Data; - - //convert IEEE754 s23e8 8-bit exponent to s10e5 5-bit exponent - if (exponent == 255) - {//special case 32 bit float is inf or NaN, use mantissa as is - exponent = 31; - } - else if (exponent < ((127 - 15) - 10)) - {//special case, if 32-bit float exponent is out of 16-bit float range, then set 16-bit float to 0 - exponent = 0; - mantissa = 0; - } - else if (exponent >= (127 + (31 - 15))) - { // max 15based exponent for s10e5 is 31 - // force s10e5 number to represent infinity by setting mantissa to 0 - // and exponent to 31 - exponent = 31; - mantissa = 0; - } - else if (exponent <= (127 - 15)) - { //convert normalized s23e8 float to denormalized s10e5 float - - //add implicit 1.0 to mantissa to convert from 1.f to use as a 0.f mantissa - mantissa |= (1 << 23); - - //shift over mantissa number of bits equal to exponent underflow - mantissa = mantissa >> (1 + ((127 - 15) - exponent)); - - //zero exponent to treat value as a denormalized number - exponent = 0; - } - else - { //change 127base exponent to 15base exponent - // no underflow or overflow of exponent - //normalized floats mantissa is treated as= 1.f, so - // no denormalization or exponent derived shifts to the mantissa - exponent -= (127 - 15); - } - - //convert 23-bit mantissa to 10-bit mantissa - mantissa >>= (23 - 10); - - //assemble s10e5 number using logical operations - rawf16Data = (signVal << 15) | (exponent << 10) | mantissa; - - //return re-assembled raw data as a 32 bit float - return rawf16Data; - } - - - //-------------------------------------------------------------------------------------- - //size of data types in bytes - //-------------------------------------------------------------------------------------- - int32 CPTypeSizeOf(int32 a_Type) - { - switch (a_Type) - { - case CP_VAL_UNORM8: - case CP_VAL_UNORM8_BGRA: - return 1; - break; - case CP_VAL_UNORM16: - return 2; - break; - case CP_VAL_FLOAT16: - return 2; - break; - case CP_VAL_FLOAT32: - return 4; - break; - default: - return 1; - break; - } - } - - - //-------------------------------------------------------------------------------------- - //get value of data pointed to by a_Ptr given type information - //-------------------------------------------------------------------------------------- - CP_ITYPE CPTypeGetVal(int32 a_Type, void *a_Ptr) - { - switch (a_Type) - { - case CP_VAL_UNORM8: - case CP_VAL_UNORM8_BGRA: - return (1.0f / 255.0f) * *((uint8 *)a_Ptr); - break; - case CP_VAL_UNORM16: - return (1.0f / 65535.0f) * *((uint16 *)a_Ptr); - break; - case CP_VAL_FLOAT16: - return CPf16Tof32(*((uint16 *)a_Ptr)); - break; - case CP_VAL_FLOAT32: - return *((float *)a_Ptr); - break; - default: - return 0; - break; - } - } - - - //-------------------------------------------------------------------------------------- - //Given a CP_ITYPE value as input, convert it to the given type specified by a_Type - // and write the value to a_Ptr - //-------------------------------------------------------------------------------------- - void CPTypeSetVal(CP_ITYPE a_Val, int32 a_Type, void *a_Ptr) - { - CP_ITYPE clampVal; //clamp value to 0-1 range to output UNORM types - - switch (a_Type) - { - case CP_VAL_UNORM8: - case CP_VAL_UNORM8_BGRA: - clampVal = VM_MIN(VM_MAX(a_Val, 0.0f), 1.0f); - *((uint8 *)a_Ptr) = (uint8)(clampVal * 255.0f); - break; - case CP_VAL_UNORM16: - clampVal = VM_MIN(VM_MAX(a_Val, 0.0f), 1.0f); - *((uint16 *)a_Ptr) = (uint16)(clampVal * 65535.0f); - break; - case CP_VAL_FLOAT16: - *((uint16 *)a_Ptr) = CPf32Tof16(a_Val); - break; - case CP_VAL_FLOAT32: - *((float *)a_Ptr) = a_Val; - break; - default: - break; - } - } - - - //-------------------------------------------------------------------------------------- - //Error handling for imagesurface class - // Pop up dialog box, and terminate application - //-------------------------------------------------------------------------------------- - void CImageSurface::FatalError([[maybe_unused]] const WCHAR *a_Msg) - { - AZ_Error("Image Processing", false, "CImageSurface Error: %s", a_Msg); - } - - - //-------------------------------------------------------------------------------------- - // Image surface - //-------------------------------------------------------------------------------------- - CImageSurface::CImageSurface(void) - { - m_Width = 0; //cubemap face width - m_Height = 0; //cubemap face height - m_NumChannels = 0; //number of channels - m_ImgData = NULL; - - } - - - //-------------------------------------------------------------------------------------- - // Clear - //-------------------------------------------------------------------------------------- - void CImageSurface::Clear(void) - { - m_Width = 0; //cubemap face width - m_Height = 0; //cubemap face height - m_NumChannels = 0; //number of channels - SAFE_DELETE_ARRAY(m_ImgData); //safe delete old image data - } - - - //-------------------------------------------------------------------------------------- - // Initialize surface and associated memory - //-------------------------------------------------------------------------------------- - void CImageSurface::Init(int32 a_Width, int32 a_Height, int32 a_NumChannels) - { - m_Width = a_Width; //cubemap face width - m_Height = a_Height; //cubemap face height - m_NumChannels = a_NumChannels; //number of channels - - SAFE_DELETE_ARRAY(m_ImgData); //safe delete old image data - - m_ImgData = new(std::nothrow) CP_ITYPE[m_Width * m_Height * m_NumChannels]; //assume tight data packing - if (!m_ImgData) - { - FatalError(L"Unable to allocate data for image in CImageSurface::Init."); - } - } - - - //-------------------------------------------------------------------------------------- - //copy and convert data from external buffer into this surface - // - // note that srcPitch == the source pitch in bytes - //-------------------------------------------------------------------------------------- - void CImageSurface::SetImageData(int32 a_SrcType, int32 a_SrcNumChannels, int32 a_SrcPitch, void *a_SrcDataPtr) - { - int32 i, j, k; - - CP_ITYPE *dstDataWalk = m_ImgData; - uint8 *srcDataWalk = (uint8 *)a_SrcDataPtr; - - int32 srcValueSize = CPTypeSizeOf(a_SrcType); - int32 srcTexelStep = srcValueSize * a_SrcNumChannels; - int32 numChannelsSet = VM_MIN(a_SrcNumChannels, m_NumChannels); - int32 srcChannelSelect; - - //loop over rows - for (j = 0; j < m_Height; j++) - { - //pointer arithmetic to offset pointer by pitch in bytes - srcDataWalk = ((uint8 *)a_SrcDataPtr + (j * a_SrcPitch)); - - //loop over texels within row - for (i = 0; i < m_Width; i++) - { - srcChannelSelect = 0; - - //loop over channels within texel - for (k = 0; k < numChannelsSet; k++) - { - if (a_SrcType == CP_VAL_UNORM8_BGRA) //swap channels 0, and 2 if in BGRA format - { - switch (k) - { - case 0: - *(dstDataWalk + 2) = CPTypeGetVal(a_SrcType, srcDataWalk + srcChannelSelect); - break; - case 2: - *(dstDataWalk + 0) = CPTypeGetVal(a_SrcType, srcDataWalk + srcChannelSelect); - break; - default: - *(dstDataWalk + k) = CPTypeGetVal(a_SrcType, srcDataWalk + srcChannelSelect); - break; - } - } - else - { - *(dstDataWalk + k) = CPTypeGetVal(a_SrcType, srcDataWalk + srcChannelSelect); - } - - srcChannelSelect += srcValueSize; - } - - dstDataWalk += m_NumChannels; - srcDataWalk += srcTexelStep; - } - } - } - - - //-------------------------------------------------------------------------------------- - // Copy and convert data from external buffer into this surface set image data degamma - // and scale - // - //-------------------------------------------------------------------------------------- - void CImageSurface::SetImageDataClampDegammaScale(int32 a_SrcType, int32 a_SrcNumChannels, int32 a_SrcPitch, - void *a_SrcDataPtr, float a_MaxClamp, float a_Gamma, float a_Scale) - { - int32 i, j, k; - - CP_ITYPE *dstDataWalk = m_ImgData; - uint8 *srcDataWalk = (uint8 *)a_SrcDataPtr; - - int32 srcValueSize = CPTypeSizeOf(a_SrcType); - int32 srcTexelStep = srcValueSize * a_SrcNumChannels; - int32 numChannelsSet = VM_MIN(a_SrcNumChannels, m_NumChannels); - int32 srcChannelSelect; - - //loop over rows - for (j = 0; j < m_Height; j++) - { - //pointer arithmetic to offset pointer by pitch in bytes - srcDataWalk = ((uint8 *)a_SrcDataPtr + (j * a_SrcPitch)); - - //loop over texels within row - for (i = 0; i < m_Width; i++) - { - srcChannelSelect = 0; - - //loop over channels within texel - for (k = 0; k < numChannelsSet; k++) - { - CP_ITYPE texelVal; - - //get texel value from external buffer - texelVal = CPTypeGetVal(a_SrcType, srcDataWalk + srcChannelSelect); - - //clamp texelVal using max value only - // (using texelVal as the min clamping arguement means no minimum clamping) - VM_CLAMP(texelVal, texelVal, texelVal, a_MaxClamp); - - if (k < 3) //only apply gamma and scale to RGB channels - { - //degamma texel val, by raising to the power gamma - texelVal = pow(texelVal, a_Gamma); - - //scale texel val in linear space (after degamma) - texelVal *= a_Scale; - } - - //write data - if ((a_SrcType == CP_VAL_UNORM8_BGRA) && (k == 0)) - { - *(dstDataWalk + 2) = texelVal; - } - else if ((a_SrcType == CP_VAL_UNORM8_BGRA) && (k == 2)) - { - *(dstDataWalk + 0) = texelVal; - } - else - { - *(dstDataWalk + k) = texelVal; - } - - srcChannelSelect += srcValueSize; - } - - dstDataWalk += m_NumChannels; - srcDataWalk += srcTexelStep; - } - } - } - - - //-------------------------------------------------------------------------------------- - //copy data from this image surface into an external buffer - // - //-------------------------------------------------------------------------------------- - void CImageSurface::GetImageData(int32 a_DstType, int32 a_DstNumChannels, int32 a_DstPitch, void *a_DstDataPtr) - { - int32 i, j, k; - - CP_ITYPE *srcDataWalk = m_ImgData; - uint8 *dstDataWalk = (uint8 *)a_DstDataPtr; - - int32 dstValueSize = CPTypeSizeOf(a_DstType); - int32 dstTexelStep = dstValueSize * a_DstNumChannels; - - int32 numChannelsSet = VM_MIN(a_DstNumChannels, m_NumChannels); - int32 dstChannelSelect; - - //loop over rows - for (j = 0; j < m_Height; j++) - { - //pointer arithmetic to offset pointer by pitch in bytes - dstDataWalk = ((uint8 *)a_DstDataPtr + (j * a_DstPitch)); - - //loop over texels within row - for (i = 0; i < m_Width; i++) - { - dstChannelSelect = 0; - - //loop over channels within texel - for (k = 0; k < numChannelsSet; k++) - { - //write data - if ((a_DstType == CP_VAL_UNORM8_BGRA) && (k == 0)) - { - CPTypeSetVal(*(srcDataWalk + 2), a_DstType, dstDataWalk + dstChannelSelect); - } - else if ((a_DstType == CP_VAL_UNORM8_BGRA) && (k == 2)) - { - CPTypeSetVal(*(srcDataWalk + 0), a_DstType, dstDataWalk + dstChannelSelect); - } - else - { - CPTypeSetVal(*(srcDataWalk + k), a_DstType, dstDataWalk + dstChannelSelect); - } - - dstChannelSelect += dstValueSize; - } - - srcDataWalk += m_NumChannels; - dstDataWalk += dstTexelStep; - } - } - } - - - //-------------------------------------------------------------------------------------- - // Scale and then apply gamma to image data, then copy image data into an external buffer - // note: only apply scale and gamma to RGB channels (e.g. first 3 channels) - // - //-------------------------------------------------------------------------------------- - void CImageSurface::GetImageDataScaleGamma(int32 a_DstType, int32 a_DstNumChannels, int32 a_DstPitch, - void *a_DstDataPtr, float a_Scale, float a_Gamma) - { - int32 i, j, k; - - CP_ITYPE *srcDataWalk = m_ImgData; - uint8 *dstDataWalk = (uint8 *)a_DstDataPtr; - - int32 dstValueSize = CPTypeSizeOf(a_DstType); - int32 dstTexelStep = dstValueSize * a_DstNumChannels; - - int32 numChannelsSet = VM_MIN(a_DstNumChannels, m_NumChannels); - int32 dstChannelSelect; - - //loop over rows - for (j = 0; j < m_Height; j++) - { - //pointer arithmetic to offset pointer by pitch in bytes - dstDataWalk = ((uint8 *)a_DstDataPtr + (j * a_DstPitch)); - - //loop over texels within row - for (i = 0; i < m_Width; i++) - { - dstChannelSelect = 0; - - //loop over channels within texel - for (k = 0; k < numChannelsSet; k++) - { - CP_ITYPE texelVal; - - texelVal = *(srcDataWalk + k); - - if (k < 3) //only apply gamma and scale to RGB channels - { - //scale texel val - texelVal *= a_Scale; - - //apply gamma to texel val by raising the texelVal to the power of (1/gamma) - texelVal = pow(texelVal, 1.0f / a_Gamma); - } - - //write out texture value - if ((a_DstType == CP_VAL_UNORM8_BGRA) && (k == 0)) - { - CPTypeSetVal(texelVal, a_DstType, dstDataWalk + (dstValueSize * 2)); - } - else if ((a_DstType == CP_VAL_UNORM8_BGRA) && (k == 2)) - { - CPTypeSetVal(texelVal, a_DstType, dstDataWalk + (dstValueSize * 0)); - } - else - { - CPTypeSetVal(texelVal, a_DstType, dstDataWalk + dstChannelSelect); - } - - - dstChannelSelect += dstValueSize; - } - - srcDataWalk += m_NumChannels; - dstDataWalk += dstTexelStep; - } - } - } - - - //-------------------------------------------------------------------------------------- - //Set image channel a_ChannelIdx to a_ClearColor for all pixels. - // - //-------------------------------------------------------------------------------------- - void CImageSurface::ClearChannelConst(int32 a_ChannelIdx, CP_ITYPE a_ClearColor) - { - int32 u, v; - CP_ITYPE *texelPtr; - - //if channel does not exist, do not attempt to clear the channel - if (a_ChannelIdx > (m_NumChannels - 1)) - { - return; - } - - for (v = 0; v < m_Height; v++) - { - for (u = 0; u < m_Width; u++) - { - texelPtr = GetSurfaceTexelPtr(u, v); - - *(texelPtr + a_ChannelIdx) = a_ClearColor; - } - } - } - - - //-------------------------------------------------------------------------------------- - //Gets texel ptr in a surface given u and v coordinates, - // - //-------------------------------------------------------------------------------------- - CP_ITYPE *CImageSurface::GetSurfaceTexelPtr(int32 u, int32 v) - { - return(m_ImgData + (((m_Width * v) + u) * m_NumChannels)); - } - - - //-------------------------------------------------------------------------------------- - //flips surface image in place horizontally - // - //-------------------------------------------------------------------------------------- - void CImageSurface::InPlaceHorizonalFlip(void) - { - int32 u, v, k; - CP_ITYPE *texelPtrTop, *texelPtrBottom; - - //iterate over V - for (v = 0; v < (m_Height / 2); v++) - { - for (u = 0; u < m_Height; u++) - { - texelPtrTop = GetSurfaceTexelPtr(u, v); - texelPtrBottom = GetSurfaceTexelPtr(u, (m_Height - 1) - v); - - //iterate over channels - for (k = 0; k < m_NumChannels; k++) - { - CP_ITYPE tmpTexelVal; - - tmpTexelVal = *(texelPtrTop + k); - *(texelPtrTop + k) = *(texelPtrBottom + k); - *(texelPtrBottom + k) = tmpTexelVal; - - } - } - } - } - - - //-------------------------------------------------------------------------------------- - //flips surface image in place vertically - // - //-------------------------------------------------------------------------------------- - void CImageSurface::InPlaceVerticalFlip(void) - { - int32 u, v, k; - CP_ITYPE *texelPtrLeft, *texelPtrRight; - - for (u = 0; u < (m_Width / 2); u++) - { - for (v = 0; v < m_Height; v++) - { - texelPtrLeft = GetSurfaceTexelPtr(u, v); - texelPtrRight = GetSurfaceTexelPtr((m_Width - 1) - u, v); - - //iterate over channels - for (k = 0; k < m_NumChannels; k++) - { - CP_ITYPE tmpTexelVal; - - tmpTexelVal = *(texelPtrLeft + k); - *(texelPtrLeft + k) = *(texelPtrRight + k); - *(texelPtrRight + k) = tmpTexelVal; - } - } - } - } - - - //-------------------------------------------------------------------------------------- - //flip image around line defined by u = v (effectively swaps the u and v axises) - //-------------------------------------------------------------------------------------- - void CImageSurface::InPlaceDiagonalUVFlip(void) - { - int32 u, v, k; - CP_ITYPE *texelPtrLeft, *texelPtrRight; - - if (m_Width != m_Height) - { //only flip image if square - return; - } - - for (v = 0; v < m_Height; v++) - { - for (u = 0; u < v; u++) //only iterate over lower left triangle - { - texelPtrLeft = GetSurfaceTexelPtr(u, v); - texelPtrRight = GetSurfaceTexelPtr(v, u); - - //iterate over channels - for (k = 0; k < m_NumChannels; k++) - { - CP_ITYPE tmpTexelVal; - - tmpTexelVal = *(texelPtrLeft + k); - *(texelPtrLeft + k) = *(texelPtrRight + k); - *(texelPtrRight + k) = tmpTexelVal; - } - } - } - } - - //-------------------------------------------------------------------------------------- - // destructor, free all memory used - //-------------------------------------------------------------------------------------- - CImageSurface::~CImageSurface() - { - SAFE_DELETE_ARRAY(m_ImgData); - } -} // namespace ImageProcessing - - - diff --git a/Gems/ImageProcessing/External/CubeMapGen/CImageSurface.h b/Gems/ImageProcessing/External/CubeMapGen/CImageSurface.h deleted file mode 100644 index abd8cc5b50..0000000000 --- a/Gems/ImageProcessing/External/CubeMapGen/CImageSurface.h +++ /dev/null @@ -1,94 +0,0 @@ -//-------------------------------------------------------------------------------------- -//CImageSurface -// Class for storing, manipulating, and copying image data to and from D3D Surfaces -// -//-------------------------------------------------------------------------------------- -// (C) 2005 ATI Research, Inc., All rights reserved. -//-------------------------------------------------------------------------------------- -// modifications by Crytek GmbH -// modifications by Amazon - -#pragma once - -#include -#include - -#include "VectorMacros.h" - - -#ifndef WCHAR -#define WCHAR wchar_t -#endif //WCHAR - -#ifndef SAFE_DELETE -#define SAFE_DELETE(p) { if(p) { delete (p); (p)=NULL; } } -#endif - -#ifndef SAFE_DELETE_ARRAY -#define SAFE_DELETE_ARRAY(p) { if(p) { delete[] (p); (p)=NULL; } } -#endif - - -//Data types processed by cube map processor -// note that UNORM data types use the full range -// of the unsigned integer to represent the range [0, 1] inclusive -// the float16 datatype is stored as D3Ds S10E5 representation -#define CP_VAL_UNORM8 0 -#define CP_VAL_UNORM8_BGRA 1 -#define CP_VAL_UNORM16 10 -#define CP_VAL_FLOAT16 20 -#define CP_VAL_FLOAT32 30 - - -// Type of data used internally by CSurfaceImage -#define CP_ITYPE float - -namespace ImageProcessing -{ - //2D images used to store cube faces for processing, note that this class is - // meant to facilitate the copying of data to and from D3D surfaces hence the name ImageSurface - class CImageSurface - { - public: - int32 m_Width; //image width - int32 m_Height; //image height - int32 m_NumChannels; //number of channels - CP_ITYPE *m_ImgData; //cubemap image data - - private: - //fatal error - void FatalError(const WCHAR *a_Msg); - - public: - CImageSurface(void); - void Clear(void); - void Init(int32 a_Width, int32 a_Height, int32 a_NumChannels); - - //copy data from external buffer into this CImageSurface - void SetImageData(int32 a_SrcType, int32 a_SrcNumChannels, int32 a_SrcPitch, void *a_SrcDataPtr); - - // copy image data from an external buffer and scale and degamma the data - void SetImageDataClampDegammaScale(int32 a_SrcType, int32 a_SrcNumChannels, int32 a_SrcPitch, void *a_SrcDataPtr, - float a_MaxClamp, float a_Degamma, float a_Scale); - - //copy data from this CImageSurface into an external buffer - void GetImageData(int32 a_DstType, int32 a_DstNumChannels, int32 a_DstPitch, void *a_DstDataPtr); - - //copy image data from an external buffer and scale and gamma the data - void GetImageDataScaleGamma(int32 a_DstType, int32 a_DstNumChannels, int32 a_DstPitch, void *a_DstDataPtr, - float a_Scale, float a_Gamma); - - //clear one of the channels in the CSurfaceImage to a particular color - void ClearChannelConst(int32 a_ChannelIdx, CP_ITYPE a_ClearColor); - - //various image operations that can be performed on the CImageSurface - void InPlaceVerticalFlip(void); - void InPlaceHorizonalFlip(void); - void InPlaceDiagonalUVFlip(void); - - CP_ITYPE *GetSurfaceTexelPtr(int32 a_U, int32 a_V); - ~CImageSurface(); - }; - -} // namespace ImageProcessing - diff --git a/Gems/ImageProcessing/External/CubeMapGen/ReadMe_CubeGen.doc b/Gems/ImageProcessing/External/CubeMapGen/ReadMe_CubeGen.doc deleted file mode 100644 index 56ad1c16b9..0000000000 Binary files a/Gems/ImageProcessing/External/CubeMapGen/ReadMe_CubeGen.doc and /dev/null differ diff --git a/Gems/ImageProcessing/External/CubeMapGen/VectorMacros.h b/Gems/ImageProcessing/External/CubeMapGen/VectorMacros.h deleted file mode 100644 index b752d0b3c1..0000000000 --- a/Gems/ImageProcessing/External/CubeMapGen/VectorMacros.h +++ /dev/null @@ -1,176 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or 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 - -//-------------------------------------------------------------------------------------- -// VectorMacros.h -// -// Fast operations on vectors, stored as arrays of floats -// -//-------------------------------------------------------------------------------------- -// (C) 2001-2005 ATI Research, Inc. All rights reserved. -//-------------------------------------------------------------------------------------- -// modifications by Crytek GmbH - -//disable warning about doubles being converted down to float -#pragma warning (disable : 4244 ) - -#define VM_LARGE_FLOAT 3.7e37f - -#define VM_MIN(a, b) (((a) < (b)) ? (a) : (b)) -#define VM_MAX(a, b) (((a) > (b)) ? (a) : (b)) - -//clamping macros -#define VM_CLAMP(d, s, mn, mx){(d) = ((s)<(mx))?( ((s)>(mn))?(s):(mn) ):(mx); } - -#define VM_CLAMP2_UNTYPED(d, s, mn, mx) {VM_CLAMP(d[0], s[0], mn, mx); VM_CLAMP(d[1], s[1], mn, mx);} -#define VM_CLAMP2(d, s, mn, mx) VM_CLAMP2_UNTYPED(((float *)(d)), ((float *)(s)), (float)(mn), (float)(mx)) - -#define VM_CLAMP3_UNTYPED(d, s, mn, mx) {VM_CLAMP(d[0], s[0], mn, mx); VM_CLAMP(d[1], s[1], mn, mx); VM_CLAMP(d[2], s[2], mn, mx);} -#define VM_CLAMP3(d, s, mn, mx) VM_CLAMP3_UNTYPED(((float *)(d)), ((float *)(s)), (float)(mn), (float)(mx)) - -#define VM_CLAMP4_UNTYPED(d, s, mn, mx) {VM_CLAMP(d[0], s[0], mn, mx); VM_CLAMP(d[1], s[1], mn, mx); VM_CLAMP(d[2], s[2], mn, mx); VM_CLAMP(d[3], s[3], mn, mx);} -#define VM_CLAMP4(d, s, mn, mx) VM_CLAMP4_UNTYPED(((float *)(d)), ((float *)(s)), (float)(mn), (float)(mx)) - - -//set vectors -#define VM_SET2_UNTYPED(d, f) { d[0]=f; d[1]=f;} -#define VM_SET2(d, f) VM_SET2_UNTYPED(((float *)(d)), ((float)(f))) - -#define VM_SET3_UNTYPED(d, f) { d[0]=f; d[1]=f; d[2]=f; } -#define VM_SET3(d, f) VM_SET3_UNTYPED(((float *)(d)), ((float)(f))) - -#define VM_SET4_UNTYPED(d, f) { d[0]=f; d[1]=f; d[2]=f; d[3]=f; } -#define VM_SET4(d, f) VM_SET4_UNTYPED(((float *)(d)), ((float)(f))) - - -//copy vectors -#define VM_COPY2_UNTYPED(d, s) { d[0]=s[0]; d[1]=s[1];} -#define VM_COPY2(d, s) VM_COPY2_UNTYPED(((float *)(d)), ((float *)(s))) - -#define VM_COPY3_UNTYPED(d, s) { d[0]=s[0]; d[1]=s[1]; d[2]=s[2]; } -#define VM_COPY3(d, s) VM_COPY3_UNTYPED(((float *)(d)), ((float *)(s))) - -#define VM_COPY4_UNTYPED(d, s) { d[0]=s[0]; d[1]=s[1]; d[2]=s[2]; d[3]=s[3]; } -#define VM_COPY4(d, s) VM_COPY4_UNTYPED(((float *)(d)), ((float *)(s))) - - -//add two vectors -#define VM_ADD2_UNTYPED(d, sa, sb) { d[0]=sa[0]+sb[0]; d[1]=sa[1]+sb[1]; } -#define VM_ADD2(d, sa, sb) VM_ADD3_UNTYPED(((float *)(d)), ((float *)(sa)), ((float *)(sb))) - -#define VM_ADD3_UNTYPED(d, sa, sb) { d[0]=sa[0]+sb[0]; d[1]=sa[1]+sb[1]; d[2]=sa[2]+sb[2]; } -#define VM_ADD3(d, sa, sb) VM_ADD3_UNTYPED(((float *)(d)), ((float *)(sa)), ((float *)(sb))) - -#define VM_ADD4_UNTYPED(d, sa, sb) { d[0]=sa[0]+sb[0]; d[1]=sa[1]+sb[1]; d[2]=sa[2]+sb[2]; d[3]=sa[3]+sb[3]; } -#define VM_ADD4(d, sa, sb) VM_ADD4_UNTYPED(((float *)(d)), ((float *)(sa)), ((float *)(sb))) - - -//subtract two vectors -#define VM_SUB2_UNTYPED(d, sa, sb) { d[0]=sa[0]-sb[0]; d[1]=sa[1]-sb[1]; } -#define VM_SUB2(d, sa, sb) VM_SUB2_UNTYPED(((float *)(d)), ((float *)(sa)), ((float *)(sb))) - -#define VM_SUB3_UNTYPED(d, sa, sb) { d[0]=sa[0]-sb[0]; d[1]=sa[1]-sb[1]; d[2]=sa[2]-sb[2]; } -#define VM_SUB3(d, sa, sb) VM_SUB3_UNTYPED(((float *)(d)), ((float *)(sa)), ((float *)(sb))) - -#define VM_SUB4_UNTYPED(d, sa, sb) { d[0]=sa[0]-sb[0]; d[1]=sa[1]-sb[1]; d[2]=sa[2]-sb[2]; d[3]=sa[3]-sb[3]; } -#define VM_SUB4(d, sa, sb) VM_SUB4_UNTYPED(((float *)(d)), ((float *)(sa)), ((float *)(sb))) - - -//multiply all elements of a vector by a scalar -#define VM_SCALE2_UNTYPED(d, s, f) {d[0]=s[0]*f; d[1]=s[1]*f; } -#define VM_SCALE2(d, s, f) VM_SCALE2_UNTYPED(((float *)(d)), ((float *)(s)), ((float)(f)) ) - -#define VM_SCALE3_UNTYPED(d, s, f) {d[0]=s[0]*f; d[1]=s[1]*f; d[2]=s[2]*f; } -#define VM_SCALE3(d, s, f) VM_SCALE3_UNTYPED(((float *)(d)), ((float *)(s)), ((float)(f)) ) - -#define VM_SCALE4_UNTYPED(d, s, f) {d[0]=s[0]*f; d[1]=s[1]*f; d[2]=s[2]*f; d[3]=s[3]*f; } -#define VM_SCALE4(d, s, f) VM_SCALE4_UNTYPED(((float *)(d)), ((float *)(s)), ((float)(f)) ) - - -//add a scalar to all elements of a vector -#define VM_BIAS2_UNTYPED(d, s, f) { d[0]=s[0]+f; d[1]=s[1]+f; } -#define VM_BIAS2(d, s, f) VM_BIAS2_UNTYPED(((float *)(d)), ((float *)(s)), ((float)(f))) - -#define VM_BIAS3_UNTYPED(d, s, f) { d[0]=s[0]+f; d[1]=s[1]+f; d[2]=s[2]+f; } -#define VM_BIAS3(d, s, f) VM_BIAS3_UNTYPED(((float *)(d)), ((float *)(s)), ((float)(f))) - -#define VM_BIAS4_UNTYPED(d, s, f) { d[0]=s[0]+f; d[1]=s[1]+f; d[2]=s[2]+f; d[3]=s[3]+f; } -#define VM_BIAS4(d, s, f) VM_BIAS4_UNTYPED(((float *)(d)), ((float *)(s)), ((float)(f))) - - -//3D cross product -#define VM_XPROD3_UNTYPED(d, sa, sb) { d[0]=sa[1]*sb[2]-sa[2]*sb[1]; d[1]=sa[2]*sb[0]-sa[0]*sb[2]; d[2]=sa[0]*sb[1]-sa[1]*sb[0]; } -#define VM_XPROD3(d, sa, sb) VM_XPROD3_UNTYPED(((float *)(d)), ((float *)(sa)), ((float *)(sb))) - - -//dot products -#define VM_DOTPROD2_UNTYPED(sa, sb) (sa[0]*sb[0]+ sa[1]*sb[1]) -#define VM_DOTPROD2(sa, sb) VM_DOTPROD2_UNTYPED(((float *)(sa)), ((float *)(sb))) - -#define VM_DOTPROD3_UNTYPED(sa, sb) (sa[0]*sb[0]+ sa[1]*sb[1]+ sa[2]*sb[2]) -#define VM_DOTPROD3(sa, sb) VM_DOTPROD3_UNTYPED(((float *)(sa)), ((float *)(sb))) - -#define VM_DOTPROD4_UNTYPED(sa, sb) (sa[0]*sb[0]+ sa[1]*sb[1]+ sa[2]*sb[2] + sa[3]*sb[3]) -#define VM_DOTPROD4(sa, sb) VM_DOTPROD4_UNTYPED(((float *)(sa)), ((float *)(sb))) - - -//dp3 then and add 4th component from second arguement -#define VM_DOTPROD3ADD_UNTYPED(pt, pl) (pt[0]*pl[0]+ pt[1]*pl[1]+ pt[2]*pl[2] + pl[3]) -#define VM_DOTPROD3ADD(pt, pl) VM_DOTPROD3ADD_UNTYPED(((float *)(pt)), ((float *)(pl))) - - -//normalize vectors -#define VM_NORM3_UNTYPED(d, s) {double __idsq; __idsq=1.0/sqrt(VM_DOTPROD3_UNTYPED(s,s)); d[0]=s[0]*__idsq; d[1]=s[1]*__idsq; d[2]=s[2]*__idsq; } -#define VM_NORM3_UNTYPED_F32(d, s) {float __idsq; __idsq=1.0/sqrt(VM_DOTPROD3_UNTYPED(s,s)); d[0]=s[0]*__idsq; d[1]=s[1]*__idsq; d[2]=s[2]*__idsq; } -#define VM_NORM3(d, s) VM_NORM3_UNTYPED_F32(((float *)(d)), ((float *)(s))) - -#define VM_NORM4_UNTYPED(d, s) {double __idsq; __idsq=1.0/sqrt(VM_DOTPROD4_UNTYPED(s,s)); d[0]=s[0]*__idsq; d[1]=s[1]*__idsq; d[2]=s[2]*__idsq; d[3]=s[3]*__idsq; } -#define VM_NORM4_UNTYPED_F32(d, s) {float __idsq; __idsq=1.0/sqrt(VM_DOTPROD4_UNTYPED(s,s)); d[0]=s[0]*__idsq; d[1]=s[1]*__idsq; d[2]=s[2]*__idsq; d[3]=s[3]*__idsq; } -#define VM_NORM4(d, s) VM_NORM4_UNTYPED_F32(((float *)(d)), ((float *)(s))) - - -//safely normalize vectors, deal with 0 length case -#define VM_SAFENORM3_UNTYPED(d, s) {float __idsq, __dp; __dp = VM_DOTPROD3_UNTYPED(s,s); \ - __idsq=( (__dp > 0.0f)?(1.0/sqrt(__dp)):0.0f ) ; d[0]=s[0]*__idsq; d[1]=s[1]*__idsq; d[2]=s[2]*__idsq; } -#define VM_SAFENORM3(d, s) VM_NORM3_UNTYPED_F32(((float *)(d)), ((float *)(s))) - - - -//absolute value -#define VM_ABS2_UNTYPED(d, s) { d[0] = fabs(s[0]); d[1] = fabs(s[1]); } -#define VM_ABS2(d, s) VM_ABS2_UNTYPED(((float *)(d)), ((float *)(s)) ) - -#define VM_ABS3_UNTYPED(d, s) { d[0] = fabs(s[0]); d[1] = fabs(s[1]); d[2] = fabs(s[2]); } -#define VM_ABS3(d, s) VM_ABS3_UNTYPED(((float *)(d)), ((float *)(s)) ) - -#define VM_ABS4_UNTYPED(d, s) { d[0] = fabs(s[0]); d[1] = fabs(s[1]); d[2] = fabs(s[2]); d[3] = fabs(s[3]); } -#define VM_ABS4(d, s) VM_ABS4_UNTYPED(((float *)(d)), ((float *)(s)) ) - - -//projection of a vector onto another vector (assumes vector v is normalized) -// computes d, which is the parallel component of s onto vector v -#define VM_PROJ3_UNTYPED(d, s, v) { double __dp; __dp = VM_DOTPROD3_UNTYPED(s, v); VM_SCALE3_UNTYPED(d, s, __dp); } -#define VM_PROJ3(d, s, v) VM_PROJ3_UNTYPED(((float *)(d)), ((float *)(s)), ((float *)(v)) ) -#define VM_PROJ3_F64(d, s, v) VM_PROJ3_UNTYPED(((double *)(d)), ((double *)(s)), ((double *)(v)) ) - - -//compute component of a vector perpendicular to another vector -// d is perpendicular component of s onto vector v -// this macro first computes the parallel projection, then subtracts off from the original vector -// to obtain the perpendicular component -#define VM_PERP3_UNTYPED(d, s, v) {double __proj[3]; VM_PROJ3_UNTYPED(__proj, s, v); VM_SUB3_UNTYPED(d, s, __proj); } -#define VM_PERP3(d, s, v) VM_PERP3_UNTYPED(((float *)(d)), ((float *)(s)), ((float *)(v)) ) -#define VM_PERP3_F64(d, s, v) VM_PERP3_UNTYPED(((double *)(d)), ((double *)(s)), ((double *)(v)) ) - - diff --git a/Gems/ImageProcessing/External/CubeMapGen/license.txt b/Gems/ImageProcessing/External/CubeMapGen/license.txt deleted file mode 100644 index aa663d5ba7..0000000000 --- a/Gems/ImageProcessing/External/CubeMapGen/license.txt +++ /dev/null @@ -1,19 +0,0 @@ -Modified BSD License (2009): - -Copyright (c) 2011, Advanced Micro Devices, Inc. -All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - -Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - -Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. - -Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -If you use the software (in whole or in part), you shall adhere to all applicable U.S., European, and other export laws, including but not limited to the U.S. Export Administration Regulations (“EAR”), (15 C.F.R. Sections 730 through 774), and E.U. Council Regulation (EC) No 1334/2000 of 22 June 2000. Further, pursuant to Section 740.6 of the EAR, you hereby certify that, except pursuant to a license granted by the United States Department of Commerce Bureau of Industry and Security or as otherwise permitted pursuant to a License Exception under the U.S. Export Administration Regulations ("EAR"), you will not (1) export, re-export or release to a national of a country in Country Groups D:1, E:1 or E:2 any restricted technology, software, or source code you receive hereunder, or (2) export to Country Groups D:1, E:1 or E:2 the direct product of such technology or software, if such foreign produced direct product is subject to national security controls as identified on the Commerce Control List (currently found in Supplement 1 to Part 774 of EAR). For the most current Country Group listings, or for additional information about the EAR or your obligations under those regulations, please refer to the U.S. Bureau of Industry and Security’s website at http://www.bis.doc.gov/. - - - diff --git a/Gems/ImageProcessing/External/CubeMapGen/readme.txt b/Gems/ImageProcessing/External/CubeMapGen/readme.txt deleted file mode 100644 index 8026674cc4..0000000000 --- a/Gems/ImageProcessing/External/CubeMapGen/readme.txt +++ /dev/null @@ -1,5 +0,0 @@ -Cropped version of CubeMapGen-1.4-Source.zip - -More detail and download access: -https://gpuopen.com/archive/gamescgi/cubemapgen/ - diff --git a/Gems/ImageProcessing/gem.json b/Gems/ImageProcessing/gem.json deleted file mode 100644 index f211bad1e3..0000000000 --- a/Gems/ImageProcessing/gem.json +++ /dev/null @@ -1,27 +0,0 @@ -{ - "gem_name": "ImageProcessing", - "GemFormatVersion": 4, - "Uuid": "eeffbd9211cf4ce0b5cc73696b427cbe", - "Name": "ImageProcessing", - "DisplayName": "Image Processing", - "Version": "0.1.0", - "Summary": "Contains ImageBuilder for Asset Processor processing image files and UI for texture property editing", - "Tags": ["Image Builder", "Texture Property Editor"], - "IconPath": "preview.png", - "IsRequired": false, - "Modules": [ - { - "Name": "Editor", - "Type": "EditorModule" - } - ], - "Dependencies": [ - { - "Uuid": "5a149b6b3c964064bd4970f0e92f72e2", - "VersionConstraints": [ - "~>0.1" - ], - "_comment": "Texture Atlas" - } - ] -} diff --git a/Gems/ImageProcessing/preview.png b/Gems/ImageProcessing/preview.png deleted file mode 100644 index 2f1ed47754..0000000000 --- a/Gems/ImageProcessing/preview.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:6d6204c6730e5675791765ca194e9b1cbec282208e280507de830afc2805e5fa -size 41127 diff --git a/Gems/LmbrCentral/Code/Source/Asset/AssetSystemDebugComponent.cpp b/Gems/LmbrCentral/Code/Source/Asset/AssetSystemDebugComponent.cpp index 70d84dee6f..20ec7627bd 100644 --- a/Gems/LmbrCentral/Code/Source/Asset/AssetSystemDebugComponent.cpp +++ b/Gems/LmbrCentral/Code/Source/Asset/AssetSystemDebugComponent.cpp @@ -72,25 +72,8 @@ namespace LmbrCentral return; } - ISystem* crySystem = GetISystem(); - if (!crySystem) - { - return; - } - - IRenderer* renderer = crySystem->GetIRenderer(); - if (!renderer) - { - return; - } - - IRenderAuxGeom* auxGeom = renderer->GetIRenderAuxGeom(); - if (!auxGeom) - { - return; - } - - float x = 10; + // ToDo: Remove class or update to work with Atom? LYN-3672 + /*float x = 10; float y = 15; ColorF color(1, 1, 1); constexpr bool center = false; @@ -161,7 +144,7 @@ namespace LmbrCentral StatusToString(asset.GetStatus()).c_str(), activeAssetLoadTime.count()); } - } + }*/ } void AssetSystemDebugComponent::AssetStatusUpdate(AZ::Data::AssetId id, AZ::Data::AssetData::AssetStatus status) diff --git a/Gems/LmbrCentral/Code/Source/Builders/CopyDependencyBuilder/XmlBuilderWorker/XmlBuilderWorker.cpp b/Gems/LmbrCentral/Code/Source/Builders/CopyDependencyBuilder/XmlBuilderWorker/XmlBuilderWorker.cpp index f50526c67f..636aa72013 100644 --- a/Gems/LmbrCentral/Code/Source/Builders/CopyDependencyBuilder/XmlBuilderWorker/XmlBuilderWorker.cpp +++ b/Gems/LmbrCentral/Code/Source/Builders/CopyDependencyBuilder/XmlBuilderWorker/XmlBuilderWorker.cpp @@ -471,7 +471,7 @@ namespace CopyDependencyBuilder [[maybe_unused]] const AZStd::string& watchFolderPath) const { // Check the existing schema info stored in the asset database - // https://jira.agscollab.com/browse/LY-99056 + // LY-99056 return SchemaMatchResult::NoMatchFound; } @@ -526,7 +526,7 @@ namespace CopyDependencyBuilder { case SchemaMatchResult::MatchFound: // Update the LastUsedSchema info stored in the asset database - // https://jira.agscollab.com/browse/LY-99056 + // LY-99056 AZ_Printf("XmlBuilderWorker", "Schema file %s found for source %s.", schemaFilePath.c_str(), sourceFilePath.c_str()); return matchResult; case SchemaMatchResult::NoMatchFound: diff --git a/Gems/LmbrCentral/Code/Source/LmbrCentral.cpp b/Gems/LmbrCentral/Code/Source/LmbrCentral.cpp index 10b3c3a317..d23ce13bfe 100644 --- a/Gems/LmbrCentral/Code/Source/LmbrCentral.cpp +++ b/Gems/LmbrCentral/Code/Source/LmbrCentral.cpp @@ -63,8 +63,6 @@ #include "Unhandled/UI/FontAssetTypeInfo.h" #include "Unhandled/UI/UICanvasAssetTypeInfo.h" -#include - // Asset types #include #include diff --git a/Gems/LmbrCentral/Code/Source/Shape/EditorBaseShapeComponent.cpp b/Gems/LmbrCentral/Code/Source/Shape/EditorBaseShapeComponent.cpp index df5c65e07c..cd21b1e855 100644 --- a/Gems/LmbrCentral/Code/Source/Shape/EditorBaseShapeComponent.cpp +++ b/Gems/LmbrCentral/Code/Source/Shape/EditorBaseShapeComponent.cpp @@ -12,7 +12,7 @@ #include "LmbrCentral_precompiled.h" #include "EditorBaseShapeComponent.h" - +#include #include #include @@ -214,8 +214,7 @@ namespace LmbrCentral { if (changeReason == ShapeChangeReasons::ShapeChanged) { - AzFramework::EntityBoundsUnionRequestBus::Broadcast( - &AzFramework::EntityBoundsUnionRequestBus::Events::RefreshEntityLocalBoundsUnion, GetEntityId()); + AZ::Interface::Get()->RefreshEntityLocalBoundsUnion(GetEntityId()); } } } // namespace LmbrCentral diff --git a/Gems/LmbrCentral/Code/Source/Shape/EditorSplineComponent.cpp b/Gems/LmbrCentral/Code/Source/Shape/EditorSplineComponent.cpp index e1951de498..144713c8ec 100644 --- a/Gems/LmbrCentral/Code/Source/Shape/EditorSplineComponent.cpp +++ b/Gems/LmbrCentral/Code/Source/Shape/EditorSplineComponent.cpp @@ -378,9 +378,7 @@ namespace LmbrCentral { SplineComponentNotificationBus::Event( GetEntityId(), &SplineComponentNotificationBus::Events::OnSplineChanged); - - AzFramework::EntityBoundsUnionRequestBus::Broadcast( - &AzFramework::EntityBoundsUnionRequestBus::Events::RefreshEntityLocalBoundsUnion, GetEntityId()); + AZ::Interface::Get()->RefreshEntityLocalBoundsUnion(GetEntityId()); } AZ::SplinePtr EditorSplineComponent::GetSpline() diff --git a/Gems/LmbrCentral/Code/Tests/Builders/SliceBuilderTests.cpp b/Gems/LmbrCentral/Code/Tests/Builders/SliceBuilderTests.cpp index 925f7512da..2514485519 100644 --- a/Gems/LmbrCentral/Code/Tests/Builders/SliceBuilderTests.cpp +++ b/Gems/LmbrCentral/Code/Tests/Builders/SliceBuilderTests.cpp @@ -304,6 +304,10 @@ public: void UnregisterComponentDescriptor(const ComponentDescriptor*) override { } void RegisterEntityAddedEventHandler(EntityAddedEvent::Handler&) override { } void RegisterEntityRemovedEventHandler(EntityRemovedEvent::Handler&) override { } + void RegisterEntityActivatedEventHandler(EntityActivatedEvent::Handler&) override { } + void RegisterEntityDeactivatedEventHandler(EntityDeactivatedEvent::Handler&) override { } + void SignalEntityActivated(Entity*) override { } + void SignalEntityDeactivated(Entity*) override { } bool AddEntity(Entity*) override { return true; } bool RemoveEntity(Entity*) override { return true; } bool DeleteEntity(const AZ::EntityId&) override { return true; } @@ -329,6 +333,7 @@ public: m_serializeContext = aznew SerializeContext(true, true); ComponentApplicationBus::Handler::BusConnect(); + AZ::Interface::Register(this); m_sliceDescriptor = SliceComponent::CreateDescriptor(); m_mockAssetDescriptor = MockAssetRefComponent::CreateDescriptor(); @@ -358,6 +363,7 @@ public: void TearDown() override { m_catalog->DisableCatalog(); + AZ::Interface::Unregister(this); ComponentApplicationBus::Handler::BusDisconnect(); Data::AssetManager::Destroy(); 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 diff --git a/Gems/LyShine/Code/Editor/UiEditorEntityContext.cpp b/Gems/LyShine/Code/Editor/UiEditorEntityContext.cpp index 3be0b3cddf..d4de0b59c8 100644 --- a/Gems/LyShine/Code/Editor/UiEditorEntityContext.cpp +++ b/Gems/LyShine/Code/Editor/UiEditorEntityContext.cpp @@ -943,7 +943,7 @@ void UiEditorEntityContext::InitializeEntities(const AzFramework::EntityList& en // Because we automatically add the EditorOnlyEntityComponent if it doesn't exist, we can encounter a situation // where an entity has duplicate EditorOnlyEntityComponents if an old canvas is resaved and an old slice it uses - // is also resaved. See https://jira.agscollab.com/browse/LY-90580 + // is also resaved. See LY-90580 // In the main editor this is handled by disabling the duplicate components, but the UI Editor doesn't use that // method (the world editor allows the user to manually add incompatible components and then disable and enable // them in the entity, the UI Editor still works how the world editor used to - it doesn't allow users to add 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/LyShine/Code/Source/LyShine.cpp b/Gems/LyShine/Code/Source/LyShine.cpp index 3ea451b7c5..bc6a27dac4 100644 --- a/Gems/LyShine/Code/Source/LyShine.cpp +++ b/Gems/LyShine/Code/Source/LyShine.cpp @@ -166,11 +166,6 @@ CLyShine::CLyShine(ISystem* system) UiAnimationSystem::StaticInitialize(); - if (m_system->GetIRenderer()) - { - m_system->GetIRenderer()->AddRenderDebugListener(this); - } - AzFramework::InputChannelEventListener::Connect(); AzFramework::InputTextEventListener::Connect(); UiCursorBus::Handler::BusConnect(); @@ -254,11 +249,6 @@ CLyShine::~CLyShine() AzFramework::InputTextEventListener::Disconnect(); AzFramework::InputChannelEventListener::Disconnect(); - if (m_system->GetIRenderer()) - { - m_system->GetIRenderer()->RemoveRenderDebugListener(this); - } - UiCanvasComponent::Shutdown(); // must be done after UiCanvasComponent::Shutdown diff --git a/Gems/LyShine/Code/Source/UiCanvasManager.cpp b/Gems/LyShine/Code/Source/UiCanvasManager.cpp index 958dba0ab8..e09a6d0efd 100644 --- a/Gems/LyShine/Code/Source/UiCanvasManager.cpp +++ b/Gems/LyShine/Code/Source/UiCanvasManager.cpp @@ -815,7 +815,10 @@ bool UiCanvasManager::HandleInputEventForInWorldCanvases(const AzFramework::Inpu // First we need to construct a ray from the either the center of the screen or the mouse position. // This requires knowledge of the camera // for initial testing we will just use a ray in the center of the viewport - const CCamera& cam = GetISystem()->GetIRenderer()->GetCamera(); + + // ToDo: Re-implement by getting the camera from Atom. LYN-3680 + return false; + const CCamera cam; // construct a ray from the camera position in the view direction of the camera const float rayLength = 5000.0f; diff --git a/Gems/LyShineExamples/Code/Source/UiCustomImageComponent.cpp b/Gems/LyShineExamples/Code/Source/UiCustomImageComponent.cpp index cb33ccac98..1bd2bd10be 100644 --- a/Gems/LyShineExamples/Code/Source/UiCustomImageComponent.cpp +++ b/Gems/LyShineExamples/Code/Source/UiCustomImageComponent.cpp @@ -98,7 +98,7 @@ namespace LyShineExamples { // if there is no texture we will just use a white texture // TODO: Get a default atom texture here when possible - //texture = gEnv->pRenderer->EF_GetTextureByID(gEnv->pRenderer->GetWhiteTextureId()); + //texture = ???->EF_GetTextureByID(???->GetWhiteTextureId()); } if (m_isRenderCacheDirty) diff --git a/Gems/Maestro/Code/Source/Cinematics/AnimScreenFaderNode.cpp b/Gems/Maestro/Code/Source/Cinematics/AnimScreenFaderNode.cpp index ba30c3de39..ca1e73fc65 100644 --- a/Gems/Maestro/Code/Source/Cinematics/AnimScreenFaderNode.cpp +++ b/Gems/Maestro/Code/Source/Cinematics/AnimScreenFaderNode.cpp @@ -348,34 +348,6 @@ bool CAnimScreenFaderNode::GetParamInfoFromType(const CAnimParamType& paramId, S //----------------------------------------------------------------------------- void CAnimScreenFaderNode::Render() { - if (!m_bActive) - { - return; - } - - if (gEnv->pRenderer) - { - size_t const paramCount = m_tracks.size(); - for (size_t paramIndex = 0; paramIndex < paramCount; ++paramIndex) - { - CScreenFaderTrack* pTrack = static_cast(GetTrackForParameter(AnimParamType::ScreenFader, paramIndex)); - - if (!pTrack) - { - continue; - } - - int textureId = -1; - if (pTrack->IsTextureVisible()) - { - textureId = (pTrack->GetActiveTexture() != 0) ? pTrack->GetActiveTexture()->GetTextureID() : -1; - } - - gEnv->pRenderer->SetState(GS_BLSRC_SRCALPHA | GS_BLDST_ONEMINUSSRCALPHA | GS_NODEPTHTEST); - gEnv->pRenderer->Draw2dImage(0, 0, m_screenWidth, m_screenHeight, textureId, 0.0f, 1.0f, 1.0f, 0.0f, 0.f, - pTrack->GetDrawColor().x, pTrack->GetDrawColor().y, pTrack->GetDrawColor().z, pTrack->GetDrawColor().w, 0.f); - } - } } bool CAnimScreenFaderNode::IsAnyTextureVisible() const 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/Maestro/Code/Source/Cinematics/Movie.cpp b/Gems/Maestro/Code/Source/Cinematics/Movie.cpp index f68ddb2b49..8ee2c68cc4 100644 --- a/Gems/Maestro/Code/Source/Cinematics/Movie.cpp +++ b/Gems/Maestro/Code/Source/Cinematics/Movie.cpp @@ -993,9 +993,6 @@ void CMovieSystem::ShowPlayedSequencesDebug() continue; } - const char* fullname = playingSequence.sequence->GetName(); - gEnv->pRenderer->Draw2dLabel(1.0f, y, 1.3f, green, false, "Sequence %s : %f (x %f)", fullname, playingSequence.currentTime, playingSequence.currentSpeed); - y += 16.0f; for (int i = 0; i < playingSequence.sequence->GetNodeCount(); ++i) @@ -1017,8 +1014,6 @@ void CMovieSystem::ShowPlayedSequencesDebug() { names.push_back(name); } - - gEnv->pRenderer->Draw2dLabel((21.0f + 100.0f * i), ((i % 2) ? (y + 8.0f) : y), 1.0f, alreadyThere ? white : purple, false, "%s", name); } y += 32.0f; diff --git a/Gems/Maestro/Code/Source/Cinematics/ScreenFaderTrack.cpp b/Gems/Maestro/Code/Source/Cinematics/ScreenFaderTrack.cpp index 8b2e615c26..3465b137b1 100644 --- a/Gems/Maestro/Code/Source/Cinematics/ScreenFaderTrack.cpp +++ b/Gems/Maestro/Code/Source/Cinematics/ScreenFaderTrack.cpp @@ -113,12 +113,6 @@ void CScreenFaderTrack::PreloadTextures() GetKey(nKeyIndex, &key); if (!key.m_strTexture.empty()) { - ITexture* pTexture = gEnv->pRenderer->EF_LoadTexture(key.m_strTexture.c_str(), FT_DONT_STREAM | FT_STATE_CLAMP); - if (pTexture) - { - pTexture->SetClamp(true); - m_preloadedTextures.push_back(pTexture); - } } else { diff --git a/Gems/Maestro/Code/Source/MaestroSystemComponent.cpp b/Gems/Maestro/Code/Source/MaestroSystemComponent.cpp index e300607fd7..cd0dfb02b3 100644 --- a/Gems/Maestro/Code/Source/MaestroSystemComponent.cpp +++ b/Gems/Maestro/Code/Source/MaestroSystemComponent.cpp @@ -122,7 +122,7 @@ namespace Maestro /////////////////////////////////////////////////////////////////////////////////////////////// void MaestroSystemComponent::OnCrySystemInitialized(ISystem& system, const SSystemInitParams& startupParams) { - if (!startupParams.bSkipMovie && !startupParams.bShaderCacheGen) + if (!startupParams.bSkipMovie) { // OnCrySystemInitialized should only ever be called once, and we should be the only one initializing gEnv->pMovieSystem AZ_Assert(!m_movieSystemEventListener && gEnv && !gEnv->pMovieSystem, "MaestroSystemComponent::OnCrySystemInitialized - movie system was alread initialized."); diff --git a/Gems/Multiplayer/Code/Source/ConnectionData/IConnectionData.h b/Gems/Multiplayer/Code/Include/IConnectionData.h similarity index 87% rename from Gems/Multiplayer/Code/Source/ConnectionData/IConnectionData.h rename to Gems/Multiplayer/Code/Include/IConnectionData.h index a7ceffd289..dcc2c940ef 100644 --- a/Gems/Multiplayer/Code/Source/ConnectionData/IConnectionData.h +++ b/Gems/Multiplayer/Code/Include/IConnectionData.h @@ -12,11 +12,13 @@ #pragma once -#include -#include +#include +#include namespace Multiplayer { + class EntityReplicationManager; + enum class ConnectionDataType { ClientToServer, @@ -42,8 +44,8 @@ namespace Multiplayer virtual EntityReplicationManager& GetReplicationManager() = 0; //! Creates and manages sending updates to the remote endpoint. - //! @param serverGameTimeMs current server game time in milliseconds - virtual void Update(AZ::TimeMs serverGameTimeMs) = 0; + //! @param hostTimeMs current server game time in milliseconds + virtual void Update(AZ::TimeMs hostTimeMs) = 0; //! Returns whether update messages can be sent to the connection. //! @return true if update messages can be sent diff --git a/Gems/Multiplayer/Code/Source/EntityDomains/IEntityDomain.h b/Gems/Multiplayer/Code/Include/IEntityDomain.h similarity index 97% rename from Gems/Multiplayer/Code/Source/EntityDomains/IEntityDomain.h rename to Gems/Multiplayer/Code/Include/IEntityDomain.h index 56ec24618d..6571797d05 100644 --- a/Gems/Multiplayer/Code/Source/EntityDomains/IEntityDomain.h +++ b/Gems/Multiplayer/Code/Include/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/IMultiplayer.h index 47d0d5a05e..039b86b2a6 100644 --- a/Gems/Multiplayer/Code/Include/IMultiplayer.h +++ b/Gems/Multiplayer/Code/Include/IMultiplayer.h @@ -15,6 +15,7 @@ #include #include #include +#include #include namespace AzNetworking @@ -56,7 +57,7 @@ namespace Multiplayer //! Gets the type of Agent this IMultiplayer impl represents //! @return The type of agents represented - virtual MultiplayerAgentType GetAgentType() = 0; + virtual MultiplayerAgentType GetAgentType() const = 0; //! Sets the type of this Multiplayer connection and calls any related callback //! @param state The state of this connection @@ -78,6 +79,14 @@ namespace Multiplayer //! @param readyForEntityUpdates Ready for entity updates or not virtual void SendReadyForEntityUpdates(bool readyForEntityUpdates) = 0; + //! Returns the current server time in milliseconds. + //! This can be one of three possible values: + //! 1. On the host outside of rewind scope, this will return the latest application elapsed time in ms. + //! 2. On the host within rewind scope, this will return the rewound time in ms. + //! 3. On the client, this will return the most recently replicated server time in ms. + //! @return the current server time in milliseconds + virtual AZ::TimeMs GetCurrentHostTimeMs() const = 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 diff --git a/Gems/Multiplayer/Code/Source/NetworkInput/IMultiplayerComponentInput.h b/Gems/Multiplayer/Code/Include/IMultiplayerComponentInput.h similarity index 100% rename from Gems/Multiplayer/Code/Source/NetworkInput/IMultiplayerComponentInput.h rename to Gems/Multiplayer/Code/Include/IMultiplayerComponentInput.h diff --git a/Gems/Multiplayer/Code/Source/NetworkEntity/INetworkEntityManager.h b/Gems/Multiplayer/Code/Include/INetworkEntityManager.h similarity index 99% rename from Gems/Multiplayer/Code/Source/NetworkEntity/INetworkEntityManager.h rename to Gems/Multiplayer/Code/Include/INetworkEntityManager.h index 891a4606ea..d9b611ece0 100644 --- a/Gems/Multiplayer/Code/Source/NetworkEntity/INetworkEntityManager.h +++ b/Gems/Multiplayer/Code/Include/INetworkEntityManager.h @@ -13,7 +13,7 @@ #pragma once #include -#include +#include #include #include #include diff --git a/Gems/Multiplayer/Code/Source/NetworkTime/INetworkTime.h b/Gems/Multiplayer/Code/Include/INetworkTime.h similarity index 50% rename from Gems/Multiplayer/Code/Source/NetworkTime/INetworkTime.h rename to Gems/Multiplayer/Code/Include/INetworkTime.h index 703fba5fb5..5346a0e0d0 100644 --- a/Gems/Multiplayer/Code/Source/NetworkTime/INetworkTime.h +++ b/Gems/Multiplayer/Code/Include/INetworkTime.h @@ -14,13 +14,10 @@ #include #include +#include namespace Multiplayer { - //! This is a strong typedef for representing the number of application frames since application start. - AZ_TYPE_SAFE_INTEGRAL(ApplicationFrameId, uint32_t); - static constexpr ApplicationFrameId InvalidApplicationFrameId = ApplicationFrameId{0xFFFFFFFF}; - //! @class INetworkTime //! @brief This is an AZ::Interface<> for managing multiplayer specific time related operations. class INetworkTime @@ -31,30 +28,24 @@ namespace Multiplayer INetworkTime() = default; virtual ~INetworkTime() = default; - //! Converts from an ApplicationFrameId to a corresponding TimeMs. - //! @param frameId the ApplicationFrameId to convert to a TimeMs - //! @return the TimeMs that corresponds to the provided ApplicationFrameId - virtual AZ::TimeMs ConvertFrameIdToTimeMs(ApplicationFrameId frameId) const = 0; + //! Returns true if the host timeMs and frameId has been temporarily altered. + //! @return true if the host timeMs and frameId has been altered, false otherwise + virtual bool IsTimeRewound() const = 0; - //! Converts from a TimeMs to an ApplicationFrameId. - //! @param timeMs the TimeMs to convert to an ApplicationFrameId - //! @return the ApplicationFrameId that corresponds to the provided TimeMs - virtual ApplicationFrameId ConvertTimeMsToFrameId(AZ::TimeMs timeMs) const = 0; + //! Retrieves the hosts current frameId (may be rewound on the server during backward reconciliation). + //! @return the hosts current frameId + virtual HostFrameId GetHostFrameId() const = 0; - //! Returns true if the application frameId has been temporarily altered. - //! @return true if the application frameId has been altered, false otherwise - virtual bool IsApplicationFrameIdRewound() const = 0; + //! Retrieves the unaltered hosts current frameId. + //! @return the hosts current frameId, unaltered by any scoped time instance + virtual HostFrameId GetUnalteredHostFrameId() const = 0; - //! Retrieves the applications current frameId (may be rewound on the server during backward reconciliation). - //! @return the applications current frameId - virtual ApplicationFrameId GetApplicationFrameId() const = 0; + //! Increments the hosts current frameId. + virtual void IncrementHostFrameId() = 0; - //! Retrieves the unaltered applications current frameId. - //! @return the applications current frameId, unaltered by any scoped time instance - virtual ApplicationFrameId GetUnalteredApplicationFrameId() const = 0; - - //! Increments the applications current frameId. - virtual void IncrementApplicationFrameId() = 0; + //! Retrieves the hosts current timeMs (may be rewound on the server during backward reconciliation). + //! @return the hosts current timeMs + virtual AZ::TimeMs GetHostTimeMs() const = 0; //! Synchronizes rewindable entity state for the current application time. virtual void SyncRewindableEntityState() = 0; @@ -66,14 +57,15 @@ namespace Multiplayer //! 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 - //! @param rewindConnectionId if this parameter matches the current rewindConnectionId, it will return the unaltered applicationFrameId - //! @return the ApplicationFrameId taking into account the provided rewinding connectionId - virtual ApplicationFrameId GetApplicationFrameIdForRewindingConnection(AzNetworking::ConnectionId rewindConnectionId) const = 0; + //! @param rewindConnectionId if this parameter matches the current rewindConnectionId, it will return the unaltered hostFrameId + //! @return the HostFrameId taking into account the provided rewinding connectionId + virtual HostFrameId GetHostFrameIdForRewindingConnection(AzNetworking::ConnectionId rewindConnectionId) const = 0; - //! Alters the current ApplicationFrameId and binds that alteration to the provided ConnectionId. - //! @param frameId the new ApplicationFrameId to use + //! Alters the current HostFrameId and binds that alteration to the provided ConnectionId. + //! @param frameId the new HostFrameId to use + //! @param timeMs the new HostTimeMs to use //! @param rewindConnectionId the rewinding ConnectionId - virtual void AlterApplicationFrameId(ApplicationFrameId frameId, AzNetworking::ConnectionId rewindConnectionId) = 0; + virtual void AlterTime(HostFrameId frameId, AZ::TimeMs timeMs, AzNetworking::ConnectionId rewindConnectionId) = 0; AZ_DISABLE_COPY_MOVE(INetworkTime); }; @@ -93,22 +85,22 @@ namespace Multiplayer class ScopedAlterTime final { public: - inline ScopedAlterTime(ApplicationFrameId frameId, AzNetworking::ConnectionId connectionId) + inline ScopedAlterTime(HostFrameId frameId, AZ::TimeMs timeMs, AzNetworking::ConnectionId connectionId) { INetworkTime* time = AZ::Interface::Get(); - m_previousApplicationFrameId = time->GetApplicationFrameId(); + m_previousHostFrameId = time->GetHostFrameId(); + m_previousHostTimeMs = time->GetHostTimeMs(); m_previousRewindConnectionId = time->GetRewindingConnectionId(); - time->AlterApplicationFrameId(frameId, connectionId); + time->AlterTime(frameId, timeMs, connectionId); } inline ~ScopedAlterTime() { INetworkTime* time = AZ::Interface::Get(); - time->AlterApplicationFrameId(m_previousApplicationFrameId, m_previousRewindConnectionId); + time->AlterTime(m_previousHostFrameId, m_previousHostTimeMs, m_previousRewindConnectionId); } private: - ApplicationFrameId m_previousApplicationFrameId = InvalidApplicationFrameId; + HostFrameId m_previousHostFrameId = InvalidHostFrameId; + AZ::TimeMs m_previousHostTimeMs = AZ::TimeMs{ 0 }; AzNetworking::ConnectionId m_previousRewindConnectionId = AzNetworking::InvalidConnectionId; }; } - -AZ_TYPE_SAFE_INTEGRAL_SERIALIZEBINDING(Multiplayer::ApplicationFrameId); diff --git a/Gems/Multiplayer/Code/Source/ReplicationWindows/IReplicationWindow.h b/Gems/Multiplayer/Code/Include/IReplicationWindow.h similarity index 96% rename from Gems/Multiplayer/Code/Source/ReplicationWindows/IReplicationWindow.h rename to Gems/Multiplayer/Code/Include/IReplicationWindow.h index 27c14f8049..eb34a2f87d 100644 --- a/Gems/Multiplayer/Code/Source/ReplicationWindows/IReplicationWindow.h +++ b/Gems/Multiplayer/Code/Include/IReplicationWindow.h @@ -13,7 +13,7 @@ #pragma once #include -#include +#include #include namespace Multiplayer diff --git a/Gems/Multiplayer/Code/Include/MultiplayerStats.cpp b/Gems/Multiplayer/Code/Include/MultiplayerStats.cpp index b9f47814b4..7672997ad5 100644 --- a/Gems/Multiplayer/Code/Include/MultiplayerStats.cpp +++ b/Gems/Multiplayer/Code/Include/MultiplayerStats.cpp @@ -14,6 +14,12 @@ namespace Multiplayer { + MultiplayerStats::Metric::Metric() + { + AZStd::uninitialized_fill_n(m_callHistory.data(), RingbufferSamples, 0); + AZStd::uninitialized_fill_n(m_byteHistory.data(), RingbufferSamples, 0); + } + void MultiplayerStats::ReserveComponentStats(NetComponentId netComponentId, uint16_t propertyCount, uint16_t rpcCount) { const uint16_t netComponentIndex = aznumeric_cast(netComponentId); @@ -71,6 +77,29 @@ namespace Multiplayer { m_totalHistoryTimeMs = metricFrameTimeMs * static_cast(RingbufferSamples); m_recordMetricIndex = ++m_recordMetricIndex % RingbufferSamples; + for (ComponentStats& componentStats : m_componentStats) + { + for (Metric& metric : componentStats.m_propertyUpdatesSent) + { + metric.m_callHistory[m_recordMetricIndex] = 0; + metric.m_byteHistory[m_recordMetricIndex] = 0; + } + for (Metric& metric : componentStats.m_propertyUpdatesRecv) + { + metric.m_callHistory[m_recordMetricIndex] = 0; + metric.m_byteHistory[m_recordMetricIndex] = 0; + } + for (Metric& metric : componentStats.m_rpcsSent) + { + metric.m_callHistory[m_recordMetricIndex] = 0; + metric.m_byteHistory[m_recordMetricIndex] = 0; + } + for (Metric& metric : componentStats.m_rpcsRecv) + { + metric.m_callHistory[m_recordMetricIndex] = 0; + metric.m_byteHistory[m_recordMetricIndex] = 0; + } + } } static void CombineMetrics(MultiplayerStats::Metric& outArg1, const MultiplayerStats::Metric& arg2) diff --git a/Gems/Multiplayer/Code/Include/MultiplayerStats.h b/Gems/Multiplayer/Code/Include/MultiplayerStats.h index fcbd741bb9..dc266a14bf 100644 --- a/Gems/Multiplayer/Code/Include/MultiplayerStats.h +++ b/Gems/Multiplayer/Code/Include/MultiplayerStats.h @@ -37,6 +37,7 @@ namespace Multiplayer using MetricRingbuffer = AZStd::array; struct Metric { + Metric(); uint64_t m_totalCalls = 0; uint64_t m_totalBytes = 0; MetricRingbuffer m_callHistory; diff --git a/Gems/Multiplayer/Code/Include/MultiplayerTypes.h b/Gems/Multiplayer/Code/Include/MultiplayerTypes.h index 5c690958b5..1bee9867e3 100644 --- a/Gems/Multiplayer/Code/Include/MultiplayerTypes.h +++ b/Gems/Multiplayer/Code/Include/MultiplayerTypes.h @@ -36,6 +36,12 @@ namespace Multiplayer AZ_TYPE_SAFE_INTEGRAL(PropertyIndex, uint16_t); AZ_TYPE_SAFE_INTEGRAL(RpcIndex, uint16_t); + AZ_TYPE_SAFE_INTEGRAL(ClientInputId, uint16_t); + + //! This is a strong typedef for representing the number of application frames since application start. + AZ_TYPE_SAFE_INTEGRAL(HostFrameId, uint32_t); + static constexpr HostFrameId InvalidHostFrameId = HostFrameId{ 0xFFFFFFFF }; + using LongNetworkString = AZ::CVarFixedString; using ReliabilityType = AzNetworking::ReliabilityType; @@ -122,3 +128,5 @@ AZ_TYPE_SAFE_INTEGRAL_SERIALIZEBINDING(Multiplayer::NetEntityId); AZ_TYPE_SAFE_INTEGRAL_SERIALIZEBINDING(Multiplayer::NetComponentId); AZ_TYPE_SAFE_INTEGRAL_SERIALIZEBINDING(Multiplayer::PropertyIndex); AZ_TYPE_SAFE_INTEGRAL_SERIALIZEBINDING(Multiplayer::RpcIndex); +AZ_TYPE_SAFE_INTEGRAL_SERIALIZEBINDING(Multiplayer::ClientInputId); +AZ_TYPE_SAFE_INTEGRAL_SERIALIZEBINDING(Multiplayer::HostFrameId); diff --git a/Gems/Multiplayer/Code/Source/NetworkEntity/NetworkEntityHandle.h b/Gems/Multiplayer/Code/Include/NetworkEntityHandle.h similarity index 99% rename from Gems/Multiplayer/Code/Source/NetworkEntity/NetworkEntityHandle.h rename to Gems/Multiplayer/Code/Include/NetworkEntityHandle.h index 0f84ed4477..9b8546ef2c 100644 --- a/Gems/Multiplayer/Code/Source/NetworkEntity/NetworkEntityHandle.h +++ b/Gems/Multiplayer/Code/Include/NetworkEntityHandle.h @@ -138,4 +138,4 @@ namespace Multiplayer }; } -#include "Source/NetworkEntity/NetworkEntityHandle.inl" +#include diff --git a/Gems/Multiplayer/Code/Source/NetworkEntity/NetworkEntityHandle.inl b/Gems/Multiplayer/Code/Include/NetworkEntityHandle.inl similarity index 100% rename from Gems/Multiplayer/Code/Source/NetworkEntity/NetworkEntityHandle.inl rename to Gems/Multiplayer/Code/Include/NetworkEntityHandle.inl diff --git a/Gems/Multiplayer/Code/Source/AutoGen/AutoComponentTypes_Source.jinja b/Gems/Multiplayer/Code/Source/AutoGen/AutoComponentTypes_Source.jinja index 57375b39f2..2bae618d94 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 {% for Component in dataFiles %} {% set ComponentDerived = Component.attrib['OverrideComponent']|booleanTrue %} {% set ControllerDerived = Component.attrib['OverrideController']|booleanTrue %} diff --git a/Gems/Multiplayer/Code/Source/AutoGen/AutoComponent_Common.jinja b/Gems/Multiplayer/Code/Source/AutoGen/AutoComponent_Common.jinja index fb7de56bb1..d211b933c5 100644 --- a/Gems/Multiplayer/Code/Source/AutoGen/AutoComponent_Common.jinja +++ b/Gems/Multiplayer/Code/Source/AutoGen/AutoComponent_Common.jinja @@ -170,12 +170,12 @@ AZ::Event<{{ Property.attrib['Type'] }}> {% set PropertyName = UpperFirst(Property.attrib['Name']) %} {{ ParseRpcParams(Property, paramNames, paramTypes, paramDefines) }} {% if IsOverride %} -void Handle{{ PropertyName }}({{ ', '.join(paramDefines) }}) override {} +void Handle{{ PropertyName }}(AzNetworking::IConnection* invokingConnection, {{ ', '.join(paramDefines) }}) override {} {% else %} //! {{ PropertyName }} Handler //! {{ Property.attrib['Description'] }} //! HandleOn {{ HandleOn }} -virtual void Handle{{ PropertyName }}({{ ', '.join(paramDefines) }}) = 0; +virtual void Handle{{ PropertyName }}(AzNetworking::IConnection* invokingConnection, {{ ', '.join(paramDefines) }}) = 0; {% endif %} {% endmacro %} {# diff --git a/Gems/Multiplayer/Code/Source/AutoGen/AutoComponent_Header.jinja b/Gems/Multiplayer/Code/Source/AutoGen/AutoComponent_Header.jinja index 14a68cddf1..faaa009e34 100644 --- a/Gems/Multiplayer/Code/Source/AutoGen/AutoComponent_Header.jinja +++ b/Gems/Multiplayer/Code/Source/AutoGen/AutoComponent_Header.jinja @@ -221,11 +221,11 @@ AZStd::fixed_vector<{{ Property.attrib['Type'] }}, {{ Property.attrib['Count'] } #include #include #include -#include +#include +#include #include #include #include -#include #include #include {% call(Include) AutoComponentMacros.ParseIncludes(Component) %} @@ -435,7 +435,7 @@ namespace {{ Component.attrib['Namespace'] }} //! MultiplayerComponent interface //! @{ NetComponentId GetNetComponentId() const override; - bool HandleRpcMessage(Multiplayer::NetEntityRole remoteRole, Multiplayer::NetworkEntityRpcMessage& rpcMessage) 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; diff --git a/Gems/Multiplayer/Code/Source/AutoGen/AutoComponent_Source.jinja b/Gems/Multiplayer/Code/Source/AutoGen/AutoComponent_Source.jinja index fb802541ce..6e54ec3d58 100644 --- a/Gems/Multiplayer/Code/Source/AutoGen/AutoComponent_Source.jinja +++ b/Gems/Multiplayer/Code/Source/AutoGen/AutoComponent_Source.jinja @@ -336,7 +336,7 @@ case {{ UpperFirst(Component.attrib['Name']) }}Internal::RemoteProcedure::{{ Upp if (m_controller) { AZ_Assert(GetNetBindComponent()->GetNetEntityRole() == Multiplayer::NetEntityRole::Authority, "Entity proxy does not have authority"); - m_controller->Handle{{ UpperFirst(Property.attrib['Name']) }}({{ ', '.join(rpcParamList) }}); + m_controller->Handle{{ UpperFirst(Property.attrib['Name']) }}(invokingConnection, {{ ', '.join(rpcParamList) }}); } {% if Property.attrib['IsReliable']|booleanTrue %} {# if the rpc is not reliable we can simply drop it, also note message reliability type is default reliable in EntityRpcMessage #} @@ -350,7 +350,7 @@ case {{ UpperFirst(Component.attrib['Name']) }}Internal::RemoteProcedure::{{ Upp if (m_controller) { AZ_Assert(GetNetBindComponent()->GetNetEntityRole() == Multiplayer::NetEntityRole::Autonomous, "Entity proxy does not have autonomy"); - m_controller->Handle{{ UpperFirst(Property.attrib['Name']) }}({{ ', '.join(rpcParamList) }}); + m_controller->Handle{{ UpperFirst(Property.attrib['Name']) }}(invokingConnection, {{ ', '.join(rpcParamList) }}); } {% else %} Handle{{ UpperFirst(Property.attrib['Name']) }}({{ ', '.join(rpcParamList) }}); @@ -1251,7 +1251,12 @@ namespace {{ Component.attrib['Namespace'] }} #pragma warning(push) #pragma warning(disable: 4065) // switch statement contains 'default' but no 'case' labels - bool {{ ComponentBaseName }}::HandleRpcMessage([[maybe_unused]] Multiplayer::NetEntityRole remoteRole, Multiplayer::NetworkEntityRpcMessage& message) + bool {{ ComponentBaseName }}::HandleRpcMessage + ( + [[maybe_unused]] AzNetworking::IConnection* invokingConnection, + [[maybe_unused]] Multiplayer::NetEntityRole remoteRole, + Multiplayer::NetworkEntityRpcMessage& message + ) { const {{ UpperFirst(Component.attrib['Name']) }}Internal::RemoteProcedure rpcType = static_cast<{{ UpperFirst(Component.attrib['Name']) }}Internal::RemoteProcedure>(message.GetRpcIndex()); switch (rpcType) diff --git a/Gems/Multiplayer/Code/Source/AutoGen/LocalPredictionPlayerInputComponent.AutoComponent.xml b/Gems/Multiplayer/Code/Source/AutoGen/LocalPredictionPlayerInputComponent.AutoComponent.xml index 4eaf7ff0fb..44edcaf505 100644 --- a/Gems/Multiplayer/Code/Source/AutoGen/LocalPredictionPlayerInputComponent.AutoComponent.xml +++ b/Gems/Multiplayer/Code/Source/AutoGen/LocalPredictionPlayerInputComponent.AutoComponent.xml @@ -12,15 +12,16 @@ + - + - + - - + + @@ -30,6 +31,6 @@ - +
diff --git a/Gems/Multiplayer/Code/Source/AutoGen/Multiplayer.AutoPackets.xml b/Gems/Multiplayer/Code/Source/AutoGen/Multiplayer.AutoPackets.xml index 5de466899c..daf55c3d92 100644 --- a/Gems/Multiplayer/Code/Source/AutoGen/Multiplayer.AutoPackets.xml +++ b/Gems/Multiplayer/Code/Source/AutoGen/Multiplayer.AutoPackets.xml @@ -3,6 +3,7 @@ + @@ -35,6 +36,7 @@ + diff --git a/Gems/Multiplayer/Code/Source/Components/LocalPredictionPlayerInputComponent.cpp b/Gems/Multiplayer/Code/Source/Components/LocalPredictionPlayerInputComponent.cpp index 24986148c4..90b590d99d 100644 --- a/Gems/Multiplayer/Code/Source/Components/LocalPredictionPlayerInputComponent.cpp +++ b/Gems/Multiplayer/Code/Source/Components/LocalPredictionPlayerInputComponent.cpp @@ -13,9 +13,41 @@ #include #include #include +#include +#include +#include +#include +#include namespace Multiplayer { + AZ_CVAR(AZ::TimeMs, cl_InputRateMs, AZ::TimeMs{ 33 }, nullptr, AZ::ConsoleFunctorFlags::Null, "Rate at which to sample and process client inputs"); + AZ_CVAR(AZ::TimeMs, cl_MaxRewindHistoryMs, AZ::TimeMs{ 2000 }, nullptr, AZ::ConsoleFunctorFlags::Null, "Maximum number of milliseconds to keep for server correction rewind and replay"); +#ifndef _RELEASE + AZ_CVAR(float, cl_DebugHackTimeMultiplier, 1.0f, nullptr, AZ::ConsoleFunctorFlags::Null, "Scalar value used to simulate clock hacking cheats for validating bank time system and anticheat"); +#endif + + AZ_CVAR(bool, sv_EnableCorrections, true, nullptr, AZ::ConsoleFunctorFlags::Null, "Enables server corrections on autonomous proxy desyncs"); + AZ_CVAR(double, sv_MaxBankTimeWindowSec, 0.2, nullptr, AZ::ConsoleFunctorFlags::Null, "Maximum bank time we allow before we start rejecting autonomous proxy move inputs due to anticheat kicking in"); + AZ_CVAR(double, sv_BankTimeDecay, 0.025, nullptr, AZ::ConsoleFunctorFlags::Null, "Amount to decay bank time by, in case of more permanent shifts in client latency"); + AZ_CVAR(AZ::TimeMs, sv_MinCorrectionTimeMs, AZ::TimeMs{ 100 }, nullptr, AZ::ConsoleFunctorFlags::Null, "Minimum time to wait between sending out corrections in order to avoid flooding corrections on high-latency connections"); + AZ_CVAR(AZ::TimeMs, sv_InputUpdateTimeMs, AZ::TimeMs{ 5 }, nullptr, AZ::ConsoleFunctorFlags::Null, "Minimum time between component updates"); + + // Debug helper functions + AZStd::string GetInputString(NetworkInput& input) + { + AzNetworking::StringifySerializer serializer(',', false); + input.Serialize(serializer); + return serializer.GetString(); + } + + AZStd::string GetCorrectionDataString(NetBindComponent* netBindComponent) + { + AzNetworking::StringifySerializer serializer(',', false); + netBindComponent->SerializeEntityCorrection(serializer); + return serializer.GetString(); + } + void LocalPredictionPlayerInputComponent::LocalPredictionPlayerInputComponent::Reflect(AZ::ReflectContext* context) { AZ::SerializeContext* serializeContext = azrtti_cast(context); @@ -27,30 +59,544 @@ namespace Multiplayer LocalPredictionPlayerInputComponentBase::Reflect(context); } + void LocalPredictionPlayerInputComponent::OnInit() + { + ; + } + + void LocalPredictionPlayerInputComponent::OnActivate([[maybe_unused]] Multiplayer::EntityIsMigrating entityIsMigrating) + { + ; + } + + void LocalPredictionPlayerInputComponent::OnDeactivate([[maybe_unused]] Multiplayer::EntityIsMigrating entityIsMigrating) + { + ; + } + + LocalPredictionPlayerInputComponentController::LocalPredictionPlayerInputComponentController(LocalPredictionPlayerInputComponent& parent) + : LocalPredictionPlayerInputComponentControllerBase(parent) + , m_autonomousUpdateEvent([this]() { UpdateAutonomous(m_autonomousUpdateEvent.TimeInQueueMs()); }, AZ::Name("AutonomousUpdate Event")) + , m_updateBankedTimeEvent([this]() { UpdateBankedTime(m_updateBankedTimeEvent.TimeInQueueMs()); }, AZ::Name("BankTimeUpdate Event")) + , m_migrateStartHandler([this](ClientInputId migratedInputId) { OnMigrateStart(migratedInputId); }) + , m_migrateEndHandler([this]() { OnMigrateEnd(); }) + { + if (GetNetEntityRole() == NetEntityRole::Autonomous) + { + m_autonomousUpdateEvent.Enqueue(AZ::TimeMs{ 1 }, true); + parent.GetNetBindComponent()->AddEntityMigrationStartEventHandler(m_migrateStartHandler); + parent.GetNetBindComponent()->AddEntityMigrationEndEventHandler(m_migrateEndHandler); + } + } + + void LocalPredictionPlayerInputComponentController::OnActivate([[maybe_unused]] Multiplayer::EntityIsMigrating entityIsMigrating) + { + if (entityIsMigrating == EntityIsMigrating::True) + { + m_allowMigrateClientInput = true; + m_serverMigrateFrameId = AZ::Interface::Get()->GetHostFrameId(); + } + } + + void LocalPredictionPlayerInputComponentController::OnDeactivate([[maybe_unused]] Multiplayer::EntityIsMigrating entityIsMigrating) + { + ; + } + void LocalPredictionPlayerInputComponentController::HandleSendClientInput ( - [[maybe_unused]] const Multiplayer::NetworkInputVector& inputArray, - [[maybe_unused]] const uint32_t& stateHash, + AzNetworking::IConnection* invokingConnection, + const Multiplayer::NetworkInputArray& inputArray, + const AZ::HashValue32& stateHash, [[maybe_unused]] const AzNetworking::PacketEncodingBuffer& clientState ) { - ; + // After receiving the first input from the client, start the update event to check for slow hacking + if (!m_updateBankedTimeEvent.IsScheduled()) + { + m_updateBankedTimeEvent.Enqueue(sv_InputUpdateTimeMs, true); + } + + if (invokingConnection == nullptr) + { + // Discard any input messages that were locally dispatched or sent by disconnected clients + return; + } + + const AZ::TimeMs currentTimeMs = AZ::GetElapsedTimeMs(); + const double clientInputRateSec = static_cast(static_cast(cl_InputRateMs)) / 1000.0; + m_lastInputReceivedTimeMs = currentTimeMs; + + // Keep track of last inputs received, also allows us to update frame ids + m_lastInputReceived = inputArray; + + // Figure out which index from the input array we want + // we start at the oldest input that has not been processed + int32_t inputArrayIndex = -1; + for (int32_t i = NetworkInputArray::MaxElements - 1; i >= 0; --i) + { + // Find an input that is newer than the last one we processed + if (m_lastInputReceived[i].GetClientInputId() > GetLastInputId()) + { + inputArrayIndex = i; + break; + } + } + + if (inputArrayIndex < 0) + { + AZLOG + ( + NET_Prediction, + "Discarding old or out of order move input (current: %u, received %u)", + aznumeric_cast(GetLastInputId()), + aznumeric_cast(m_lastInputReceived[0].GetClientInputId()) + ); + return; + } + + bool lostInput = false; + if (GetLastInputId() < inputArray.GetPreviousInputId()) + { + // last move id processed is older than the previous input id, we missed some input packets + lostInput = true; + } + + SetLastInputId(m_lastInputReceived[0].GetClientInputId()); // Set this variable in case of migration + + while (inputArrayIndex >= 0) + { + NetworkInput& input = m_lastInputReceived[inputArrayIndex]; + + // Anticheat, if we're receiving too many inputs, and fall outside our variable latency input window + // Discard move input events, client may be speed hacking + if (m_clientBankedTime < sv_MaxBankTimeWindowSec) + { + m_clientBankedTime = AZStd::min(m_clientBankedTime + clientInputRateSec, (double)sv_MaxBankTimeWindowSec); // clamp to boundary + + { + ScopedAlterTime scopedTime(input.GetHostFrameId(), input.GetHostTimeMs(), invokingConnection->GetConnectionId()); + GetNetBindComponent()->ProcessInput(input, static_cast(clientInputRateSec)); + } + if (lostInput) + { + AZLOG(NET_Prediction, "InputLost InputId=%u", aznumeric_cast(input.GetClientInputId())); + } + else + { + AZLOG(NET_Prediction, "Processed InputId=%u", aznumeric_cast(input.GetClientInputId())); + } + } + else + { + AZLOG(NET_Prediction, "Dropped InputId=%u", aznumeric_cast(input.GetClientInputId())); + } + --inputArrayIndex; + } + + if (sv_EnableCorrections && (currentTimeMs - m_lastCorrectionSentTimeMs > sv_MinCorrectionTimeMs)) + { + m_lastCorrectionSentTimeMs = currentTimeMs; + + AzNetworking::HashSerializer hashSerializer; + GetNetBindComponent()->SerializeEntityCorrection(hashSerializer); + + const AZ::HashValue32 localAuthorityHash = hashSerializer.GetHash(); + + if (stateHash != localAuthorityHash) + { + // Produce correction for client + AzNetworking::PacketEncodingBuffer correction; + correction.Resize(correction.GetCapacity()); + AzNetworking::NetworkInputSerializer serializer(correction.GetBuffer(), correction.GetCapacity()); + + // only deserialize if we have data (for client/server profile/debug mismatches) + if (correction.GetSize() > 0) + { + GetNetBindComponent()->SerializeEntityCorrection(serializer); + } + + correction.Resize(serializer.GetSize()); + + // Send correction + SendClientInputCorrection(GetLastInputId(), correction); + +#ifdef _DEBUG + // In debug, show which states caused the correction + AZStd::string clientStateString; + AZStd::string serverStateString; + { + // Write in client state + AzNetworking::NetworkOutputSerializer clientStateSerializer(clientState.GetBuffer(), clientState.GetSize()); + GetNetBindComponent()->SerializeEntityCorrection(clientStateSerializer); + + // Read out state values + AzNetworking::StringifySerializer clientValues; + GetNetBindComponent()->SerializeEntityCorrection(clientValues); + + // Restore server state + AzNetworking::NetworkOutputSerializer serverStateSerializer(correction.GetBuffer(), correction.GetSize()); + GetNetBindComponent()->SerializeEntityCorrection(serverStateSerializer); + + // Read out state values + AzNetworking::StringifySerializer serverValues; + GetNetBindComponent()->SerializeEntityCorrection(serverValues); + + AZStd::map> mapComparison; + // put the server value in the first part of the pair + for (const auto& pair : serverValues.GetValueMap()) + { + mapComparison[pair.first].first = pair.second; + } + // put the client value in the second part of the pair + for (const auto& pair : clientValues.GetValueMap()) + { + mapComparison[pair.first].second = pair.second; + } + + bool firstIt = true; + for (const auto& mapPair : mapComparison) + { + if (mapPair.second.first != mapPair.second.second) + { + if (!firstIt) + { + clientStateString += ","; + serverStateString += ","; + } + firstIt = false; + + AZStd::string clientValue = mapPair.second.second.empty() ? "" : mapPair.second.second; + AZStd::string serverValue = mapPair.second.first.empty() ? "" : mapPair.second.first; + clientStateString += mapPair.first + "=" + clientValue; + serverStateString += mapPair.first + "=" + serverValue; + } + } + } +#else + const AZStd::string clientStateString = "available in debug only"; + const AZStd::string serverStateString = "available in debug only"; +#endif + + AZLOG_ERROR("** Autonomous proxy desync detected! ** clientState=[%s], serverState=[%s]", clientStateString.c_str(), serverStateString.c_str()); + } + } } void LocalPredictionPlayerInputComponentController::HandleSendMigrateClientInput ( - [[maybe_unused]] const Multiplayer::MigrateNetworkInputVector& inputArray + AzNetworking::IConnection* invokingConnection, + const Multiplayer::NetworkInputMigrationVector& inputArray ) { - ; + if (!m_allowMigrateClientInput) + { + AZLOG_ERROR("Client attempting to SendMigrateClientInput message when server was not expecting it. This may be an attempt to cheat"); + return; + } + + // We only allow the client to send this message exactly once, when the component has been migrated + // Any further processing of these messages from the client would be exploitable + m_allowMigrateClientInput = false; + + if (invokingConnection == nullptr) + { + // Discard any input migration messages that were locally dispatched or sent by disconnected clients + return; + } + + const float clientInputRateSec = static_cast(static_cast(cl_InputRateMs)) / 1000.0; + + // Copy array so we can modify input ids + NetworkInputMigrationVector inputArrayCopy = inputArray; + + for (uint32_t i = 0; i < inputArrayCopy.GetSize(); ++i) + { + NetworkInput& input = inputArrayCopy[i]; + + ++ModifyLastInputId(); + input.SetClientInputId(GetLastInputId()); + + ScopedAlterTime scopedTime(input.GetHostFrameId(), input.GetHostTimeMs(), invokingConnection->GetConnectionId()); + GetNetBindComponent()->ProcessInput(input, clientInputRateSec); + + AZLOG + ( + NET_Prediction, + "Migrated InputId=%d - i=[%s] o=[%s]", + aznumeric_cast(input.GetClientInputId()), + GetInputString(input).c_str(), + GetCorrectionDataString(GetNetBindComponent()).c_str() + ); + + // Don't bother checking for corrections here, the next regular input will trigger any corrections if necessary + // Also don't bother with any cheat detection here, because the input array is limited in size and at most and can only be sent once + // So this highly constrains anything a malicious client can do + } } void LocalPredictionPlayerInputComponentController::HandleSendClientInputCorrection ( - [[maybe_unused]] const Multiplayer::ClientInputId& inputId, - [[maybe_unused]] const AzNetworking::PacketEncodingBuffer& correction + AzNetworking::IConnection* invokingConnection, + const Multiplayer::ClientInputId& inputId, + const AzNetworking::PacketEncodingBuffer& correction ) { - ; + AZ_Assert(inputId <= m_clientInputId, "Invalid correction frame id, correction is for a move the client has not yet submitted to the server"); + if (inputId > m_clientInputId) + { + AZLOG_ERROR("Discarding correction for non-existent move, correction represents a move we haven't sent to the server yet"); + return; + } + + if (inputId <= m_lastCorrectionInputId) + { + AZLOG(NET_Prediction, "Discarding old correction for client frame %u", aznumeric_cast(inputId)); + return; + } + + m_lastCorrectionInputId = inputId; + + // Apply the correction + AzNetworking::TrackChangedSerializer serializer(correction.GetBuffer(), correction.GetSize()); + GetNetBindComponent()->SerializeEntityCorrection(serializer); + m_correctionEvent.Signal(); + + AZLOG + ( + NET_Prediction, + "Corrected InputId=%d - o=[%s]", + aznumeric_cast(m_lastCorrectionInputId), + GetCorrectionDataString(GetNetBindComponent()).c_str() + ); + + const uint32_t inputHistorySize = m_inputHistory.Size(); + const uint32_t historicalDelta = aznumeric_cast(m_clientInputId - inputId); // Do not replay the move we just corrected, that was already processed by the server + + // If this correction is for a move outside our input history window, just start replaying from the oldest move we have available + const uint32_t startReplayIndex = (inputHistorySize > historicalDelta) ? (inputHistorySize - historicalDelta) : 0; + + // Flag that we are replaying inputs + struct ScopedReplayingInput + { + ScopedReplayingInput(LocalPredictionPlayerInputComponentController* instance) + : m_instance(instance) + { + m_instance->m_replayingInput = true; + } + ~ScopedReplayingInput() + { + m_instance->m_replayingInput = false; + } + LocalPredictionPlayerInputComponentController* m_instance; + }; + ScopedReplayingInput markReplayingInput(this); + + const float clientInputRateSec = static_cast(static_cast(cl_InputRateMs)) / 1000.0; + for (uint32_t replayIndex = startReplayIndex; replayIndex < inputHistorySize; ++replayIndex) + { + // Reprocess the input for this frame + NetworkInput& input = m_inputHistory[replayIndex]; + ScopedAlterTime scopedTime(input.GetHostFrameId(), input.GetHostTimeMs(), invokingConnection->GetConnectionId()); + GetNetBindComponent()->ProcessInput(input, clientInputRateSec); + + AZLOG + ( + NET_Prediction, + "Replayed InputId=%d - i=[%s] o=[%s]", + aznumeric_cast(input.GetClientInputId()), + GetInputString(input).c_str(), + GetCorrectionDataString(GetNetBindComponent()).c_str() + ); + } + } + + bool LocalPredictionPlayerInputComponentController::IsReplayingInput() const + { + return m_replayingInput; + } + + bool LocalPredictionPlayerInputComponentController::IsMigrating() const + { + return m_lastMigratedInputId != ClientInputId{ 0 }; + } + + ClientInputId LocalPredictionPlayerInputComponentController::GetLastInputId() const + { + return m_clientInputId; + } + + HostFrameId LocalPredictionPlayerInputComponentController::GetInputFrameId(const NetworkInput& input) const + { + // If the client has sent us an invalid server frame id + // this is because they are in the process of migrating from one server to another + // In this situation, use whatever the server frame id was when this component was migrated + // This will match the closest state to what the client sees + return (input.GetHostFrameId() == InvalidHostFrameId) ? m_serverMigrateFrameId : input.GetHostFrameId(); + } + + void LocalPredictionPlayerInputComponentController::CorrectionEventAddHandle(CorrectionEvent::Handler& handler) + { + handler.Connect(m_correctionEvent); + } + + void LocalPredictionPlayerInputComponentController::OnMigrateStart(ClientInputId migratedInputId) + { + m_lastMigratedInputId = migratedInputId; + } + + void LocalPredictionPlayerInputComponentController::OnMigrateEnd() + { + NetworkInputMigrationVector inputArray; + + // Roll up all inputs that the new server doesn't have and send them now + for (AZStd::size_t i = 0; i < m_inputHistory.Size(); ++i) + { + NetworkInput& input = m_inputHistory[i]; + + // New server already has these inputs + if (input.GetClientInputId() <= m_lastMigratedInputId) + { + continue; + } + + // Clear out the old server frame id + // We don't know what server frame ids to use for the new server yet, but the new server will figure out how to deal with this + input.SetHostFrameId(InvalidHostFrameId); + + // New server doesn't have these inputs + if (!inputArray.PushBack(input)) + { + break; // Reached capacity + } + } + + // Send these inputs to the server + SendMigrateClientInput(inputArray); + + // Done migrating + m_lastMigratedInputId = ClientInputId{ 0 }; + } + + void LocalPredictionPlayerInputComponentController::UpdateAutonomous(AZ::TimeMs deltaTimeMs) + { + const double deltaTime = static_cast(deltaTimeMs) / 1000.0; + const double inputRate = static_cast(static_cast(cl_InputRateMs)) / 1000.0; + const double maxRewindHistory = static_cast(static_cast(cl_MaxRewindHistoryMs)) / 1000.0; + +#ifndef _RELEASE + m_moveAccumulator += deltaTime * cl_DebugHackTimeMultiplier; +#else + m_moveAccumulator += deltaTime; +#endif + + const uint32_t maxClientInputs = inputRate > 0.0 ? static_cast(maxRewindHistory / inputRate) : 0; + + INetworkTime* networkTime = AZ::Interface::Get(); + IMultiplayer* multiplayer = AZ::Interface::Get(); + while (m_moveAccumulator >= inputRate) + { + m_moveAccumulator -= inputRate; + ++m_clientInputId; + + NetworkInputArray inputArray(GetEntityHandle()); + NetworkInput& input = inputArray[0]; + + input.SetClientInputId(m_clientInputId); + input.SetHostFrameId(networkTime->GetHostFrameId()); + input.SetHostTimeMs(multiplayer->GetCurrentHostTimeMs()); + + // Allow components to form the input for this frame + GetNetBindComponent()->CreateInput(input, inputRate); + + // Process the input for this frame + GetNetBindComponent()->ProcessInput(input, inputRate); + + AZLOG + ( + NET_Prediction, + "Processed InutId=%d - i=[%s] o=[%s]", + aznumeric_cast(m_clientInputId), + GetInputString(input).c_str(), + GetCorrectionDataString(GetNetBindComponent()).c_str() + ); + + // Generate a hash based on the current client predicted states + AzNetworking::HashSerializer hashSerializer; + GetNetBindComponent()->SerializeEntityCorrection(hashSerializer); + + // In debug, send the entire client output state to the server to make it easier to debug desync issues + AzNetworking::PacketEncodingBuffer processInputResult; +#ifdef _DEBUG + AzNetworking::NetworkInputSerializer processInputResultSerializer(processInputResult.GetBuffer(), processInputResult.GetCapacity()); + GetNetBindComponent()->SerializeEntityCorrection(processInputResultSerializer); + processInputResult.Resize(processInputResultSerializer.GetSize()); +#endif + + // Save this input and discard move history outside our client rewind window + m_inputHistory.PushBack(input); + while (m_inputHistory.Size() > maxClientInputs) + { + m_inputHistory.PopFront(); + } + + const size_t inputHistorySize = m_inputHistory.Size(); + + // Form the rest of the input array using the n most recent elements in the history buffer + // NOTE: inputArray[0] has already been initialized hence start at i = 1 + for (uint32_t i = 1; i < NetworkInputArray::MaxElements; ++i) + { + if (i < inputHistorySize) + { + inputArray[i] = m_inputHistory[inputHistorySize - 1 - i]; + } + else // History is too small? + { + // Plug in the most recent input + inputArray[i] = input; + } + } + + // Send the input to server (only when we are not migrating) + if (!IsMigrating()) + { + SendClientInput(inputArray, hashSerializer.GetHash(), processInputResult); + } + } + } + + void LocalPredictionPlayerInputComponentController::UpdateBankedTime(AZ::TimeMs deltaTimeMs) + { + const double deltaTime = static_cast(deltaTimeMs) / 1000.0; + const double inputRate = static_cast(static_cast(cl_InputRateMs)) / 1000.0; + const double maxRewindHistory = static_cast(static_cast(cl_MaxRewindHistoryMs)) / 1000.0; + + // Update banked time accumulator + m_clientBankedTime -= deltaTime; + + // Forcibly tick any clients who are too far behind our variable latency window + // Client may be slow hacking + if (m_clientBankedTime < -sv_MaxBankTimeWindowSec) + { + m_clientBankedTime = -sv_MaxBankTimeWindowSec; // clamp to boundary + + NetworkInput& input = m_lastInputReceived[0]; + { + ScopedAlterTime scopedTime(input.GetHostFrameId(), input.GetHostTimeMs(), AzNetworking::InvalidConnectionId); + GetNetBindComponent()->ProcessInput(input, inputRate); + } + + AZLOG + ( + NET_Prediction, + "Forced InputId=%d - i=[%s] o=[%s]", + aznumeric_cast(input.GetClientInputId()), + GetInputString(input).c_str(), + GetCorrectionDataString(GetNetBindComponent()).c_str() + ); + } + + // Decay our bank time window, in case the remote endpoint has suffered a more persistent shift in latency, this should cause the client to eventually recover + m_clientBankedTime = m_clientBankedTime * (1.0 - sv_BankTimeDecay); } } diff --git a/Gems/Multiplayer/Code/Source/Components/LocalPredictionPlayerInputComponent.h b/Gems/Multiplayer/Code/Source/Components/LocalPredictionPlayerInputComponent.h index b332315799..15a4f3a048 100644 --- a/Gems/Multiplayer/Code/Source/Components/LocalPredictionPlayerInputComponent.h +++ b/Gems/Multiplayer/Code/Source/Components/LocalPredictionPlayerInputComponent.h @@ -13,9 +13,12 @@ #pragma once #include +#include namespace Multiplayer { + using CorrectionEvent = AZ::Event<>; + class LocalPredictionPlayerInputComponent : public LocalPredictionPlayerInputComponentBase { @@ -24,24 +27,87 @@ namespace Multiplayer static void Reflect([[maybe_unused]] AZ::ReflectContext* context); - void OnInit() override {} - void OnActivate([[maybe_unused]] Multiplayer::EntityIsMigrating entityIsMigrating) override {} - void OnDeactivate([[maybe_unused]] Multiplayer::EntityIsMigrating entityIsMigrating) override {} - - + void OnInit() override; + void OnActivate([[maybe_unused]] Multiplayer::EntityIsMigrating entityIsMigrating) override; + void OnDeactivate([[maybe_unused]] Multiplayer::EntityIsMigrating entityIsMigrating) override; }; class LocalPredictionPlayerInputComponentController : public LocalPredictionPlayerInputComponentControllerBase { public: - LocalPredictionPlayerInputComponentController(LocalPredictionPlayerInputComponent& parent) : LocalPredictionPlayerInputComponentControllerBase(parent) {} + LocalPredictionPlayerInputComponentController(LocalPredictionPlayerInputComponent& parent); - void OnActivate([[maybe_unused]] Multiplayer::EntityIsMigrating entityIsMigrating) override {} - void OnDeactivate([[maybe_unused]] Multiplayer::EntityIsMigrating entityIsMigrating) override {} + void OnActivate([[maybe_unused]] Multiplayer::EntityIsMigrating entityIsMigrating) override; + void OnDeactivate([[maybe_unused]] Multiplayer::EntityIsMigrating entityIsMigrating) override; - void HandleSendClientInput(const Multiplayer::NetworkInputVector& inputArray, const uint32_t& stateHash, const AzNetworking::PacketEncodingBuffer& clientState) override; - void HandleSendMigrateClientInput(const Multiplayer::MigrateNetworkInputVector& inputArray) override; - void HandleSendClientInputCorrection(const Multiplayer::ClientInputId& inputId, const AzNetworking::PacketEncodingBuffer& correction) override; + void HandleSendClientInput + ( + AzNetworking::IConnection* invokingConnection, + const Multiplayer::NetworkInputArray& inputArray, + const AZ::HashValue32& stateHash, + const AzNetworking::PacketEncodingBuffer& clientState + ) override; + + void HandleSendMigrateClientInput + ( + AzNetworking::IConnection* invokingConnection, + const Multiplayer::NetworkInputMigrationVector& inputArray + ) override; + + void HandleSendClientInputCorrection + ( + AzNetworking::IConnection* invokingConnection, + const Multiplayer::ClientInputId& inputId, + const AzNetworking::PacketEncodingBuffer& correction + ) override; + + //! Return true if we're currently replaying inputs after a correction. + //! If this value returns true, effects, audio, and other cosmetic triggers should be suppressed + //! @return true if we're within correction scope and replaying inputs + bool IsReplayingInput() const; + + //! Return true if we're currently migrating from one host to another. + //! @return boolean true if we're currently migrating from one host to another + bool IsMigrating() const; + + ClientInputId GetLastInputId() const; + HostFrameId GetInputFrameId(const NetworkInput& input) const; + + void CorrectionEventAddHandle(CorrectionEvent::Handler& handler); + + private: + + void OnMigrateStart(ClientInputId migratedInputId); + void OnMigrateEnd(); + void UpdateAutonomous(AZ::TimeMs deltaTimeMs); + void UpdateBankedTime(AZ::TimeMs deltaTimeMs); + + // Implicitly sorted player input history, back() is the input that corresponds to the latest client input Id + NetworkInputHistory m_inputHistory; + + // Anti-cheat accumulator for clients who purposely mess with their clock rate + NetworkInputArray m_lastInputReceived; + + AZ::ScheduledEvent m_autonomousUpdateEvent; // Drives autonomous input collection + AZ::ScheduledEvent m_updateBankedTimeEvent; // Drives authority bank time updates + + CorrectionEvent m_correctionEvent; + EntityMigrationStartEvent::Handler m_migrateStartHandler; + EntityMigrationEndEvent::Handler m_migrateEndHandler; + + double m_moveAccumulator = 0.0; + double m_clientBankedTime = 0.0; + + AZ::TimeMs m_lastInputReceivedTimeMs = AZ::TimeMs{ 0 }; + AZ::TimeMs m_lastCorrectionSentTimeMs = AZ::TimeMs{ 0 }; + + ClientInputId m_clientInputId = ClientInputId{ 0 }; + ClientInputId m_lastCorrectionInputId = ClientInputId{ 0 }; + ClientInputId m_lastMigratedInputId = ClientInputId{ 0 }; // Used to resend inputs that were queued during a migration event + HostFrameId m_serverMigrateFrameId = InvalidHostFrameId; + + bool m_replayingInput = false; // True if we're replaying inputs under a correction event (use this to suppress effects or audio) + bool m_allowMigrateClientInput = false; // True if this component was migrated, we will allow the client to send us migrated inputs (one time only) }; } diff --git a/Gems/Multiplayer/Code/Source/Components/MultiplayerComponent.h b/Gems/Multiplayer/Code/Source/Components/MultiplayerComponent.h index 3642a55476..0f64221dde 100644 --- a/Gems/Multiplayer/Code/Source/Components/MultiplayerComponent.h +++ b/Gems/Multiplayer/Code/Source/Components/MultiplayerComponent.h @@ -15,7 +15,7 @@ #include #include #include -#include +#include #include #include @@ -69,7 +69,7 @@ namespace Multiplayer virtual NetComponentId GetNetComponentId() const = 0; - virtual bool HandleRpcMessage(NetEntityRole netEntityRole, NetworkEntityRpcMessage& rpcMessage) = 0; + virtual bool HandleRpcMessage(AzNetworking::IConnection* invokingConnection, NetEntityRole netEntityRole, NetworkEntityRpcMessage& rpcMessage) = 0; virtual bool SerializeStateDeltaMessage(ReplicationRecord& replicationRecord, AzNetworking::ISerializer& serializer) = 0; virtual void NotifyStateDeltaChanges(ReplicationRecord& replicationRecord) = 0; virtual bool HasController() const = 0; diff --git a/Gems/Multiplayer/Code/Source/Components/MultiplayerController.h b/Gems/Multiplayer/Code/Source/Components/MultiplayerController.h index 9e3c7d68ab..de07e39e66 100644 --- a/Gems/Multiplayer/Code/Source/Components/MultiplayerController.h +++ b/Gems/Multiplayer/Code/Source/Components/MultiplayerController.h @@ -12,7 +12,7 @@ #pragma once -#include +#include #include namespace Multiplayer diff --git a/Gems/Multiplayer/Code/Source/Components/NetBindComponent.cpp b/Gems/Multiplayer/Code/Source/Components/NetBindComponent.cpp index bb1dac5a4e..eba09734a9 100644 --- a/Gems/Multiplayer/Code/Source/Components/NetBindComponent.cpp +++ b/Gems/Multiplayer/Code/Source/Components/NetBindComponent.cpp @@ -13,10 +13,10 @@ #include #include #include -#include #include #include #include +#include #include #include #include @@ -192,12 +192,12 @@ namespace Multiplayer return bounds; } - bool NetBindComponent::HandleRpcMessage(NetEntityRole remoteRole, NetworkEntityRpcMessage& message) + bool NetBindComponent::HandleRpcMessage(AzNetworking::IConnection* invokingConnection, NetEntityRole remoteRole, NetworkEntityRpcMessage& message) { auto findIt = m_multiplayerComponentMap.find(message.GetComponentId()); if (findIt != m_multiplayerComponentMap.end()) { - return findIt->second->HandleRpcMessage(remoteRole, message); + return findIt->second->HandleRpcMessage(invokingConnection, remoteRole, message); } return false; } @@ -274,9 +274,19 @@ namespace Multiplayer m_localNotificationRecord.Clear(); } - void NetBindComponent::NotifyMigration(HostId remoteHostId, AzNetworking::ConnectionId connectionId) + void NetBindComponent::NotifyMigrationStart(ClientInputId migratedInputId) { - m_entityMigrationEvent.Signal(m_netEntityHandle, remoteHostId, connectionId); + m_entityMigrationStartEvent.Signal(migratedInputId); + } + + void NetBindComponent::NotifyMigrationEnd() + { + m_entityMigrationEndEvent.Signal(); + } + + void NetBindComponent::NotifyServerMigration(HostId hostId, AzNetworking::ConnectionId connectionId) + { + m_entityServerMigrationEvent.Signal(m_netEntityHandle, hostId, connectionId); } void NetBindComponent::AddEntityStopEventHandler(EntityStopEvent::Handler& eventHandler) @@ -289,9 +299,19 @@ namespace Multiplayer eventHandler.Connect(m_dirtiedEvent); } - void NetBindComponent::AddEntityMigrationEventHandler(EntityMigrationEvent::Handler& eventHandler) + void NetBindComponent::AddEntityMigrationStartEventHandler(EntityMigrationStartEvent::Handler& eventHandler) { - eventHandler.Connect(m_entityMigrationEvent); + eventHandler.Connect(m_entityMigrationStartEvent); + } + + void NetBindComponent::AddEntityMigrationEndEventHandler(EntityMigrationEndEvent::Handler& eventHandler) + { + eventHandler.Connect(m_entityMigrationEndEvent); + } + + void NetBindComponent::AddEntityServerMigrationEventHandler(EntityServerMigrationEvent::Handler& eventHandler) + { + eventHandler.Connect(m_entityServerMigrationEvent); } bool NetBindComponent::SerializeEntityCorrection(AzNetworking::ISerializer& serializer) diff --git a/Gems/Multiplayer/Code/Source/Components/NetBindComponent.h b/Gems/Multiplayer/Code/Source/Components/NetBindComponent.h index e992dbfd72..0885e44aa4 100644 --- a/Gems/Multiplayer/Code/Source/Components/NetBindComponent.h +++ b/Gems/Multiplayer/Code/Source/Components/NetBindComponent.h @@ -21,8 +21,9 @@ #include #include #include -#include -#include +#include +#include +#include #include #include @@ -34,7 +35,9 @@ namespace Multiplayer using EntityStopEvent = AZ::Event; using EntityDirtiedEvent = AZ::Event<>; - using EntityMigrationEvent = AZ::Event; + using EntityMigrationStartEvent = AZ::Event; + using EntityMigrationEndEvent = AZ::Event<>; + using EntityServerMigrationEvent = AZ::Event; //! @class NetBindComponent //! @brief Component that provides net-binding to a networked entity. @@ -72,7 +75,7 @@ namespace Multiplayer void ProcessInput(NetworkInput& networkInput, float deltaTime); AZ::Aabb GetRewindBoundsForInput(const NetworkInput& networkInput, float deltaTime) const; - bool HandleRpcMessage(NetEntityRole remoteRole, NetworkEntityRpcMessage& message); + bool HandleRpcMessage(AzNetworking::IConnection* invokingConnection, NetEntityRole remoteRole, NetworkEntityRpcMessage& message); bool HandlePropertyChangeMessage(AzNetworking::ISerializer& serializer, bool notifyChanges = true); RpcSendEvent& GetSendAuthorityToClientRpcEvent(); @@ -84,11 +87,15 @@ namespace Multiplayer void MarkDirty(); void NotifyLocalChanges(); - void NotifyMigration(HostId remoteHostId, AzNetworking::ConnectionId connectionId); + void NotifyMigrationStart(ClientInputId migratedInputId); + void NotifyMigrationEnd(); + void NotifyServerMigration(HostId hostId, AzNetworking::ConnectionId connectionId); void AddEntityStopEventHandler(EntityStopEvent::Handler& eventHandler); void AddEntityDirtiedEventHandler(EntityDirtiedEvent::Handler& eventHandler); - void AddEntityMigrationEventHandler(EntityMigrationEvent::Handler& eventHandler); + void AddEntityMigrationStartEventHandler(EntityMigrationStartEvent::Handler& eventHandler); + void AddEntityMigrationEndEventHandler(EntityMigrationEndEvent::Handler& eventHandler); + void AddEntityServerMigrationEventHandler(EntityServerMigrationEvent::Handler& eventHandler); bool SerializeEntityCorrection(AzNetworking::ISerializer& serializer); @@ -119,7 +126,7 @@ namespace Multiplayer ReplicationRecord m_currentRecord = NetEntityRole::InvalidRole; ReplicationRecord m_totalRecord = NetEntityRole::InvalidRole; - ReplicationRecord m_predictableRecord = NetEntityRole::InvalidRole; + ReplicationRecord m_predictableRecord = NetEntityRole::Autonomous; ReplicationRecord m_localNotificationRecord = NetEntityRole::InvalidRole; PrefabEntityId m_prefabEntityId; AZStd::unordered_map m_multiplayerComponentMap; @@ -133,7 +140,9 @@ namespace Multiplayer EntityStopEvent m_entityStopEvent; EntityDirtiedEvent m_dirtiedEvent; - EntityMigrationEvent m_entityMigrationEvent; + EntityMigrationStartEvent m_entityMigrationStartEvent; + EntityMigrationEndEvent m_entityMigrationEndEvent; + EntityServerMigrationEvent m_entityServerMigrationEvent; AZ::Event<> m_onRemove; RpcSendEvent::Handler m_handleLocalServerRpcMessageEventHandle; AZ::Event<>::Handler m_handleMarkedDirty; diff --git a/Gems/Multiplayer/Code/Source/ConnectionData/ClientToServerConnectionData.cpp b/Gems/Multiplayer/Code/Source/ConnectionData/ClientToServerConnectionData.cpp index 4420e0689c..ee308f6ed8 100644 --- a/Gems/Multiplayer/Code/Source/ConnectionData/ClientToServerConnectionData.cpp +++ b/Gems/Multiplayer/Code/Source/ConnectionData/ClientToServerConnectionData.cpp @@ -50,8 +50,9 @@ namespace Multiplayer return m_entityReplicationManager; } - void ClientToServerConnectionData::Update([[maybe_unused]] AZ::TimeMs serverGameTimeMs) + void ClientToServerConnectionData::Update(AZ::TimeMs hostTimeMs) { m_entityReplicationManager.ActivatePendingEntities(); + m_entityReplicationManager.SendUpdates(hostTimeMs); } } diff --git a/Gems/Multiplayer/Code/Source/ConnectionData/ClientToServerConnectionData.h b/Gems/Multiplayer/Code/Source/ConnectionData/ClientToServerConnectionData.h index 76a809b351..b72a6aad2b 100644 --- a/Gems/Multiplayer/Code/Source/ConnectionData/ClientToServerConnectionData.h +++ b/Gems/Multiplayer/Code/Source/ConnectionData/ClientToServerConnectionData.h @@ -12,7 +12,8 @@ #pragma once -#include +#include +#include namespace Multiplayer { @@ -32,7 +33,7 @@ namespace Multiplayer ConnectionDataType GetConnectionDataType() const override; AzNetworking::IConnection* GetConnection() const override; EntityReplicationManager& GetReplicationManager() override; - void Update(AZ::TimeMs serverGameTimeMs) override; + void Update(AZ::TimeMs hostTimeMs) override; bool CanSendUpdates() const override; void SetCanSendUpdates(bool canSendUpdates) override; //! @} diff --git a/Gems/Multiplayer/Code/Source/ConnectionData/ServerToClientConnectionData.cpp b/Gems/Multiplayer/Code/Source/ConnectionData/ServerToClientConnectionData.cpp index 7a7e266a38..d2440d28f4 100644 --- a/Gems/Multiplayer/Code/Source/ConnectionData/ServerToClientConnectionData.cpp +++ b/Gems/Multiplayer/Code/Source/ConnectionData/ServerToClientConnectionData.cpp @@ -35,7 +35,7 @@ namespace Multiplayer if (netBindComponent != nullptr) { netBindComponent->AddEntityStopEventHandler(m_controlledEntityRemovedHandler); - netBindComponent->AddEntityMigrationEventHandler(m_controlledEntityMigrationHandler); + netBindComponent->AddEntityServerMigrationEventHandler(m_controlledEntityMigrationHandler); } m_entityReplicationManager.SetMaxRemoteEntitiesPendingCreationCount(sv_ClientMaxRemoteEntitiesPendingCreationCount); @@ -63,7 +63,7 @@ namespace Multiplayer return m_entityReplicationManager; } - void ServerToClientConnectionData::Update(AZ::TimeMs serverGameTimeMs) + void ServerToClientConnectionData::Update(AZ::TimeMs hostTimeMs) { m_entityReplicationManager.ActivatePendingEntities(); @@ -73,7 +73,7 @@ namespace Multiplayer // potentially false if we just migrated the player, if that is the case, don't send any more updates if (netBindComponent != nullptr && (netBindComponent->GetNetEntityRole() == NetEntityRole::Authority)) { - m_entityReplicationManager.SendUpdates(serverGameTimeMs); + m_entityReplicationManager.SendUpdates(hostTimeMs); } } } diff --git a/Gems/Multiplayer/Code/Source/ConnectionData/ServerToClientConnectionData.h b/Gems/Multiplayer/Code/Source/ConnectionData/ServerToClientConnectionData.h index 7ea62b15fd..b02e6de9aa 100644 --- a/Gems/Multiplayer/Code/Source/ConnectionData/ServerToClientConnectionData.h +++ b/Gems/Multiplayer/Code/Source/ConnectionData/ServerToClientConnectionData.h @@ -12,7 +12,8 @@ #pragma once -#include +#include +#include namespace Multiplayer { @@ -33,7 +34,7 @@ namespace Multiplayer ConnectionDataType GetConnectionDataType() const override; AzNetworking::IConnection* GetConnection() const override; EntityReplicationManager& GetReplicationManager() override; - void Update(AZ::TimeMs serverGameTimeMs) override; + void Update(AZ::TimeMs hostTimeMs) override; bool CanSendUpdates() const override; void SetCanSendUpdates(bool canSendUpdates) override; //! @} @@ -49,7 +50,7 @@ namespace Multiplayer EntityReplicationManager m_entityReplicationManager; NetworkEntityHandle m_controlledEntity; EntityStopEvent::Handler m_controlledEntityRemovedHandler; - EntityMigrationEvent::Handler m_controlledEntityMigrationHandler; + EntityServerMigrationEvent::Handler m_controlledEntityMigrationHandler; AzNetworking::IConnection* m_connection = nullptr; bool m_canSendUpdates = false; }; diff --git a/Gems/Multiplayer/Code/Source/Debug/MultiplayerDebugSystemComponent.cpp b/Gems/Multiplayer/Code/Source/Debug/MultiplayerDebugSystemComponent.cpp index 506581b5e4..aec8d8520e 100644 --- a/Gems/Multiplayer/Code/Source/Debug/MultiplayerDebugSystemComponent.cpp +++ b/Gems/Multiplayer/Code/Source/Debug/MultiplayerDebugSystemComponent.cpp @@ -235,7 +235,7 @@ namespace Multiplayer if (m_displayMultiplayerStats) { - if (ImGui::Begin("Multiplayer Stats", &m_displayMultiplayerStats, ImGuiWindowFlags_HorizontalScrollbar)) + if (ImGui::Begin("Multiplayer Stats", &m_displayMultiplayerStats, ImGuiWindowFlags_None)) { IMultiplayer* multiplayer = AZ::Interface::Get(); const Multiplayer::MultiplayerStats& stats = multiplayer->GetStats(); @@ -254,7 +254,7 @@ namespace Multiplayer if (ImGui::BeginTable("", 5, flags)) { // The first column will use the default _WidthStretch when ScrollX is Off and _WidthFixed when ScrollX is On - ImGui::TableSetupColumn("Name", ImGuiTableColumnFlags_NoHide, TEXT_BASE_WIDTH * 36.0f); + ImGui::TableSetupColumn("Name", ImGuiTableColumnFlags_WidthStretch); ImGui::TableSetupColumn("Total Calls", ImGuiTableColumnFlags_WidthFixed, TEXT_BASE_WIDTH * 12.0f); ImGui::TableSetupColumn("Total Bytes", ImGuiTableColumnFlags_WidthFixed, TEXT_BASE_WIDTH * 12.0f); ImGui::TableSetupColumn("Calls/Sec", ImGuiTableColumnFlags_WidthFixed, TEXT_BASE_WIDTH * 12.0f); diff --git a/Gems/Multiplayer/Code/Source/EntityDomains/FullOwnershipEntityDomain.h b/Gems/Multiplayer/Code/Source/EntityDomains/FullOwnershipEntityDomain.h index 95bfc211cf..c1abbe74cd 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/MultiplayerSystemComponent.cpp b/Gems/Multiplayer/Code/Source/MultiplayerSystemComponent.cpp index 03c661ab03..e6fb77eca7 100644 --- a/Gems/Multiplayer/Code/Source/MultiplayerSystemComponent.cpp +++ b/Gems/Multiplayer/Code/Source/MultiplayerSystemComponent.cpp @@ -127,7 +127,8 @@ namespace Multiplayer void MultiplayerSystemComponent::OnTick([[maybe_unused]] float deltaTime, [[maybe_unused]] AZ::ScriptTimePoint time) { - AZ::TimeMs serverGameTimeMs = AZ::GetElapsedTimeMs(); + AZ::TimeMs deltaTimeMs = aznumeric_cast(static_cast(deltaTime * 1000.0f)); + AZ::TimeMs hostTimeMs = AZ::GetElapsedTimeMs(); // Handle deferred local rpc messages that were generated during the updates m_networkEntityManager.DispatchLocalDeferredRpcMessages(); @@ -137,18 +138,19 @@ namespace Multiplayer m_networkEntityManager.NotifyEntitiesDirtied(); MultiplayerStats& stats = GetStats(); + stats.TickStats(deltaTimeMs); stats.m_entityCount = GetNetworkEntityManager()->GetEntityCount(); stats.m_serverConnectionCount = 0; stats.m_clientConnectionCount = 0; // Send out the game state update to all connections { - auto sendNetworkUpdates = [serverGameTimeMs, &stats](IConnection& connection) + auto sendNetworkUpdates = [hostTimeMs, &stats](IConnection& connection) { if (connection.GetUserData() != nullptr) { IConnectionData* connectionData = reinterpret_cast(connection.GetUserData()); - connectionData->Update(serverGameTimeMs); + connectionData->Update(hostTimeMs); if (connectionData->GetConnectionDataType() == ConnectionDataType::ServerToClient) { stats.m_clientConnectionCount++; @@ -481,7 +483,7 @@ namespace Multiplayer } } - MultiplayerAgentType MultiplayerSystemComponent::GetAgentType() + MultiplayerAgentType MultiplayerSystemComponent::GetAgentType() const { return m_agentType; } @@ -528,6 +530,18 @@ namespace Multiplayer }); } + AZ::TimeMs MultiplayerSystemComponent::GetCurrentHostTimeMs() const + { + if (GetAgentType() == MultiplayerAgentType::Client) + { + return m_lastReplicatedHostTimeMs; + } + else // ClientServer or DedicatedServer + { + return m_networkTime.GetHostTimeMs(); + } + } + 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 f25e530b61..477745e6b5 100644 --- a/Gems/Multiplayer/Code/Source/MultiplayerSystemComponent.h +++ b/Gems/Multiplayer/Code/Source/MultiplayerSystemComponent.h @@ -84,12 +84,13 @@ namespace Multiplayer //! IMultiplayer interface //! @{ - MultiplayerAgentType GetAgentType() override; + MultiplayerAgentType GetAgentType() const override; void InitializeMultiplayer(MultiplayerAgentType state) override; void AddConnectionAcquiredHandler(ConnectionAcquiredEvent::Handler& handler) override; void AddSessionInitHandler(SessionInitEvent::Handler& handler) override; void AddSessionShutdownHandler(SessionShutdownEvent::Handler& handler) override; void SendReadyForEntityUpdates(bool readyForEntityUpdates) override; + AZ::TimeMs GetCurrentHostTimeMs() const override; const char* GetComponentGemName(NetComponentId netComponentId) const override; const char* GetComponentName(NetComponentId netComponentId) const override; const char* GetComponentPropertyName(NetComponentId netComponentId, PropertyIndex propertyIndex) const override; @@ -119,5 +120,8 @@ namespace Multiplayer SessionInitEvent m_initEvent; SessionShutdownEvent m_shutdownEvent; ConnectionAcquiredEvent m_connAcquiredEvent; + + 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 74bdcd5cf0..1e7649f561 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 @@ -93,10 +93,10 @@ namespace Multiplayer } } - void EntityReplicationManager::SendUpdates(AZ::TimeMs serverGameTimeMs) + void EntityReplicationManager::SendUpdates(AZ::TimeMs hostTimeMs) { m_frameTimeMs = AZ::GetElapsedTimeMs(); - SendEntityUpdates(serverGameTimeMs); + SendEntityUpdates(hostTimeMs); SendEntityRpcs(m_deferredRpcMessagesReliable, true); SendEntityRpcs(m_deferredRpcMessagesUnreliable, false); @@ -118,7 +118,7 @@ namespace Multiplayer void EntityReplicationManager::SendEntityUpdatesPacketHelper ( - AZ::TimeMs serverGameTimeMs, + AZ::TimeMs hostTimeMs, EntityReplicatorList& toSendList, uint32_t maxPayloadSize, AzNetworking::IConnection& connection @@ -127,7 +127,8 @@ namespace Multiplayer uint32_t pendingPacketSize = 0; EntityReplicatorList replicatorUpdatedList; MultiplayerPackets::EntityUpdates entityUpdatePacket; - entityUpdatePacket.SetHostTimeMs(serverGameTimeMs); + entityUpdatePacket.SetHostTimeMs(hostTimeMs); + entityUpdatePacket.SetHostFrameId(InvalidHostFrameId); // Serialize everything while (!toSendList.empty()) { @@ -249,7 +250,7 @@ namespace Multiplayer return toSendList; } - void EntityReplicationManager::SendEntityUpdates(AZ::TimeMs serverGameTimeMs) + void EntityReplicationManager::SendEntityUpdates(AZ::TimeMs hostTimeMs) { EntityReplicatorList toSendList = GenerateEntityUpdateList(); @@ -264,7 +265,7 @@ namespace Multiplayer // While our to send list is not empty, build up another packet to send do { - SendEntityUpdatesPacketHelper(serverGameTimeMs, toSendList, m_maxPayloadSize, m_connection); + SendEntityUpdatesPacketHelper(hostTimeMs, toSendList, m_maxPayloadSize, m_connection); } while (!toSendList.empty()); } @@ -747,7 +748,7 @@ namespace Multiplayer bool EntityReplicationManager::HandleEntityUpdateMessage ( - [[maybe_unused]] AzNetworking::IConnection* connection, + [[maybe_unused]] AzNetworking::IConnection* invokingConnection, const AzNetworking::IPacketHeader& packetHeader, const NetworkEntityUpdateMessage& updateMessage ) @@ -803,7 +804,7 @@ namespace Multiplayer return handled; } - bool EntityReplicationManager::HandleEntityRpcMessage([[maybe_unused]] AzNetworking::IConnection* connection, NetworkEntityRpcMessage& message) + bool EntityReplicationManager::HandleEntityRpcMessage(AzNetworking::IConnection* invokingConnection, NetworkEntityRpcMessage& message) { EntityReplicator* entityReplicator = GetEntityReplicator(message.GetEntityId()); const bool isReplicatorValid = (entityReplicator != nullptr) && !entityReplicator->IsMarkedForRemoval(); @@ -815,7 +816,7 @@ namespace Multiplayer } else { - return entityReplicator->HandleRpcMessage(message); + return entityReplicator->HandleRpcMessage(invokingConnection, message); } } @@ -833,8 +834,7 @@ namespace Multiplayer ); return false; } - - return entityReplicator->HandleRpcMessage(message); + return entityReplicator->HandleRpcMessage(nullptr, message); } AZ::TimeMs EntityReplicationManager::GetResendTimeoutTimeMs() const @@ -877,7 +877,6 @@ namespace Multiplayer AzNetworking::TimeoutResult EntityReplicationManager::OrphanedEntityRpcs::HandleTimeout(AzNetworking::TimeoutQueue::TimeoutItem& item) { NetEntityId timedOutEntityId = aznumeric_cast(item.m_userData); - auto entityRpcsIter = m_entityRpcMap.find(timedOutEntityId); if (entityRpcsIter != m_entityRpcMap.end()) { @@ -887,7 +886,6 @@ namespace Multiplayer } m_entityRpcMap.erase(entityRpcsIter); } - return AzNetworking::TimeoutResult::Delete; } @@ -1089,7 +1087,7 @@ namespace Multiplayer if (m_updateMode == EntityReplicationManager::Mode::LocalServerToRemoteServer) { - netBindComponent->NotifyMigration(GetRemoteHostId(), GetConnection().GetConnectionId()); + netBindComponent->NotifyServerMigration(GetRemoteHostId(), GetConnection().GetConnectionId()); } bool didSucceed = true; @@ -1127,7 +1125,7 @@ namespace Multiplayer } } - bool EntityReplicationManager::HandleMessage([[maybe_unused]] AzNetworking::IConnection* connection, MultiplayerPackets::EntityMigration& message) + bool EntityReplicationManager::HandleMessage([[maybe_unused]] AzNetworking::IConnection* invokingConnection, MultiplayerPackets::EntityMigration& message) { EntityReplicator* replicator = GetEntityReplicator(message.GetEntityId()); { diff --git a/Gems/Multiplayer/Code/Source/NetworkEntity/EntityReplication/EntityReplicationManager.h b/Gems/Multiplayer/Code/Source/NetworkEntity/EntityReplication/EntityReplicationManager.h index a6470e6c34..4fc14e210f 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 @@ -59,7 +59,7 @@ namespace Multiplayer HostId GetRemoteHostId() const; void ActivatePendingEntities(); - void SendUpdates(AZ::TimeMs serverGameTimeMs); + void SendUpdates(AZ::TimeMs hostTimeMs); void Clear(bool forMigration); bool SetEntityRebasing(NetworkEntityHandle& entityHandle); @@ -82,10 +82,10 @@ namespace Multiplayer void AddAutonomousEntityReplicatorCreatedHandle(AZ::Event::Handler& handler); - bool HandleMessage(AzNetworking::IConnection* connection, MultiplayerPackets::EntityMigration& message); + bool HandleMessage(AzNetworking::IConnection* invokingConnection, MultiplayerPackets::EntityMigration& message); bool HandleEntityDeleteMessage(EntityReplicator* entityReplicator, const AzNetworking::IPacketHeader& packetHeader, const NetworkEntityUpdateMessage& updateMessage); - bool HandleEntityUpdateMessage(AzNetworking::IConnection* connection, const AzNetworking::IPacketHeader& packetHeader, const NetworkEntityUpdateMessage& updateMessage); - bool HandleEntityRpcMessage(AzNetworking::IConnection* connection, NetworkEntityRpcMessage& message); + bool HandleEntityUpdateMessage(AzNetworking::IConnection* invokingConnection, const AzNetworking::IPacketHeader& packetHeader, const NetworkEntityUpdateMessage& updateMessage); + bool HandleEntityRpcMessage(AzNetworking::IConnection* invokingConnection, NetworkEntityRpcMessage& message); AZ::TimeMs GetResendTimeoutTimeMs() const; @@ -118,9 +118,9 @@ namespace Multiplayer using EntityReplicatorList = AZStd::deque; EntityReplicatorList GenerateEntityUpdateList(); - void SendEntityUpdatesPacketHelper(AZ::TimeMs serverGameTimeMs, EntityReplicatorList& toSendList, uint32_t maxPayloadSize, AzNetworking::IConnection& connection); + void SendEntityUpdatesPacketHelper(AZ::TimeMs hostTimeMs, EntityReplicatorList& toSendList, uint32_t maxPayloadSize, AzNetworking::IConnection& connection); - void SendEntityUpdates(AZ::TimeMs serverGameTimeMs); + void SendEntityUpdates(AZ::TimeMs hostTimeMs); void SendEntityRpcs(RpcMessages& deferredRpcs, bool reliable); void MigrateEntityInternal(NetEntityId entityId); @@ -155,31 +155,27 @@ namespace Multiplayer OrphanedEntityRpcs(EntityReplicationManager& replicationManager); void Update(); bool DispatchOrphanedRpcs(EntityReplicator& entityReplicator); - void AddOrphanedRpc(NetEntityId entityId, NetworkEntityRpcMessage& entityPrcMessage); + void AddOrphanedRpc(NetEntityId entityId, NetworkEntityRpcMessage& entityRpcMessage); AZStd::size_t Size() const { return m_entityRpcMap.size(); } private: AzNetworking::TimeoutResult HandleTimeout(AzNetworking::TimeoutQueue::TimeoutItem& item) override; - struct OrphanedRpcs { OrphanedRpcs() = default; OrphanedRpcs(OrphanedRpcs&& rhs) { + m_rpcMessages.swap(rhs.m_rpcMessages); m_timeoutId = rhs.m_timeoutId; rhs.m_timeoutId = AzNetworking::TimeoutId{ 0 }; - m_rpcMessages.swap(rhs.m_rpcMessages); } - - AzNetworking::TimeoutId m_timeoutId = AzNetworking::TimeoutId{ 0 }; RpcMessages m_rpcMessages; + AzNetworking::TimeoutId m_timeoutId = AzNetworking::TimeoutId{ 0 }; }; - typedef AZStd::unordered_map EntityRpcMap; EntityRpcMap m_entityRpcMap; AzNetworking::TimeoutQueue m_timeoutQueue; EntityReplicationManager& m_replicationManager; }; - OrphanedEntityRpcs m_orphanedEntityRpcs; EntityReplicatorMap m_entityReplicatorMap; diff --git a/Gems/Multiplayer/Code/Source/NetworkEntity/EntityReplication/EntityReplicator.cpp b/Gems/Multiplayer/Code/Source/NetworkEntity/EntityReplication/EntityReplicator.cpp index b645101677..7431b95a22 100644 --- a/Gems/Multiplayer/Code/Source/NetworkEntity/EntityReplication/EntityReplicator.cpp +++ b/Gems/Multiplayer/Code/Source/NetworkEntity/EntityReplication/EntityReplicator.cpp @@ -628,7 +628,7 @@ namespace Multiplayer return result; } - bool EntityReplicator::HandleRpcMessage(NetworkEntityRpcMessage& entityRpcMessage) + 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(); @@ -676,7 +676,7 @@ namespace Multiplayer switch (result) { case RpcValidationResult::HandleRpc: - return m_netBindComponent->HandleRpcMessage(GetRemoteNetworkRole(), entityRpcMessage); + return m_netBindComponent->HandleRpcMessage(invokingConnection, GetRemoteNetworkRole(), entityRpcMessage); case RpcValidationResult::DropRpc: return true; case RpcValidationResult::DropRpcAndDisconnect: @@ -703,7 +703,7 @@ namespace Multiplayer break; } - AZ_Assert(false, "Unhandled ERpcValidationResult %d", result); + AZ_Assert(false, "Unhandled RpcValidationResult %d", result); return false; } } diff --git a/Gems/Multiplayer/Code/Source/NetworkEntity/EntityReplication/EntityReplicator.h b/Gems/Multiplayer/Code/Source/NetworkEntity/EntityReplication/EntityReplicator.h index 66274f638e..93494ab07c 100644 --- a/Gems/Multiplayer/Code/Source/NetworkEntity/EntityReplication/EntityReplicator.h +++ b/Gems/Multiplayer/Code/Source/NetworkEntity/EntityReplication/EntityReplicator.h @@ -75,8 +75,8 @@ namespace Multiplayer const PropertyPublisher* GetPropertyPublisher() const; PropertySubscriber* GetPropertySubscriber(); - // Handlers for messages - bool HandleRpcMessage(NetworkEntityRpcMessage& entityRpcMessage); + // Handlers for Rpc messages + bool HandleRpcMessage(AzNetworking::IConnection* invokingConnection, NetworkEntityRpcMessage& entityRpcMessage); //! AZ::EntityBus overrides //! @{ diff --git a/Gems/Multiplayer/Code/Source/NetworkEntity/INetworkEntityDomain.h b/Gems/Multiplayer/Code/Source/NetworkEntity/INetworkEntityDomain.h deleted file mode 100644 index 24e43de66a..0000000000 --- a/Gems/Multiplayer/Code/Source/NetworkEntity/INetworkEntityDomain.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. -* -*/ - -#pragma once - -#include - -namespace Multiplayer -{ - //! @class INetworkEntityDomain - //! @brief A class that determines if an entity should belong to a particular EntityManager. - class INetworkEntityDomain - { - public: - using EntitiesNotInDomain = AZStd::unordered_set; - - virtual ~INetworkEntityDomain() = default; - - //! Enable Entity Domain Exit Tracking for entities on the server. - //! @param ownedEntitySet - virtual void ActivateTracking(const INetworkEntityManager::OwnedEntitySet& ownedEntitySet) = 0; - - //! Return the set of entities not in this domain. - //! @param outEntitiesNotInDomain - virtual void RetrieveEntitiesNotInDomain(EntitiesNotInDomain& outEntitiesNotInDomain) const = 0; - - //! Returns whether or not an entity should be owned by an entity manager. - //! @param entityHandle the handle of the entity to check for inclusion in the domain - //! @return false if this entity should not belong to the entity manger, true if it could be owned by the entity manager - virtual bool IsInDomain(const ConstNetworkEntityHandle& entityHandle) const = 0; - }; -} diff --git a/Gems/Multiplayer/Code/Source/NetworkEntity/NetworkEntityAuthorityTracker.cpp b/Gems/Multiplayer/Code/Source/NetworkEntity/NetworkEntityAuthorityTracker.cpp index a37d444046..797d67e3ef 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 diff --git a/Gems/Multiplayer/Code/Source/NetworkEntity/NetworkEntityHandle.cpp b/Gems/Multiplayer/Code/Source/NetworkEntity/NetworkEntityHandle.cpp index 650b113186..ca0275d20b 100644 --- a/Gems/Multiplayer/Code/Source/NetworkEntity/NetworkEntityHandle.cpp +++ b/Gems/Multiplayer/Code/Source/NetworkEntity/NetworkEntityHandle.cpp @@ -10,7 +10,7 @@ * */ -#include +#include #include #include #include diff --git a/Gems/Multiplayer/Code/Source/NetworkEntity/NetworkEntityManager.cpp b/Gems/Multiplayer/Code/Source/NetworkEntity/NetworkEntityManager.cpp index ce55f66caa..1c7fb5f7af 100644 --- a/Gems/Multiplayer/Code/Source/NetworkEntity/NetworkEntityManager.cpp +++ b/Gems/Multiplayer/Code/Source/NetworkEntity/NetworkEntityManager.cpp @@ -218,7 +218,7 @@ namespace Multiplayer { NetBindComponent* netBindComponent = entity->FindComponent(); AZ_Assert(netBindComponent != nullptr, "Attempting to send an RPC to an entity with no NetBindComponent"); - netBindComponent->HandleRpcMessage(NetEntityRole::Server, rpcMessage); + netBindComponent->HandleRpcMessage(nullptr, NetEntityRole::Server, rpcMessage); } } m_localDeferredRpcMessages.clear(); diff --git a/Gems/Multiplayer/Code/Source/NetworkEntity/NetworkEntityManager.h b/Gems/Multiplayer/Code/Source/NetworkEntity/NetworkEntityManager.h index 4439503373..ae2cb0dd9e 100644 --- a/Gems/Multiplayer/Code/Source/NetworkEntity/NetworkEntityManager.h +++ b/Gems/Multiplayer/Code/Source/NetworkEntity/NetworkEntityManager.h @@ -15,11 +15,11 @@ #include #include #include -#include #include #include #include -#include +#include +#include #include #include diff --git a/Gems/Multiplayer/Code/Source/NetworkEntity/NetworkEntityTracker.cpp b/Gems/Multiplayer/Code/Source/NetworkEntity/NetworkEntityTracker.cpp index 4ced19f8d9..69f715317a 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 ffc150e5cc..4cfb242154 100644 --- a/Gems/Multiplayer/Code/Source/NetworkEntity/NetworkEntityTracker.h +++ b/Gems/Multiplayer/Code/Source/NetworkEntity/NetworkEntityTracker.h @@ -13,7 +13,7 @@ #pragma once #include -#include +#include #include #include diff --git a/Gems/Multiplayer/Code/Source/NetworkInput/NetworkInput.cpp b/Gems/Multiplayer/Code/Source/NetworkInput/NetworkInput.cpp index a02bc4209d..0ab1d5ffcc 100644 --- a/Gems/Multiplayer/Code/Source/NetworkInput/NetworkInput.cpp +++ b/Gems/Multiplayer/Code/Source/NetworkInput/NetworkInput.cpp @@ -48,19 +48,34 @@ namespace Multiplayer return m_inputId; } - void NetworkInput::SetServerTimeMs(AZ::TimeMs serverTimeMs) + void NetworkInput::SetHostFrameId(HostFrameId hostFrameId) { - m_serverTimeMs = serverTimeMs; + m_hostFrameId = hostFrameId; } - AZ::TimeMs NetworkInput::GetServerTimeMs() const + HostFrameId NetworkInput::GetHostFrameId() const { - return m_serverTimeMs; + return m_hostFrameId; } - AZ::TimeMs& NetworkInput::ModifyServerTimeMs() + HostFrameId& NetworkInput::ModifyHostFrameId() { - return m_serverTimeMs; + return m_hostFrameId; + } + + void NetworkInput::SetHostTimeMs(AZ::TimeMs hostTimeMs) + { + m_hostTimeMs = hostTimeMs; + } + + AZ::TimeMs NetworkInput::GetHostTimeMs() const + { + return m_hostTimeMs; + } + + AZ::TimeMs& NetworkInput::ModifyHostTimeMs() + { + return m_hostTimeMs; } void NetworkInput::AttachNetBindComponent(NetBindComponent* netBindComponent) @@ -76,17 +91,19 @@ namespace Multiplayer bool NetworkInput::Serialize(AzNetworking::ISerializer& serializer) { - if (!serializer.Serialize(m_inputId, "InputId")) + if (!serializer.Serialize(m_inputId, "InputId") + || !serializer.Serialize(m_hostTimeMs, "HostTimeMs") + || !serializer.Serialize(m_hostFrameId, "HostFrameId")) { return false; } - uint8_t componentInputCount = static_cast(m_componentInputs.size()); + uint16_t componentInputCount = static_cast(m_componentInputs.size()); serializer.Serialize(componentInputCount, "ComponentInputCount"); m_componentInputs.resize(componentInputCount); if (serializer.GetSerializerMode() == AzNetworking::SerializerMode::WriteToObject) { - for (uint8_t i = 0; i < componentInputCount; ++i) + for (uint16_t i = 0; i < componentInputCount; ++i) { // We need to do a little extra work here, the delta serializer won't actually write out values if they were the same as the parent. // We need to make sure we don't lose state that is intrinsic to the underlying type @@ -148,7 +165,7 @@ namespace Multiplayer void NetworkInput::CopyInternal(const NetworkInput& rhs) { m_inputId = rhs.m_inputId; - m_serverTimeMs = rhs.m_serverTimeMs; + m_hostTimeMs = rhs.m_hostTimeMs; m_componentInputs.resize(rhs.m_componentInputs.size()); for (int32_t i = 0; i < rhs.m_componentInputs.size(); ++i) { diff --git a/Gems/Multiplayer/Code/Source/NetworkInput/NetworkInput.h b/Gems/Multiplayer/Code/Source/NetworkInput/NetworkInput.h index 43768c4196..b2b0fa12c6 100644 --- a/Gems/Multiplayer/Code/Source/NetworkInput/NetworkInput.h +++ b/Gems/Multiplayer/Code/Source/NetworkInput/NetworkInput.h @@ -12,8 +12,9 @@ #pragma once -#include -#include +#include +#include +#include #include namespace Multiplayer @@ -21,8 +22,6 @@ namespace Multiplayer // Forwards class NetBindComponent; - AZ_TYPE_SAFE_INTEGRAL(ClientInputId, uint16_t); - //! @class NetworkInput //! @brief A single networked client input command. class NetworkInput final @@ -30,8 +29,8 @@ namespace Multiplayer public: //! Intentionally restrict instancing of these objects to associated containers classes only //! This is a mechanism used to restrict calling autonomous client predicted setter functions to the ProcessInput call chain only - friend class NetworkInputVector; - friend class MigrateNetworkInputVector; + friend class NetworkInputArray; + friend class NetworkInputMigrationVector; friend class NetworkInputHistory; friend class NetworkInputChild; @@ -42,9 +41,13 @@ namespace Multiplayer ClientInputId GetClientInputId() const; ClientInputId& ModifyClientInputId(); - void SetServerTimeMs(AZ::TimeMs serverTimeMs); - AZ::TimeMs GetServerTimeMs() const; - AZ::TimeMs& ModifyServerTimeMs(); + void SetHostFrameId(HostFrameId hostFrameId); + HostFrameId GetHostFrameId() const; + HostFrameId& ModifyHostFrameId(); + + void SetHostTimeMs(AZ::TimeMs hostTimeMs); + AZ::TimeMs GetHostTimeMs() const; + AZ::TimeMs& ModifyHostTimeMs(); void AttachNetBindComponent(NetBindComponent* netBindComponent); @@ -72,10 +75,9 @@ namespace Multiplayer MultiplayerComponentInputVector m_componentInputs; ClientInputId m_inputId = ClientInputId{ 0 }; - AZ::TimeMs m_serverTimeMs = AZ::TimeMs{ 0 }; + HostFrameId m_hostFrameId = InvalidHostFrameId; + AZ::TimeMs m_hostTimeMs = AZ::TimeMs{ 0 }; ConstNetworkEntityHandle m_owner; bool m_wasAttached = false; }; } - -AZ_TYPE_SAFE_INTEGRAL_SERIALIZEBINDING(Multiplayer::ClientInputId); diff --git a/Gems/Multiplayer/Code/Source/NetworkInput/NetworkInputVector.cpp b/Gems/Multiplayer/Code/Source/NetworkInput/NetworkInputArray.cpp similarity index 53% rename from Gems/Multiplayer/Code/Source/NetworkInput/NetworkInputVector.cpp rename to Gems/Multiplayer/Code/Source/NetworkInput/NetworkInputArray.cpp index 466a112e12..0f5a0d7c0c 100644 --- a/Gems/Multiplayer/Code/Source/NetworkInput/NetworkInputVector.cpp +++ b/Gems/Multiplayer/Code/Source/NetworkInput/NetworkInputArray.cpp @@ -10,21 +10,21 @@ * */ -#include -#include +#include +#include #include #include namespace Multiplayer { - NetworkInputVector::NetworkInputVector() + NetworkInputArray::NetworkInputArray() : m_owner() , m_inputs() { ; } - NetworkInputVector::NetworkInputVector(const ConstNetworkEntityHandle& entityHandle) + NetworkInputArray::NetworkInputArray(const ConstNetworkEntityHandle& entityHandle) : m_owner(entityHandle) , m_inputs() { @@ -38,27 +38,27 @@ namespace Multiplayer } } - NetworkInput& NetworkInputVector::operator[](uint32_t index) + NetworkInput& NetworkInputArray::operator[](uint32_t index) { return m_inputs[index].m_networkInput; } - const NetworkInput& NetworkInputVector::operator[](uint32_t index) const + const NetworkInput& NetworkInputArray::operator[](uint32_t index) const { return m_inputs[index].m_networkInput; } - void NetworkInputVector::SetPreviousInputId(ClientInputId previousInputId) + void NetworkInputArray::SetPreviousInputId(ClientInputId previousInputId) { m_previousInputId = previousInputId; } - ClientInputId NetworkInputVector::GetPreviousInputId() const + ClientInputId NetworkInputArray::GetPreviousInputId() const { return m_previousInputId; } - bool NetworkInputVector::Serialize(AzNetworking::ISerializer& serializer) + bool NetworkInputArray::Serialize(AzNetworking::ISerializer& serializer) { // Always serialize the full first element if (!m_inputs[0].m_networkInput.Serialize(serializer)) @@ -105,67 +105,4 @@ namespace Multiplayer serializer.Serialize(m_previousInputId, "PreviousInputId"); return true; } - - - MigrateNetworkInputVector::MigrateNetworkInputVector() - : m_owner() - { - ; - } - - MigrateNetworkInputVector::MigrateNetworkInputVector(const ConstNetworkEntityHandle& entityHandle) - : m_owner(entityHandle) - { - ; - } - - uint32_t MigrateNetworkInputVector::GetSize() const - { - return aznumeric_cast(m_inputs.size()); - } - - NetworkInput& MigrateNetworkInputVector::operator[](uint32_t index) - { - return m_inputs[index].m_networkInput; - } - - const NetworkInput& MigrateNetworkInputVector::operator[](uint32_t index) const - { - return m_inputs[index].m_networkInput; - } - - bool MigrateNetworkInputVector::PushBack(const NetworkInput& networkInput) - { - if (m_inputs.size() < m_inputs.capacity()) - { - m_inputs.push_back(networkInput); - return true; - } - return false; - } - - bool MigrateNetworkInputVector::Serialize(AzNetworking::ISerializer& serializer) - { - NetEntityId ownerId = m_owner.GetNetEntityId(); - serializer.Serialize(ownerId, "OwnerId"); - - uint32_t inputCount = aznumeric_cast(m_inputs.size()); - serializer.Serialize(inputCount, "InputCount"); - - if (serializer.GetSerializerMode() == AzNetworking::SerializerMode::WriteToObject) - { - // make sure all the possible NetworkInputs get attached prior to serialization, this double sends the size, but this message is only sent on server migration - m_inputs.resize(inputCount); - m_owner = GetNetworkEntityManager()->GetEntity(ownerId); - NetBindComponent* netBindComponent = m_owner.GetNetBindComponent(); - if (netBindComponent) - { - for (uint32_t i = 0; i < m_inputs.size(); ++i) - { - m_inputs[i].m_networkInput.AttachNetBindComponent(netBindComponent); - } - } - } - return serializer.Serialize(m_inputs, "Inputs"); - } } diff --git a/Gems/Multiplayer/Code/Source/NetworkInput/NetworkInputArray.h b/Gems/Multiplayer/Code/Source/NetworkInput/NetworkInputArray.h new file mode 100644 index 0000000000..504992fecb --- /dev/null +++ b/Gems/Multiplayer/Code/Source/NetworkInput/NetworkInputArray.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 + +#include +#include +#include +#include + +namespace Multiplayer +{ + //! @class NetworkInputArray + //! @brief An array of network inputs. Used to mitigate loss of input packets on the server. Compresses subsequent elements. + class NetworkInputArray final + { + public: + static constexpr uint32_t MaxElements = 8; // Never try to replicate a list larger than this amount + + NetworkInputArray(); + NetworkInputArray(const ConstNetworkEntityHandle& entityHandle); + ~NetworkInputArray() = default; + + NetworkInput& operator[](uint32_t index); + const NetworkInput& operator[](uint32_t index) const; + + void SetPreviousInputId(ClientInputId previousInputId); + ClientInputId GetPreviousInputId() const; + + bool Serialize(AzNetworking::ISerializer& serializer); + + private: + + struct Wrapper // Strictly a workaround to deal with the private constructor of NetworkInput + { + Wrapper() : m_networkInput() {} + Wrapper(const NetworkInput& networkInput) : m_networkInput(networkInput) {} + NetworkInput m_networkInput; + }; + + ConstNetworkEntityHandle m_owner; + AZStd::array m_inputs; + ClientInputId m_previousInputId; + }; +} diff --git a/Gems/Multiplayer/Code/Source/NetworkInput/NetworkInputChild.cpp b/Gems/Multiplayer/Code/Source/NetworkInput/NetworkInputChild.cpp index bb5f9a488d..8f70f7e1fa 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 new file mode 100644 index 0000000000..dee72156ed --- /dev/null +++ b/Gems/Multiplayer/Code/Source/NetworkInput/NetworkInputMigrationVector.cpp @@ -0,0 +1,80 @@ +/* +* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or +* its licensors. +* +* For complete copyright and license terms please see the LICENSE at the root of this +* distribution (the "License"). All use of this software is governed by the License, +* or, if provided, by the license below or the license accompanying this file. Do not +* remove or 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 Multiplayer +{ + NetworkInputMigrationVector::NetworkInputMigrationVector() + : m_owner() + { + ; + } + + NetworkInputMigrationVector::NetworkInputMigrationVector(const ConstNetworkEntityHandle& entityHandle) + : m_owner(entityHandle) + { + ; + } + + uint32_t NetworkInputMigrationVector::GetSize() const + { + return aznumeric_cast(m_inputs.size()); + } + + NetworkInput& NetworkInputMigrationVector::operator[](uint32_t index) + { + return m_inputs[index].m_networkInput; + } + + const NetworkInput& NetworkInputMigrationVector::operator[](uint32_t index) const + { + return m_inputs[index].m_networkInput; + } + + bool NetworkInputMigrationVector::PushBack(const NetworkInput& networkInput) + { + if (m_inputs.size() < m_inputs.capacity()) + { + m_inputs.push_back(networkInput); + return true; + } + return false; + } + + bool NetworkInputMigrationVector::Serialize(AzNetworking::ISerializer& serializer) + { + NetEntityId ownerId = m_owner.GetNetEntityId(); + serializer.Serialize(ownerId, "OwnerId"); + + uint32_t inputCount = aznumeric_cast(m_inputs.size()); + serializer.Serialize(inputCount, "InputCount"); + + if (serializer.GetSerializerMode() == AzNetworking::SerializerMode::WriteToObject) + { + // make sure all the possible NetworkInputs get attached prior to serialization, this double sends the size, but this message is only sent on server migration + m_inputs.resize(inputCount); + m_owner = GetNetworkEntityManager()->GetEntity(ownerId); + NetBindComponent* netBindComponent = m_owner.GetNetBindComponent(); + if (netBindComponent) + { + for (uint32_t i = 0; i < m_inputs.size(); ++i) + { + m_inputs[i].m_networkInput.AttachNetBindComponent(netBindComponent); + } + } + } + return serializer.Serialize(m_inputs, "Inputs"); + } +} diff --git a/Gems/Multiplayer/Code/Source/NetworkInput/NetworkInputVector.h b/Gems/Multiplayer/Code/Source/NetworkInput/NetworkInputMigrationVector.h similarity index 53% rename from Gems/Multiplayer/Code/Source/NetworkInput/NetworkInputVector.h rename to Gems/Multiplayer/Code/Source/NetworkInput/NetworkInputMigrationVector.h index be41495577..c6ea425fec 100644 --- a/Gems/Multiplayer/Code/Source/NetworkInput/NetworkInputVector.h +++ b/Gems/Multiplayer/Code/Source/NetworkInput/NetworkInputMigrationVector.h @@ -13,54 +13,22 @@ #pragma once #include -#include +#include +#include #include namespace Multiplayer { - //! @class NetworkInputVector - //! @brief An array of network inputs. Used to mitigate loss of input packets on the server. Compresses subsequent elements. - class NetworkInputVector final - { - public: - static constexpr uint32_t MaxElements = 8; // Never try to replicate a list larger than this amount - - NetworkInputVector(); - NetworkInputVector(const ConstNetworkEntityHandle& entityHandle); - ~NetworkInputVector() = default; - - NetworkInput& operator[](uint32_t index); - const NetworkInput& operator[](uint32_t index) const; - - void SetPreviousInputId(ClientInputId previousInputId); - ClientInputId GetPreviousInputId() const; - - bool Serialize(AzNetworking::ISerializer& serializer); - - private: - - struct Wrapper // Strictly a workaround to deal with the private constructor of NetworkInput - { - Wrapper() : m_networkInput() {} - Wrapper(const NetworkInput& networkInput) : m_networkInput(networkInput) {} - NetworkInput m_networkInput; - }; - - ConstNetworkEntityHandle m_owner; - AZStd::fixed_vector m_inputs; - ClientInputId m_previousInputId; - }; - - //! @class MigrateNetworkInputVector + //! @class NetworkInputMigrationVector //! @brief A variable sized array of input commands, used specifically when migrate a clients inputs. - class MigrateNetworkInputVector final + class NetworkInputMigrationVector final { public: static constexpr uint32_t MaxElements = 90; // Never try to migrate a list larger than this amount, bumped up to handle DTLS connection time - MigrateNetworkInputVector(); - MigrateNetworkInputVector(const ConstNetworkEntityHandle& entityHandle); - virtual ~MigrateNetworkInputVector() = default; + NetworkInputMigrationVector(); + NetworkInputMigrationVector(const ConstNetworkEntityHandle& entityHandle); + virtual ~NetworkInputMigrationVector() = default; uint32_t GetSize() const; NetworkInput& operator[](uint32_t index); diff --git a/Gems/Multiplayer/Code/Source/NetworkTime/NetworkTime.cpp b/Gems/Multiplayer/Code/Source/NetworkTime/NetworkTime.cpp index b062569dce..9a0e784d36 100644 --- a/Gems/Multiplayer/Code/Source/NetworkTime/NetworkTime.cpp +++ b/Gems/Multiplayer/Code/Source/NetworkTime/NetworkTime.cpp @@ -24,36 +24,31 @@ namespace Multiplayer AZ::Interface::Unregister(this); } - AZ::TimeMs NetworkTime::ConvertFrameIdToTimeMs([[maybe_unused]] ApplicationFrameId frameId) const - { - return AZ::TimeMs{0}; - } - - ApplicationFrameId NetworkTime::ConvertTimeMsToFrameId([[maybe_unused]] AZ::TimeMs timeMs) const - { - return ApplicationFrameId{0}; - } - - bool NetworkTime::IsApplicationFrameIdRewound() const + bool NetworkTime::IsTimeRewound() const { return m_rewindingConnectionId != AzNetworking::InvalidConnectionId; } - ApplicationFrameId NetworkTime::GetApplicationFrameId() const + HostFrameId NetworkTime::GetHostFrameId() const { - return m_applicationFrameId; + return m_hostFrameId; } - ApplicationFrameId NetworkTime::GetUnalteredApplicationFrameId() const + HostFrameId NetworkTime::GetUnalteredHostFrameId() const { return m_unalteredFrameId; } - void NetworkTime::IncrementApplicationFrameId() + void NetworkTime::IncrementHostFrameId() { - AZ_Assert(!IsApplicationFrameIdRewound(), "Incrementing the global application frameId is unsupported under a rewound time scope"); + AZ_Assert(!IsTimeRewound(), "Incrementing the global application frameId is unsupported under a rewound time scope"); ++m_unalteredFrameId; - m_applicationFrameId = m_unalteredFrameId; + m_hostFrameId = m_unalteredFrameId; + } + + AZ::TimeMs NetworkTime::GetHostTimeMs() const + { + return m_hostTimeMs; } void NetworkTime::SyncRewindableEntityState() @@ -66,14 +61,15 @@ namespace Multiplayer return m_rewindingConnectionId; } - ApplicationFrameId NetworkTime::GetApplicationFrameIdForRewindingConnection(AzNetworking::ConnectionId rewindConnectionId) const + HostFrameId NetworkTime::GetHostFrameIdForRewindingConnection(AzNetworking::ConnectionId rewindConnectionId) const { - return (IsApplicationFrameIdRewound() && (rewindConnectionId == m_rewindingConnectionId)) ? m_unalteredFrameId : m_applicationFrameId; + return (IsTimeRewound() && (rewindConnectionId == m_rewindingConnectionId)) ? m_unalteredFrameId : m_hostFrameId; } - void NetworkTime::AlterApplicationFrameId(ApplicationFrameId frameId, AzNetworking::ConnectionId rewindConnectionId) + void NetworkTime::AlterTime(HostFrameId frameId, AZ::TimeMs timeMs, AzNetworking::ConnectionId rewindConnectionId) { - m_applicationFrameId = frameId; + m_hostFrameId = frameId; + m_hostTimeMs = timeMs; m_rewindingConnectionId = rewindConnectionId; } } diff --git a/Gems/Multiplayer/Code/Source/NetworkTime/NetworkTime.h b/Gems/Multiplayer/Code/Source/NetworkTime/NetworkTime.h index 55ccb45e69..06e758b349 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 @@ -28,22 +28,22 @@ namespace Multiplayer //! INetworkTime overrides. //! @{ - AZ::TimeMs ConvertFrameIdToTimeMs(ApplicationFrameId frameId) const override; - ApplicationFrameId ConvertTimeMsToFrameId(AZ::TimeMs timeMs) const override; - bool IsApplicationFrameIdRewound() const override; - ApplicationFrameId GetApplicationFrameId() const override; - ApplicationFrameId GetUnalteredApplicationFrameId() const override; - void IncrementApplicationFrameId() override; + bool IsTimeRewound() const override; + HostFrameId GetHostFrameId() const override; + HostFrameId GetUnalteredHostFrameId() const override; + void IncrementHostFrameId() override; + AZ::TimeMs GetHostTimeMs() const override; void SyncRewindableEntityState() override; AzNetworking::ConnectionId GetRewindingConnectionId() const override; - ApplicationFrameId GetApplicationFrameIdForRewindingConnection(AzNetworking::ConnectionId rewindConnectionId) const override; - void AlterApplicationFrameId(ApplicationFrameId frameId, AzNetworking::ConnectionId rewindConnectionId) override; + HostFrameId GetHostFrameIdForRewindingConnection(AzNetworking::ConnectionId rewindConnectionId) const override; + void AlterTime(HostFrameId frameId, AZ::TimeMs timeMs, AzNetworking::ConnectionId rewindConnectionId) override; //! @} private: - ApplicationFrameId m_applicationFrameId = ApplicationFrameId{0}; - ApplicationFrameId m_unalteredFrameId = ApplicationFrameId{0}; + HostFrameId m_hostFrameId = HostFrameId{ 0 }; + HostFrameId m_unalteredFrameId = HostFrameId{ 0 }; + AZ::TimeMs m_hostTimeMs = AZ::TimeMs{ 0 }; AzNetworking::ConnectionId m_rewindingConnectionId = AzNetworking::InvalidConnectionId; }; } diff --git a/Gems/Multiplayer/Code/Source/NetworkTime/RewindableObject.h b/Gems/Multiplayer/Code/Source/NetworkTime/RewindableObject.h index cdea98dc07..4e830d4480 100644 --- a/Gems/Multiplayer/Code/Source/NetworkTime/RewindableObject.h +++ b/Gems/Multiplayer/Code/Source/NetworkTime/RewindableObject.h @@ -12,7 +12,7 @@ #pragma once -#include +#include #include #include #include @@ -87,25 +87,25 @@ namespace Multiplayer //! Returns what the appropriate current time is for this rewindable property. //! @return the appropriate current time is for this rewindable property - ApplicationFrameId GetCurrentTimeForProperty() const; + HostFrameId GetCurrentTimeForProperty() const; //! Updates the latest value for this object instance, if frameTime represents a current or future time. //! Any attempts to set old values on the object will fail //! @param value the new value to set in the object history //! @param frameTime the time to set the value for - void SetValueForTime(const BASE_TYPE& value, ApplicationFrameId frameTime); + void SetValueForTime(const BASE_TYPE& value, HostFrameId frameTime); //! Const value accessor, returns the correct value for the provided input time. //! @param frameTime the frame time to return the associated value for //! @return value given the current input time - const BASE_TYPE& GetValueForTime(ApplicationFrameId frameTime) const; + const BASE_TYPE& GetValueForTime(HostFrameId frameTime) const; //! Helper method to compute clamped array index values accounting for the offset head index. AZStd::size_t GetOffsetIndex(AZStd::size_t absoluteIndex) const; AZStd::array m_history; AzNetworking::ConnectionId m_owningConnectionId = AzNetworking::InvalidConnectionId; - ApplicationFrameId m_headTime = ApplicationFrameId{0}; + HostFrameId m_headTime = HostFrameId{0}; uint32_t m_headIndex = 0; }; } diff --git a/Gems/Multiplayer/Code/Source/NetworkTime/RewindableObject.inl b/Gems/Multiplayer/Code/Source/NetworkTime/RewindableObject.inl index 69752210bb..0835421ebd 100644 --- a/Gems/Multiplayer/Code/Source/NetworkTime/RewindableObject.inl +++ b/Gems/Multiplayer/Code/Source/NetworkTime/RewindableObject.inl @@ -48,7 +48,7 @@ namespace Multiplayer inline RewindableObject &RewindableObject::operator =(const RewindableObject& rhs) { INetworkTime* networkTime = AZ::Interface::Get(); - SetValueForTime(rhs.GetValueForTime(networkTime->GetApplicationFrameId()), GetCurrentTimeForProperty()); + SetValueForTime(rhs.GetValueForTime(networkTime->GetHostFrameId()), GetCurrentTimeForProperty()); return *this; } @@ -73,7 +73,7 @@ namespace Multiplayer template inline BASE_TYPE& RewindableObject::Modify() { - const ApplicationFrameId frameTime = GetCurrentTimeForProperty(); + const HostFrameId frameTime = GetCurrentTimeForProperty(); if (frameTime < m_headTime) { AZ_Assert(false, "Trying to mutate a rewindable in the past"); @@ -103,7 +103,7 @@ namespace Multiplayer template inline bool RewindableObject::Serialize(AzNetworking::ISerializer& serializer) { - const ApplicationFrameId frameTime = GetCurrentTimeForProperty(); + const HostFrameId frameTime = GetCurrentTimeForProperty(); BASE_TYPE value = GetValueForTime(frameTime); if (serializer.Serialize(value, "Element") && (serializer.GetSerializerMode() == AzNetworking::SerializerMode::WriteToObject)) { @@ -113,14 +113,14 @@ namespace Multiplayer } template - inline ApplicationFrameId RewindableObject::GetCurrentTimeForProperty() const + inline HostFrameId RewindableObject::GetCurrentTimeForProperty() const { INetworkTime* networkTime = AZ::Interface::Get(); - return networkTime->GetApplicationFrameIdForRewindingConnection(m_owningConnectionId); + return networkTime->GetHostFrameIdForRewindingConnection(m_owningConnectionId); } template - inline void RewindableObject::SetValueForTime(const BASE_TYPE& value, ApplicationFrameId frameTime) + inline void RewindableObject::SetValueForTime(const BASE_TYPE& value, HostFrameId frameTime) { if (frameTime < m_headTime) { @@ -155,7 +155,7 @@ namespace Multiplayer } template - inline const BASE_TYPE &RewindableObject::GetValueForTime(ApplicationFrameId frameTime) const + inline const BASE_TYPE &RewindableObject::GetValueForTime(HostFrameId frameTime) const { if (frameTime > m_headTime) { diff --git a/Gems/Multiplayer/Code/Source/ReplicationWindows/NullReplicationWindow.cpp b/Gems/Multiplayer/Code/Source/ReplicationWindows/NullReplicationWindow.cpp index 698376dccf..726c75ad86 100644 --- a/Gems/Multiplayer/Code/Source/ReplicationWindows/NullReplicationWindow.cpp +++ b/Gems/Multiplayer/Code/Source/ReplicationWindows/NullReplicationWindow.cpp @@ -10,7 +10,7 @@ * */ -#include "NullReplicationWindow.h" +#include namespace Multiplayer { diff --git a/Gems/Multiplayer/Code/Source/ReplicationWindows/NullReplicationWindow.h b/Gems/Multiplayer/Code/Source/ReplicationWindows/NullReplicationWindow.h index 76562a34e2..1922e65941 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 f6aa6b2de9..c54a610de2 100644 --- a/Gems/Multiplayer/Code/Source/ReplicationWindows/ServerToClientReplicationWindow.cpp +++ b/Gems/Multiplayer/Code/Source/ReplicationWindows/ServerToClientReplicationWindow.cpp @@ -56,6 +56,8 @@ namespace Multiplayer ServerToClientReplicationWindow::ServerToClientReplicationWindow(NetworkEntityHandle controlledEntity, const AzNetworking::IConnection* connection) : m_controlledEntity(controlledEntity) + , m_entityActivatedEventHandler([this](AZ::Entity* entity) { OnEntityActivated(entity); }) + , m_entityDeactivatedEventHandler([this](AZ::Entity* entity) { OnEntityDeactivated(entity); }) , m_connection(connection) , m_lastCheckedSentPackets(connection->GetMetrics().m_packetsSent) , m_lastCheckedLostPackets(connection->GetMetrics().m_packetsLost) @@ -74,7 +76,9 @@ namespace Multiplayer //} m_updateWindowEvent.Enqueue(sv_ClientReplicationWindowUpdateMs, true); - AZ::EntitySystemBus::Handler::BusConnect(); + + AZ::Interface::Get()->RegisterEntityActivatedEventHandler(m_entityActivatedEventHandler); + AZ::Interface::Get()->RegisterEntityDeactivatedEventHandler(m_entityDeactivatedEventHandler); } bool ServerToClientReplicationWindow::ReplicationSetUpdateReady() @@ -146,24 +150,29 @@ namespace Multiplayer } ); + NetworkEntityTracker* networkEntityTracker = GetNetworkEntityTracker(); + // Add all the neighbors for (AzFramework::VisibilityEntry* visEntry : gatheredEntries) { - // TODO: Discard entities that don't have a NetBindComponent - //if (mp_ControlledFilteredEntityComponent && mp_ControlledFilteredEntityComponent->IsEntityFiltered(iterator.Get())) //{ // continue; //} // We want to find the closest extent to the player and prioritize using that distance - const AZ::Vector3 supportNormal = controlledEntityPosition - visEntry->m_boundingVolume.GetCenter(); - const AZ::Vector3 closestPosition = visEntry->m_boundingVolume.GetSupport(supportNormal); - const float gatherDistanceSquared = controlledEntityPosition.GetDistanceSq(closestPosition); - const float priority = (gatherDistanceSquared > 0.0f) ? 1.0f / gatherDistanceSquared : 0.0f; AZ::Entity* entity = static_cast(visEntry->m_userData); - NetworkEntityHandle entityHandle(entity, GetNetworkEntityTracker()); - AddEntityToReplicationSet(entityHandle, priority, gatherDistanceSquared); + NetBindComponent* entryNetBindComponent = entity->template FindComponent(); + if (entryNetBindComponent != nullptr) + { + const AZ::Vector3 supportNormal = controlledEntityPosition - visEntry->m_boundingVolume.GetCenter(); + const AZ::Vector3 closestPosition = visEntry->m_boundingVolume.GetSupport(supportNormal); + const float gatherDistanceSquared = controlledEntityPosition.GetDistanceSq(closestPosition); + const float priority = (gatherDistanceSquared > 0.0f) ? 1.0f / gatherDistanceSquared : 0.0f; + + NetworkEntityHandle entityHandle(entryNetBindComponent, networkEntityTracker); + AddEntityToReplicationSet(entityHandle, priority, gatherDistanceSquared); + } } // Add in Autonomous Entities @@ -200,10 +209,8 @@ namespace Multiplayer //} } - void ServerToClientReplicationWindow::OnEntityActivated(const AZ::EntityId& entityId) + void ServerToClientReplicationWindow::OnEntityActivated(AZ::Entity* entity) { - AZ::Entity* entity = AZ::Interface::Get()->FindEntity(entityId); - ConstNetworkEntityHandle entityHandle(entity, GetNetworkEntityTracker()); NetBindComponent* netBindComponent = entityHandle.GetNetBindComponent(); if (netBindComponent != nullptr) @@ -231,10 +238,8 @@ namespace Multiplayer } } - void ServerToClientReplicationWindow::OnEntityDeactivated(const AZ::EntityId& entityId) + void ServerToClientReplicationWindow::OnEntityDeactivated(AZ::Entity* entity) { - AZ::Entity* entity = AZ::Interface::Get()->FindEntity(entityId); - ConstNetworkEntityHandle entityHandle(entity, GetNetworkEntityTracker()); NetBindComponent* netBindComponent = entityHandle.GetNetBindComponent(); if (netBindComponent != nullptr) diff --git a/Gems/Multiplayer/Code/Source/ReplicationWindows/ServerToClientReplicationWindow.h b/Gems/Multiplayer/Code/Source/ReplicationWindows/ServerToClientReplicationWindow.h index 4dad4bd01f..55a6a4b56e 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 @@ -27,7 +27,6 @@ namespace Multiplayer class ServerToClientReplicationWindow : public IReplicationWindow - , public AZ::EntitySystemBus::Handler { public: @@ -56,11 +55,8 @@ namespace Multiplayer //! @} private: - //! EntitySystemBus interface - //! @{ - void OnEntityActivated(const AZ::EntityId&) override; - void OnEntityDeactivated(const AZ::EntityId&) override; - //! @} + void OnEntityActivated(AZ::Entity* entity); + void OnEntityDeactivated(AZ::Entity* entity); //void CollectControlledEntitiesRecursive(ReplicationSet& replicationSet, EntityHierarchyComponent::Authority& hierarchyController); //void OnAddFilteredEntity(NetEntityId filteredEntityId); @@ -79,6 +75,9 @@ namespace Multiplayer NetworkEntityHandle m_controlledEntity; AZ::TransformInterface* m_controlledEntityTransform = nullptr; + AZ::EntityActivatedEvent::Handler m_entityActivatedEventHandler; + AZ::EntityDeactivatedEvent::Handler m_entityDeactivatedEventHandler; + //FilteredEntityComponent::Authority* m_controlledFilteredEntityComponent = nullptr; //NetBindComponent* m_controlledNetBindComponent = nullptr; diff --git a/Gems/Multiplayer/Code/Tests/RewindableObjectTests.cpp b/Gems/Multiplayer/Code/Tests/RewindableObjectTests.cpp index d2d41723eb..367b7ee0de 100644 --- a/Gems/Multiplayer/Code/Tests/RewindableObjectTests.cpp +++ b/Gems/Multiplayer/Code/Tests/RewindableObjectTests.cpp @@ -37,12 +37,12 @@ namespace UnitTest { test = i; EXPECT_EQ(i, test); - AZ::Interface::Get()->IncrementApplicationFrameId(); + AZ::Interface::Get()->IncrementHostFrameId(); } for (uint32_t i = 0; i < 16; ++i) { - Multiplayer::ScopedAlterTime time(static_cast(i), AzNetworking::InvalidConnectionId); + Multiplayer::ScopedAlterTime time(static_cast(i), AZ::TimeMs{ 0 }, AzNetworking::InvalidConnectionId); EXPECT_EQ(i, test); } @@ -50,12 +50,12 @@ namespace UnitTest { test = i; EXPECT_EQ(i, test); - AZ::Interface::Get()->IncrementApplicationFrameId(); + AZ::Interface::Get()->IncrementHostFrameId(); } for (uint32_t i = 16; i < 48; ++i) { - Multiplayer::ScopedAlterTime time(static_cast(i), AzNetworking::InvalidConnectionId); + Multiplayer::ScopedAlterTime time(static_cast(i), AZ::TimeMs{ 0 }, AzNetworking::InvalidConnectionId); EXPECT_EQ(i, test); } } @@ -68,12 +68,12 @@ namespace UnitTest { test = i; EXPECT_EQ(i, test); - AZ::Interface::Get()->IncrementApplicationFrameId(); + AZ::Interface::Get()->IncrementHostFrameId(); } { // Note that we didn't actually set any value for time rewindableBufferFrames, so we're testing fetching a value past the last time set - Multiplayer::ScopedAlterTime time(static_cast(RewindableBufferFrames), AzNetworking::InvalidConnectionId); + Multiplayer::ScopedAlterTime time(static_cast(RewindableBufferFrames), AZ::TimeMs{ 0 }, AzNetworking::InvalidConnectionId); EXPECT_EQ(RewindableBufferFrames - 1, test); } } @@ -91,12 +91,12 @@ namespace UnitTest { Object& value = test.Modify(); value.value = i; - AZ::Interface::Get()->IncrementApplicationFrameId(); + AZ::Interface::Get()->IncrementHostFrameId(); } for (uint32_t i = 0; i < RewindableBufferFrames; ++i) { - Multiplayer::ScopedAlterTime time(static_cast(i), AzNetworking::InvalidConnectionId); + Multiplayer::ScopedAlterTime time(static_cast(i), AZ::TimeMs{ 0 }, AzNetworking::InvalidConnectionId); const Object& value = test; EXPECT_EQ(value.value, i); } @@ -105,19 +105,19 @@ namespace UnitTest TEST_F(RewindableObjectTests, TestBackfillOnLargeTimestep) { Multiplayer::RewindableObject test(0); - Multiplayer::ScopedAlterTime time1(static_cast(0), AzNetworking::InvalidConnectionId); + Multiplayer::ScopedAlterTime time1(static_cast(0), AZ::TimeMs{ 0 }, AzNetworking::InvalidConnectionId); test = 1; - Multiplayer::ScopedAlterTime time2(static_cast(31), AzNetworking::InvalidConnectionId); + Multiplayer::ScopedAlterTime time2(static_cast(31), AZ::TimeMs{ 0 }, AzNetworking::InvalidConnectionId); test = 2; for (uint32_t i = 0; i < 31; ++i) { - Multiplayer::ScopedAlterTime time(static_cast(i), AzNetworking::InvalidConnectionId); + Multiplayer::ScopedAlterTime time(static_cast(i), AZ::TimeMs{ 0 }, AzNetworking::InvalidConnectionId); EXPECT_EQ(1, test); } - Multiplayer::ScopedAlterTime time3(static_cast(31), AzNetworking::InvalidConnectionId); + Multiplayer::ScopedAlterTime time3(static_cast(31), AZ::TimeMs{ 0 }, AzNetworking::InvalidConnectionId); EXPECT_EQ(2, test); } @@ -127,13 +127,13 @@ namespace UnitTest for (uint32_t i = 0; i < 1000; ++i) { - AZ::Interface::Get()->IncrementApplicationFrameId(); + AZ::Interface::Get()->IncrementHostFrameId(); } test = 1000; for (uint32_t i = 0; i < 1000; ++i) { - Multiplayer::ScopedAlterTime time(static_cast(1000 - i), AzNetworking::InvalidConnectionId); + Multiplayer::ScopedAlterTime time(static_cast(1000 - i), AZ::TimeMs{ 0 }, AzNetworking::InvalidConnectionId); EXPECT_EQ(1000, test); } } diff --git a/Gems/Multiplayer/Code/multiplayer_files.cmake b/Gems/Multiplayer/Code/multiplayer_files.cmake index f26e40355e..1f4e57ae43 100644 --- a/Gems/Multiplayer/Code/multiplayer_files.cmake +++ b/Gems/Multiplayer/Code/multiplayer_files.cmake @@ -10,10 +10,18 @@ # 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 Source/Multiplayer_precompiled.cpp Source/Multiplayer_precompiled.h Source/MultiplayerSystemComponent.cpp @@ -41,13 +49,11 @@ set(FILES Source/ConnectionData/ClientToServerConnectionData.cpp Source/ConnectionData/ClientToServerConnectionData.h Source/ConnectionData/ClientToServerConnectionData.inl - Source/ConnectionData/IConnectionData.h Source/ConnectionData/ServerToClientConnectionData.cpp Source/ConnectionData/ServerToClientConnectionData.h Source/ConnectionData/ServerToClientConnectionData.inl Source/EntityDomains/FullOwnershipEntityDomain.cpp Source/EntityDomains/FullOwnershipEntityDomain.h - Source/EntityDomains/IEntityDomain.h Source/NetworkEntity/EntityReplication/EntityReplicationManager.cpp Source/NetworkEntity/EntityReplication/EntityReplicationManager.h Source/NetworkEntity/EntityReplication/EntityReplicator.cpp @@ -59,12 +65,9 @@ set(FILES Source/NetworkEntity/EntityReplication/PropertySubscriber.h Source/NetworkEntity/EntityReplication/ReplicationRecord.cpp Source/NetworkEntity/EntityReplication/ReplicationRecord.h - Source/NetworkEntity/INetworkEntityManager.h Source/NetworkEntity/NetworkEntityAuthorityTracker.cpp Source/NetworkEntity/NetworkEntityAuthorityTracker.h Source/NetworkEntity/NetworkEntityHandle.cpp - Source/NetworkEntity/NetworkEntityHandle.h - Source/NetworkEntity/NetworkEntityHandle.inl Source/NetworkEntity/NetworkEntityManager.cpp Source/NetworkEntity/NetworkEntityManager.h Source/NetworkEntity/NetworkSpawnableLibrary.cpp @@ -76,16 +79,16 @@ set(FILES Source/NetworkEntity/NetworkEntityTracker.inl Source/NetworkEntity/NetworkEntityUpdateMessage.cpp Source/NetworkEntity/NetworkEntityUpdateMessage.h - Source/NetworkInput/IMultiplayerComponentInput.h Source/NetworkInput/NetworkInput.cpp Source/NetworkInput/NetworkInput.h + Source/NetworkInput/NetworkInputArray.cpp + Source/NetworkInput/NetworkInputArray.h Source/NetworkInput/NetworkInputChild.cpp Source/NetworkInput/NetworkInputChild.h Source/NetworkInput/NetworkInputHistory.cpp Source/NetworkInput/NetworkInputHistory.h - Source/NetworkInput/NetworkInputVector.cpp - Source/NetworkInput/NetworkInputVector.h - Source/NetworkTime/INetworkTime.h + Source/NetworkInput/NetworkInputMigrationVector.cpp + Source/NetworkInput/NetworkInputMigrationVector.h Source/NetworkTime/NetworkTime.cpp Source/NetworkTime/NetworkTime.h Source/NetworkTime/RewindableObject.h @@ -96,7 +99,6 @@ set(FILES Source/Pipeline/NetworkSpawnableHolderComponent.h Source/ReplicationWindows/NullReplicationWindow.cpp Source/ReplicationWindows/NullReplicationWindow.h - Source/ReplicationWindows/IReplicationWindow.h Source/ReplicationWindows/ServerToClientReplicationWindow.cpp Source/ReplicationWindows/ServerToClientReplicationWindow.h ) 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 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 0a8bca33ea..b71bd47288 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,38 @@ namespace PhysX bool EditorShapeColliderComponent::IsPhysicsEnabled() const { - return m_editorBody != nullptr && m_editorBody->m_simulating; + 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 { - 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 +793,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. 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 diff --git a/Gems/Prefab/PrefabBuilder/PrefabBuilderComponent.cpp b/Gems/Prefab/PrefabBuilder/PrefabBuilderComponent.cpp index 84a4cd5cc6..a95ec60d61 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::ProductAssetDependencyContainer& 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)); } @@ -248,20 +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(), 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 diff --git a/Gems/Prefab/PrefabBuilder/PrefabBuilderComponent.h b/Gems/Prefab/PrefabBuilder/PrefabBuilderComponent.h index 7fbd0b4be0..f78e2cb889 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::ProductAssetDependencyContainer& registeredDependencies, AZStd::vector& outputProducts) const; void ProcessJob(const AssetBuilderSDK::ProcessJobRequest& request, AssetBuilderSDK::ProcessJobResponse& response); 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/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/ScriptCanvas/Code/Include/ScriptCanvas/Execution/Interpreted/ExecutionInterpretedAPI.cpp b/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Execution/Interpreted/ExecutionInterpretedAPI.cpp index f0cea19645..9e061135fc 100644 --- a/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Execution/Interpreted/ExecutionInterpretedAPI.cpp +++ b/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Execution/Interpreted/ExecutionInterpretedAPI.cpp @@ -582,7 +582,7 @@ namespace ScriptCanvas int SetExecutionOut(lua_State* lua) { // \note Return values could become necessary. - // \see https://jira.agscollab.com/browse/LY-99750 + // \see LY-99750 AZ_Assert(lua_isuserdata(lua, -3), "Error in compiled lua file, 1st argument to SetExecutionOut is not userdata (Nodeable)"); AZ_Assert(lua_isnumber(lua, -2), "Error in compiled lua file, 2nd argument to SetExecutionOut is not a number"); @@ -605,7 +605,7 @@ namespace ScriptCanvas int SetExecutionOutResult(lua_State* lua) { // \note Return values could become necessary. - // \see https://jira.agscollab.com/browse/LY-99750 + // \see LY-99750 AZ_Assert(lua_isuserdata(lua, -3), "Error in compiled lua file, 1st argument to SetExecutionOutResult is not userdata (Nodeable)"); AZ_Assert(lua_isnumber(lua, -2), "Error in compiled lua file, 2nd argument to SetExecutionOutResult is not a number"); 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/Grammar/AbstractCodeModel.cpp b/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Grammar/AbstractCodeModel.cpp index 5e11b17c54..8dff6da9b1 100644 --- a/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Grammar/AbstractCodeModel.cpp +++ b/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Grammar/AbstractCodeModel.cpp @@ -3114,7 +3114,7 @@ namespace ScriptCanvas /// NOTE: after basic iteration works correctly /// \todo when subsequent input (from nodes connected to the break slot) looks up the slot from the node with key or the value, /// it is going to have to find the output of the get/key value functions in BOTH the child outs of break and loop - /// https://jira.agscollab.com/browse/LY-109862 may be required for this + /// LY-109862 may be required for this ExecutionTreePtr lastExecution = forEachLoopBody; 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/Tests/ScriptCanvasBuilderTests.cpp b/Gems/ScriptCanvas/Code/Tests/ScriptCanvasBuilderTests.cpp index ca7e2a3583..32437ae22a 100644 --- a/Gems/ScriptCanvas/Code/Tests/ScriptCanvasBuilderTests.cpp +++ b/Gems/ScriptCanvas/Code/Tests/ScriptCanvasBuilderTests.cpp @@ -82,6 +82,10 @@ protected: void UnregisterComponentDescriptor(const AZ::ComponentDescriptor*) override { } void RegisterEntityAddedEventHandler(AZ::EntityAddedEvent::Handler&) override { } void RegisterEntityRemovedEventHandler(AZ::EntityRemovedEvent::Handler&) override { } + void RegisterEntityActivatedEventHandler(AZ::EntityActivatedEvent::Handler&) override { } + void RegisterEntityDeactivatedEventHandler(AZ::EntityDeactivatedEvent::Handler&) override { } + void SignalEntityActivated(AZ::Entity*) override { } + void SignalEntityDeactivated(AZ::Entity*) override { } bool AddEntity(AZ::Entity*) override { return true; } bool RemoveEntity(AZ::Entity*) override { return true; } bool DeleteEntity(const AZ::EntityId&) override { return true; } 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 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/TextureAtlas/Code/Source/TextureAtlasSystemComponent.cpp b/Gems/TextureAtlas/Code/Source/TextureAtlasSystemComponent.cpp index 1fe3e07e61..80d4898c41 100644 --- a/Gems/TextureAtlas/Code/Source/TextureAtlasSystemComponent.cpp +++ b/Gems/TextureAtlas/Code/Source/TextureAtlasSystemComponent.cpp @@ -98,14 +98,16 @@ namespace TextureAtlasNamespace SResourceAsync* pInfo = new SResourceAsync(); pInfo->eClassName = eRCN_Texture; pInfo->pResource = iterator->second.m_atlas->GetTexture(); - gEnv->pRenderer->ReleaseResourceAsync(pInfo); + // ToDo: Update to work with Atom? LYN-3680 + // ???->ReleaseResourceAsync(pInfo); } // Reload Texture AZStd::string imagePath = iterator->second.m_path.substr(0, iterator->second.m_path.find_last_of('.')); imagePath.append(".dds"); - uint32 loadTextureFlags = (FT_USAGE_ALLOWREADSRGB | FT_DONT_STREAM); - ITexture* texture = gEnv->pRenderer->EF_LoadTexture(imagePath.c_str(), loadTextureFlags); + // ToDo: Update to work with Atom? LYN-3680 + // uint32 loadTextureFlags = (FT_USAGE_ALLOWREADSRGB | FT_DONT_STREAM); + ITexture* texture = nullptr; if (!texture || !texture->IsTextureLoaded()) { @@ -189,8 +191,9 @@ namespace TextureAtlasNamespace AzFramework::StringFunc::Path::ReplaceExtension(imagePath, "dds"); // Load the image in - uint32 loadTextureFlags = (FT_USAGE_ALLOWREADSRGB | FT_DONT_STREAM); - ITexture* texture = gEnv->pRenderer->EF_LoadTexture(imagePath.c_str(), loadTextureFlags); + // ToDo: Update to work with Atom? LYN-3680 + // uint32 loadTextureFlags = (FT_USAGE_ALLOWREADSRGB | FT_DONT_STREAM); + ITexture* texture = nullptr; if (!texture || !texture->IsTextureLoaded()) { @@ -241,7 +244,8 @@ namespace TextureAtlasNamespace SResourceAsync* pInfo = new SResourceAsync(); pInfo->eClassName = eRCN_Texture; pInfo->pResource = temp.m_atlas->GetTexture(); - gEnv->pRenderer->ReleaseResourceAsync(pInfo); + // ToDo: Update to work with Atom? LYN-3680 + // ???->ReleaseResourceAsync(pInfo); } // Delete the atlas SAFE_DELETE(temp.m_atlas); diff --git a/Gems/Vegetation/Code/Source/Debugger/DebugComponent.cpp b/Gems/Vegetation/Code/Source/Debugger/DebugComponent.cpp index ec8c929719..099bd2e90c 100644 --- a/Gems/Vegetation/Code/Source/Debugger/DebugComponent.cpp +++ b/Gems/Vegetation/Code/Source/Debugger/DebugComponent.cpp @@ -192,25 +192,8 @@ void DebugComponent::DrawGlobalDebugInfo() void DebugComponent::DrawInstanceDebug() { #if defined(VEG_PROFILE_ENABLED) - ISystem* crySystem = GetISystem(); - if (!crySystem) - { - return; - } - - IRenderer* renderer = crySystem->GetIRenderer(); - if (!renderer) - { - return; - } - - IRenderAuxGeom* renderAuxGeom = renderer->GetIRenderAuxGeom(); - if (!renderAuxGeom) - { - return; - } - - renderAuxGeom->SetRenderFlags(e_Mode3D | e_FillModeSolid | e_CullModeBack | e_DepthWriteOff | e_DepthTestOn); + // ToDo: Re-implement with Atom. LYN-3681 + /*renderAuxGeom->SetRenderFlags(e_Mode3D | e_FillModeSolid | e_CullModeBack | e_DepthWriteOff | e_DepthTestOn); AZStd::unordered_map areaDebugDisplayDataMap; @@ -241,7 +224,7 @@ void DebugComponent::DrawInstanceDebug() AABB bounds(pos - radius, pos + radius); renderAuxGeom->DrawAABB(bounds, true, ColorB(areaDebugDisplayData.m_instanceColor.ToU32()), eBBD_Faceted); - } + }*/ #endif } @@ -922,25 +905,8 @@ void DebugComponent::RemoveConsoleVariables() void DebugComponent::DrawDebugStats() { - ISystem* crySystem = GetISystem(); - if (!crySystem) - { - return; - } - - IRenderer* renderer = crySystem->GetIRenderer(); - if (!renderer) - { - return; - } - - IRenderAuxGeom* renderAuxGeom = renderer->GetIRenderAuxGeom(); - if (!renderAuxGeom) - { - return; - } - - if (!m_debugData) + // ToDo: Re-implement with Atom. LYN-3681 + /*if (!m_debugData) { return; } @@ -961,7 +927,7 @@ void DebugComponent::DrawDebugStats() destroyTaskCount, m_debugData->m_areaTaskQueueCount.load(AZStd::memory_order_relaxed), m_debugData->m_areaTaskActiveCount.load(AZStd::memory_order_relaxed) - ).c_str()); + ).c_str());*/ } void DebugComponent::AddConsoleVariables() 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 diff --git a/Gems/WhiteBox/Code/Source/EditorWhiteBoxComponent.cpp b/Gems/WhiteBox/Code/Source/EditorWhiteBoxComponent.cpp index e88b4ce686..d4ab543404 100644 --- a/Gems/WhiteBox/Code/Source/EditorWhiteBoxComponent.cpp +++ b/Gems/WhiteBox/Code/Source/EditorWhiteBoxComponent.cpp @@ -414,8 +414,7 @@ namespace WhiteBox m_localAabb.reset(); m_faces.reset(); - AzFramework::EntityBoundsUnionRequestBus::Broadcast( - &AzFramework::EntityBoundsUnionRequestBus::Events::RefreshEntityLocalBoundsUnion, GetEntityId()); + AZ::Interface::Get()->RefreshEntityLocalBoundsUnion(GetEntityId()); // must have been created in Activate or have had the Entity made visible again if (m_renderMesh.has_value()) diff --git a/Registry/AssetProcessorPlatformConfig.setreg b/Registry/AssetProcessorPlatformConfig.setreg index 087a0f5d96..5f397db06b 100644 --- a/Registry/AssetProcessorPlatformConfig.setreg +++ b/Registry/AssetProcessorPlatformConfig.setreg @@ -188,9 +188,12 @@ "pattern": ".*\\\\/ArtSource\\\\/.*" }, //------------------------------------------------------------------------------ - // RC params mapping examples + // Copying Files Automatically Into the Cache //------------------------------------------------------------------------------ + // The below section is used to register patterns (*.something) to copy into the cache + // the "params" block must either be "copy" (copy the file) or "skip" (used for per-platfrom skipping) + // note that productAssetType is a means of setting the output asset Type (as in AZ::Data::AssetType) of a simple job // and is the recommended way to specify that a certain kind of file (such as '*.myextension') becomes registered as the // actual UUID of that type in the engine itself. @@ -198,88 +201,43 @@ // Use a regex for matching files, same params for all platforms // "RC TGAs": { // "pattern": ".+\\\\.tga$", - // "params": "/tga /texture" + // "params": "copy" //} - // Use a glob, have special params for es3 platform + // Example Use a glob instead of a regex, skip the copy for the "server" platform // "RC TIFFs": { // "glob": "*.tif", - // "params": "/texture", - // "es3": "/pvrt" + // "params": "copy", + // "server": "skip" //} // You can also modify a version to compile all matching files again // By default the version is empty // "RC tif": { // "glob": "*.tif", - // "params": "\\someparams", + // "params": "copy", // "version": 1.0 //} - // This will make the AssetProcessor compile all the .tif files again + // This will make the AssetProcessor compile all the .tif files again if version changes. // you can also optionally supply a priority. - // this is used to sort jobs when no other external circumstance sorts them - // for example, copy jobs will be higher in priority than other jobs that are not copy jobs - // however if they're both copy jobs or both not, and no other circumstances apply, then priority will be used. - // default priority is zero if not specified - - // you can specify an option to skip processing for a file type based on the platform. - // for example, if you dont want to process tif files for ios, you can make tif files - // process on any platform except for ios: - // "RC tif": { - // "glob": "*.tif", - // "params": "\\someparams", - // "ios": "skip" - //} - - // you can specify an option to output product dependencies for a copy job. - // please note that you only need to set this option when cry code is required to parse the asset. - // otherwise product dependencies will be output automatically by the CopyDependencyBuilder. - // for example, if you want to output the product dependencies for font assets: - // "RC font": { - // "glob": "*.font", - // "params": "copy", - // "outputProductDependencies": true - //} - - // you can also specify an option to make all jobs critical that matches some pattern/glob. - // for example, if you want to make all png files critical than set critical to true. - // Note that by default all copy jobs are critical. - // Critical jobs are processed before non critical jobs and also prevent the runtime or editor from starting until they are all complete. - // "RC png": { - // "glob": "*.png", - // "params": "\\someparams", - // "critical": true - //} - - // you can also specify an option to make all the job store in the asset server cache location if you are running AP in server mode. - // For example, if you want to store all png jobs in the asset server cache location including their logs, you can set checkServer = true. - // The client(i.e if you are running AP in non-server mode) will also check for this flag to know which jobs to fetch from the asset server cache location. - // if unsucessful, it will process the job locally as usual. - // "RC png": { - // "glob": "*.png", - // "params": "\\someparams", - // "critical": true, - // "checkServer": true - //} + // this is used to sort jobs when no other external circumstance sorts them (higher wins, default is 0) // note that the FULL PATH to the file will be used as the match, not the relative path // so ensure start your patterns with .* or as appropriate. // Also, any rules which match will apply - so if you have two rules which both apply to PNG files for example // but you only want one, you might want to use exclusion patterns: - //Example: process everything EXCEPT the ones in the libs/ui folder with these params + //Example: copy everything EXCEPT the ones in the libs/ui // "RC png-normal": { // "pattern": "(?!.*libs\\\\/ui\\\\/).*\\.png", - // "params": "/imagecompressor=CTSquish /streaming=0", - // "lockSource": true + // "params": "copy" //} - //Example: Process everything in the libs/ui folder with linear color space + //Example: Process everything in the libs/ui folder // "RC png-ui": { // "pattern": "(.*libs\\\\/ui\\\\/).*\\.png", - // "params": "/imagecompressor=CTSquish /streaming=0 /colorspace=linear,linear", - // "lockSource": true + // "params": "copy" //} // More example Regexes: @@ -288,20 +246,8 @@ // "pattern": "((.*libs\\\\/ui\\\\/)|(.*editor\\\\/).*\\\\.png" // This pattern will only match anything with editor/ or libs/ui/ in it - // Give every [Section Name] its own unique Name or else they will overwrite each other! - "RC i_caf": { - "glob": "*.i_caf", - "params": "/cafAlignTracks=1 /animConfigFolder=Animations /skipdba=1 /refresh=1", - // force server to send the 'pc' platform to RC.EXE so it compiles the same as PC. - "server": "/cafAlignTracks=1 /animConfigFolder=Animations /skipdba=1 /refresh=1 /p=pc", - "priority": 5, - "productAssetType": "{6023CFF8-FCBA-4528-A8BF-6E0E10B9AB9C}" - }, - "RC caf": { - "glob": "*.caf", - "params": "copy", - "productAssetType": "{6023CFF8-FCBA-4528-A8BF-6E0E10B9AB9C}" - }, + // This is a JSON object - every entry must start with "RC" but make sure + // to give every entry its own unique Name or else they will overwrite each other: "RC mp4": { "glob": "*.mp4", "params": "copy", @@ -331,22 +277,6 @@ "glob": "*.img", "params": "copy" }, - "RC dba": { - "glob": "*.dba", - "params": "copy", - "productAssetType": "{511562BE-65A5-4538-A5F1-AC685366243E}", - "version": 2 - }, - "RC cgf": { - "glob": "*.cgf", - "params": "/VertexPositionFormat=exporter /VertexIndexFormat=u32", - // on server, feed rc.exe the param /p=pc to force it to compile assets for server platform in pc format. - "server": "/VertexPositionFormat=exporter /VertexIndexFormat=u32 /p=pc", - "lockSource": true, - "priority": 10 - // allow CGF files to compile first, so untextured models appear before their textures for faster startup - // other available params: /SplitLODs=1 - }, "RC surfaceTagNameList": { "glob": "*.surfaceTagNameList", "params": "copy", @@ -357,43 +287,6 @@ "params": "copy", "productAssetType": "{B36FEB5C-41B6-4B58-A212-21EF5AEF523C}" }, - "RC fbx": { - "glob": "*.fbx", - // Priority set to 9 so its "before" things like materials but after things like actors and motions (which build using a proper AssetBuilderSDK builder and thus are not in this file) - "priority": 9, - "version": 5 - }, - "RC chr": { - "glob": "*.chr", - "params": "copy", - "productAssetType": "{60161B46-21F0-4396-A4F0-F2CCF0664CDE}", - "version": 2 - }, - "RC skin": { - "glob": "*.skin", - "params": "copy" - }, - "RC cfi": { - "glob": "*.cfi", - "params": "copy" - }, - "RC cfx": { - "glob": "*.cfx", - "params": "copy" - }, - "RC cfr": { - "glob": "*.cfr", - "params": "copy" - }, - // Warning: If you change the VertexIndexFormat, make sure you update the vtx_idx typedef in Code\CryEngine\CryCommon\ProjectDefines.h - "RC abc": { - "glob": "*.abc", - "params": "/SkipFilesWithoutBuildConfig=0 /VertexIndexFormat=u32", - "console": "/SkipFilesWithoutBuildConfig=0 /VertexIndexFormat=u32", - "mobile": "/SkipFilesWithoutBuildConfig=0 /VertexIndexFormat=u16", - "version": 3, - "server": "skip" - }, "RC png-entityicon": { "pattern": "(.*EntityIcons\\\\/).*\\\\.png", "productAssetType": "{3436C30E-E2C5-4C3B-A7B9-66C94A28701B}", @@ -411,11 +304,6 @@ "productAssetType": "{C1D209C1-F81A-4586-A34E-1615995F9F3F}", "version": 2 }, - "RC adb": { - "glob": "*.adb", - "params": "copy", - "productAssetType": "{50908273-CA36-4668-9828-15DD5092F973}" - }, "RC bspace": { "glob": "*.bspace", "params": "copy" @@ -425,15 +313,6 @@ "params": "copy", "productAssetType": "{DF036C63-9AE6-4AC3-A6AC-8A1D76126C01}" }, - // note - this used to be skinnedMeshAsset but its now Character Definition File specific. - // .skin has its own type. - - "RC chrparams": { - "glob": "*.chrparams", - "params": "copy", - "productAssetType": "{4BBB785A-6824-4803-A607-F9323E7BEEF1}", - "version": 2 - }, "RC comb": { "glob": "*.comb", "params": "copy" diff --git a/Templates/DefaultGem/Template/CMakeLists.txt b/Templates/DefaultGem/Template/CMakeLists.txt index eaf5cdff3e..fb63008782 100644 --- a/Templates/DefaultGem/Template/CMakeLists.txt +++ b/Templates/DefaultGem/Template/CMakeLists.txt @@ -9,13 +9,18 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # {END_LICENSE} +set(o3de_gem_path ${CMAKE_CURRENT_LIST_DIR}) +set(o3de_gem_json ${o3de_gem_path}/gem.json) +o3de_gem_name(${o3de_gem_json} o3de_gem_name) +o3de_restricted_path(${o3de_gem_json} o3de_gem_restricted_path) + # Currently we are in the DefaultProjectSource folder: ${CMAKE_CURRENT_LIST_DIR} # Get the platform specific folder ${pal_dir} for the current folder: ${CMAKE_CURRENT_LIST_DIR}/Platform/${PAL_PLATFORM_NAME} # Note: ly_get_list_relative_pal_filename will take care of the details for us, as this may be a restricted platform # in which case it will see if that platform is present here or in the restricted folder. # i.e. It could here: DefaultProjectSource/Platform/ or # //DefaultProjectSource -ly_get_list_relative_pal_filename(pal_dir ${CMAKE_CURRENT_LIST_DIR}/Platform/${PAL_PLATFORM_NAME}) +ly_get_list_relative_pal_filename(pal_dir ${CMAKE_CURRENT_LIST_DIR}/Platform/${PAL_PLATFORM_NAME} ${o3de_gem_restricted_path} ${o3de_gem_path} ${o3de_gem_name}) # Now that we have the platform abstraction layer (PAL) folder for this folder, thats where we will find the # project cmake for this platform. diff --git a/Templates/DefaultGem/Template/Code/CMakeLists.txt b/Templates/DefaultGem/Template/Code/CMakeLists.txt index 8510dc53d5..3511f8ff83 100644 --- a/Templates/DefaultGem/Template/Code/CMakeLists.txt +++ b/Templates/DefaultGem/Template/Code/CMakeLists.txt @@ -15,7 +15,7 @@ # in which case it will see if that platform is present here or in the restricted folder. # i.e. It could here in our gem : Gems/${Name}/Code/Platform/ or # //Gems/${Name}/Code -ly_get_list_relative_pal_filename(pal_dir ${CMAKE_CURRENT_LIST_DIR}/Platform/${PAL_PLATFORM_NAME}) +ly_get_list_relative_pal_filename(pal_dir ${CMAKE_CURRENT_LIST_DIR}/Platform/${PAL_PLATFORM_NAME} ${o3de_gem_restricted_path} ${o3de_gem_path} ${o3de_gem_name}) # Now that we have the platform abstraction layer (PAL) folder for this folder, thats where we will find the # traits for this platform. Traits for a platform are defines for things like whether or not something in this gem diff --git a/Templates/DefaultGem/Template/gem.json b/Templates/DefaultGem/Template/gem.json index 0d233d0c50..5b8fb3fde0 100644 --- a/Templates/DefaultGem/Template/gem.json +++ b/Templates/DefaultGem/Template/gem.json @@ -4,7 +4,11 @@ "license": "What license ${Name} uses goes here: i.e. https://opensource.org/licenses/MIT", "display_name": "${Name}", "summary": "A short description of ${Name}.", - "canonical_tags": ["Gem"], - "user_tags": ["${Name}"], + "canonical_tags": [ + "Gem" + ], + "user_tags": [ + "${Name}" + ], "icon_path": "preview.png" } diff --git a/Templates/DefaultGem/template.json b/Templates/DefaultGem/template.json index 9b14a7af3a..22d4eb27e6 100644 --- a/Templates/DefaultGem/template.json +++ b/Templates/DefaultGem/template.json @@ -1,5 +1,7 @@ { "template_name": "DefaultGem", + "restricted": "o3de", + "restricted_platform_relative_path": "Templates", "origin": "The primary repo for DefaultGem goes here: i.e. http://www.mydomain.com", "license": "What license DefaultGem uses goes here: i.e. https://opensource.org/licenses/MIT", "display_name": "DefaultGem", @@ -270,6 +272,10 @@ } ], "createDirectories": [ + { + "dir": "Assets", + "origin": "Assets" + }, { "dir": "Code", "origin": "Code" @@ -339,4 +345,4 @@ "origin": "Platform/iOS" } ] -} \ No newline at end of file +} diff --git a/Templates/DefaultProject/Template/CMakeLists.txt b/Templates/DefaultProject/Template/CMakeLists.txt index c314f0da5c..ad0a4c869d 100644 --- a/Templates/DefaultProject/Template/CMakeLists.txt +++ b/Templates/DefaultProject/Template/CMakeLists.txt @@ -23,38 +23,64 @@ function(add_vs_debugger_arguments) endforeach() endfunction() +set(o3de_project_path ${CMAKE_CURRENT_LIST_DIR}) +set(o3de_project_json ${o3de_project_path}/project.json) + if(NOT PROJECT_NAME) cmake_minimum_required(VERSION 3.19) project(${Name} LANGUAGES C CXX VERSION 1.0.0.0 ) - include(EngineFinder.cmake OPTIONAL) - find_package(o3de REQUIRED) - o3de_initialize() - add_vs_debugger_arguments() -else() - # Add the project_name to global LY_PROJECTS_TARGET_NAME property - file(READ "${CMAKE_CURRENT_LIST_DIR}/project.json" project_json) - string(JSON project_target_name ERROR_VARIABLE json_error GET ${project_json} "project_name") - if(json_error) - message(FATAL_ERROR "Unable to read key 'project_name' from 'project.json'") + # set this project as the only project + set(LY_PROJECTS ${CMAKE_CURRENT_LIST_DIR}) + + # o3de manifest + include(o3de_manifest.cmake) + + ################################################################################ + # Set the engine_path and resolve this engines restricted path if it has one + ################################################################################ + o3de_engine_path(${o3de_project_json} o3de_engine_path) + o3de_project_name(${o3de_project_json} o3de_project_name) + o3de_restricted_path(${o3de_project_json} o3de_project_restricted_path) + message(STATUS "O3DE Project Name: ${o3de_project_name}") + message(STATUS "O3DE Project Path: ${o3de_project_path}") + if(o3de_project_restricted_path) + message(STATUS "O3DE Project Restricted Path: ${o3de_project_restricted_path}") endif() - set_property(GLOBAL APPEND PROPERTY LY_PROJECTS_TARGET_NAME ${project_target_name}) + # add the engines cmake folder to the CMAKE_MODULE_PATH + list(APPEND CMAKE_MODULE_PATH "${o3de_engine_path}/cmake") - # Currently we are in the ${Name} folder: ${CMAKE_CURRENT_LIST_DIR} - # Get the platform specific folder ${pal_dir} for the current folder: ${CMAKE_CURRENT_LIST_DIR}/Platform/${PAL_PLATFORM_NAME} + # add subdirectory on the engine path for this project + add_subdirectory(${o3de_engine_path} o3de) + + # add this --project-path arguments to visual studio debugger + add_vs_debugger_arguments() + +else() + ###################################################### + # the engine is calling add sub_directory() on us + ###################################################### + o3de_project_name(${o3de_project_json} o3de_project_name) + o3de_restricted_path(${o3de_project_json} o3de_project_restricted_path) + + # Currently we are in the folder: ${CMAKE_CURRENT_LIST_DIR} + # Get the platform specific folder ${pal_dir} for the folder: ${CMAKE_CURRENT_LIST_DIR}/Platform/${PAL_PLATFORM_NAME} # Note: ly_get_list_relative_pal_filename will take care of the details for us, as this may be a restricted platform # in which case it will see if that platform is present here or in the restricted folder. - # i.e. It could here: ${Name}/Platform/ or - # //${Name} - ly_get_list_relative_pal_filename(pal_dir ${CMAKE_CURRENT_LIST_DIR}/Platform/${PAL_PLATFORM_NAME}) + # i.e. It could here: TestDP/Platform/ or + # //TestDP + ly_get_list_relative_pal_filename(pal_dir ${CMAKE_CURRENT_LIST_DIR}/Platform/${PAL_PLATFORM_NAME} ${o3de_project_restricted_path} ${o3de_project_path} ${o3de_project_name}) # Now that we have the platform abstraction layer (PAL) folder for this folder, thats where we will find the # project cmake for this platform. include(${pal_dir}/${PAL_PLATFORM_NAME_LOWERCASE}_project.cmake) + # Add the project_name to global LY_PROJECTS_TARGET_NAME property + set_property(GLOBAL APPEND PROPERTY LY_PROJECTS_TARGET_NAME ${o3de_project_name}) + add_subdirectory(Code) endif() diff --git a/Templates/DefaultProject/Template/Code/CMakeLists.txt b/Templates/DefaultProject/Template/Code/CMakeLists.txt index cb98254b3b..38999c031c 100644 --- a/Templates/DefaultProject/Template/Code/CMakeLists.txt +++ b/Templates/DefaultProject/Template/Code/CMakeLists.txt @@ -15,7 +15,7 @@ # in which case it will see if that platform is present here or in the restricted folder. # i.e. It could here : ${Name}/Code/Platform/ or # //${Name}/Code -ly_get_list_relative_pal_filename(pal_dir ${CMAKE_CURRENT_LIST_DIR}/Platform/${PAL_PLATFORM_NAME}) +ly_get_list_relative_pal_filename(pal_dir ${CMAKE_CURRENT_LIST_DIR}/Platform/${PAL_PLATFORM_NAME} ${o3de_project_restricted_path} ${o3de_project_path} ${o3de_project_name}) # Now that we have the platform abstraction layer (PAL) folder for this folder, thats where we will find the # traits for this platform. Traits for a platform are defines for things like whether or not something in this project diff --git a/Templates/DefaultProject/Template/EngineFinder.cmake b/Templates/DefaultProject/Template/EngineFinder.cmake deleted file mode 100644 index d1b83b6b6c..0000000000 --- a/Templates/DefaultProject/Template/EngineFinder.cmake +++ /dev/null @@ -1,56 +0,0 @@ -# {BEGIN_LICENSE} -# -# All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -# its licensors. -# -# For complete copyright and license terms please see the LICENSE at the root of this -# distribution (the "License"). All use of this software is governed by the License, -# or, if provided, by the license below or the license accompanying this file. Do not -# remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# -# {END_LICENSE} - -# This file is copied during engine registration. Edits to this file will be lost next -# time a registration happens. -include_guard() - -# Read the engine name from the project_json file -file(READ ${CMAKE_CURRENT_LIST_DIR}/project.json project_json) -string(JSON LY_ENGINE_NAME_TO_USE ERROR_VARIABLE json_error GET ${project_json} engine) -if(json_error) - message(FATAL_ERROR "Unable to read key 'engine' from 'project.json', error: ${json_error}") -endif() - -# Read the list of paths from ~.o3de/o3de_manifest.json -file(TO_CMAKE_PATH "$ENV{USERPROFILE}" home_directory) # Windows -if((NOT home_directory) OR (NOT EXISTS ${home_directory})) - file(TO_CMAKE_PATH "$ENV{HOME}" home_directory)# Unix -endif() - -if (NOT home_directory) - message(FATAL_ERROR "Cannot find user home directory, the o3de manifest cannot be found") -endif() -# Set manifest path to path in the user home directory -set(manifest_path ${home_directory}/.o3de/o3de_manifest.json) - -if(EXISTS ${manifest_path}) - file(READ ${manifest_path} manifest_json) - string(JSON engines_count ERROR_VARIABLE json_error LENGTH ${manifest_json} engines) - if(json_error) - message(FATAL_ERROR "Unable to read key 'engines' from '${manifest_path}', error: ${json_error}") - endif() - math(EXPR engines_count "${engines_count}-1") - foreach(engine_path_index RANGE ${engines_count}) - string(JSON engine_path ERROR_VARIABLE json_error GET ${manifest_json} engines ${engine_path_index}) - if(${json_error}) - message(FATAL_ERROR "Unable to read engines[${engine_path_index}] '${manifest_path}', error: ${json_error}") - endif() - list(APPEND CMAKE_MODULE_PATH "${engine_path}/cmake") - endforeach() -endif() - - - - - diff --git a/Templates/DefaultProject/Template/ShaderLib/raytracingscenesrg.srgi b/Templates/DefaultProject/Template/ShaderLib/raytracingscenesrg.srgi index ac1d663bb8..ac27571828 100644 --- a/Templates/DefaultProject/Template/ShaderLib/raytracingscenesrg.srgi +++ b/Templates/DefaultProject/Template/ShaderLib/raytracingscenesrg.srgi @@ -1,3 +1,4 @@ +// {BEGIN_LICENSE} /* * All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or * its licensors. @@ -9,6 +10,7 @@ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * */ +// {END_LICENSE} #pragma once diff --git a/Templates/DefaultProject/Template/project.json b/Templates/DefaultProject/Template/project.json index 5c4a152caf..7f6b5d3b78 100644 --- a/Templates/DefaultProject/Template/project.json +++ b/Templates/DefaultProject/Template/project.json @@ -4,8 +4,12 @@ "license": "What license ${Name} uses goes here: i.e. https://opensource.org/licenses/MIT", "display_name": "${Name}", "summary": "A short description of ${Name}.", - "canonical_tags": ["Project"], - "user_tags": ["${Name}"], + "canonical_tags": [ + "Project" + ], + "user_tags": [ + "${Name}" + ], "icon_path": "preview.png", "engine": "o3de" -} \ No newline at end of file +} diff --git a/Templates/DefaultProject/template.json b/Templates/DefaultProject/template.json index 10e3079f2e..56278a6b04 100644 --- a/Templates/DefaultProject/template.json +++ b/Templates/DefaultProject/template.json @@ -1,5 +1,7 @@ { "template_name": "DefaultProject", + "restricted": "o3de", + "restricted_platform_relative_path": "Templates", "origin": "The primary repo for DefaultProject goes here: i.e. http://www.mydomain.com", "license": "What license DefaultProject uses goes here: i.e. https://opensource.org/licenses/MIT", "display_name": "DefaultProject", @@ -268,12 +270,6 @@ "isTemplated": false, "isOptional": false }, - { - "file": "EngineFinder.cmake", - "origin": "EngineFinder.cmake", - "isTemplated": true, - "isOptional": false - }, { "file": "Platform/Android/android_project.cmake", "origin": "Platform/Android/android_project.cmake", @@ -568,6 +564,12 @@ "isTemplated": true, "isOptional": false }, + { + "file": "ShaderLib/raytracingscenesrg.srgi", + "origin": "ShaderLib/raytracingscenesrg.srgi", + "isTemplated": true, + "isOptional": false + }, { "file": "ShaderLib/scenesrg.srgi", "origin": "ShaderLib/scenesrg.srgi", diff --git a/Tests/Atom/windows/screenshot_comparison_atomsampleviewer_windows.py b/Tests/Atom/windows/screenshot_comparison_atomsampleviewer_windows.py index 7d05046b7e..fca50c9901 100755 --- a/Tests/Atom/windows/screenshot_comparison_atomsampleviewer_windows.py +++ b/Tests/Atom/windows/screenshot_comparison_atomsampleviewer_windows.py @@ -86,7 +86,7 @@ # return final_path -# # Commenting out debug due to https://jira.agscollab.com/browse/ATOM-1677 +# # Commenting out debug due to ATOM-1677 # @pytest.mark.parametrize("platform,configuration,project,spec,sample", [ # pytest.param("win_x64_vs2017", "profile", "BaseViewer", "all", "RPI/BistroBenchmark", # marks=pytest.mark.skipif(not WINDOWS, reason="Only supported on Windows hosts")), diff --git a/Tests/pipeline/product_dependency_tests/TestFixtures.py b/Tests/pipeline/product_dependency_tests/TestFixtures.py index c7feab76f3..91151748a5 100755 --- a/Tests/pipeline/product_dependency_tests/TestFixtures.py +++ b/Tests/pipeline/product_dependency_tests/TestFixtures.py @@ -52,8 +52,8 @@ def HeliosProjectFixture(request): # These tests are run on Jenkins after other tests, to minimize time spent on Jenkins jobs. # Verify that the correct project has been set before this test starts. - # Temporarily disabling while https://jira.agscollab.com/browse/LY-103017 is not in Helios branch - # Creating a task to revert this change later: https://jira.agscollab.com/browse/LY-103334 + # Temporarily disabling while LY-103017 is not in Helios branch + # Creating a task to revert this change later: LY-103334 # Run asset processor once to process all assets, so the tests themselves can run at consistent speeds. SubprocessUtils.SubprocessWithTimeout([buildInfo.assetProcessorBatch], engineRoot, 120) diff --git a/Tools/LyTestTools/ly_test_tools/__init__.py b/Tools/LyTestTools/ly_test_tools/__init__.py index 1c78176b87..d534f5e0d2 100755 --- a/Tools/LyTestTools/ly_test_tools/__init__.py +++ b/Tools/LyTestTools/ly_test_tools/__init__.py @@ -17,7 +17,7 @@ logger = logging.getLogger(__name__) # Supported platforms. ALL_PLATFORM_OPTIONS = ['android', 'ios', 'linux', 'mac', 'windows'] -ALL_LAUNCHER_OPTIONS = ['android', 'base', 'mac', 'windows', 'windows_editor', 'windows_dedicated'] +ALL_LAUNCHER_OPTIONS = ['android', 'base', 'mac', 'windows', 'windows_editor', 'windows_dedicated', 'windows_generic'] ANDROID = False IOS = False # Not implemented - see SPEC-2505 LINUX = sys.platform.startswith('linux') # Not implemented - see SPEC-2501 @@ -37,12 +37,15 @@ if WINDOWS: HOST_OS_PLATFORM = 'windows' HOST_OS_EDITOR = 'windows_editor' HOST_OS_DEDICATED_SERVER = 'windows_dedicated' + HOST_OS_GENERIC_EXECUTABLE = 'windows_generic' import ly_test_tools.mobile.android - from ly_test_tools.launchers import AndroidLauncher, WinLauncher, DedicatedWinLauncher, WinEditor + from ly_test_tools.launchers import ( + AndroidLauncher, WinLauncher, DedicatedWinLauncher, WinEditor, WinGenericLauncher) ANDROID = ly_test_tools.mobile.android.can_run_android() LAUNCHERS['windows'] = WinLauncher LAUNCHERS['windows_editor'] = WinEditor LAUNCHERS['windows_dedicated'] = DedicatedWinLauncher + LAUNCHERS['windows_generic'] = WinGenericLauncher LAUNCHERS['android'] = AndroidLauncher elif MAC: HOST_OS_PLATFORM = 'mac' diff --git a/Tools/LyTestTools/ly_test_tools/_internal/pytest_plugin/test_tools_fixtures.py b/Tools/LyTestTools/ly_test_tools/_internal/pytest_plugin/test_tools_fixtures.py index c4249441b0..87a396ea1c 100755 --- a/Tools/LyTestTools/ly_test_tools/_internal/pytest_plugin/test_tools_fixtures.py +++ b/Tools/LyTestTools/ly_test_tools/_internal/pytest_plugin/test_tools_fixtures.py @@ -29,7 +29,7 @@ import ly_test_tools.environment.file_system import ly_test_tools.launchers.launcher_helper import ly_test_tools.launchers.platforms.base import ly_test_tools.environment.watchdog -from ly_test_tools import ALL_PLATFORM_OPTIONS, HOST_OS_PLATFORM +from ly_test_tools import ALL_PLATFORM_OPTIONS, HOST_OS_PLATFORM, HOST_OS_DEDICATED_SERVER, HOST_OS_GENERIC_EXECUTABLE logger = logging.getLogger(__name__) @@ -260,7 +260,7 @@ def dedicated_launcher(request, workspace, crash_log_watchdog): return _dedicated_launcher( request=request, workspace=workspace, - launcher_platform=get_fixture_argument(request, 'launcher_platform', HOST_OS_PLATFORM), + launcher_platform=get_fixture_argument(request, 'launcher_platform', HOST_OS_DEDICATED_SERVER), level=get_fixture_argument(request, 'level', '')) @@ -281,6 +281,21 @@ def _dedicated_launcher(request, workspace, launcher_platform, level=""): return launcher + +@pytest.fixture(scope="function") +def generic_launcher(workspace, request, crash_log_watchdog): + # type: (...) -> ly_test_tools.launchers.platforms.base.Launcher + return _generic_launcher( + workspace=workspace, + launcher_platform=get_fixture_argument(request, 'launcher_platform', HOST_OS_GENERIC_EXECUTABLE), + exe_file_name=get_fixture_argument(request, 'exe_file_name', '')) + + +def _generic_launcher(workspace, launcher_platform, exe_file_name): + """Separate implementation to call directly during unit tests""" + return ly_test_tools.launchers.launcher_helper.create_generic_launcher(workspace, launcher_platform, exe_file_name) + + @pytest.fixture def automatic_process_killer(request): # type: (_pytest.fixtures.SubRequest) -> ly_process_killer diff --git a/Tools/LyTestTools/ly_test_tools/launchers/__init__.py b/Tools/LyTestTools/ly_test_tools/launchers/__init__.py index 2203d2eb39..5f7a391afb 100755 --- a/Tools/LyTestTools/ly_test_tools/launchers/__init__.py +++ b/Tools/LyTestTools/ly_test_tools/launchers/__init__.py @@ -11,5 +11,6 @@ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. from ly_test_tools.launchers.platforms.base import Launcher from ly_test_tools.launchers.platforms.mac.launcher import MacLauncher -from ly_test_tools.launchers.platforms.win.launcher import WinLauncher, DedicatedWinLauncher, WinEditor +from ly_test_tools.launchers.platforms.win.launcher import ( + WinLauncher, DedicatedWinLauncher, WinEditor, WinGenericLauncher) from ly_test_tools.launchers.platforms.android.launcher import AndroidLauncher diff --git a/Tools/LyTestTools/ly_test_tools/launchers/launcher_helper.py b/Tools/LyTestTools/ly_test_tools/launchers/launcher_helper.py index 4ed4c43dee..45f5e6e73f 100755 --- a/Tools/LyTestTools/ly_test_tools/launchers/launcher_helper.py +++ b/Tools/LyTestTools/ly_test_tools/launchers/launcher_helper.py @@ -61,3 +61,19 @@ def create_editor(workspace, launcher_platform=ly_test_tools.HOST_OS_EDITOR, arg """ launcher_class = ly_test_tools.LAUNCHERS.get(launcher_platform, ly_test_tools.HOST_OS_EDITOR) return launcher_class(workspace, args) + + +def create_generic_launcher(workspace, launcher_platform, exe_file_name, args=None): + # type: (ly_test_tools.managers.workspace.WorkspaceManager, str, str, List[str]) -> Launcher + """ + Create a generic launcher compatible with the specified workspace. + Allows custom .exe files to serve as the launcher instead of ones listed in the ly_test_tools.LAUNCHERS constant + + :param workspace: lumberyard workspace to use + :param launcher_platform: the platform to target for a launcher (i.e. 'windows' for WinLauncher) + :param exe_file_name: .exe file name which has to be launched for this launcher (i.e. 'MaterialEditor.exe') + :param args: List of arguments to pass to the launcher's 'args' argument during construction + :return: Launcher instance. + """ + launcher_class = ly_test_tools.LAUNCHERS.get(launcher_platform, ly_test_tools.HOST_OS_GENERIC_EXECUTABLE) + return launcher_class(workspace, exe_file_name, args) diff --git a/Tools/LyTestTools/ly_test_tools/launchers/platforms/base.py b/Tools/LyTestTools/ly_test_tools/launchers/platforms/base.py index 6b53c1f8f3..36746b510f 100755 --- a/Tools/LyTestTools/ly_test_tools/launchers/platforms/base.py +++ b/Tools/LyTestTools/ly_test_tools/launchers/platforms/base.py @@ -70,7 +70,7 @@ class Launcher(object): return config_dict - def setup(self, backupFiles = True, launch_ap = True): + def setup(self, backupFiles=True, launch_ap=True): """ Perform setup of this launcher, must be called before launching. Subclasses should call its parent's setup() before calling its own code, unless it changes configuration files @@ -193,7 +193,7 @@ class Launcher(object): """ raise NotImplementedError("There is no binary file for this launcher") - def start(self, backupFiles = True, launch_ap = True): + def start(self, backupFiles=True, launch_ap=None): """ Automatically prepare and launch the application When called using "with launcher.start():" it will automatically call stop() when block exits @@ -203,14 +203,14 @@ class Launcher(object): """ return _Application(self, backupFiles, launch_ap=launch_ap) - def _start_impl(self, backupFiles = True, launch_ap=True): + def _start_impl(self, backupFiles = True, launch_ap=None): """ Implementation of start(), intended to be called via context manager in _Application :param backupFiles: Bool to backup settings files :return None: """ - self.setup(backupFiles, launch_ap=launch_ap) + self.setup(backupFiles=backupFiles, launch_ap=launch_ap) self.launch() def stop(self): @@ -326,7 +326,7 @@ class _Application(object): """ Context-manager for opening an application, enables using both "launcher.start()" and "with launcher.start()" """ - def __init__(self, launcher, backupFiles = True, launch_ap = True): + def __init__(self, launcher, backupFiles = True, launch_ap=None): """ Called during both "launcher.start()" and "with launcher.start()" @@ -334,7 +334,7 @@ class _Application(object): :return None: """ self.launcher = launcher - launcher._start_impl(backupFiles, launch_ap=launch_ap) + launcher._start_impl(backupFiles, launch_ap) def __enter__(self): """ diff --git a/Tools/LyTestTools/ly_test_tools/launchers/platforms/win/launcher.py b/Tools/LyTestTools/ly_test_tools/launchers/platforms/win/launcher.py index 800771c9bc..30c3e6eddd 100755 --- a/Tools/LyTestTools/ly_test_tools/launchers/platforms/win/launcher.py +++ b/Tools/LyTestTools/ly_test_tools/launchers/platforms/win/launcher.py @@ -42,21 +42,26 @@ class WinLauncher(Launcher): assert self.workspace.project is not None return os.path.join(self.workspace.paths.build_directory(), f"{self.workspace.project}.GameLauncher.exe") - def setup(self, backupFiles = True, launch_ap = True): + def setup(self, backupFiles=True, launch_ap=True): """ Perform setup of this launcher, must be called before launching. Subclasses should call its parent's setup() before calling its own code, unless it changes configuration files :param backupFiles: Bool to backup setup files + :param lauch_ap: Bool to lauch the asset processor :return: None """ # Backup if backupFiles: self.backup_settings() + # Base setup defaults to None + if launch_ap is None: + launch_ap = True + # Modify and re-configure self.configure_settings() - super(WinLauncher, self).setup(launch_ap=launch_ap) + super(WinLauncher, self).setup(backupFiles, launch_ap) def launch(self): """ @@ -177,6 +182,21 @@ class WinLauncher(Launcher): class DedicatedWinLauncher(WinLauncher): + def setup(self, backupFiles=True, launch_ap=False): + """ + Perform setup of this launcher, must be called before launching. + Subclasses should call its parent's setup() before calling its own code, unless it changes configuration files + + :param backupFiles: Bool to backup setup files + :param lauch_ap: Bool to lauch the asset processor + :return: None + """ + # Base setup defaults to None + if launch_ap is None: + launch_ap = False + + super(DedicatedWinLauncher, self).setup(backupFiles, launch_ap) + def binary_path(self): """ Return full path to the dedicated server launcher for the build directory. @@ -203,3 +223,28 @@ class WinEditor(WinLauncher): """ assert self.workspace.project is not None return os.path.join(self.workspace.paths.build_directory(), "Editor.exe") + + +class WinGenericLauncher(WinLauncher): + + def __init__(self, build, exe_file_name, args=None): + super(WinGenericLauncher, self).__init__(build, args) + self.exe_file_name = exe_file_name + self.expected_executable_path = os.path.join( + self.workspace.paths.build_directory(), f"{self.exe_file_name}.exe") + + if not os.path.exists(self.expected_executable_path): + raise ProcessNotStartedError( + f"Unable to locate executable '{self.exe_file_name}.exe' " + f"in path: '{self.expected_executable_path}'") + + def binary_path(self): + """ + Return full path to the .exe file for this build's configuration and project + Relies on the build_directory() in self.workspace.paths to be accurate + + :return: full path to the given exe file + """ + assert self.workspace.project is not None, ( + 'Project cannot be NoneType - please specify a project name string.') + return self.expected_executable_path diff --git a/Tools/LyTestTools/tests/unit/test_launcher_win.py b/Tools/LyTestTools/tests/unit/test_launcher_win.py index 193589f457..37e04ac99e 100755 --- a/Tools/LyTestTools/tests/unit/test_launcher_win.py +++ b/Tools/LyTestTools/tests/unit/test_launcher_win.py @@ -184,3 +184,31 @@ class TestDedicatedWinLauncher(object): launcher.workspace.build(dedicated=True) mock_workspace.build.assert_called_once_with(dedicated=True) + + +class TestWinGenericLauncher(object): + + @mock.patch('ly_test_tools.launchers.platforms.win.launcher.os.path.exists') + def test_BinaryPath_DummyPathExeExists_AddPathToExe(self, mock_os_path_exists): + dummy_path = "dummy_workspace_path" + dummy_executable = 'SomeCustomLauncher.exe' + mock_os_path_exists.return_value = True + mock_workspace = mock.MagicMock() + mock_workspace.paths.build_directory.return_value = dummy_path + launcher = ly_test_tools.launchers.WinGenericLauncher(mock_workspace, dummy_executable, ["some_args"]) + + under_test = launcher.binary_path() + + assert dummy_executable in under_test, f"executable named {dummy_executable} not found" + assert dummy_path in under_test, "workspace path unexpectedly missing " + + @mock.patch('ly_test_tools.launchers.platforms.win.launcher.os.path.exists') + def test_BinaryPath_DummyPathExeDoesNotExist_RaiseProcessNotStartedError(self, mock_os_path_exists): + dummy_path = "dummy_workspace_path" + dummy_executable = 'SomeCustomLauncher.exe' + mock_os_path_exists.return_value = False + mock_workspace = mock.MagicMock() + mock_workspace.paths.build_directory.return_value = dummy_path + + with pytest.raises(ly_test_tools.launchers.exceptions.ProcessNotStartedError): + ly_test_tools.launchers.WinGenericLauncher(mock_workspace, dummy_executable, ["some_args"]) 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) diff --git a/cmake/PAL.cmake b/cmake/PAL.cmake index c7adb660f0..7802ac8c58 100644 --- a/cmake/PAL.cmake +++ b/cmake/PAL.cmake @@ -22,7 +22,7 @@ file(GLOB detection_files "cmake/Platform/*/PALDetection_*.cmake") foreach(detection_file ${detection_files}) include(${detection_file}) endforeach() -file(GLOB detection_files "restricted/*/cmake/PALDetection_*.cmake") +file(GLOB detection_files ${o3de_engine_restricted_path}/*/cmake/PALDetection_*.cmake) foreach(detection_file ${detection_files}) include(${detection_file}) endforeach() @@ -36,43 +36,99 @@ string(TOLOWER ${PAL_HOST_PLATFORM_NAME} PAL_HOST_PLATFORM_NAME_LOWERCASE) ly_set(PAL_HOST_PLATFORM_NAME_LOWERCASE ${PAL_HOST_PLATFORM_NAME_LOWERCASE}) set(PAL_RESTRICTED_PLATFORMS) -file(GLOB pal_restricted_files "restricted/*/cmake/PAL_*.cmake") + +string(LENGTH ${o3de_engine_restricted_path} engine_restricted_length) +file(GLOB pal_restricted_files ${o3de_engine_restricted_path}/*/cmake/PAL_*.cmake) foreach(pal_restricted_file ${pal_restricted_files}) - string(FIND ${pal_restricted_file} "restricted/" start) - math(EXPR start "${start} + 11") string(FIND ${pal_restricted_file} "/cmake/PAL" end) if(${end} GREATER -1) - math(EXPR length "${end} - ${start}") - string(SUBSTRING ${pal_restricted_file} ${start} ${length} platform) + math(EXPR platform_length "${end} - ${engine_restricted_length} - 1") + math(EXPR platform_start "${engine_restricted_length} + 1") + string(SUBSTRING ${pal_restricted_file} ${platform_start} ${platform_length} platform) list(APPEND PAL_RESTRICTED_PLATFORMS "${platform}") endif() endforeach() ly_set(PAL_RESTRICTED_PLATFORMS ${PAL_RESTRICTED_PLATFORMS}) function(ly_get_absolute_pal_filename out_name in_name) - if(${ARGC} GREATER 2) - set(repo_dir ${ARGV2}) - else() - if(DEFINED LY_ROOT_FOLDER) - set(repo_dir ${LY_ROOT_FOLDER}) - else() - set(repo_dir ${CMAKE_CURRENT_SOURCE_DIR}) - endif() - endif() - set(full_name ${in_name}) - if (NOT EXISTS ${full_name}) - string(REGEX MATCH "${repo_dir}/(.*)/Platform/([^/]*)/?(.*)$" match ${full_name}) - if(PAL_RESTRICTED_PLATFORMS) - if("${CMAKE_MATCH_2}" IN_LIST PAL_RESTRICTED_PLATFORMS) - set(full_name ${repo_dir}/restricted/${CMAKE_MATCH_2}/${CMAKE_MATCH_1}) - if(NOT "${CMAKE_MATCH_3}" STREQUAL "") - string(APPEND full_name "/" ${CMAKE_MATCH_3}) + + if(${ARGC} GREATER 4) + # The user has supplied an object restricted path, the object path and the object name for consideration + set(object_restricted_path ${ARGV2}) + set(object_path ${ARGV3}) + set(object_name ${ARGV4}) + + # if the file is not in the object path then we cannot determine a PAL file for it + file(RELATIVE_PATH relative_path ${object_path} ${full_name}) + if (NOT (IS_ABSOLUTE relative_path OR relative_path MATCHES [[^(\.\./)+(.*)]])) + if (NOT EXISTS ${full_name}) + string(REGEX MATCH "${object_path}/(.*)/Platform/([^/]*)/?(.*)$" match ${full_name}) + if(NOT CMAKE_MATCH_1) + string(REGEX MATCH "${object_path}/Platform/([^/]*)/?(.*)$" match ${full_name}) + set(full_name ${object_restricted_path}/${CMAKE_MATCH_1}/${object_name}) + if(CMAKE_MATCH_2) + string(APPEND full_name "/" ${CMAKE_MATCH_2}) + endif() + elseif("${CMAKE_MATCH_2}" IN_LIST PAL_RESTRICTED_PLATFORMS) + set(full_name ${object_restricted_path}/${CMAKE_MATCH_2}/${object_name}/${CMAKE_MATCH_1}) + if(CMAKE_MATCH_3) + string(APPEND full_name "/" ${CMAKE_MATCH_3}) + endif() endif() endif() endif() + set(${out_name} ${full_name} PARENT_SCOPE) + + elseif(${ARGC} GREATER 3) + # The user has supplied an object restricted path, the object path for consideration + set(object_restricted_path ${ARGV2}) + set(object_path ${ARGV3}) + + # if the file is not in the object path then we cannot determine a PAL file for it + file(RELATIVE_PATH relative_path ${object_path} ${full_name}) + if (NOT (IS_ABSOLUTE relative_path OR relative_path MATCHES [[^(\.\./)+(.*)]])) + if (NOT EXISTS ${full_name}) + string(REGEX MATCH "${object_path}/(.*)/Platform/([^/]*)/?(.*)$" match ${full_name}) + if(NOT CMAKE_MATCH_1) + string(REGEX MATCH "${object_path}/Platform/([^/]*)/?(.*)$" match ${full_name}) + set(full_name ${object_restricted_path}/${CMAKE_MATCH_1}) + if(CMAKE_MATCH_2) + string(APPEND full_name "/" ${CMAKE_MATCH_2}) + endif() + elseif("${CMAKE_MATCH_2}" IN_LIST PAL_RESTRICTED_PLATFORMS) + set(full_name ${object_restricted_path}/${CMAKE_MATCH_2}/${CMAKE_MATCH_1}) + if(CMAKE_MATCH_3) + string(APPEND full_name "/" ${CMAKE_MATCH_3}) + endif() + endif() + endif() + endif() + set(${out_name} ${full_name} PARENT_SCOPE) + + else() + # The user has not supplied any path so we must assume it is the o3de engine restricted and o3de engine path + # if the file is not in the o3de engine path then we cannot determine a PAL file for it + file(RELATIVE_PATH relative_path ${o3de_engine_path} ${full_name}) + if (NOT (IS_ABSOLUTE relative_path OR relative_path MATCHES [[^(\.\./)+(.*)]])) + if (NOT EXISTS ${full_name}) + string(REGEX MATCH "${o3de_engine_path}/(.*)/Platform/([^/]*)/?(.*)$" match ${full_name}) + if(NOT CMAKE_MATCH_1) + string(REGEX MATCH "${o3de_engine_path}/Platform/([^/]*)/?(.*)$" match ${full_name}) + set(full_name ${o3de_engine_restricted_path}/${CMAKE_MATCH_1}) + if(CMAKE_MATCH_2) + string(APPEND full_name "/" ${CMAKE_MATCH_2}) + endif() + elseif("${CMAKE_MATCH_2}" IN_LIST PAL_RESTRICTED_PLATFORMS) + set(full_name ${o3de_engine_restricted_path}/${CMAKE_MATCH_2}/${CMAKE_MATCH_1}) + if(CMAKE_MATCH_3) + string(APPEND full_name "/" ${CMAKE_MATCH_3}) + endif() + endif() + endif() + endif() + set(${out_name} ${full_name} PARENT_SCOPE) endif() - set(${out_name} ${full_name} PARENT_SCOPE) endfunction() function(ly_get_list_relative_pal_filename out_name in_name) @@ -93,3 +149,25 @@ set(LY_DISABLE_TEST_MODULES FALSE CACHE BOOL "Option to forcibly disable the inc if(LY_DISABLE_TEST_MODULES) ly_set(PAL_TRAIT_BUILD_TESTS_SUPPORTED FALSE) endif() + +################################################################################ +# Add each restricted platform in the engines restricted folder +# If the enabled restricted platform does not have a folder add one. +# If the restricted platform folder does not have a CMakeLists.txt, create one +# so the add_subdirectory on the external folder does not fail. +################################################################################ +function(o3de_add_engine_restricted_platform_external_subdirs) + foreach(restricted_platform ${PAL_RESTRICTED_PLATFORMS}) + if(restricted_platform IN_LIST enabled_platforms) + set(o3de_engine_restricted_platform_folder ${o3de_engine_restricted_path}/${restricted_platform}) + if(NOT EXISTS ${o3de_engine_restricted_platform_folder}) + file(MAKE_DIRECTORY ${o3de_engine_restricted_platform_folder}) + endif() + set(o3de_engine_restricted_platform_folder_cmakelists ${o3de_engine_restricted_platform_folder}/CMakeLists.txt) + if(NOT EXISTS ${o3de_engine_restricted_platform_folder_cmakelists}) + file(TOUCH ${o3de_engine_restricted_platform_folder_cmakelists}) + endif() + list(APPEND LY_EXTERNAL_SUBDIRS ${o3de_engine_restricted_platform_folder}) + endif() + endforeach() +endfunction() 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/cmake/Tools/add_remove_gem.py b/cmake/Tools/add_remove_gem.py deleted file mode 100755 index fab488bdbc..0000000000 --- a/cmake/Tools/add_remove_gem.py +++ /dev/null @@ -1,634 +0,0 @@ -# -# All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -# its licensors. -# -# For complete copyright and license terms please see the LICENSE at the root of this -# distribution (the "License"). All use of this software is governed by the License, -# or, if provided, by the license below or the license accompanying this file. Do not -# remove or 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 argparse -import logging -import os -import sys -import pathlib - -from cmake.Tools import utils -from cmake.Tools import common - -logger = logging.getLogger() -logging.basicConfig() - - -def add_gem_dependency(cmake_file: str, - gem_target: str) -> int: - """ - adds a gem dependency to a cmake file - :param cmake_file: path to the cmake file - :param gem_target: name of the cmake target - :return: 0 for success or non 0 failure code - """ - if not os.path.isfile(cmake_file): - logger.error(f'Failed to locate cmake file {cmake_file}') - return 1 - - # on a line by basis, see if there already is Gem::{gem_name} - # find the first occurrence of a gem, copy its formatting and replace - # the gem name with the new one and append it - # if the gem is already present fail - t_data = [] - added = False - with open(cmake_file, 'r') as s: - for line in s: - if f'Gem::{gem_target}' in line: - logger.warning(f'{gem_target} is already a gem dependency.') - return 0 - if not added and r'Gem::' in line: - new_gem = ' ' * line.find(r'Gem::') + f'Gem::{gem_target}\n' - t_data.append(new_gem) - added = True - t_data.append(line) - - # if we didn't add it the set gem dependencies could be empty so - # add a new gem, if empty the correct format is 1 tab=4spaces - if not added: - index = 0 - for line in t_data: - index = index + 1 - if r'set(GEM_DEPENDENCIES' in line: - t_data.insert(index, f' Gem::{gem_target}\n') - added = True - break - - # if we didn't add it then it's not here, add a whole new one - if not added: - t_data.append('\n') - t_data.append('set(GEM_DEPENDENCIES\n') - t_data.append(f' Gem::{gem_target}\n') - t_data.append(')\n') - - # write the cmake - os.unlink(cmake_file) - with open(cmake_file, 'w') as s: - s.writelines(t_data) - - return 0 - - -def get_project_gem_list(project_path: str, - platform: str = 'Common') -> set: - runtime_gems = get_gem_list(get_dependencies_cmake(project_path, 'runtime', platform)) - tool_gems = get_gem_list(get_dependencies_cmake(project_path, 'tool', platform)) - server_gems = get_gem_list(get_dependencies_cmake(project_path, 'server', platform)) - return runtime_gems.union(tool_gems.union(server_gems)) - - -def get_gem_list(cmake_file: str) -> set: - """ - Gets a list of declared gem dependencies of a cmake file - :param cmake_file: path to the cmake file - :return: set of gems found - """ - if not os.path.isfile(cmake_file): - logger.error(f'Failed to locate cmake file {cmake_file}') - return set() - - gem_list = set() - with open(cmake_file, 'r') as s: - for line in s: - gem_name = line.split('Gem::') - if len(gem_name) > 1: - # Only take the name as everything leading up to the first '.' if found - # Gem naming conventions will have GemName.Editor, GemName.Server, and GemName - # as different targets of the GemName Gem - gem_list.add(gem_name[1].split('.')[0].replace('\n', '')) - return gem_list - - -def remove_gem_dependency(cmake_file: str, - gem_target: str) -> int: - """ - removes a gem dependency from a cmake file - :param cmake_file: path to the cmake file - :param gem_target: cmake target name - :return: 0 for success or non 0 failure code - """ - if not os.path.isfile(cmake_file): - logger.error(f'Failed to locate cmake file {cmake_file}') - return 1 - - # on a line by basis, remove any line with Gem::{gem_name} - t_data = [] - # Remove the gem from the cmake_dependencies file by skipping the gem name entry - removed = False - with open(cmake_file, 'r') as s: - for line in s: - if f'Gem::{gem_target}' in line: - removed = True - else: - t_data.append(line) - - if not removed: - logger.error(f'Failed to remove Gem::{gem_target} from cmake file {cmake_file}') - return 1 - - # write the cmake - os.unlink(cmake_file) - with open(cmake_file, 'w') as s: - s.writelines(t_data) - - return 0 - - -def add_gem_subdir(cmake_file: str, - gem_name: str) -> int: - """ - adds a gem subdir to a cmake file - :param cmake_file: path to the cmake file - :param gem_name: name of the gem to add - :return: 0 for success or non 0 failure code - """ - if not os.path.isfile(cmake_file): - logger.error(f'Failed to locate cmake file {cmake_file}') - return 1 - - if not utils.validate_identifier(gem_name): - logger.error(f'{gem_name} is not a valid gem name') - return 1 - - # on a line by basis, see if there already is Gem::{gem_name} - # find the first occurrence of a gem, copy its formatting and replace - # the gem name with the new one and append it - # if the gem is already present fail - t_data = [] - added = False - add_line = f'add_subdirectory({gem_name})' - with open(cmake_file, 'r') as s: - for line in s: - if add_line in line: - logger.info(f'{add_line} is already in {cmake_file} - skipping.') - return 0 - if not added and r'add_subdirectory(' in line: - new_gem = ' ' * line.find(r'add_subdirectory(') + f'add_subdirectory({gem_name})\n' - t_data.append(new_gem) - added = True - t_data.append(line) - - if not added: - logger.error(f'Failed to add add_subdirectory({gem_name}) from {cmake_file}.') - return 1 - - # write the cmake - os.unlink(cmake_file) - with open(cmake_file, 'w') as s: - s.writelines(t_data) - - return 0 - - -def remove_gem_subdir(cmake_file: str, - gem_name: str) -> int: - """ - removes a gem subdir form a cmake file - :param cmake_file: path to the cmake file - :param gem_name: name of the gem to remove - :return: 0 for success or non 0 failure code - """ - if not os.path.isfile(cmake_file): - logger.error(f'Failed to locate cmake file {cmake_file}') - return 1 - - # on a line by basis, remove any line with Gem::{gem_name} - t_data = [] - # Remove the gem from the cmake_dependencies file by skipping the gem name entry - removed = False - with open(cmake_file, 'r') as s: - for line in s: - if f'add_subdirectory({gem_name})' in line: - removed = True - else: - t_data.append(line) - - if not removed: - logger.error(f'Failed to remove add_subdirectory({gem_name}) from {cmake_file}') - return 1 - - # write the cmake - os.unlink(cmake_file) - with open(cmake_file, 'w') as s: - s.writelines(t_data) - - return 0 - - -def get_dependencies_cmake(project_path: str, - dependency_type: str = 'runtime', - platform: str = 'Common') -> str: - if not project_path: - return '' - if platform == 'Common': - dependencies_file = f'{dependency_type}_dependencies.cmake' - gem_path = os.path.join(project_path, 'Gem', 'Code', dependencies_file) - if os.path.isfile(gem_path): - return gem_path - return os.path.join(project_path, 'Code', dependencies_file) - else: - dependencies_file = f'{platform.lower()}_{dependency_type}_dependencies.cmake' - gem_path = os.path.join(project_path, 'Gem', 'Code', 'Platform', platform, dependencies_file) - if os.path.isfile(gem_path): - return gem_path - return os.path.join(project_path, 'Code', 'Platform', platform, dependencies_file) - -# this function is making some not so good assumptions about gem naming -def find_all_gems(gem_folder_list: list) -> list: - """ - Find all Modules which appear to be gems living within a list of folders - This method can be replaced or improved on with something more deterministic when LYN-1942 is done - :param gem_folder_list: - :return: list of gem objects containing gem Name and Path - """ - module_gems = {} - for folder in gem_folder_list: - root_len = len(os.path.normpath(folder).split(os.sep)) - for root, dirs, files in os.walk(folder): - for file in files: - if file == 'CMakeLists.txt': - with open(os.path.join(root, file), 'r') as s: - for line in s: - trimmed = line.lstrip() - if trimmed.startswith('NAME '): - trimmed = trimmed.rstrip(' \n') - split_trimmed = trimmed.split(' ') - # Is this a type indicating a gem lives here - if len(split_trimmed) == 3 and split_trimmed[2] in ['MODULE', 'GEM_MODULE', - '${PAL_TRAIT_MONOLITHIC_DRIVEN_MODULE_TYPE}']: - # Hold our "Name parts" such as Gem.MyGem.Editor as ['Gem', 'MyGem', 'Editor'] - name_split = split_trimmed[1].split('.') - split_folders = os.path.normpath(root).split(os.sep) - # This verifies we were passed a folder lower in the folder structure than the - # gem we've found, so we'll name it by the first directory. This is the common - # case currently of being handed "Gems" where things that live under Gems are - # known by the directory name - if len(split_folders) > root_len: - # Assume the gem is named by the root folder. May modules may exist - # together within the gem that are added collectively - gem_name = split_folders[root_len] - else: - # We were passed the folder with the gem already inside it, we have to name - # it by the gem name we found - gem_name = name_split[0] - this_gem = module_gems.get(gem_name, None) - if not this_gem: - if len(split_folders) > root_len: - # Assume the gem is named by the root folder. May modules may exist - # together within the gem that are added collectively - this_gem = {'Name': gem_name, - 'Path': os.path.join(folder, split_folders[root_len])} - else: - this_gem = {'Name': gem_name, 'Path': folder} - # Add any module types we know to be tools only here - if len(name_split) > 1 and name_split[1] in ['Editor', 'Builder']: - this_gem['Tools'] = True - else: - this_gem['Runtime'] = True - this_gem['Tools'] = True - - module_gems[gem_name] = this_gem - break - - return sorted(list(module_gems.values()), key=lambda x: x.get('Name')) - - -def find_gem_modules(gem_folder: str) -> list: - """ - Find all gem modules which appear to be gems living in this folder - :param gem_folder: the folder to walk down - :return: list of gem targets - """ - module_identifiers = [ - 'MODULE', - 'GEM_MODULE', - '${PAL_TRAIT_MONOLITHIC_DRIVEN_MODULE_TYPE}' - ] - modules = [] - for root, dirs, files in os.walk(gem_folder): - for file in files: - if file == 'CMakeLists.txt': - with open(os.path.join(root, file), 'r') as s: - for line in s: - trimmed = line.lstrip() - if trimmed.startswith('NAME '): - trimmed = trimmed.rstrip(' \n') - split_trimmed = trimmed.split(' ') - if len(split_trimmed) == 3 and split_trimmed[2] in module_identifiers: - modules.append(split_trimmed[1]) - return modules - - -def add_remove_gem(add: bool, - dev_root: str, - gem_path: str, - gem_target: str, - project_path: str, - dependencies_file: str or None, - project_restricted_path: str = 'restricted', - runtime_dependency: bool = False, - tool_dependency: bool = False, - server_dependency: bool = False, - platforms: str = 'Common', - gem_cmake: str = None) -> int: - """ - add a gem to a project - :param add: should we add a gem, if false we remove a gem - :param dev_root: the dev root of the engine - :param gem_path: path to the gem to add - :param gem_target: the name of teh cmake gem module - :param project_path: path to the project to add the gem to - :param dependencies_file: if this dependency goes/is in a specific file - :param project_restricted_path: path to the projects restricted folder - :param runtime_dependency: bool to specify this is a runtime gem for the game - :param tool_dependency: bool to specify this is a tool gem for the editor - :param server_dependency: bool to specify this is a server gem for the server - :param platforms: str to specify common or which specific platforms - :param gem_cmake: str to specify that this gem should be removed from the Gems/CMakeLists.txt - :return: 0 for success or non 0 failure code - """ - - # if no dev root error - if not dev_root: - logger.error('Dev root cannot be empty.') - return 1 - if not os.path.isabs(dev_root): - dev_root = os.path.abspath(dev_root) - dev_root = pathlib.Path(dev_root) - if not dev_root.is_dir(): - logger.error(f'Dev root {dev_root} is not a folder.') - return 1 - - # if no project path error - if not project_path: - logger.error('Project path cannot be empty.') - return 1 - if not os.path.isabs(project_path): - project_path = f'{dev_root}/{project_path}' - project_path = pathlib.Path(project_path) - if not project_path.is_dir(): - logger.error(f'Project path {project_path} is not a folder.') - return 1 - - project_restricted_path = project_restricted_path.replace('\\', '/') - if not os.path.isabs(project_restricted_path): - project_restricted_path = f'{dev_root}/{project_restricted_path}' - project_restricted_path = pathlib.Path(project_restricted_path) - if not project_restricted_path.is_dir(): - logger.error(f'Project Restricted path {project_restricted_path} is not a folder.') - return 1 - - # if no gem path error - if not gem_path: - logger.error('Gem path cannot be empty.') - return 1 - if not os.path.isabs(gem_path): - gem_path = f'{dev_root}/Gems/{gem_path}' - gem_path = pathlib.Path(gem_path) - # make sure this gem already exists if we're adding. We can always remove a gem. - if add and not gem_path.is_dir(): - logger.error(f'{gem_path} dir does not exist.') - return 1 - - # find all available modules in this gem_path - modules = find_gem_modules(gem_path) - if len(modules) == 0: - logger.error(f'No gem modules found.') - return 1 - - # if gem target not specified, see if there is only 1 module - if not gem_target: - if len(modules) == 1: - gem_target = modules[0] - else: - logger.error(f'Gem target not specified: {modules}') - return 1 - elif gem_target not in modules: - logger.error(f'Gem target not in gem modules: {modules}') - return 1 - - # gem cmake list text file is assumed to be in the parent folder is not specified - if add or isinstance(gem_cmake, str): - if not gem_cmake: - gem_cmake = gem_path.parent / 'CMakeLists.txt' - if not os.path.isabs(gem_cmake): - gem_cmake = f'{dev_root}/{gem_cmake}' - gem_cmake = pathlib.Path(gem_cmake) - if not gem_cmake.is_file(): - logger.error(f'CMakeLists.txt file {gem_cmake} does not exist.') - return 1 - - # if the user has not specified either we will assume they meant the most common which is runtime - if not runtime_dependency and not tool_dependency and not server_dependency and not dependencies_file: - logger.warning("Dependency type not specified: Assuming '--runtime-dependency'") - runtime_dependency = True - - ret_val = 0 - - # if the user has specified the dependencies file then ignore the runtime_dependency and tool_dependency flags - if dependencies_file: - dependencies_file = pathlib.Path(dependencies_file) - # make sure this is a project has a dependencies_file - if not dependencies_file.is_file(): - logger.error(f'Dependencies file {dependencies_file} is not present.') - return 1 - if add: - # add the dependency - ret_val = add_gem_dependency(dependencies_file, gem_target) - else: - # remove the dependency - ret_val = remove_gem_dependency(dependencies_file, gem_target) - else: - if ',' in platforms: - platforms = platforms.split(',') - else: - platforms = [platforms] - for platform in platforms: - if runtime_dependency: - # make sure this is a project has a runtime_dependencies.cmake file - project_runtime_dependencies_file = pathlib.Path(get_dependencies_cmake(project_path, 'runtime', platform)) - if not project_runtime_dependencies_file.is_file(): - logger.error(f'Runtime dependencies file {project_runtime_dependencies_file} is not present.') - return 1 - - if add: - # add the dependency - ret_val = add_gem_dependency(project_runtime_dependencies_file, gem_target) - else: - # remove the dependency - ret_val = remove_gem_dependency(project_runtime_dependencies_file, gem_target) - - if (ret_val == 0 or not add) and tool_dependency: - # make sure this is a project has a tool_dependencies.cmake file - project_tool_dependencies_file = pathlib.Path(get_dependencies_cmake(project_path, 'tool', platform)) - if not project_tool_dependencies_file.is_file(): - logger.error(f'Tool dependencies file {project_tool_dependencies_file} is not present.') - return 1 - - if add: - # add the dependency - ret_val = add_gem_dependency(project_tool_dependencies_file, gem_target) - else: - # remove the dependency - ret_val = remove_gem_dependency(project_tool_dependencies_file, gem_target) - - if (ret_val == 0 or not add) and server_dependency: - # make sure this is a project has a tool_dependencies.cmake file - project_server_dependencies_file = pathlib.Path(get_dependencies_cmake(project_path, 'server', platform)) - if not project_server_dependencies_file.is_file(): - logger.error(f'Server dependencies file {project_server_dependencies_file} is not present.') - return 1 - - if add: - # add the dependency - ret_val = add_gem_dependency(project_server_dependencies_file, gem_target) - else: - # remove the dependency - ret_val = remove_gem_dependency(project_server_dependencies_file, gem_target) - - if add: - # add the gem subdir to the CMakeList.txt - ret_val = add_gem_subdir(gem_cmake, gem_path.name) - elif gem_cmake: - # remove the gem subdir from the CMakeList.txt - ret_val = remove_gem_subdir(gem_cmake, gem_path.name) - - return ret_val - - -def _run_add_gem(args: argparse) -> int: - return add_remove_gem(True, - common.determine_engine_root(), - args.gem_path, - args.gem_target, - args.project_path, - args.dependencies_file, - args.project_restricted_path, - args.runtime_dependency, - args.tool_dependency, - args.server_dependency, - args.platforms, - args.add_to_cmake) - - -def _run_remove_gem(args: argparse) -> int: - return add_remove_gem(False, - common.determine_engine_root(), - args.gem_path, - args.gem_target, - args.project_path, - args.dependencies_file, - args.project_restricted_path, - args.runtime_dependency, - args.tool_dependency, - args.server_dependency, - args.platforms, - args.remove_from_cmake) - - -def add_args(parser, subparsers) -> None: - """ - add_args is called to add expected parser arguments and subparsers arguments to each command such that it can be - invoked locally or aggregated by a central python file. - Ex. Directly run from this file alone with: python add_remove_gem.py add_gem --gem TestGem --project TestProject - OR - lmbr.py can aggregate commands by importing add_remove_gem, call add_args and - execute: python lmbr.py add_gem --gem TestGem --project TestProject - :param parser: the caller instantiates a parser and passes it in here - :param subparsers: the caller instantiates subparsers and passes it in here - """ - add_gem_subparser = subparsers.add_parser('add-gem') - add_gem_subparser.add_argument('-pp', '--project-path', type=str, required=True, - help='The path to the project, can be absolute or dev root relative') - add_gem_subparser.add_argument('-prp', '--project-restricted-path', type=str, required=False, - default='restricted', - help='The path to the projects restricted folder, can be absolute or dev root' - ' relative') - add_gem_subparser.add_argument('-gp', '--gem-path', type=str, required=True, - help='The path to the gem, can be absolute or dev root/Gems relative') - add_gem_subparser.add_argument('-gt', '--gem-target', type=str, required=False, - help='The cmake target name to add. If not specified it will assume gem_name') - add_gem_subparser.add_argument('-df', '--dependencies-file', type=str, required=False, - help='The cmake dependencies file in which the gem dependencies are specified.' - 'If not specified it will assume ') - add_gem_subparser.add_argument('-rd', '--runtime-dependency', action='store_true', required=False, - default=False, - help='Optional toggle if this gem should be added as a runtime dependency') - add_gem_subparser.add_argument('-td', '--tool-dependency', action='store_true', required=False, - default=False, - help='Optional toggle if this gem should be added as a tool dependency') - add_gem_subparser.add_argument('-sd', '--server-dependency', action='store_true', required=False, - default=False, - help='Optional toggle if this gem should be added as a server dependency') - add_gem_subparser.add_argument('-pl', '--platforms', type=str, required=False, - default='Common', - help='Optional list of platforms this gem should be added to.' - ' Ex. --platforms Mac,Windows,Linux') - add_gem_subparser.add_argument('-a', '--add-to-cmake', type=str, required=False, - default=None, - help='Add the gem folder to the CMakeLists.txt so that it builds. If not' - ' specified it will assume the CMakeLists.txt file in the parent folder of' - ' the gem_path.') - add_gem_subparser.set_defaults(func=_run_add_gem) - - remove_gem_subparser = subparsers.add_parser('remove-gem') - remove_gem_subparser.add_argument('-pp', '--project-path', type=str, required=True, - help='The path to the project, can be absolute or dev root relative') - remove_gem_subparser.add_argument('-prp', '--project-restricted-path', type=str, required=False, - default='restricted', - help='The path to the projects restricted folder, can be absolute or dev root' - ' relative') - remove_gem_subparser.add_argument('-gp', '--gem-path', type=str, required=True, - help='The path to the gem, can be absolute or dev root/Gems relative') - remove_gem_subparser.add_argument('-gt', '--gem-target', type=str, required=False, - help='The cmake target name to add. If not specified it will assume gem_name') - remove_gem_subparser.add_argument('-df', '--dependencies-file', type=str, required=False, - help='The cmake dependencies file in which the gem dependencies are specified.' - 'If not specified it will assume ') - remove_gem_subparser.add_argument('-rd', '--runtime-dependency', action='store_true', required=False, - default=False, - help='Optional toggle if this gem should be removed as a runtime dependency') - remove_gem_subparser.add_argument('-td', '--tool-dependency', action='store_true', required=False, - default=False, - help='Optional toggle if this gem should be removed as a server dependency') - remove_gem_subparser.add_argument('-sd', '--server-dependency', action='store_true', required=False, - default=False, - help='Optional toggle if this gem should be removed as a server dependency') - remove_gem_subparser.add_argument('-pl', '--platforms', type=str, required=False, - default='Common', - help='Optional list of platforms this gem should be removed from' - ' Ex. --platforms Mac,Windows,Linux') - remove_gem_subparser.add_argument('-r', '--remove-from-cmake', type=str, required=False, - default=None, - help='Remove the gem folder from the CMakeLists.txt that includes it so that it ' - 'no longer builds build. If not specified it will assume you dont want to' - ' remove it.') - remove_gem_subparser.set_defaults(func=_run_remove_gem) - - -if __name__ == "__main__": - # parse the command line args - the_parser = argparse.ArgumentParser() - - # add subparsers - the_subparsers = the_parser.add_subparsers(help='sub-command help') - - # add args to the parser - add_args(the_parser, the_subparsers) - - # parse args - the_args = the_parser.parse_args() - - # run - ret = the_args.func(the_args) - - # return - sys.exit(ret) diff --git a/cmake/Tools/current_project.py b/cmake/Tools/current_project.py deleted file mode 100755 index 8be18fd3c9..0000000000 --- a/cmake/Tools/current_project.py +++ /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. -# - -import argparse -import logging -import os -import sys -import re - -from cmake.Tools import common - -logger = logging.getLogger() -logging.basicConfig() - - -def set_current_project(dev_root: str, - project_path: str) -> int: - """ - set what the current project is - :param dev_root: the dev root of the engine - :param project_path: the path of the project you want to set - :return: 0 for success or non 0 failure code - """ - project_path = project_path.strip() - if not project_path.isalnum(): - logger.error('Project Name invalid. Set current project failed.') - return 1 - try: - with open(os.path.join(dev_root, 'bootstrap.cfg'), 'r') as s: - data = s.read() - data = re.sub(r'(.*project_path\s*?[=:]\s*?)([^\n]+)\n', r'\1 {}\n'.format(project_path), - data, flags=re.IGNORECASE) - if os.path.isfile(os.path.join(dev_root, 'bootstrap.cfg')): - os.unlink(os.path.join(dev_root, 'bootstrap.cfg')) - with open(os.path.join(dev_root, 'bootstrap.cfg'), 'w') as s: - s.write(data) - except Exception as e: - logger.error('Set current project failed.' + str(e)) - return 1 - return 0 - - -def get_current_project(dev_root: str) -> str: - """ - get what the current project set is - :param dev_root: the dev root of the engine - :return: project_path or None on failure - """ - try: - with open(os.path.join(dev_root, 'bootstrap.cfg'), 'r') as s: - data = s.read() - project_path = re.search(r'(.*project_path\s*?[=:]\s*?)(?P[^\n]+)\n', - data, flags=re.IGNORECASE).group('project_path').strip() - except Exception as e: - logger.error('Failed to get current project. Exception: ' + str(e)) - return '' - return project_path - - -def _run_get_current_project(args: argparse) -> int: - project_path = get_current_project(common.determine_engine_root()) - if project_path: - print(project_path) - return 0 - return 1 - - -def _run_set_current_project(args: argparse) -> int: - return set_current_project(common.determine_engine_root(), args.project_path) - - -def add_args(parser, subparsers) -> None: - """ - add_args is called to add expected parser arguments and subparsers arguments to each command such that it can be - invoked locally or aggregated by a central python file. - Ex. Directly run from this file alone with: python current_project.py set_current_project --project TestProject - OR - lmbr.py can aggregate commands by importing current_project, call add_args and - execute: python lmbr.py set_current_project --project TestProject - :param parser: the caller instantiates a parser and passes it in here - :param subparsers: the caller instantiates subparsers and passes it in here - """ - get_current_project_subparser = subparsers.add_parser('get-current-project') - get_current_project_subparser.set_defaults(func=_run_get_current_project) - - set_current_project_subparser = subparsers.add_parser('set-current-project') - set_current_project_subparser.add_argument('-pp', '--project-path', required=True, - help='The path to the project, can be absolute or dev root relative') - set_current_project_subparser.set_defaults(func=_run_set_current_project) - - -if __name__ == "__main__": - # parse the command line args - the_parser = argparse.ArgumentParser() - - # add subparsers - the_subparsers = the_parser.add_subparsers(help='sub-command help') - - # add args to the parser - add_args(the_parser, the_subparsers) - - # parse args - the_args = the_parser.parse_args() - - # run - ret = the_args.func(the_args) - - # return - sys.exit(ret) diff --git a/cmake/Tools/engine_template.py b/cmake/Tools/engine_template.py index bf1ca93e57..eefb8c5541 100755 --- a/cmake/Tools/engine_template.py +++ b/cmake/Tools/engine_template.py @@ -21,7 +21,7 @@ import uuid import re from cmake.Tools import utils -from cmake.Tools import common +import cmake.Tools.registration as registration logger = logging.getLogger() logging.basicConfig() @@ -117,7 +117,7 @@ def _transform(s_data: str, end = t_data.find('{END_LICENSE}') end = t_data.find('\n', end) if end != -1: - t_data = t_data[:line_start] + t_data[end+1:] + t_data = t_data[:line_start] + t_data[end + 1:] ################################################################### return t_data @@ -131,8 +131,6 @@ def _transform_copy(source_file: str, :param source_file: the source file to be transformed :param destination_file: the destination file, this is the transformed file :param replacements: list of transformation pairs A->B - :param keep_restricted_in_instance: whether or not you want ot keep the templates restricted files in your instance - or separate them out into the restricted folder :param keep_license_text: whether or not you want to keep license text """ # if its a known binary type just copy it, else try to transform it. @@ -159,7 +157,7 @@ def _transform_copy(source_file: str, pass -def _execute_template_json(json_data: str, +def _execute_template_json(json_data: dict, destination_path: str, template_path: str, replacements: list, @@ -203,7 +201,7 @@ def _execute_template_json(json_data: str, shutil.copy(in_file, out_file) -def _execute_restricted_template_json(json_data: str, +def _execute_restricted_template_json(json_data: dict, restricted_platform: str, destination_name, template_name, @@ -215,11 +213,22 @@ def _execute_restricted_template_json(json_data: str, replacements: list, keep_restricted_in_instance: bool = False, keep_license_text: bool = False) -> None: + # if we are not keeping restricted in instance make restricted.json if not present + if not keep_restricted_in_instance: + restricted_json = f"{destination_restricted_path}/restricted.json".replace('//', '/') + os.makedirs(os.path.dirname(restricted_json), exist_ok=True) + if not os.path.isfile(restricted_json): + with open(restricted_json, 'w') as s: + restricted_json_data = {} + restricted_json_data.update({"restricted_name": destination_name}) + s.write(json.dumps(restricted_json_data, indent=4)) + # create dirs first # for each createDirectory entry, transform the folder name for create_directory in json_data['createDirectories']: # construct the new folder name - new_dir = f"{destination_restricted_path}/{restricted_platform}/{destination_restricted_platform_relative_path}/{destination_name}/{create_directory['dir']}".replace('//', '/') + new_dir = f"{destination_restricted_path}/{restricted_platform}/{destination_restricted_platform_relative_path}/{destination_name}/{create_directory['dir']}".replace( + '//', '/') if keep_restricted_in_instance: new_dir = f"{destination_path}/{create_directory['origin']}".replace('//', '/') @@ -233,7 +242,8 @@ def _execute_restricted_template_json(json_data: str, # regular copy if not templated for copy_file in json_data['copyFiles']: # construct the input file name - in_file = f"{template_restricted_path}/{restricted_platform}/{template_restricted_platform_relative_path}/{template_name}/Template/{copy_file['file']}".replace('//', '/') + in_file = f"{template_restricted_path}/{restricted_platform}/{template_restricted_platform_relative_path}/{template_name}/Template/{copy_file['file']}".replace( + '//', '/') # the file can be marked as optional, if it is and it does not exist skip if copy_file['isOptional'] and copy_file['isOptional'] == 'true': @@ -241,7 +251,8 @@ def _execute_restricted_template_json(json_data: str, continue # construct the output file name - out_file = f"{destination_restricted_path}/{restricted_platform}/{destination_restricted_platform_relative_path}/{destination_name}/{copy_file['file']}".replace('//', '/') + out_file = f"{destination_restricted_path}/{restricted_platform}/{destination_restricted_platform_relative_path}/{destination_name}/{copy_file['file']}".replace( + '//', '/') if keep_restricted_in_instance: out_file = f"{destination_path}/{copy_file['origin']}".replace('//', '/') @@ -258,7 +269,8 @@ def _execute_restricted_template_json(json_data: str, shutil.copy(in_file, out_file) -def _instantiate_template(destination_name: str, +def _instantiate_template(template_json_data: dict, + destination_name: str, template_name: str, destination_path: str, template_path: str, @@ -272,47 +284,47 @@ def _instantiate_template(destination_name: str, """ Internal function to create a concrete instance from a template - :param destination_path: the folder you want to instantiate the template in, absolute or dev_root relative + :param template_json_data: the template json data + :param destination_name: the name of folder you want to instantiate the template in + :param template_name: the name of the template + :param destination_path: the path you want to instantiate the template in :param template_path: the path of the template - :param template_path_rel: the relative path of the template + :param destination_restricted_path: the path of the restricted destination :param template_restricted_path: the path of the restricted template + :param destination_restricted_platform_relative_path: any path after the Platform of the restricted destination + :param template_restricted_platform_relative_path: any path after the Platform of the restricted template :param replacements: optional list of strings uses to make concrete names out of templated parameters. X->Y pairs Ex. ${Name},TestGem,${Player},TestGemPlayer This will cause all references to ${Name} be replaced by TestGem, and all ${Player} replaced by 'TestGemPlayer' - :param keep_restricted_in_instance: whether or not you want ot keep the templates restricted files in your instance + :param keep_restricted_in_instance: whether or not you want to keep the templates restricted files in your instance or separate them out into the restricted folder - :param keep_license_text: whether or not you want ot keep the templates license text in your instance. + :param keep_license_text: whether or not you want to keep the templates license text in your instance. template can have license blocks starting with {BEGIN_LICENSE} and ending with {END_LICENSE}, this controls if you want to keep the license text from the template in the new instance. It is false by default - because most customers will not want license text in there instances, but we may want to keep them. + because most customers will not want license text in their instances, but we may want to keep them. :return: 0 for success or non 0 failure code """ - # make sure the template json is found - template_json = f'{template_path}/{template_file_name}' - if not os.path.isfile(template_json): - logger.error(f'Template json {template_json} not found.') - return 1 - - # load the template json and execute it - with open(template_json, 'r') as s: - try: - json_data = json.load(s) - except Exception as e: - logger.error(f'Failed to load {template_json}: ' + str(e)) - return 1 - _execute_template_json(json_data, - destination_path, - template_path, - replacements, - keep_license_text) + # execute the template json + _execute_template_json(template_json_data, + destination_path, + template_path, + replacements, + keep_license_text) # execute restricted platform jsons if any - if os.path.isdir(template_restricted_path): + if template_restricted_path: for restricted_platform in os.listdir(template_restricted_path): + if os.path.isfile(restricted_platform): + continue template_restricted_platform = f'{template_restricted_path}/{restricted_platform}' template_restricted_platform_path_rel = f'{template_restricted_platform}/{template_restricted_platform_relative_path}/{template_name}' platform_json = f'{template_restricted_platform_path_rel}/{template_file_name}'.replace('//', '/') + if os.path.isfile(platform_json): + if not registration.valid_o3de_template_json(platform_json): + logger.error(f'Template json {platform_json} is invalid.') + return 1 + # load the template json and execute it with open(platform_json, 'r') as s: try: @@ -320,72 +332,64 @@ def _instantiate_template(destination_name: str, except Exception as e: logger.error(f'Failed to load {platform_json}: ' + str(e)) return 1 - _execute_restricted_template_json(json_data, - restricted_platform, - destination_name, - template_name, - destination_path, - destination_restricted_path, - template_restricted_path, - destination_restricted_platform_relative_path, - template_restricted_platform_relative_path, - replacements, - keep_restricted_in_instance, - keep_license_text) + else: + _execute_restricted_template_json(json_data, + restricted_platform, + destination_name, + template_name, + destination_path, + destination_restricted_path, + template_restricted_path, + destination_restricted_platform_relative_path, + template_restricted_platform_relative_path, + replacements, + keep_restricted_in_instance, + keep_license_text) return 0 -def create_template(dev_root: str, - source_path: str, +def create_template(source_path: str, template_path: str, - source_restricted_path: str, - template_restricted_path: str, - source_restricted_platform_relative_path: str, - template_restricted_platform_relative_path: str, + source_restricted_path: str = None, + source_restricted_name: str = None, + template_restricted_path: str = None, + template_restricted_name: str = None, + source_restricted_platform_relative_path: str = None, + template_restricted_platform_relative_path: str = None, keep_restricted_in_template: bool = False, keep_license_text: bool = False, replace: list = None) -> int: """ - Create a generic template from a source directory using replacement + Create a template from a source directory using replacement - :param dev_root: the path to dev root of the engine - :param source_path: source folder, absolute or dev_root relative - :param template_path: the path of the template to create, can be absolute or relative to dev root/Templates, if none - then it will be the source_name - :param source_restricted_path: path to the projects restricted folder + :param source_path: The path to the source that you want to make into a template + :param template_path: the path of the template to create, can be absolute or relative to default templates path + :param source_restricted_path: path to the source restricted folder + :param source_restricted_name: name of the source restricted folder :param template_restricted_path: path to the templates restricted folder + :param template_restricted_name: name of the templates restricted folder + :param source_restricted_platform_relative_path: any path after the platform in the source restricted + :param template_restricted_platform_relative_path: any path after the platform in the template restricted :param replace: optional list of strings uses to make templated parameters out of concrete names. X->Y pairs Ex. TestGem,${Name},TestGemPlayer,${Player} This will cause all references to 'TestGem' be replaced by ${Name}, and all 'TestGemPlayer' replaced by ${Player} Note these replacements are executed in order, so if you have larger matches, do them first, i.e. TestGemPlayer,${Player},TestGem,${Name} TestGemPlayer will get matched first and become ${Player} and will not become ${Name}Player - :param keep_restricted_in_template: whether or not you want ot keep the templates restricted in your template. - :param keep_license_text: whether or not you want ot keep the templates license text in your instance. - template can have license blocks starting with {BEGIN_LICENSE} and ending with {END_LICENSE}, + :param keep_restricted_in_template: whether or not you want to keep the templates restricted in your template. + :param keep_license_text: whether or not you want to keep the templates license text in your instance. + Templated files can have license blocks starting with {BEGIN_LICENSE} and ending with {END_LICENSE}, this controls if you want to keep the license text from the template in the new instance. It is false by default - because most customers will not want license text in there instances, but we may want to keep them. + because most people will not want license text in their instances. :return: 0 for success or non 0 failure code """ - # if no dev root error - if not dev_root: - logger.error('Dev root cannot be empty.') - return 1 - dev_root = dev_root.replace('\\', '/') - if not os.path.isabs(dev_root): - dev_root = os.path.abspath(dev_root) - if not os.path.isdir(dev_root): - logger.error(f'Dev root {dev_root} is not a folder.') - return 1 # if no src path error if not source_path: logger.error('Src path cannot be empty.') return 1 source_path = source_path.replace('\\', '/') - if not os.path.isabs(source_path): - source_path = f'{dev_root}/{source_path}' if not os.path.isdir(source_path): logger.error(f'Src path {source_path} is not a folder.') return 1 @@ -393,13 +397,15 @@ def create_template(dev_root: str, # source_name is now the last component of the source_path source_name = os.path.basename(source_path) - # if no new template path error + # if no template path, error if not template_path: - logger.warning('Template path empty. Using source name') + logger.info(f'Template path empty. Using source name {source_name}') template_path = source_name template_path = template_path.replace('\\', '/') if not os.path.isabs(template_path): - template_path = f'{dev_root}/Templates/{template_path}' + default_templates_folder = registration.get_registered(default_folder='templates') + template_path = f'{default_templates_folder}/{template_path}' + logger.info(f'Template path not a full path. Using default templates folder {template_path}') if os.path.isdir(template_path): logger.error(f'Template path {template_path} is already exists.') return 1 @@ -412,26 +418,85 @@ def create_template(dev_root: str, logger.error(f'Template path cannot be a restricted name. {template_name}') return 1 + if source_restricted_name and not source_restricted_path: + source_restricted_path = registration.get_registered(restricted_name=source_restricted_name) + # source_restricted_path - source_restricted_path = source_restricted_path.replace('\\', '/') - if not os.path.isabs(source_restricted_path): - source_restricted_path = f'{dev_root}/{source_restricted_path}' - if not os.path.isdir(source_restricted_path): - logger.error(f'Src restricted path {source_restricted_path} is not a folder.') - return 1 + if source_restricted_path: + source_restricted_path = source_restricted_path.replace('\\', '/') + if not os.path.isabs(source_restricted_path): + engine_json = f'{registration.get_this_engine_path()}/engine.json' + if not registration.valid_o3de_engine_json(engine_json): + logger.error(f"Engine json {engine_json} is not valid.") + return 1 + with open(engine_json) as s: + try: + engine_json_data = json.load(s) + except Exception as e: + logger.error(f"Failed to read engine json {engine_json}: {str(e)}") + return 1 + try: + engine_restricted = engine_json_data['restricted'] + except Exception as e: + logger.error(f"Engine json {engine_json} restricted not found.") + return 1 + engine_restricted_folder = registration.get_registered(restricted_name=engine_restricted) + new_source_restricted_path = f'{engine_restricted_folder}/{source_restricted_path}' + logger.info(f'Source restricted path {source_restricted_path} not a full path. We must assume this engines' + f' restricted folder {new_source_restricted_path}') + if not os.path.isdir(source_restricted_path): + logger.error(f'Source restricted path {source_restricted_path} is not a folder.') + return 1 + + if template_restricted_name and not template_restricted_path: + template_restricted_path = registration.get_registered(restricted_name=template_restricted_name) + + if not template_restricted_name: + template_restricted_name = template_name # template_restricted_path - template_restricted_path = template_restricted_path.replace('\\', '/') - if not os.path.isabs(template_restricted_path): - template_restricted_path = f'{dev_root}/{template_restricted_path}' - if not os.path.isdir(template_restricted_path): - os.makedirs(template_restricted_path) + if template_restricted_path: + template_restricted_path = template_restricted_path.replace('\\', '/') + if not os.path.isabs(template_restricted_path): + default_templates_restricted_folder = registration.get_registered(restricted_name='templates') + new_template_restricted_path = f'{default_templates_restricted_folder}/{template_restricted_path}' + logger.info(f'Template restricted path {template_restricted_path} not a full path. We must assume the' + f' default templates restricted folder {new_template_restricted_path}') + template_restricted_path = new_template_restricted_path + + if os.path.isdir(template_restricted_path): + # see if this is already a restricted path, if it is get the "restricted_name" from the restricted json + # so we can set "restricted" to it for this template + restricted_json = f'{template_restricted_path}/restricted.json' + if os.path.isfile(restricted_json): + if not registration.valid_o3de_restricted_json(restricted_json): + logger.error(f'{restricted_json} is not valid.') + return 1 + with open(restricted_json, 'r') as s: + try: + restricted_json_data = json.load(s) + except Exception as e: + logger.error(f'Failed to load {restricted_json}: ' + str(e)) + return 1 + try: + template_restricted_name = restricted_json_data['restricted_name'] + except Exception as e: + logger.error(f'Failed to read restricted_name from {restricted_json}') + return 1 + else: + os.makedirs(template_restricted_path) # source restricted relative - source_restricted_platform_relative_path = source_restricted_platform_relative_path.replace('\\', '/') + if source_restricted_platform_relative_path: + source_restricted_platform_relative_path = source_restricted_platform_relative_path.replace('\\', '/') + else: + source_restricted_platform_relative_path = '' # template restricted relative - template_restricted_platform_relative_path = template_restricted_platform_relative_path.replace('\\', '/') + if template_restricted_platform_relative_path: + template_restricted_platform_relative_path = template_restricted_platform_relative_path.replace('\\', '/') + else: + template_restricted_platform_relative_path = '' logger.info(f'Processing Src: {source_path}') @@ -452,7 +517,7 @@ def create_template(dev_root: str, def _transform_into_template(s_data: object) -> (bool, object): """ Internal function to transform any data into templated data - :param source_data: the input data, this could be file data or file name data + :param s_data: the input data, this could be file data or file name data :return: bool: whether or not the returned data MAY need to be transformed to instantiate it t_data: potentially transformed data 0 for success or non 0 failure code """ @@ -507,7 +572,7 @@ def create_template(dev_root: str, platform: str) -> (bool, object): """ Internal function to transform a restricted platform file name into restricted template file name - :param source_data: the input data, this could be file data or file name data + :param s_data: the input data, this could be file data or file name data :return: bool: whether or not the returned data MAY need to be transformed to instantiate it t_data: potentially transformed data 0 for success or non 0 failure code """ @@ -581,14 +646,14 @@ def create_template(dev_root: str, else: after.append(components[x]) else: - for x in range(0, num_components-1): + for x in range(0, num_components - 1): relative += f'{components[x]}/' if os.path.isdir(f'{source_path}/{relative}'): before.append(components[x]) else: after.append(components[x]) - after.append(components[num_components-1]) + after.append(components[num_components - 1]) before.append("Platform") warn_if_not_platform = f'{source_path}/{"/".join(before)}' @@ -598,7 +663,8 @@ def create_template(dev_root: str, origin_entry_rel = '/'.join(before) if not os.path.isdir(warn_if_not_platform): - logger.warning(f'{entry_abs} -> {origin_entry_rel}: Other Platforms not found in {warn_if_not_platform}') + logger.warning( + f'{entry_abs} -> {origin_entry_rel}: Other Platforms not found in {warn_if_not_platform}') destination_entry_rel = origin_entry_rel destination_entry_abs = f'{template_path}/Template/{origin_entry_rel}' @@ -666,7 +732,8 @@ def create_template(dev_root: str, "dir": destination_entry_rel, "origin": origin_entry_rel }) - _transform_restricted_into_copyfiles_and_createdirs(source_path, restricted_platform, root_abs, entry_abs) + _transform_restricted_into_copyfiles_and_createdirs(source_path, restricted_platform, root_abs, + entry_abs) def _transform_dir_into_copyfiles_and_createdirs(root_abs: str, path_abs: str = None) -> None: @@ -722,6 +789,11 @@ def create_template(dev_root: str, # if not then create a normal relative and abs dst entry name _, origin_entry_rel = _transform_into_template(entry_rel) if platform and found_platform in restricted_platforms: + # if we don't have a template restricted path and we found restricted files... warn and skip + # the file/dir + if not template_restricted_path: + logger.warning("Restricted platform files found!!! {entry_rel}, {found_platform}") + continue _, destination_entry_rel = _transform_into_template_restricted_filename(entry_rel, found_platform) destination_entry_abs = f'{template_restricted_path}/{found_platform}/{template_restricted_platform_relative_path}/{template_name}/Template/{destination_entry_rel}' else: @@ -831,10 +903,13 @@ def create_template(dev_root: str, # every src may have a matching restricted folder per restricted platform # run the transformation on each src restricted folder - for restricted_platform in os.listdir(source_restricted_path): - restricted_platform_src_path_abs = f'{source_restricted_path}/{restricted_platform}/{source_restricted_platform_relative_path}/{source_name}'.replace('//', '/') - if os.path.isdir(restricted_platform_src_path_abs): - _transform_restricted_into_copyfiles_and_createdirs(source_path, restricted_platform, restricted_platform_src_path_abs) + if source_restricted_path: + for restricted_platform in os.listdir(source_restricted_path): + restricted_platform_src_path_abs = f'{source_restricted_path}/{restricted_platform}/{source_restricted_platform_relative_path}/{source_name}'.replace( + '//', '/') + if os.path.isdir(restricted_platform_src_path_abs): + _transform_restricted_into_copyfiles_and_createdirs(source_path, restricted_platform, + restricted_platform_src_path_abs) # sort copy_files.sort(key=lambda x: x['file']) @@ -845,12 +920,17 @@ def create_template(dev_root: str, json_data = {} json_data.update({'template_name': template_name}) json_data.update({'origin': f'The primary repo for {template_name} goes here: i.e. http://www.mydomain.com'}) - json_data.update({'license': f'What license {template_name} uses goes here: i.e. https://opensource.org/licenses/MIT'}) + json_data.update( + {'license': f'What license {template_name} uses goes here: i.e. https://opensource.org/licenses/MIT'}) json_data.update({'display_name': template_name}) json_data.update({'summary': f"A short description of {template_name}."}) json_data.update({'canonical_tags': []}) json_data.update({'user_tags': [f"{template_name}"]}) json_data.update({'icon_path': "preview.png"}) + if template_restricted_path: + json_data.update({'restricted': template_restricted_name}) + if template_restricted_platform_relative_path != '': + json_data.update({'template_restricted_platform_relative_path': template_restricted_platform_relative_path}) json_data.update({'copyFiles': copy_files}) json_data.update({'createDirectories': create_dirs}) @@ -862,133 +942,258 @@ def create_template(dev_root: str, with open(json_name, 'w') as s: s.write(json.dumps(json_data, indent=4)) - #copy the default preview.png + # copy the default preview.png this_script_parent = os.path.dirname(os.path.realpath(__file__)) preview_png_src = f'{this_script_parent}/preview.png' preview_png_dst = f'{template_path}/Template/preview.png' if not os.path.isfile(preview_png_dst): shutil.copy(preview_png_src, preview_png_dst) - # now write out each restricted platform template json separately - for restricted_platform in restricted_platform_entries: - restricted_template_path = f'{template_restricted_path}/{restricted_platform}/{template_restricted_platform_relative_path}/{template_name}'.replace('//', '/') + # if no restricted template path was given and restricted platform files were found + if not template_restricted_path and len(restricted_platform_entries): + logger.info(f'Restricted platform files found!!! and no template restricted path was found...') - #sort - restricted_platform_entries[restricted_platform]['copyFiles'].sort(key=lambda x: x['file']) - restricted_platform_entries[restricted_platform]['createDirs'].sort(key=lambda x: x['dir']) + if template_restricted_path: + # now write out each restricted platform template json separately + for restricted_platform in restricted_platform_entries: + restricted_template_path = f'{template_restricted_path}/{restricted_platform}/{template_restricted_platform_relative_path}/{template_name}'.replace( + '//', '/') - json_data = {} - json_data.update({'template_name': template_name}) - json_data.update({'origin': f'The primary repo for {template_name} goes here: i.e. http://www.mydomain.com'}) - json_data.update({'license': f'What license {template_name} uses goes here: i.e. https://opensource.org/licenses/MIT'}) - json_data.update({'display_name': template_name}) - json_data.update({'summary': f"A short description of {template_name}."}) - json_data.update({'canonical_tags': []}) - json_data.update({'user_tags': [f'{template_name}']}) - json_data.update({'icon_path': "preview.png"}) - json_data.update({'copyFiles': restricted_platform_entries[restricted_platform]['copyFiles']}) - json_data.update({'createDirectories': restricted_platform_entries[restricted_platform]['createDirs']}) + # sort + restricted_platform_entries[restricted_platform]['copyFiles'].sort(key=lambda x: x['file']) + restricted_platform_entries[restricted_platform]['createDirs'].sort(key=lambda x: x['dir']) - json_name = f'{restricted_template_path}/{template_file_name}' - os.makedirs(os.path.dirname(json_name), exist_ok=True) + json_data = {} + json_data.update({'template_name': template_name}) + json_data.update( + {'origin': f'The primary repo for {template_name} goes here: i.e. http://www.mydomain.com'}) + json_data.update( + {'license': f'What license {template_name} uses goes here: i.e. https://opensource.org/licenses/MIT'}) + json_data.update({'display_name': template_name}) + json_data.update({'summary': f"A short description of {template_name}."}) + json_data.update({'canonical_tags': []}) + json_data.update({'user_tags': [f'{template_name}']}) + json_data.update({'icon_path': "preview.png"}) + json_data.update({'copyFiles': restricted_platform_entries[restricted_platform]['copyFiles']}) + json_data.update({'createDirectories': restricted_platform_entries[restricted_platform]['createDirs']}) - # if the json file we are about to write already exists for some reason, delete it - if os.path.isfile(json_name): - os.unlink(json_name) - with open(json_name, 'w') as s: - s.write(json.dumps(json_data, indent=4)) + json_name = f'{restricted_template_path}/{template_file_name}' + os.makedirs(os.path.dirname(json_name), exist_ok=True) - preview_png_dst = f'{restricted_template_path}/Template/preview.png' - if not os.path.isfile(preview_png_dst): - shutil.copy(preview_png_src, preview_png_dst) + # if the json file we are about to write already exists for some reason, delete it + if os.path.isfile(json_name): + os.unlink(json_name) + with open(json_name, 'w') as s: + s.write(json.dumps(json_data, indent=4)) + + preview_png_dst = f'{restricted_template_path}/Template/preview.png' + if not os.path.isfile(preview_png_dst): + shutil.copy(preview_png_src, preview_png_dst) return 0 -def find_all_gem_templates(template_folder_list: list) -> list: - """ - Find all subfolders in the given list of folders which appear to be gem templates - :param template_folder_list: List of folders to search - :return: list of tuples of TemplateName, AbsolutePath - """ - return find_all_templates(template_folder_list, 'gem.json') - - -def find_all_project_templates(template_folder_list: list) -> list: - """ - Find all subfolders in the given list of folders which appear to be project templates - :param template_folder_list: List of folders to search - :return: list of tuples of TemplateName, AbsolutePath - """ - return find_all_templates(template_folder_list, 'project.json') - - -def find_all_templates(template_folder_list: list, template_marker_file: str) -> list: - """ - Find all subfolders in the given list of folders which appear to be templates - :param template_folder_list: List of folders to search - :param template_marker_file: file expected in the template folder - :return: list of tuples of TemplateName, AbsolutePath - """ - templates_found = [] - for folder in template_folder_list: - for root, dirs, files in os.walk(folder): - for dir in dirs: - if os.path.isfile(os.path.join(root, dir, template_file_name)) and \ - os.path.isfile(os.path.join(root, dir, 'Template', template_marker_file)): - templates_found.append((dir, os.path.join(root, dir))) - break # We only want root folders containing templates, do not recurse - return templates_found - - -def create_from_template(dev_root: str, - destination_path: str, - template_path: str, - destination_restricted_path: str, - template_restricted_path: str, - destination_restricted_platform_relative_path: str, - template_restricted_platform_relative_path: str, +def create_from_template(destination_path: str, + template_path: str = None, + template_name: str = None, + destination_restricted_path: str = None, + destination_restricted_name: str = None, + template_restricted_path: str = None, + template_restricted_name: str = None, + destination_restricted_platform_relative_path: str = None, + template_restricted_platform_relative_path: str = None, keep_restricted_in_instance: bool = False, keep_license_text: bool = False, replace: list = None) -> int: """ - Generic template instantiation. - :param dev_root: the path to the dev root of the engine - :param destination_path: the folder you want to put the instantiate template in, absolute or dev_root relative - :param template_path: the name of the template you want to instance + Generic template instantiation for non o3de object templates. This function makes NO assumptions! + Assumptions are made only for specializations like create_project or create_gem etc... So this function + will NOT try to divine intent. + :param destination_path: the folder you want to instantiate the template into + :param template_path: the path to the template you want to instance + :param template_name: the name of the template you want to instance, resolves template_path :param destination_restricted_path: path to the projects restricted folder - :param template_restricted_path: path to the templates restricted folder - :param keep_restricted_in_instance: whether or not you want ot keep the templates restricted files in your instance + :param destination_restricted_name: name of the projects restricted folder, resolves destination_restricted_path + :param template_restricted_path: path of the templates restricted folder + :param template_restricted_name: name of the templates restricted folder, resolves template_restricted_path + :param destination_restricted_platform_relative_path: any path after the platform in the destination restricted + :param template_restricted_platform_relative_path: any path after the platform in the template restricted + :param keep_restricted_in_instance: whether or not you want to keep the templates restricted files in your instance or separate them out into the restricted folder - :param keep_license_text: whether or not you want ot keep the templates license text in your instance. + :param keep_license_text: whether or not you want to keep the templates license text in your instance. template can have license blocks starting with {BEGIN_LICENSE} and ending with {END_LICENSE}, this controls if you want to keep the license text from the template in the new instance. It is false by default - because most customers will not want license text in there instances, but we may want to keep them. + because most customers will not want license text in their instances, but we may want to keep them. :param replace: optional list of strings uses to make concrete names out of templated parameters. X->Y pairs Ex. ${Name},TestGem,${Player},TestGemPlayer This will cause all references to ${Name} be replaced by TestGem, and all ${Player} replaced by 'TestGemPlayer' :return: 0 for success or non 0 failure code """ - # if no dev root error - if not dev_root: - logger.error('Dev root cannot be empty.') - return 1 - dev_root = dev_root.replace('\\', '/') - if not os.path.isabs(dev_root): - dev_root = os.path.abspath(dev_root) - if not os.path.isdir(dev_root): - logger.error(f'Dev root {dev_root} is not a folder.') + if template_name and template_path: + logger.error(f'Template Name and Template Path provided, these are mutually exclusive.') return 1 - # if no destination_path error + if destination_restricted_name and destination_restricted_path: + logger.error(f'Destination Restricted Name and Destination Restricted Path provided, these are mutually' + f' exclusive.') + return 1 + + if template_restricted_name and template_restricted_path: + logger.error(f'Template Restricted Name and Template Restricted Path provided, these are mutually exclusive.') + return 1 + + # need either the template name or path + if not template_path and not template_name: + logger.error(f'Template Name or Template Path must be specified.') + return 1 + + if template_name: + template_path = registration.get_registered(template_name=template_name) + + if not os.path.isdir(template_path): + logger.error(f'Could not find the template {template_name}=>{template_path}') + return 1 + + # template folder name is now the last component of the template_path + template_folder_name = os.path.basename(template_path) + + # the template.json should be in the template_path, make sure it's there a nd valid + template_json = f'{template_path}/template.json' + if not registration.valid_o3de_template_json(template_json): + logger.error(f'Template json {template_path} is invalid.') + return 1 + + # read in the template.json + with open(template_json) as s: + try: + template_json_data = json.load(s) + except Exception as e: + logger.error(f'Could read template json {template_json}: {str(e)}.') + return 1 + + # read template name from the json + try: + template_name = template_json_data['template_name'] + except Exception as e: + logger.error(f'Could not read "template_name" from template json {template_json}: {str(e)}.') + return 1 + + # if the user has not specified either a restricted name or restricted path + # see if the template itself specifies a restricted name + if not template_restricted_name and not template_restricted_path: + try: + template_json_restricted_name = template_json_data['restricted'] + except Exception as e: + # the template json doesn't have a 'restricted' element warn and use it + logger.info(f'The template does not specify a "restricted".') + else: + template_restricted_name = template_json_restricted_name + + # if no restricted name or path we continue on as if there is no template restricted files. + if template_restricted_name or template_restricted_path: + # If the user specified a --template-restricted-name we need to check that against the templates + # 'restricted' if it has one and see if they match. If they match then we don't have a problem. + # If they don't then we error out. If supplied but not present in the template we warn and use it. + # If not supplied we set what's in the template. If not supplied and not in the template we continue + # on as if there is no template restricted files. + if template_restricted_name: + # The user specified a --template-restricted-name + try: + template_json_restricted_name = template_json_data['restricted'] + except Exception as e: + # the template json doesn't have a 'restricted' element warn and use it + logger.info(f'The template does not specify a "restricted".' + f' Using supplied {template_restricted_name}') + else: + if template_json_restricted_name != template_restricted_name: + logger.error( + f'The supplied --template-restricted-name {template_restricted_name} does not match the' + f' templates "restricted". Either the the --template-restricted-name is incorrect or the' + f' templates "restricted" is wrong. Note that since this template specifies "restricted" as' + f' {template_json_restricted_name}, --template-restricted-name need not be supplied.') + + template_restricted_path = registration.get_registered(restricted_name=template_restricted_name) + else: + # The user has supplied the --template-restricted-path, see if that matches the template specifies. + # If it does then we do not have a problem. If it doesn't match then error out. If not specified + # in the template then warn and use the --template-restricted-path + template_restricted_path = template_restricted_path.replace('\\', '/') + try: + template_json_restricted_name = template_json_data['restricted'] + except Exception as e: + # the template json doesn't have a 'restricted' element warn and use it + logger.info(f'The template does not specify a "restricted".' + f' Using supplied {template_restricted_path}') + else: + template_json_restricted_path = registration.get_registered( + restricted_name=template_json_restricted_name) + if template_json_restricted_path != template_restricted_path: + logger.error( + f'The supplied --template-restricted-path {template_restricted_path} does not match the' + f' templates "restricted" {template_restricted_name} => {template_json_restricted_path}.' + f' Either the the supplied --template-restricted-path is incorrect or the templates' + f' "restricted" is wrong. Note that since this template specifies "restricted" as' + f' {template_json_restricted_name} --template-restricted-path need not be supplied' + f' and {template_json_restricted_path} will be used.') + return 1 + + # check and make sure the restricted exists + if not os.path.isdir(template_restricted_path): + logger.error(f'Template restricted path {template_restricted_path} does not exist.') + return 1 + + # If the user specified a --template-restricted-platform-relative-path we need to check that against + # the templates 'restricted_platform_relative_path' and see if they match. If they match we don't have + # a problem. If they don't match then we error out. If supplied but not present in the template we warn + # and use --template-restricted-platform-relative-path. If not supplied we set what's in the template. + # If not supplied and not in the template set empty string. + if template_restricted_platform_relative_path: + # The user specified a --template-restricted-platform-relative-path + template_restricted_platform_relative_path = template_restricted_platform_relative_path.replace( + '\\', '/') + try: + template_json_restricted_platform_relative_path = template_json_data[ + 'restricted_platform_relative_path'] + except Exception as e: + # the template json doesn't have a 'restricted_platform_relative_path' element warn and use it + logger.info(f'The template does not specify a "restricted_platform_relative_path".' + f' Using {template_restricted_platform_relative_path}') + else: + # the template has a 'restricted_platform_relative_path', if it matches we are fine, if not + # something is wrong with either the --template-restricted-platform-relative or the template is. + if template_restricted_platform_relative_path != template_json_restricted_platform_relative_path: + logger.error(f'The supplied --template-restricted-platform-relative-path does not match the' + f' templates "restricted_platform_relative_path". Either' + f' --template-restricted-platform-relative-path is incorrect or the templates' + f' "restricted_platform_relative_path" is wrong. Note that since this template' + f' specifies "restricted_platform_relative_path" it need not be supplied and' + f' {template_json_restricted_platform_relative_path} will be used.') + return 1 + else: + # The user has not supplied --template-restricted-platform-relative-path, try to read it from + # the template json. + try: + template_restricted_platform_relative_path = template_json_data[ + 'restricted_platform_relative_path'] + except Exception as e: + # The template json doesn't have a 'restricted_platform_relative_path' element, set empty string. + template_restricted_platform_relative_path = '' + + if not template_restricted_platform_relative_path: + template_restricted_platform_relative_path = '' + + # if no destination_path, error if not destination_path: - logger.error('Dst path cannot be empty.') + logger.error('Destination path cannot be empty.') return 1 destination_path = destination_path.replace('\\', '/') - if not os.path.isabs(destination_path): - destination_path = f'{dev_root}/{destination_path}' + if os.path.isdir(destination_path): + logger.error(f'Destination path {destination_path} already exists.') + return 1 + else: + os.makedirs(destination_path) - # dst name is now the last component of the destination_path + # destination name is now the last component of the destination_path destination_name = os.path.basename(destination_path) # destination name cannot be the same as a restricted platform name @@ -996,40 +1201,30 @@ def create_from_template(dev_root: str, logger.error(f'Destination path cannot be a restricted name. {destination_name}') return 1 - # if no template_path error - if not template_path: - logger.error('Template path cannot be empty.') - return 1 - template_path = template_path.replace('\\', '/') - if not os.path.isabs(template_path): - template_path = f'{dev_root}/Templates/{template_path}' - if not os.path.isdir(template_path): - logger.error(f'Could not find the template {template_path}') - return 1 + # destination restricted name + if destination_restricted_name: + destination_restricted_path = registration.get_registered(restricted_name=destination_restricted_name) - # template name is now the last component of the template_path - template_name = os.path.basename(template_path) - - # destination_restricted_path - destination_restricted_path = destination_restricted_path.replace('\\', '/') - if not os.path.isabs(destination_restricted_path): - destination_restricted_path = f'{dev_root}/{destination_restricted_path}' - if not os.path.isdir(destination_restricted_path): - os.makedirs(destination_restricted_path) - - # template_restricted_path - template_restricted_path = template_restricted_path.replace('\\', '/') - if not os.path.isabs(template_restricted_path): - template_restricted_path = f'{dev_root}/{template_restricted_path}' - if not os.path.isdir(template_restricted_path): - logger.error(f'Template restricted path {template_restricted_path} is not a folder.') - return 1 + # destination restricted path + elif destination_restricted_path: + destination_restricted_path = destination_restricted_path.replace('\\', '/') + if os.path.isabs(destination_restricted_path): + restricted_default_path = registration.get_registered(default='restricted') + new_destination_restricted_path = f'{restricted_default_path}/{destination_restricted_path}' + logger.info(f'{destination_restricted_path} is not a full path, making it relative' + f' to default restricted path = {new_destination_restricted_path}') + destination_restricted_path = new_destination_restricted_path + elif template_restricted_path: + restricted_default_path = registration.get_registered(default='restricted') + logger.info(f'--destination-restricted-path is not specified, using default restricted path / destination name' + f' = {restricted_default_path}') + destination_restricted_path = restricted_default_path # destination restricted relative - destination_restricted_platform_relative_path = destination_restricted_platform_relative_path.replace('\\', '/') - - # template restricted relative - template_restricted_platform_relative_path = template_restricted_platform_relative_path.replace('\\', '/') + if destination_restricted_platform_relative_path: + destination_restricted_platform_relative_path = destination_restricted_platform_relative_path.replace('\\', '/') + else: + destination_restricted_platform_relative_path = '' # any user supplied replacements replacements = list() @@ -1043,23 +1238,56 @@ def create_from_template(dev_root: str, replacements.append(("${NameUpper}", destination_name.upper())) replacements.append(("${NameLower}", destination_name.lower())) - return _instantiate_template(destination_name, - template_name, - destination_path, - template_path, - template_restricted_path, - replacements, - keep_restricted_in_instance, - keep_license_text) + if _instantiate_template(template_json_data, + destination_name, + template_name, + destination_path, + template_path, + destination_restricted_path, + template_restricted_path, + destination_restricted_platform_relative_path, + template_restricted_platform_relative_path, + replacements, + keep_restricted_in_instance, + keep_license_text): + logger.error(f'Instantiation of the template has failed.') + return 1 + + # We created the destination, now do anything extra that a destination requires + + # If we are not keeping the restricted in the destination read the destination restricted this might be a new + # restricted folder, so make sure the restricted has this destinations name + # Note there is no linking of non o3de objects to o3de restricted. So this will make no attempt to figure out + # if this destination was actually an o3de object and try to alter the .json + if not keep_restricted_in_instance: + if destination_restricted_path: + os.makedirs(destination_restricted_path, exist_ok=True) + + # read the restricted_name from the destination restricted.json + restricted_json = f"{destination_restricted_path}/restricted.json".replace('//', '/') + if not os.path.isfile(restricted_json): + with open(restricted_json, 'w') as s: + restricted_json_data = {} + restricted_json_data.update({'restricted_name': destination_name}) + s.write(json.dumps(restricted_json_data, indent=4)) + + logger.warning(f'Instantiation successful. NOTE: This is a generic instantiation of the template. If this' + f' was a template of an o3de object like a project, gem, template, etc. then you should have used' + f' specialization that knows how to link that object type via its project.json or gem.json, etc.' + f' Create from template is meant only to instance a template of a non o3de object.') + + return 0 -def create_project(dev_root: str, - project_path: str, - template_path: str, - project_restricted_path: str = "restricted", - template_restricted_path: str = "restricted", - project_restricted_platform_relative_path: str or None = '', - template_restricted_platform_relative_path: str = "Templates", +def create_project(project_path: str, + template_path: str = None, + template_name: str = None, + project_restricted_path: str = None, + project_restricted_name: str = None, + template_restricted_path: str = None, + template_restricted_name: str = None, + project_restricted_platform_relative_path: str = None, + template_restricted_platform_relative_path: str = None, keep_restricted_in_project: bool = False, keep_license_text: bool = False, replace: list = None, @@ -1067,61 +1295,196 @@ def create_project(dev_root: str, editor_system_component_class_id: str = None, module_id: str = None) -> int: """ - Template instantiation that make all default assumptions for a Project template instantiation, reducing the effort - needed in instancing a project - :param dev_root: the path to the dev root of the engine - :param project_path: the project path, can be absolute or dev_root relative - :param template_path: the path to the template you want to instance, can be abs or relative, - defaults to DefaultProject - :param project_restricted_path: path to the projects restricted folder - :param template_restricted_path: path to the templates restricted folder - :param project_restricted_platform_relative_path: path to append to the project-restricted-path - :param template_restricted_platform_relative_path: path to append to the template_restricted_path - :param keep_restricted_in_project: whether or not you want ot keep the templates restricted files in your project or + Template instantiation specialization that makes all default assumptions for a Project template instantiation, + reducing the effort needed in instancing a project + :param project_path: the project path, can be absolute or relative to default projects path + :param template_path: the path to the template you want to instance, can be absolute or relative to default templates path + :param template_name: the name the registered template you want to instance, defaults to DefaultProject, resolves template_path + :param project_restricted_path: path to the projects restricted folder, can be absolute or relative to the restricted='projects' + :param project_restricted_name: name of the registered projects restricted path, resolves project_restricted_path + :param template_restricted_path: templates restricted path can be absolute or relative to restricted='templates' + :param template_restricted_name: name of the registered templates restricted path, resolves template_restricted_path + :param project_restricted_platform_relative_path: any path after the platform to append to the project_restricted_path + :param template_restricted_platform_relative_path: any path after the platform to append to the template_restricted_path + :param keep_restricted_in_project: whether or not you want to keep the templates restricted files in your project or separate them out into the restricted folder - :param keep_license_text: whether or not you want ot keep the templates license text in your instance. + :param keep_license_text: whether or not you want to keep the templates license text in your instance. template can have license blocks starting with {BEGIN_LICENSE} and ending with {END_LICENSE}, this controls if you want to keep the license text from the template in the new instance. It is false by default - because most customers will not want license text in there instances, but we may want to keep them. + because most customers will not want license text in their instances, but we may want to keep them. :param replace: optional list of strings uses to make concrete names out of templated parameters. X->Y pairs Ex. ${Name},TestGem,${Player},TestGemPlayer This will cause all references to ${Name} be replaced by TestGem, and all ${Player} replaced by 'TestGemPlayer' :param system_component_class_id: optionally specify a uuid for the system component class, default is random uuid - :param editor_system_component_class_id: optionally specify a uuid for the editor system component class, default is random uuid + :param editor_system_component_class_id: optionally specify a uuid for the editor system component class, default is + random uuid :param module_id: optionally specify a uuid for the module class, default is random uuid :return: 0 for success or non 0 failure code """ - # if no dev root error - if not dev_root: - logger.error('Dev root cannot be empty.') - return 1 - dev_root = dev_root.replace('\\', '/') - if not os.path.isabs(dev_root): - dev_root = os.path.abspath(dev_root) - if not os.path.isdir(dev_root): - logger.error(f'Dev root {dev_root} is not a folder.') + if template_name and template_path: + logger.error(f'Template Name and Template Path provided, these are mutually exclusive.') return 1 - if not template_path: - logger.error('Template path cannot be empty.') + if project_restricted_name and project_restricted_path: + logger.error(f'Project Restricted Name and Project Restricted Path provided, these are mutually exclusive.') return 1 - template_path = template_path.replace('\\', '/') - if not os.path.isabs(template_path): - template_path = f'{dev_root}/Templates/{template_path}' + + if template_restricted_name and template_restricted_path: + logger.error(f'Template Restricted Name and Template Restricted Path provided, these are mutually exclusive.') + return 1 + + if not template_path and not template_name: + template_name = 'DefaultProject' + + if template_name and not template_path: + template_path = registration.get_registered(template_name=template_name) + if not os.path.isdir(template_path): - logger.error(f'Could not find the template {template_path}') + logger.error(f'Could not find the template {template_name}=>{template_path}') return 1 - # template name is now the last component of the template_path - template_name = os.path.basename(template_path) + # template folder name is now the last component of the template_path + template_folder_name = os.path.basename(template_path) - # project path + # the template.json should be in the template_path, make sure it's there and valid + template_json = f'{template_path}/template.json' + if not registration.valid_o3de_template_json(template_json): + logger.error(f'Template json {template_path} is not valid.') + return 1 + + # read in the template.json + with open(template_json) as s: + try: + template_json_data = json.load(s) + except Exception as e: + logger.error(f'Could read template json {template_json}: {str(e)}.') + return 1 + + # read template name from the json + try: + template_name = template_json_data['template_name'] + except Exception as e: + logger.error(f'Could not read "template_name" from template json {template_json}: {str(e)}.') + return 1 + + # if the user has not specified either a restricted name or restricted path + # see if the template itself specifies a restricted name + if not template_restricted_name and not template_restricted_path: + try: + template_json_restricted_name = template_json_data['restricted'] + except Exception as e: + # the template json doesn't have a 'restricted' element warn and use it + logger.info(f'The template does not specify a "restricted".') + else: + template_restricted_name = template_json_restricted_name + + # if no restricted name or path we continue on as if there is no template restricted files. + if template_restricted_name or template_restricted_path: + # If the user specified a --template-restricted-name we need to check that against the templates + # 'restricted' if it has one and see if they match. If they match then we don't have a problem. + # If they don't then we error out. If supplied but not present in the template we warn and use it. + # If not supplied we set what's in the template. If not supplied and not in the template we continue + # on as if there is no template restricted files. + if template_restricted_name and not template_restricted_path: + # The user specified a --template-restricted-name + try: + template_json_restricted_name = template_json_data['restricted'] + except Exception as e: + # the template json doesn't have a 'restricted' element warn and use it + logger.info(f'The template does not specify a "restricted".' + f' Using supplied {template_restricted_name}') + else: + if template_json_restricted_name != template_restricted_name: + logger.error( + f'The supplied --template-restricted-name {template_restricted_name} does not match the' + f' templates "restricted". Either the the --template-restricted-name is incorrect or the' + f' templates "restricted" is wrong. Note that since this template specifies "restricted" as' + f' {template_json_restricted_name}, --template-restricted-name need not be supplied.') + + template_restricted_path = registration.get_registered(restricted_name=template_restricted_name) + else: + # The user has supplied the --template-restricted-path, see if that matches the template specifies. + # If it does then we do not have a problem. If it doesn't match then error out. If not specified + # in the template then warn and use the --template-restricted-path + template_restricted_path = template_restricted_path.replace('\\', '/') + try: + template_json_restricted_name = template_json_data['restricted'] + except Exception as e: + # the template json doesn't have a 'restricted' element warn and use it + logger.info(f'The template does not specify a "restricted".' + f' Using supplied {template_restricted_path}') + else: + template_json_restricted_path = registration.get_registered( + restricted_name=template_json_restricted_name) + if template_json_restricted_path != template_restricted_path: + logger.error( + f'The supplied --template-restricted-path {template_restricted_path} does not match the' + f' templates "restricted" {template_restricted_name} => {template_json_restricted_path}.' + f' Either the the supplied --template-restricted-path is incorrect or the templates' + f' "restricted" is wrong. Note that since this template specifies "restricted" as' + f' {template_json_restricted_name} --template-restricted-path need not be supplied' + f' and {template_json_restricted_path} will be used.') + return 1 + + # check and make sure the restricted exists + if not os.path.isdir(template_restricted_path): + logger.error(f'Template restricted path {template_restricted_path} does not exist.') + return 1 + + # If the user specified a --template-restricted-platform-relative-path we need to check that against + # the templates 'restricted_platform_relative_path' and see if they match. If they match we don't have + # a problem. If they don't match then we error out. If supplied but not present in the template we warn + # and use --template-restricted-platform-relative-path. If not supplied we set what's in the template. + # If not supplied and not in the template set empty string. + if template_restricted_platform_relative_path: + # The user specified a --template-restricted-platform-relative-path + template_restricted_platform_relative_path = template_restricted_platform_relative_path.replace('\\', '/') + try: + template_json_restricted_platform_relative_path = template_json_data[ + 'restricted_platform_relative_path'] + except Exception as e: + # the template json doesn't have a 'restricted_platform_relative_path' element warn and use it + logger.info(f'The template does not specify a "restricted_platform_relative_path".' + f' Using {template_restricted_platform_relative_path}') + else: + # the template has a 'restricted_platform_relative_path', if it matches we are fine, if not + # something is wrong with either the --template-restricted-platform-relative or the template is. + if template_restricted_platform_relative_path != template_json_restricted_platform_relative_path: + logger.error(f'The supplied --template-restricted-platform-relative-path does not match the' + f' templates "restricted_platform_relative_path". Either' + f' --template-restricted-platform-relative-path is incorrect or the templates' + f' "restricted_platform_relative_path" is wrong. Note that since this template' + f' specifies "restricted_platform_relative_path" it need not be supplied and' + f' {template_json_restricted_platform_relative_path} will be used.') + return 1 + else: + # The user has not supplied --template-restricted-platform-relative-path, try to read it from + # the template json. + try: + template_restricted_platform_relative_path = template_json_data[ + 'restricted_platform_relative_path'] + except Exception as e: + # The template json doesn't have a 'restricted_platform_relative_path' element, set empty string. + template_restricted_platform_relative_path = '' + if not template_restricted_platform_relative_path: + template_restricted_platform_relative_path = '' + + # if no project path, error if not project_path: logger.error('Project path cannot be empty.') return 1 project_path = project_path.replace('\\', '/') if not os.path.isabs(project_path): - project_path = f'{dev_root}/{project_path}' + default_projects_folder = registration.get_registered(default_folder='projects') + new_project_path = f'{default_projects_folder}/{project_path}' + logger.info(f'Project Path {project_path} is not a full path, we must assume its relative' + f' to default projects path = {new_project_path}') + project_path = new_project_path + if os.path.isdir(project_path): + logger.error(f'Project path {project_path} already exists.') + return 1 + else: + os.makedirs(project_path) # project name is now the last component of the project_path project_name = os.path.basename(project_path) @@ -1131,26 +1494,30 @@ def create_project(dev_root: str, logger.error(f'Project path cannot be a restricted name. {project_name}') return 1 - # project_restricted_path - project_restricted_path = project_restricted_path.replace('\\', '/') - if not os.path.isabs(project_restricted_path): - project_restricted_path = f'{dev_root}/{project_restricted_path}' - if not os.path.isdir(project_restricted_path): - os.makedirs(project_restricted_path) + # project restricted name + if project_restricted_name and not project_restricted_path: + project_restricted_path = registration.get_registered(restricted_name=project_restricted_name) - # template_restricted_path - template_restricted_path = template_restricted_path.replace('\\', '/') - if not os.path.isabs(template_restricted_path): - template_restricted_path = f'{dev_root}/{template_restricted_path}' - if not os.path.isdir(template_restricted_path): - logger.error(f'Template restricted path {template_restricted_path} is not a folder.') - return 1 + # project restricted path + elif project_restricted_path: + project_restricted_path = project_restricted_path.replace('\\', '/') + if not os.path.isabs(project_restricted_path): + default_projects_restricted_folder = registration.get_registered(restricted_name='projects') + new_project_restricted_path = f'{default_projects_restricted_folder}/{project_restricted_path}' + logger.info(f'Project restricted path {project_restricted_path} is not a full path, we must assume its' + f' relative to default projects restricted path = {new_project_restricted_path}') + project_restricted_path = new_project_restricted_path + elif template_restricted_path: + project_restricted_default_path = registration.get_registered(restricted_name='projects') + logger.info(f'--project-restricted-path is not specified, using default project restricted path / project name' + f' = {project_restricted_default_path}') + project_restricted_path = project_restricted_default_path - # project restricted relative - project_restricted_platform_relative_path = project_restricted_platform_relative_path.replace('\\', '/') - - # template restricted relative - template_restricted_platform_relative_path = template_restricted_platform_relative_path.replace('\\', '/') + # project restricted relative path + if project_restricted_platform_relative_path: + project_restricted_platform_relative_path = project_restricted_platform_relative_path.replace('\\', '/') + else: + project_restricted_platform_relative_path = '' # any user supplied replacements replacements = list() @@ -1185,14 +1552,15 @@ def create_project(dev_root: str, if editor_system_component_class_id: if '{' not in editor_system_component_class_id or '-' not in editor_system_component_class_id: logger.error( - f'Editor System component class id {editor_system_component_class_id} is malformed. Should look like Ex.' + - '{b60c92eb-3139-454b-a917-a9d3c5819594}') + f'Editor System component class id {editor_system_component_class_id} is malformed. Should look like' + f' Ex.' + '{b60c92eb-3139-454b-a917-a9d3c5819594}') return 1 replacements.append(("${EditorSysCompClassId}", editor_system_component_class_id)) else: replacements.append(("${EditorSysCompClassId}", '{' + str(uuid.uuid4()) + '}')) - if _instantiate_template(project_name, + if _instantiate_template(template_json_data, + project_name, template_name, project_path, template_path, @@ -1202,14 +1570,65 @@ def create_project(dev_root: str, template_restricted_platform_relative_path, replacements, keep_restricted_in_project, - keep_license_text) == 0: + keep_license_text): + logger.error(f'Instantiation of the template has failed.') + return 1 - # we created the project, now do anything extra that a project requires + # We created the project, now do anything extra that a project requires + + # If we are not keeping the restricted in the project read the name of the restricted folder from the + # restricted json and set that as this projects restricted + if not keep_restricted_in_project: + if project_restricted_path: + os.makedirs(project_restricted_path, exist_ok=True) + + # read the restricted_name from the projects restricted.json + restricted_json = f"{project_restricted_path}/restricted.json".replace('//', '/') + if os.path.isfile(restricted_json): + if not registration.valid_o3de_restricted_json(restricted_json): + logger.error(f'Restricted json {restricted_json} is not valid.') + return 1 + else: + with open(restricted_json, 'w') as s: + restricted_json_data = {} + restricted_json_data.update({'restricted_name': project_name}) + s.write(json.dumps(restricted_json_data, indent=4)) + + with open(restricted_json, 'r') as s: + try: + restricted_json_data = json.load(s) + except Exception as e: + logger.error(f'Failed to load restricted json {restricted_json}.') + return 1 + + try: + restricted_name = restricted_json_data["restricted_name"] + except Exception as e: + logger.error(f'Failed to read "restricted_name" from restricted json {restricted_json}.') + return 1 + + # set the "restricted": "restricted_name" element of the project.json + project_json = f"{project_path}/project.json".replace('//', '/') + if not registration.valid_o3de_project_json(project_json): + logger.error(f'Project json {project_json} is not valid.') + return 1 + + with open(project_json, 'r') as s: + try: + project_json_data = json.load(s) + except Exception as e: + logger.error(f'Failed to load project json {project_json}.') + return 1 + + project_json_data.update({"restricted": restricted_name}) + os.unlink(project_json) + with open(project_json, 'w') as s: + try: + s.write(json.dumps(project_json_data, indent=4)) + except Exception as e: + logger.error(f'Failed to write project json {project_json}.') + return 1 - # If we do not keep the restricted folders in the project then we have to make sure - # the restricted project folder has a CMakeLists.txt file in it so that when the restricted - # folders CMakeLists.txt is executed it will find a CMakeLists.txt in the restricted project root - if not keep_restricted_in_project: for restricted_platform in restricted_platforms: restricted_project = f'{project_restricted_path}/{restricted_platform}/{project_name}' os.makedirs(restricted_project, exist_ok=True) @@ -1218,25 +1637,38 @@ def create_project(dev_root: str, with open(cmakelists_file_name, 'w') as d: if keep_license_text: d.write('# {BEGIN_LICENSE}\n') - d.write('# All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or\n') + d.write('# All or portions of this file Copyright (c) Amazon.com, Inc. or its' + ' affiliates or\n') d.write('# its licensors.\n') d.write('#\n') - d.write('# For complete copyright and license terms please see the LICENSE at the root of this\n') - d.write('# distribution (the "License"). All use of this software is governed by the License,\n') - d.write('# or, if provided, by the license below or the license accompanying this file. Do not\n') - d.write('# remove or modify any license notices. This file is distributed on an "AS IS" BASIS,\n') + d.write('# For complete copyright and license terms please see the LICENSE at the' + ' root of this\n') + d.write('# distribution (the "License"). All use of this software is governed by' + ' the License,\n') + d.write('# or, if provided, by the license below or the license accompanying this' + ' file. Do not\n') + d.write('# remove or modify any license notices. This file is distributed on an' + ' "AS IS" BASIS,\n') d.write('# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n') d.write('# {END_LICENSE}\n') + + # copy the o3de_manifest.cmake into the project root + engine_path = registration.get_this_engine_path() + o3de_manifest_cmake = f'{engine_path}/cmake/o3de_manifest.cmake' + shutil.copy(o3de_manifest_cmake, project_path) + return 0 -def create_gem(dev_root: str, - gem_path: str, - template_path: str, - gem_restricted_path: str, - template_restricted_path: str, - gem_restricted_platform_relative_path: str or None, - template_restricted_platform_relative_path: str, +def create_gem(gem_path: str, + template_path: str = None, + template_name: str = None, + gem_restricted_path: str = None, + gem_restricted_name: str = None, + template_restricted_path: str = None, + template_restricted_name: str = None, + gem_restricted_platform_relative_path: str = None, + template_restricted_platform_relative_path: str = None, keep_restricted_in_gem: bool = False, keep_license_text: bool = False, replace: list = None, @@ -1244,46 +1676,194 @@ def create_gem(dev_root: str, editor_system_component_class_id: str = None, module_id: str = None) -> int: """ - Template instantiation that make all default assumptions for a Gem template instantiation, reducing the effort - needed in instancing a gem - :param dev_root: the path to the dev root of the engine - :param gem_path: the gem path, can be absolute or dev_root/Gems relative - :param gem_restricted_path: the gem restricted path, can be absolute or dev_root/Gems relative - :param template_path: the template path you want to instance, abs or dev_root/Templates relative, - defaults to DefaultGem - :param template_restricted_path: path to the templates restricted folder - :param keep_restricted_in_gem: whether or not you want ot keep the templates restricted files in your instance or - seperate them out into the restricted folder - :param keep_license_text: whether or not you want ot keep the templates license text in your instance. template can + Template instantiation specialization that makes all default assumptions for a Gem template instantiation, + reducing the effort needed in instancing a gem + :param gem_path: the gem path, can be absolute or relative to default gems path + :param template_path: the template path you want to instance, can be absolute or relative to default templates path + :param template_name: the name of the registered template you want to instance, defaults to DefaultGem, resolves template_path + :param gem_restricted_path: path to the gems restricted folder, can be absolute or relative to the restricted='gems' + :param gem_restricted_name: str = name of the registered gems restricted path, resolves gem_restricted_path + :param template_restricted_path: the templates restricted path, can be absolute or relative to the restricted='templates' + :param template_restricted_name: name of the registered templates restricted path, resolves template_restricted_path + :param gem_restricted_platform_relative_path: any path after the platform to append to the gem_restricted_path + :param template_restricted_platform_relative_path: any path after the platform to append to the template_restricted_path + :param keep_restricted_in_gem: whether or not you want to keep the templates restricted files in your instance or + separate them out into the restricted folder + :param keep_license_text: whether or not you want to keep the templates license text in your instance. template can have license blocks starting with {BEGIN_LICENSE} and ending with {END_LICENSE}, this controls if you want to keep the license text from the template in the new instance. It is false by default because most customers will not - want license text in there instances, but we may want to keep them. + want license text in their instances, but we may want to keep them. :param replace: optional list of strings uses to make concrete names out of templated parameters. X->Y pairs Ex. ${Name},TestGem,${Player},TestGemPlayer This will cause all references to ${Name} be replaced by TestGem, and all ${Player} replaced by 'TestGemPlayer' :param system_component_class_id: optionally specify a uuid for the system component class, default is random uuid - :param editor_system_component_class_id: optionally specify a uuid for the editor system component class, default is random uuid + :param editor_system_component_class_id: optionally specify a uuid for the editor system component class, default is + random uuid :param module_id: optionally specify a uuid for the module class, default is random uuid :return: 0 for success or non 0 failure code """ - # if no dev root error - if not dev_root: - logger.error('Dev root cannot be empty.') - return 1 - dev_root = dev_root.replace('\\', '/') - if not os.path.isabs(dev_root): - dev_root = os.path.abspath(dev_root) - if not os.path.isdir(dev_root): - logger.error(f'Dev root {dev_root} is not a folder.') + if template_name and template_path: + logger.error(f'Template Name and Template Path provided, these are mutually exclusive.') return 1 - # if no destination_path error + if gem_restricted_name and gem_restricted_path: + logger.error(f'Gem Restricted Name and Gem Restricted Path provided, these are mutually exclusive.') + return 1 + + if template_restricted_name and template_restricted_path: + logger.error(f'Template Restricted Name and Template Restricted Path provided, these are mutually exclusive.') + return 1 + + if not template_name and not template_path: + template_name = 'DefaultGem' + + if template_name and not template_path: + template_path = registration.get_registered(template_name=template_name) + + if not os.path.isdir(template_path): + logger.error(f'Could not find the template {template_name}=>{template_path}') + return 1 + + # template name is now the last component of the template_path + template_folder_name = os.path.basename(template_path) + + # the template.json should be in the template_path, make sure it's there and valid + template_json = f'{template_path}/template.json' + if not registration.valid_o3de_template_json(template_json): + logger.error(f'Template json {template_path} is not valid.') + return 1 + + # read in the template.json + with open(template_json) as s: + try: + template_json_data = json.load(s) + except Exception as e: + logger.error(f'Could read template json {template_json}: {str(e)}.') + return 1 + + # read template name from the json + try: + template_name = template_json_data['template_name'] + except Exception as e: + logger.error(f'Could not read "template_name" from template json {template_json}: {str(e)}.') + return 1 + + # if the user has not specified either a restricted name or restricted path + # see if the template itself specifies a restricted name + if not template_restricted_name and not template_restricted_path: + try: + template_json_restricted_name = template_json_data['restricted'] + except Exception as e: + # the template json doesn't have a 'restricted' element warn and use it + logger.info(f'The template does not specify a "restricted".') + else: + template_restricted_name = template_json_restricted_name + + # if no restricted name or path we continue on as if there is no template restricted files. + if template_restricted_name or template_restricted_path: + # if the user specified a --template-restricted-name we need to check that against the templates 'restricted' + # if it has one and see if they match. If they match then we don't have a problem. If they don't then we error + # out. If supplied but not present in the template we warn and use it. If not supplied we set what's in the + # template. If not supplied and not in the template we continue on as if there is no template restricted files. + if template_restricted_name and not template_restricted_path: + # The user specified a --template-restricted-name + try: + template_json_restricted_name = template_json_data['restricted'] + except Exception as e: + # the template json doesn't have a 'restricted' element warn and use it + logger.info(f'The template does not specify a "restricted".' + f' Using supplied {template_restricted_name}') + else: + if template_json_restricted_name != template_restricted_name: + logger.error( + f'The supplied --template-restricted-name {template_restricted_name} does not match the' + f' templates "restricted". Either the the --template-restricted-name is incorrect or the' + f' templates "restricted" is wrong. Note that since this template specifies "restricted" as' + f' {template_json_restricted_name}, --template-restricted-name need not be supplied.') + + template_restricted_path = registration.get_registered(restricted_name=template_restricted_name) + else: + # The user has supplied the --template-restricted-path, see if that matches the template specifies. + # If it does then we do not have a problem. If it doesn't match then error out. If not specified + # in the template then warn and use the --template-restricted-path + template_restricted_path = template_restricted_path.replace('\\', '/') + try: + template_json_restricted_name = template_json_data['restricted'] + except Exception as e: + # the template json doesn't have a 'restricted' element warn and use it + logger.info(f'The template does not specify a "restricted".' + f' Using supplied {template_restricted_path}') + else: + template_json_restricted_path = registration.get_registered( + restricted_name=template_json_restricted_name) + if template_json_restricted_path != template_restricted_path: + logger.error( + f'The supplied --template-restricted-path {template_restricted_path} does not match the' + f' templates "restricted" {template_restricted_name} => {template_json_restricted_path}.' + f' Either the the supplied --template-restricted-path is incorrect or the templates' + f' "restricted" is wrong. Note that since this template specifies "restricted" as' + f' {template_json_restricted_name} --template-restricted-path need not be supplied' + f' and {template_json_restricted_path} will be used.') + return 1 + # check and make sure the restricted path exists + if not os.path.isdir(template_restricted_path): + logger.error(f'Template restricted path {template_restricted_path} does not exist.') + return 1 + + # If the user specified a --template-restricted-platform-relative-path we need to check that against + # the templates 'restricted_platform_relative_path' and see if they match. If they match we don't have + # a problem. If they don't match then we error out. If supplied but not present in the template we warn + # and use --template-restricted-platform-relative-path. If not supplied we set what's in the template. + # If not supplied and not in the template set empty string. + if template_restricted_platform_relative_path: + # The user specified a --template-restricted-platform-relative-path + template_restricted_platform_relative_path = template_restricted_platform_relative_path.replace('\\', '/') + try: + template_json_restricted_platform_relative_path = template_json_data[ + 'restricted_platform_relative_path'] + except Exception as e: + # the template json doesn't have a 'restricted_platform_relative_path' element warn and use it + logger.info(f'The template does not specify a "restricted_platform_relative_path".' + f' Using {template_restricted_platform_relative_path}') + else: + # the template has a 'restricted_platform_relative_path', if it matches we are fine, if not something is + # wrong with either the --template-restricted-platform-relative or the template is + if template_restricted_platform_relative_path != template_json_restricted_platform_relative_path: + logger.error(f'The supplied --template-restricted-platform-relative-path does not match the' + f' templates "restricted_platform_relative_path". Either' + f' --template-restricted-platform-relative-path is incorrect or the templates' + f' "restricted_platform_relative_path" is wrong. Note that since this template' + f' specifies "restricted_platform_relative_path" it need not be supplied and' + f' {template_json_restricted_platform_relative_path} will be used.') + return 1 + else: + # The user has not supplied --template-restricted-platform-relative-path, try to read it from + # the template json. + try: + template_restricted_platform_relative_path = template_json_data[ + 'restricted_platform_relative_path'] + except Exception as e: + # The template json doesn't have a 'restricted_platform_relative_path' element, set empty string. + template_restricted_platform_relative_path = '' + if not template_restricted_platform_relative_path: + template_restricted_platform_relative_path = '' + + # if no gem_path, error if not gem_path: logger.error('Gem path cannot be empty.') return 1 gem_path = gem_path.replace('\\', '/') if not os.path.isabs(gem_path): - gem_path = f'{dev_root}/Gems/{gem_path}' + default_gems_folder = registration.get_registered(default_folder='gems') + new_gem_path = f'{default_gems_folder}/{gem_path}' + logger.info(f'Gem Path {gem_path} is not a full path, we must assume its relative' + f' to default gems path = {new_gem_path}') + gem_path = new_gem_path + if os.path.isdir(gem_path): + logger.error(f'Gem path {gem_path} already exists.') + return 1 + else: + os.makedirs(gem_path) # gem name is now the last component of the gem_path gem_name = os.path.basename(gem_path) @@ -1293,39 +1873,30 @@ def create_gem(dev_root: str, logger.error(f'Gem path cannot be a restricted name. {gem_name}') return 1 - if not template_path: - logger.error('Template path cannot be empty.') - return 1 - template_path = template_path.replace('\\', '/') - if not os.path.isabs(template_path): - template_path = f'{dev_root}/Templates/{template_path}' - if not os.path.isdir(template_path): - logger.error(f'Could not find the template {template_path}') - return 1 + # gem restricted name + if gem_restricted_name and not gem_restricted_path: + gem_restricted_path = registration.get_registered(restricted_name=gem_restricted_name) - # template name is now the last component of the template_path - template_name = os.path.basename(template_path) - - # gem_restricted_path - gem_restricted_path = gem_restricted_path.replace('\\', '/') - if not os.path.isabs(gem_restricted_path): - gem_restricted_path = f'{dev_root}/{gem_restricted_path}' - if not os.path.isdir(gem_restricted_path): - os.makedirs(gem_restricted_path) - - # template_restricted_path - template_restricted_path = template_restricted_path.replace('\\', '/') - if not os.path.isabs(template_restricted_path): - template_restricted_path = f'{dev_root}/{template_restricted_path}' - if not os.path.isdir(template_restricted_path): - logger.error(f'Template restricted path {template_restricted_path} is not a folder.') - return 1 + # gem restricted path + elif gem_restricted_path: + gem_restricted_path = gem_restricted_path.replace('\\', '/') + if not os.path.isabs(gem_restricted_path): + default_gems_restricted_folder = registration.get_registered(restricted_name='gems') + new_gem_restricted_path = f'{default_gems_restricted_folder}/{gem_restricted_path}' + logger.info(f'Gem restricted path {gem_restricted_path} is not a full path, we must assume its' + f' relative to default gems restricted path = {new_gem_restricted_path}') + gem_restricted_path = new_gem_restricted_path + elif template_restricted_path: + gem_restricted_default_path = registration.get_registered(restricted_name='gems') + logger.info(f'--gem-restricted-path is not specified, using default gem restricted path / gem name' + f' = {gem_restricted_default_path}') + gem_restricted_path = gem_restricted_default_path # gem restricted relative - gem_restricted_platform_relative_path = gem_restricted_platform_relative_path.replace('\\', '/') - - # template restricted relative - template_restricted_platform_relative_path = template_restricted_platform_relative_path.replace('\\', '/') + if gem_restricted_platform_relative_path: + gem_restricted_platform_relative_path = gem_restricted_platform_relative_path.replace('\\', '/') + else: + gem_restricted_platform_relative_path = '' # any user supplied replacements replacements = list() @@ -1360,32 +1931,115 @@ def create_gem(dev_root: str, if editor_system_component_class_id: if '{' not in editor_system_component_class_id or '-' not in editor_system_component_class_id: logger.error( - f'Editor System component class id {editor_system_component_class_id} is malformed. Should look like Ex.' + - '{b60c92eb-3139-454b-a917-a9d3c5819594}') + f'Editor System component class id {editor_system_component_class_id} is malformed. Should look like' + f' Ex.' + '{b60c92eb-3139-454b-a917-a9d3c5819594}') return 1 replacements.append(("${EditorSysCompClassId}", editor_system_component_class_id)) else: replacements.append(("${EditorSysCompClassId}", '{' + str(uuid.uuid4()) + '}')) - return _instantiate_template(gem_name, - template_name, - gem_path, - template_path, - gem_restricted_path, - template_restricted_path, - gem_restricted_platform_relative_path, - template_restricted_platform_relative_path, - replacements, - keep_restricted_in_gem, - keep_license_text) + if _instantiate_template(template_json_data, + gem_name, + template_name, + gem_path, + template_path, + gem_restricted_path, + template_restricted_path, + gem_restricted_platform_relative_path, + template_restricted_platform_relative_path, + replacements, + keep_restricted_in_gem, + keep_license_text): + logger.error(f'Instantiation of the template has failed.') + return 1 + + # We created the gem, now do anything extra that a gem requires + + # If we are not keeping the restricted in the gem read the name of the restricted folder from the + # restricted json and set that as this gems restricted + if not keep_restricted_in_gem: + if gem_restricted_path: + os.makedirs(gem_restricted_path, exist_ok=True) + + # read the restricted_name from the gems restricted.json + restricted_json = f"{gem_restricted_path}/restricted.json".replace('//', '/') + if os.path.isfile(restricted_json): + if not registration.valid_o3de_restricted_json(restricted_json): + logger.error(f'Restricted json {restricted_json} is not valid.') + return 1 + else: + with open(restricted_json, 'w') as s: + restricted_json_data = {} + restricted_json_data.update({'restricted_name': gem_name}) + s.write(json.dumps(restricted_json_data, indent=4)) + + with open(restricted_json, 'r') as s: + try: + restricted_json_data = json.load(s) + except Exception as e: + logger.error(f'Failed to load restricted json {restricted_json}.') + return 1 + + try: + restricted_name = restricted_json_data["restricted_name"] + except Exception as e: + logger.error(f'Failed to read "restricted_name" from restricted json {restricted_json}.') + return 1 + + # set the "restricted": "restricted_name" element of the gem.json + gem_json = f"{gem_path}/gem.json".replace('//', '/') + if not registration.valid_o3de_gem_json(gem_json): + logger.error(f'Gem json {gem_json} is not valid.') + return 1 + + with open(gem_json, 'r') as s: + try: + gem_json_data = json.load(s) + except Exception as e: + logger.error(f'Failed to load gem json {gem_json}.') + return 1 + + gem_json_data.update({"restricted": restricted_name}) + os.unlink(gem_json) + with open(gem_json, 'w') as s: + try: + s.write(json.dumps(gem_json_data, indent=4)) + except Exception as e: + logger.error(f'Failed to write project json {gem_json}.') + return 1 + + for restricted_platform in restricted_platforms: + restricted_gem = f'{gem_restricted_path}/{restricted_platform}/{gem_name}' + os.makedirs(restricted_gem, exist_ok=True) + cmakelists_file_name = f'{restricted_gem}/CMakeLists.txt' + if not os.path.isfile(cmakelists_file_name): + with open(cmakelists_file_name, 'w') as d: + if keep_license_text: + d.write('# {BEGIN_LICENSE}\n') + d.write( + '# All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or\n') + d.write('# its licensors.\n') + d.write('#\n') + d.write( + '# For complete copyright and license terms please see the LICENSE at the root of this\n') + d.write( + '# distribution (the "License"). All use of this software is governed by the License,\n') + d.write( + '# or, if provided, by the license below or the license accompanying this file. Do not\n') + d.write( + '# remove or modify any license notices. This file is distributed on an "AS IS" BASIS,\n') + d.write('# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n') + d.write('# {END_LICENSE}\n') + return 0 def _run_create_template(args: argparse) -> int: - return create_template(common.determine_engine_root(), - args.source_path, + return create_template(args.source_path, args.template_path, args.source_restricted_path, + args.source_restricted_name, args.template_restricted_path, + args.template_restricted_name, args.source_restricted_platform_relative_path, args.template_restricted_platform_relative_path, args.keep_restricted_in_template, @@ -1394,11 +2048,13 @@ def _run_create_template(args: argparse) -> int: def _run_create_from_template(args: argparse) -> int: - return create_from_template(common.determine_engine_root(), - args.destination_path, + return create_from_template(args.destination_path, args.template_path, + args.template_name, args.destination_restricted_path, + args.destination_restricted_name, args.template_restricted_path, + args.template_restricted_name, args.destination_restricted_platform_relative_path, args.template_restricted_platform_relative_path, args.keep_restricted_in_instance, @@ -1407,11 +2063,13 @@ def _run_create_from_template(args: argparse) -> int: def _run_create_project(args: argparse) -> int: - return create_project(common.determine_engine_root(), - args.project_path, + return create_project(args.project_path, args.template_path, + args.template_name, args.project_restricted_path, + args.project_restricted_name, args.template_restricted_path, + args.template_restricted_name, args.project_restricted_platform_relative_path, args.template_restricted_platform_relative_path, args.keep_restricted_in_project, @@ -1423,11 +2081,13 @@ def _run_create_project(args: argparse) -> int: def _run_create_gem(args: argparse) -> int: - return create_gem(common.determine_engine_root(), - args.gem_path, + return create_gem(args.gem_path, args.template_path, + args.template_name, args.gem_restricted_path, + args.gem_restricted_name, args.template_restricted_path, + args.template_restricted_name, args.gem_restricted_platform_relative_path, args.template_restricted_platform_relative_path, args.keep_restricted_in_gem, @@ -1452,49 +2112,55 @@ def add_args(parser, subparsers) -> None: # turn a directory into a template create_template_subparser = subparsers.add_parser('create-template') create_template_subparser.add_argument('-sp', '--source-path', type=str, required=True, - help='The path to the source that you want to make into a template,' - ' can be absolute or dev root relative.' - 'Ex. C:/o3de/Test' - 'Test = ') - create_template_subparser.add_argument('-srp', '--source-restricted-path', type=str, required=False, - default='restricted', - help='The path to the src restricted folder if any to read from, can be' - ' absolute or dev root relative, default is the dev root/restricted.') - create_template_subparser.add_argument('-srprp', '--source-restricted-platform-relative-path', type=str, required=False, - default='', + help='The path to the source that you want to make into a template') + create_template_subparser.add_argument('-tp', '--template-path', type=str, required=False, + help='The path to the template to create, can be absolute or relative' + ' to default templates path') + group = create_template_subparser.add_mutually_exclusive_group(required=True) + group.add_argument('-srp', '--source-restricted-path', type=str, required=False, + default=None, + help='The path to the source restricted folder.') + group.add_argument('-srn', '--source-restricted-name', type=str, required=False, + default=None, + help='The name of the source restricted folder. If supplied this will resolve' + ' the --source-restricted-path.') + + group = create_template_subparser.add_mutually_exclusive_group(required=True) + group.add_argument('-trp', '--template-restricted-path', type=str, required=False, + default=None, + help='The path to the templates restricted folder.') + group.add_argument('-trn', '--template-restricted-name', type=str, required=False, + default=None, + help='The name of the templates restricted folder. If supplied this will resolve' + ' the --template-restricted-path.') + + create_template_subparser.add_argument('-srprp', '--source-restricted-platform-relative-path', type=str, + required=False, + default=None, help='Any path to append to the --source-restricted-path/' - ' to where the restricted source is.' + ' to where the restricted source is. EX.' ' --source-restricted-path C:/restricted' ' --source-restricted-platform-relative-path some/folder' ' => C:/restricted//some/folder/') - create_template_subparser.add_argument('-tp', '--template-path', type=str, required=False, - help='The path to the template you wish to create,' - ' can be absolute or dev root/Templates relative, default is' - ' source_name which is the last component of source path' - ' Ex. C:/o3de/TestTemplate' - ' Test = ') - create_template_subparser.add_argument('-trp', '--template-restricted-path', type=str, required=False, - default='restricted', - help='The path to where to put the templates restricted folders write to if' - ' any, can be absolute or dev root relative, default is' - ' dev root/restricted.') create_template_subparser.add_argument('-trprp', '--template-restricted-platform-relative-path', type=str, - required=False, - default='Templates', - help='Any path to append to the --template-restricted-path/' - ' to where the restricted template source is.' - ' --template-restricted-path C:/restricted' - ' --template-restricted-platform-relative-path some/folder' - ' => C:/restricted//some/folder/') + required=False, + default=None, + help='Any path to append to the --template-restricted-path/' + ' to where the restricted template source is.' + ' --template-restricted-path C:/restricted' + ' --template-restricted-platform-relative-path some/folder' + ' => C:/restricted//some/folder/') create_template_subparser.add_argument('-kr', '--keep-restricted-in-template', action='store_true', default=False, help='Should the template keep the restricted platforms in the template, or' ' create the restricted files in the restricted folder, default is' - ' False') + ' False so it will create a restricted folder by default') create_template_subparser.add_argument('-kl', '--keep-license-text', action='store_true', default=False, - help='Should license text be kept in the instantiation,' - ' default is False') + help='Should license in the template files text be kept in the' + ' instantiation, default is False, so will not keep license text' + ' by default. License text is defined as all lines of text starting' + ' on a line with {BEGIN_LICENSE} and ending line {END_LICENSE}.') create_template_subparser.add_argument('-r', '--replace', type=str, required=False, nargs='*', help='String that specifies A->B replacement pairs.' @@ -1505,34 +2171,51 @@ def add_args(parser, subparsers) -> None: ' Note: is automatically ${NameUpper}') create_template_subparser.set_defaults(func=_run_create_template) - # creation from a template + # create from template create_from_template_subparser = subparsers.add_parser('create-from-template') create_from_template_subparser.add_argument('-dp', '--destination-path', type=str, required=True, help='The path to where you want the template instantiated,' ' can be absolute or dev root relative.' 'Ex. C:/o3de/Test' 'Test = ') - create_from_template_subparser.add_argument('-drp', '--destination-restricted-path', type=str, required=False, - default='restricted', - help='The path to the dst restricted folder to read from if any, can be' - ' absolute or dev root relative. default is dev root/restricted') - create_from_template_subparser.add_argument('-drprp', '--destination-restricted-platform-relative-path', type=str, required=False, + + group = create_from_template_subparser.add_mutually_exclusive_group(required=True) + group.add_argument('-tp', '--template-path', type=str, required=False, + help='The path to the template you want to instantiate, can be absolute' + ' or dev root/Templates relative.' + 'Ex. C:/o3de/Template/TestTemplate' + 'TestTemplate = ') + group.add_argument('-tn', '--template-name', type=str, required=False, + help='The name to the registered template you want to instantiate. If supplied this will' + ' resolve the --template-path.') + + group = create_from_template_subparser.add_mutually_exclusive_group(required=True) + group.add_argument('-drp', '--destination-restricted-path', type=str, required=False, + default=None, + help='The destination restricted path is where the restricted files' + ' will be written to.') + group.add_argument('-drn', '--destination-restricted-name', type=str, required=False, + default=None, + help='The name the registered restricted path where the restricted files' + ' will be written to. If supplied this will resolve the --destination-restricted-path.') + + group = create_from_template_subparser.add_mutually_exclusive_group(required=False) + group.add_argument('-trp', '--template-restricted-path', type=str, required=False, + default=None, + help='The template restricted path to read from if any') + group.add_argument('-trn', '--template-restricted-name', type=str, required=False, + default=None, + help='The name of the registered restricted path to read from if any. If supplied this will' + ' resolve the --template-restricted-path.') + + create_from_template_subparser.add_argument('-drprp', '--destination-restricted-platform-relative-path', type=str, + required=False, default='', help='Any path to append to the --destination-restricted-path/' - ' to where the restricted destination is.' - ' --destination-restricted-path C:/instance' - ' --destination-restricted-platform-relative-path some/folder' - ' => C:/instance//some/folder/') - create_from_template_subparser.add_argument('-tp', '--template-path', type=str, required=True, - help='The path to the template you want to instantiate, can be absolute' - ' or dev root/Templates relative.' - 'Ex. C:/o3de/Template/TestTemplate' - 'TestTemplate = ') - create_from_template_subparser.add_argument('-trp', '--template-restricted-path', type=str, required=False, - default='restricted', - help='The path to the template restricted folder to write to if any,' - ' can be absolute or dev root relative, default is' - ' dev root/restricted') + ' to where the restricted destination is.' + ' --destination-restricted-path C:/instance' + ' --destination-restricted-platform-relative-path some/folder' + ' => C:/instance//some/folder/') create_from_template_subparser.add_argument('-trprp', '--template-restricted-platform-relative-path', type=str, required=False, default='Templates', @@ -1548,8 +2231,10 @@ def add_args(parser, subparsers) -> None: ' is False') create_from_template_subparser.add_argument('-kl', '--keep-license-text', action='store_true', default=False, - help='Should license text be kept in the instantiation,' - ' default is False') + help='Should license in the template files text be kept in the instantiation,' + ' default is False, so will not keep license text by default.' + ' License text is defined as all lines of text starting on a line' + ' with {BEGIN_LICENSE} and ending line {END_LICENSE}.') create_from_template_subparser.add_argument('-r', '--replace', type=str, required=False, nargs='*', help='String that specifies A->B replacement pairs.' @@ -1567,31 +2252,48 @@ def add_args(parser, subparsers) -> None: ' can be an absolute path or dev root relative.' ' Ex. C:/o3de/TestProject' ' TestProject = ') - create_project_subparser.add_argument('-prp', '--project-restricted-path', type=str, required=False, - default='restricted', - help='The path to the project restricted folder to write to if any, can be' - ' absolute or dev root relative, default is dev root/restricted') + + group = create_project_subparser.add_mutually_exclusive_group(required=False) + group.add_argument('-tp', '--template-path', type=str, required=False, + default=None, + help='the path to the template you want to instance, can be absolute or' + ' relative to default templates path') + group.add_argument('-tn', '--template-name', type=str, required=False, + default=None, + help='The name the registered template you want to instance, defaults' + ' to DefaultProject. If supplied this will resolve the --template-path.') + + group = create_project_subparser.add_mutually_exclusive_group(required=False) + group.add_argument('-prp', '--project-restricted-path', type=str, required=False, + default=None, + help='path to the projects restricted folder, can be absolute or relative' + ' to the restricted="projects"') + group.add_argument('-prn', '--project-restricted-name', type=str, required=False, + default=None, + help='The name of the registered projects restricted path. If supplied this will resolve' + ' the --project-restricted-path.') + + group = create_project_subparser.add_mutually_exclusive_group(required=False) + group.add_argument('-trp', '--template-restricted-path', type=str, required=False, + default=None, + help='The templates restricted path can be absolute or relative to' + ' restricted="templates"') + group.add_argument('-trn', '--template-restricted-name', type=str, required=False, + default=None, + help='The name of the registered templates restricted path. If supplied this will resolve' + ' the --template-restricted-path.') + create_project_subparser.add_argument('-prprp', '--project-restricted-platform-relative-path', type=str, required=False, - default='', + default=None, help='Any path to append to the --project-restricted-path/' ' to where the restricted project is.' ' --project-restricted-path C:/restricted' ' --project-restricted-platform-relative-path some/folder' ' => C:/restricted//some/folder/') - create_project_subparser.add_argument('-tp', '--template-path', type=str, required=False, - default='DefaultProject', - help='The path to the template you want to instantiate, can be absolute' - ' or dev root/Templates relative, defaults to the DefaultProject.' - ' Ex. C:/o3de/Template/TestTemplate' - ' TestTemplate = ') - create_project_subparser.add_argument('-trp', '--template-restricted-path', type=str, required=False, - default='restricted', - help='The path to the template restricted folder to read from if any, can be' - ' absolute or dev root relative, default is dev root/restricted') create_project_subparser.add_argument('-trprp', '--template-restricted-platform-relative-path', type=str, required=False, - default='Templates', + default=None, help='Any path to append to the --template-restricted-path/' ' to where the restricted template is.' ' --template-restricted-path C:/restricted' @@ -1603,7 +2305,10 @@ def add_args(parser, subparsers) -> None: 'create the restricted files in the restricted folder, default is False') create_project_subparser.add_argument('-kl', '--keep-license-text', action='store_true', default=False, - help='Should license text be kept in the instantiation, default is False') + help='Should license in the template files text be kept in the instantiation,' + ' default is False, so will not keep license text by default.' + ' License text is defined as all lines of text starting on a line' + ' with {BEGIN_LICENSE} and ending line {END_LICENSE}.') create_project_subparser.add_argument('-r', '--replace', required=False, nargs='*', help='String that specifies ADDITIONAL A->B replacement pairs. ${Name} and' @@ -1618,9 +2323,10 @@ def add_args(parser, subparsers) -> None: create_project_subparser.add_argument('--system-component-class-id', type=utils.validate_uuid4, required=False, help='The uuid you want to associate with the system class component, default' ' is a random uuid Ex. {b60c92eb-3139-454b-a917-a9d3c5819594}') - create_project_subparser.add_argument('--editor-system-component-class-id', type=utils.validate_uuid4, required=False, - help='The uuid you want to associate with the editor system class component, default' - ' is a random uuid Ex. {b60c92eb-3139-454b-a917-a9d3c5819594}') + create_project_subparser.add_argument('--editor-system-component-class-id', type=utils.validate_uuid4, + required=False, + help='The uuid you want to associate with the editor system class component,' + ' default is a random uuid Ex. {b60c92eb-3139-454b-a917-a9d3c5819594}') create_project_subparser.add_argument('--module-id', type=utils.validate_uuid4, required=False, help='The uuid you want to associate with the module, default is a random' ' uuid Ex. {b60c92eb-3139-454b-a917-a9d3c5819594}') @@ -1629,33 +2335,50 @@ def add_args(parser, subparsers) -> None: # creation of a gem from a template (like create from template but makes gem assumptions) create_gem_subparser = subparsers.add_parser('create-gem') create_gem_subparser.add_argument('-gp', '--gem-path', type=str, required=True, - help='The path to the gem you want to create, can be absolute or dev root/Gems' - ' relative.' - ' Ex. C:/o3de/TestGem' - ' TestGem = ') - create_gem_subparser.add_argument('-grp', '--gem-restricted-path', type=str, required=False, - default='restricted', - help='The path to the gem restricted to write to folder if any, can be' - 'absolute or dev root relative, default is dev root/restricted.') + help='The gem path, can be absolute or relative to default gems path') + + group = create_gem_subparser.add_mutually_exclusive_group(required=False) + group.add_argument('-tp', '--template-path', type=str, required=False, + default=None, + help='The template path you want to instance, can be absolute or relative' + ' to default templates path') + group.add_argument('-tn', '--template-name', type=str, required=False, + default=None, + help='The name of the registered template you want to instance, defaults' + ' to DefaultGem. If supplied this will resolve the --template-path.') + + group = create_gem_subparser.add_mutually_exclusive_group(required=False) + group.add_argument('-grp', '--gem-restricted-path', type=str, required=False, + default=None, + help='The path to the gem restricted to write to folder if any, can be' + 'absolute or dev root relative, default is dev root/restricted.') + group.add_argument('-grn', '--gem-restricted-name', type=str, required=False, + default=None, + help='The path to the gem restricted to write to folder if any, can be' + 'absolute or dev root relative, default is dev root/restricted. If supplied' + ' this will resolve the --gem-restricted-path.') + + group = create_gem_subparser.add_mutually_exclusive_group(required=False) + group.add_argument('-trp', '--template-restricted-path', type=str, required=False, + default=None, + help='The templates restricted path, can be absolute or relative to' + ' the restricted="templates"') + group.add_argument('-trn', '--template-restricted-name', type=str, required=False, + default=None, + help='The name of the registered templates restricted path. If supplied' + ' this will resolve the --template-restricted-path.') + create_gem_subparser.add_argument('-grprp', '--gem-restricted-platform-relative-path', type=str, required=False, - default='Gems', + default=None, help='Any path to append to the --gem-restricted-path/' ' to where the restricted template is.' ' --gem-restricted-path C:/restricted' ' --gem-restricted-platform-relative-path some/folder' ' => C:/restricted//some/folder/') - create_gem_subparser.add_argument('-tp', '--template-path', type=str, required=False, - default='DefaultGem', - help='The path to the template you want to instantiate, can be absolute or' - ' relative to the dev root/Templates. Default is DefaultGem.') - create_gem_subparser.add_argument('-trp', '--template-restricted-path', type=str, required=False, - default='restricted', - help='The path to the gem restricted folder to read from if any, can be' - 'absolute or dev root relative, default is dev root/restricted.') create_gem_subparser.add_argument('-trprp', '--template-restricted-platform-relative-path', type=str, required=False, - default='Templates', + default=None, help='Any path to append to the --template-restricted-path/' ' to where the restricted template is.' ' --template-restricted-path C:/restricted' @@ -1678,14 +2401,17 @@ def add_args(parser, subparsers) -> None: 'create the restricted files in the restricted folder, default is False') create_gem_subparser.add_argument('-kl', '--keep-license-text', action='store_true', default=False, - help='Should license text be kept in the instantiation, default is False') + help='Should license in the template files text be kept in the instantiation,' + ' default is False, so will not keep license text by default.' + ' License text is defined as all lines of text starting on a line' + ' with {BEGIN_LICENSE} and ending line {END_LICENSE}.') create_gem_subparser.add_argument('--system-component-class-id', type=utils.validate_uuid4, required=False, help='The uuid you want to associate with the system class component, default' ' is a random uuid Ex. {b60c92eb-3139-454b-a917-a9d3c5819594}') create_gem_subparser.add_argument('--editor-system-component-class-id', type=utils.validate_uuid4, required=False, - help='The uuid you want to associate with the editor system class component, default' - ' is a random uuid Ex. {b60c92eb-3139-454b-a917-a9d3c5819594}') + help='The uuid you want to associate with the editor system class component,' + ' default is a random uuid Ex. {b60c92eb-3139-454b-a917-a9d3c5819594}') create_gem_subparser.add_argument('--module-id', type=utils.validate_uuid4, required=False, help='The uuid you want to associate with the gem module,' ' default is a random uuid Ex. {b60c92eb-3139-454b-a917-a9d3c5819594}') diff --git a/cmake/Tools/global_project.py b/cmake/Tools/global_project.py new file mode 100644 index 0000000000..1d84d9dcfb --- /dev/null +++ b/cmake/Tools/global_project.py @@ -0,0 +1,168 @@ +# +# All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or +# its licensors. +# +# For complete copyright and license terms please see the LICENSE at the root of this +# distribution (the "License"). All use of this software is governed by the License, +# or, if provided, by the license below or the license accompanying this file. Do not +# remove or 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 argparse +import logging +import os +import sys +import re +import pathlib +import json +import cmake.Tools.registration as registration + +logger = logging.getLogger() +logging.basicConfig() + + +def set_global_project(project_name: str or None, + project_path: str or pathlib.Path or None) -> int: + """ + set what the current project is + :param project_name: the name of the project you want to set, resolves project_path + :param project_path: the path of the project you want to set + :return: 0 for success or non 0 failure code + """ + if project_path and project_name: + logger.error(f'Project Name and Project Path provided, these are mutually exclusive.') + return 1 + + if not project_name and not project_path: + logger.error('Must specify either a Project name or Project Path.') + return 1 + + if project_name and not project_path: + project_path = registration.get_registered(project_name=project_name) + + if not project_path: + logger.error(f'Project Path {project_path} has not been registered.') + return 1 + + project_path = pathlib.Path(project_path).resolve() + + bootstrap_setreg_file = registration.get_o3de_registry_folder() / 'bootstrap.setreg' + if bootstrap_setreg_file.is_file(): + with bootstrap_setreg_file.open('r') as f: + try: + json_data = json.load(f) + except Exception as e: + logger.error(f'Bootstrap.setreg failed to load: {str(e)}') + else: + try: + json_data["Amazon"]["AzCore"]["Bootstrap"]["project_path"] = project_path + except Exception as e: + logger.error(f'Bootstrap.setreg failed to load: {str(e)}') + else: + try: + os.unlink(bootstrap_setreg_file) + except Exception as e: + logger.error(f'Failed to unlink bootstrap file {bootstrap_setreg_file}: {str(e)}') + return 1 + else: + json_data = {} + json_data.update({"Amazon":{"AzCore":{"Bootstrap":{"project_path":project_path.as_posix()}}}}) + + with bootstrap_setreg_file.open('w') as s: + s.write(json.dumps(json_data, indent=4)) + + return 0 + + +def get_global_project() -> pathlib.Path or None: + """ + get what the current project set is + :return: project_path or None on failure + """ + bootstrap_setreg_file = registration.get_o3de_registry_folder() / 'bootstrap.setreg' + if not bootstrap_setreg_file.is_file(): + logger.error(f'Bootstrap.setreg file {bootstrap_setreg_file} does not exist.') + return None + + with bootstrap_setreg_file.open('r') as f: + try: + json_data = json.load(f) + except Exception as e: + logger.error(f'Bootstrap.setreg failed to load: {str(e)}') + else: + try: + project_path = json_data["Amazon"]["AzCore"]["Bootstrap"]["project_path"] + except Exception as e: + logger.error(f'Bootstrap.setreg cannot find Amazon:AzCore:Bootstrap:project_path: {str(e)}') + else: + return pathlib.Path(project_path).resolve() + return None + +def _run_get_global_project(args: argparse) -> int: + if args.override_home_folder: + registration.override_home_folder = args.override_home_folder + + project_path = get_global_project() + if project_path: + print(project_path.as_posix()) + return 0 + return 1 + + +def _run_set_global_project(args: argparse) -> int: + if args.override_home_folder: + registration.override_home_folder = args.override_home_folder + + return set_global_project(args.project_name, + args.project_path) + + +def add_args(parser, subparsers) -> None: + """ + add_args is called to add expected parser arguments and subparsers arguments to each command such that it can be + invoked locally or aggregated by a central python file. + Ex. Directly run from this file alone with: python global_project.py set_global_project --project-name TestProject + OR + o3de.py can aggregate commands by importing global_project, call add_args and + execute: python o3de.py set_global_project --project-path C:/TestProject + :param parser: the caller instantiates a parser and passes it in here + :param subparsers: the caller instantiates subparsers and passes it in here + """ + get_global_project_subparser = subparsers.add_parser('get-global-project') + get_global_project_subparser.add_argument('-ohf', '--override-home-folder', type=str, required=False, + help='By default the home folder is the user folder, override it to this folder.') + + get_global_project_subparser.set_defaults(func=_run_get_global_project) + + set_global_project_subparser = subparsers.add_parser('set-global-project') + group = set_global_project_subparser.add_mutually_exclusive_group(required=True) + group.add_argument('-pn', '--project-name', required=False, + help='The name of the project. If supplied this will resolve the --project-path.') + group.add_argument('-pp', '--project-path', required=False, + help='The path to the project') + + set_global_project_subparser.add_argument('-ohf', '--override-home-folder', type=str, required=False, + help='By default the home folder is the user folder, override it to this folder.') + + set_global_project_subparser.set_defaults(func=_run_set_global_project) + + +if __name__ == "__main__": + # parse the command line args + the_parser = argparse.ArgumentParser() + + # add subparsers + the_subparsers = the_parser.add_subparsers(help='sub-command help') + + # add args to the parser + add_args(the_parser, the_subparsers) + + # parse args + the_args = the_parser.parse_args() + + # run + ret = the_args.func(the_args) + + # return + sys.exit(ret) diff --git a/cmake/Tools/registration.py b/cmake/Tools/registration.py index c16a712859..292ec33d1f 100755 --- a/cmake/Tools/registration.py +++ b/cmake/Tools/registration.py @@ -11,6 +11,7 @@ """ This file contains all the code that has to do with registering engines, projects, gems and templates """ + import argparse import logging import os @@ -19,133 +20,611 @@ import json import pathlib import hashlib import shutil -import urllib +import zipfile +import urllib.parse +import urllib.request logger = logging.getLogger() logging.basicConfig() -def backup(file_name): +def backup_file(file_name: str or pathlib.Path) -> None: index = 0 renamed = False while not renamed: - backup_file_name = pathlib.Path(str(file_name) + '.bak' + str(index)) + backup_file_name = pathlib.Path(str(file_name) + '.bak' + str(index)).resolve() + index += 1 if not backup_file_name.is_file(): - file_name = pathlib.Path(file_name) + file_name = pathlib.Path(file_name).resolve() file_name.rename(backup_file_name) - renamed = True - -def register_shipped_engine_o3de_objects(): - # register this engines shipped projects, gems and templates - engine_path = get_this_engine_path() - for root, dirs, files in os.walk(engine_path / 'AtomSampleViewer', topdown=False): - for name in files: - if name == 'project.json': - register(project_path=root) - elif name == 'gem.json': - register(gem_path=root) - elif name == 'template.json': - register(template_path=root) - - for root, dirs, files in os.walk(engine_path / 'AtomTest', topdown=False): - for name in files: - if name == 'project.json': - register(project_path=root) - elif name == 'gem.json': - register(gem_path=root) - elif name == 'template.json': - register(template_path=root) - - for root, dirs, files in os.walk(engine_path / 'Gems', topdown=False): - for name in files: - if name == 'gem.json': - register(gem_path=root) - - engine_templates = os.listdir(engine_path / 'Templates') - for engine_template in engine_templates: - register(template_path=engine_path / 'Templates' / engine_template) - - engine_projects = os.listdir(engine_path) - for engine_project in engine_projects: - engine_project_json = engine_path / engine_project / 'project.json' - if engine_project_json.is_file(): - register(project_path=engine_path / engine_project) + if backup_file_name.is_file(): + renamed = True -def get_this_engine_path(): - return pathlib.Path(os.path.realpath(__file__)).parent.parent.parent +def backup_folder(folder: str or pathlib.Path) -> None: + index = 0 + renamed = False + while not renamed: + backup_folder_name = pathlib.Path(str(folder) + '.bak' + str(index)).resolve() + index += 1 + if not backup_folder_name.is_dir(): + folder = pathlib.Path(folder).resolve() + folder.rename(backup_folder_name) + if backup_folder_name.is_dir(): + renamed = True -def get_home_folder(): - return pathlib.Path(os.path.expanduser("~")) +def get_this_engine_path() -> pathlib.Path: + return pathlib.Path(os.path.realpath(__file__)).parents[2].resolve() -def get_o3de_folder(): +override_home_folder = None + + +def get_home_folder() -> pathlib.Path: + if override_home_folder: + return pathlib.Path(override_home_folder).resolve() + else: + return pathlib.Path(os.path.expanduser("~")).resolve() + + +def get_o3de_folder() -> pathlib.Path: o3de_folder = get_home_folder() / '.o3de' o3de_folder.mkdir(parents=True, exist_ok=True) return o3de_folder -def get_o3de_cache(): - cache_folder = get_o3de_folder() / 'cache' +def get_o3de_registry_folder() -> pathlib.Path: + registry_folder = get_o3de_folder() / 'Registry' + registry_folder.mkdir(parents=True, exist_ok=True) + return registry_folder + + +def get_o3de_cache_folder() -> pathlib.Path: + cache_folder = get_o3de_folder() / 'Cache' cache_folder.mkdir(parents=True, exist_ok=True) return cache_folder -def get_o3de_registry(): - registry_path = get_o3de_folder() / 'o3de_manifest.json' - if not registry_path.is_file(): +def get_o3de_download_folder() -> pathlib.Path: + download_folder = get_o3de_folder() / 'Download' + download_folder.mkdir(parents=True, exist_ok=True) + return download_folder + +def get_o3de_engines_folder() -> pathlib.Path: + engines_folder = get_o3de_folder() / 'Engines' + engines_folder.mkdir(parents=True, exist_ok=True) + return engines_folder + + +def get_o3de_projects_folder() -> pathlib.Path: + projects_folder = get_o3de_folder() / 'Projects' + projects_folder.mkdir(parents=True, exist_ok=True) + return projects_folder + + +def get_o3de_gems_folder() -> pathlib.Path: + gems_folder = get_o3de_folder() / 'Gems' + gems_folder.mkdir(parents=True, exist_ok=True) + return gems_folder + + +def get_o3de_templates_folder() -> pathlib.Path: + templates_folder = get_o3de_folder() / 'Templates' + templates_folder.mkdir(parents=True, exist_ok=True) + return templates_folder + + +def get_o3de_restricted_folder() -> pathlib.Path: + restricted_folder = get_o3de_folder() / 'Restricted' + restricted_folder.mkdir(parents=True, exist_ok=True) + return restricted_folder + + +def get_o3de_logs_folder() -> pathlib.Path: + restricted_folder = get_o3de_folder() / 'Logs' + restricted_folder.mkdir(parents=True, exist_ok=True) + return restricted_folder + + +def register_shipped_engine_o3de_objects() -> int: + engine_path = get_this_engine_path() + + ret_val = 0 + + # directories with engines + starting_engines_directories = [ + ] + for engines_directory in sorted(starting_engines_directories, reverse=True): + error_code = register_all_engines_in_folder(engines_path=engines_directory) + if error_code: + ret_val = error_code + + # specific engines + starting_engines = [ + ] + for engine_path in sorted(starting_engines): + error_code = register(engine_path=engine_path) + if error_code: + ret_val = error_code + + # directories with projects + starting_projects_directories = [ + ] + for projects_directory in sorted(starting_projects_directories, reverse=True): + error_code = register_all_projects_in_folder(engine_path=engine_path, projects_path=projects_directory) + if error_code: + ret_val = error_code + + # specific projects + starting_projects = [ + f'{engine_path}/AutomatedTesting' + ] + for project_path in sorted(starting_projects, reverse=True): + error_code = register(engine_path=engine_path, project_path=project_path) + if error_code: + ret_val = error_code + + # directories with gems + starting_gems_directories = [ + f'{engine_path}/Gems' + ] + for gems_directory in sorted(starting_gems_directories, reverse=True): + error_code = register_all_gems_in_folder(engine_path=engine_path, gems_path=gems_directory) + if error_code: + ret_val = error_code + + # specific gems + starting_gems = [ + ] + for gem_path in sorted(starting_gems, reverse=True): + error_code = register(engine_path=engine_path, gem_path=gem_path) + if error_code: + ret_val = error_code + + # directories with templates + starting_templates_directories = [ + f'{engine_path}/Templates' + ] + for templates_directory in sorted(starting_templates_directories, reverse=True): + error_code = register_all_templates_in_folder(engine_path=engine_path, templates_path=templates_directory) + if error_code: + ret_val = error_code + + # specific templates + starting_templates = [ + ] + for template_path in sorted(starting_templates, reverse=True): + error_code = register(engine_path=engine_path, template_path=template_path) + if error_code: + ret_val = error_code + + # directories with restricted + starting_restricted_directories = [ + ] + for restricted_directory in sorted(starting_restricted_directories, reverse=True): + error_code = register_all_restricted_in_folder(engine_path=engine_path, restricted_path=restricted_directory) + if error_code: + ret_val = error_code + + # specific restricted + starting_restricted = [ + ] + for restricted_path in sorted(starting_restricted, reverse=True): + error_code = register(engine_path=engine_path, restricted_path=restricted_path) + if error_code: + ret_val = error_code + + # directories with repos + starting_repo_directories = [ + ] + for repos_directory in sorted(starting_repo_directories, reverse=True): + error_code = register_all_repos_in_folder(engine_path=engine_path, repos_path=repos_directory) + if error_code: + ret_val = error_code + + # specific repos + starting_repos = [ + ] + for repo_uri in sorted(starting_repos, reverse=True): + error_code = register(repo_uri=repo_uri) + if error_code: + ret_val = error_code + + # register anything in the users default folders globally + error_code = register_all_engines_in_folder(get_registered(default_folder='engines')) + if error_code: + ret_val = error_code + error_code = register_all_projects_in_folder(get_registered(default_folder='projects')) + if error_code: + ret_val = error_code + error_code = register_all_gems_in_folder(get_registered(default_folder='gems')) + if error_code: + ret_val = error_code + error_code = register_all_templates_in_folder(get_registered(default_folder='templates')) + if error_code: + ret_val = error_code + error_code = register_all_restricted_in_folder(get_registered(default_folder='restricted')) + if error_code: + ret_val = error_code + error_code = register_all_restricted_in_folder(get_registered(default_folder='projects')) + if error_code: + ret_val = error_code + error_code = register_all_restricted_in_folder(get_registered(default_folder='gems')) + if error_code: + ret_val = error_code + error_code = register_all_restricted_in_folder(get_registered(default_folder='templates')) + if error_code: + ret_val = error_code + + starting_external_subdirectories = [ + f'{engine_path}/Gems/Atom', + f'{engine_path}/Gems/AtomLyIntegration' + ] + for external_subdir in sorted(starting_external_subdirectories, reverse=True): + error_code = add_external_subdirectory(engine_path=engine_path, external_subdir=external_subdir) + if error_code: + ret_val = error_code + + json_data = load_o3de_manifest() + engine_object = find_engine_data(json_data) + gems = json_data['gems'].copy() + gems.extend(engine_object['gems']) + for gem_path in sorted(gems, key=len): + gem_path = pathlib.Path(gem_path).resolve() + gem_cmake_lists_txt = gem_path / 'CMakeLists.txt' + if gem_cmake_lists_txt.is_file(): + add_gem_to_cmake(engine_path=engine_path, gem_path=gem_path, supress_errors=True) # don't care about errors + + return ret_val + + +def register_all_in_folder(folder_path: str or pathlib.Path, + remove: bool = False, + engine_path: str or pathlib.Path = None, + exclude: list = None) -> int: + if not folder_path: + logger.error(f'Folder path cannot be empty.') + return 1 + + folder_path = pathlib.Path(folder_path).resolve() + if not folder_path.is_dir(): + logger.error(f'Folder path is not dir.') + return 1 + + engines_set = set() + projects_set = set() + gems_set = set() + templates_set = set() + restricted_set = set() + repo_set = set() + + ret_val = 0 + for root, dirs, files in os.walk(folder_path): + if root in exclude: + continue + + for name in files: + if name == 'engine.json': + engines_set.add(root) + elif name == 'project.json': + projects_set.add(root) + elif name == 'gem.json': + gems_set.add(root) + elif name == 'template.json': + templates_set.add(root) + elif name == 'restricted.json': + restricted_set.add(root) + elif name == 'repo.json': + repo_set.add(root) + + for engine in sorted(engines_set, reverse=True): + error_code = register(engine_path=engine, remove=remove) + if error_code: + ret_val = error_code + + for project in sorted(projects_set, reverse=True): + error_code = register(engine_path=engine_path, project_path=project, remove=remove) + if error_code: + ret_val = error_code + + for gem in sorted(gems_set, reverse=True): + error_code = register(engine_path=engine_path, gem_path=gem, remove=remove) + if error_code: + ret_val = error_code + + for template in sorted(templates_set, reverse=True): + error_code = register(engine_path=engine_path, template_path=template, remove=remove) + if error_code: + ret_val = error_code + + for restricted in sorted(restricted_set, reverse=True): + error_code = register(engine_path=engine_path, restricted_path=restricted, remove=remove) + if error_code: + ret_val = error_code + + for repo in sorted(repo_set, reverse=True): + error_code = register(engine_path=engine_path, repo_uri=repo, remove=remove) + if error_code: + ret_val = error_code + + return ret_val + + +def register_all_engines_in_folder(engines_path: str or pathlib.Path, + remove: bool = False) -> int: + if not engines_path: + logger.error(f'Engines path cannot be empty.') + return 1 + + engines_path = pathlib.Path(engines_path).resolve() + if not engines_path.is_dir(): + logger.error(f'Engines path is not dir.') + return 1 + + engines_set = set() + + ret_val = 0 + for root, dirs, files in os.walk(engines_path): + for name in files: + if name == 'engine.json': + engines_set.add(name) + + for engine in sorted(engines_set, reverse=True): + error_code = register(engine_path=engine, remove=remove) + if error_code: + ret_val = error_code + + return ret_val + + +def register_all_projects_in_folder(projects_path: str or pathlib.Path, + remove: bool = False, + engine_path: str or pathlib.Path = None) -> int: + if not projects_path: + logger.error(f'Projects path cannot be empty.') + return 1 + + projects_path = pathlib.Path(projects_path).resolve() + if not projects_path.is_dir(): + logger.error(f'Projects path is not dir.') + return 1 + + projects_set = set() + + ret_val = 0 + for root, dirs, files in os.walk(projects_path): + for name in files: + if name == 'project.json': + projects_set.add(root) + + for project in sorted(projects_set, reverse=True): + error_code = register(engine_path=engine_path, project_path=project, remove=remove) + if error_code: + ret_val = error_code + + return ret_val + + +def register_all_gems_in_folder(gems_path: str or pathlib.Path, + remove: bool = False, + engine_path: str or pathlib.Path = None) -> int: + if not gems_path: + logger.error(f'Gems path cannot be empty.') + return 1 + + gems_path = pathlib.Path(gems_path).resolve() + if not gems_path.is_dir(): + logger.error(f'Gems path is not dir.') + return 1 + + gems_set = set() + + ret_val = 0 + for root, dirs, files in os.walk(gems_path): + for name in files: + if name == 'gem.json': + gems_set.add(root) + + for gem in sorted(gems_set, reverse=True): + error_code = register(engine_path=engine_path, gem_path=gem, remove=remove) + if error_code: + ret_val = error_code + + return ret_val + + +def register_all_templates_in_folder(templates_path: str or pathlib.Path, + remove: bool = False, + engine_path: str or pathlib.Path = None) -> int: + if not templates_path: + logger.error(f'Templates path cannot be empty.') + return 1 + + templates_path = pathlib.Path(templates_path).resolve() + if not templates_path.is_dir(): + logger.error(f'Templates path is not dir.') + return 1 + + templates_set = set() + + ret_val = 0 + for root, dirs, files in os.walk(templates_path): + for name in files: + if name == 'template.json': + templates_set.add(root) + + for template in sorted(templates_set, reverse=True): + error_code = register(engine_path=engine_path, template_path=template, remove=remove) + if error_code: + ret_val = error_code + + return ret_val + + +def register_all_restricted_in_folder(restricted_path: str or pathlib.Path, + remove: bool = False, + engine_path: str or pathlib.Path = None) -> int: + if not restricted_path: + logger.error(f'Restricted path cannot be empty.') + return 1 + + restricted_path = pathlib.Path(restricted_path).resolve() + if not restricted_path.is_dir(): + logger.error(f'Restricted path is not dir.') + return 1 + + restricted_set = set() + + ret_val = 0 + for root, dirs, files in os.walk(restricted_path): + for name in files: + if name == 'restricted.json': + restricted_set.add(root) + + for restricted in sorted(restricted_set, reverse=True): + error_code = register(engine_path=engine_path, restricted_path=restricted, remove=remove) + if error_code: + ret_val = error_code + + return ret_val + + +def register_all_repos_in_folder(repos_path: str or pathlib.Path, + remove: bool = False, + engine_path: str or pathlib.Path = None) -> int: + if not repos_path: + logger.error(f'Repos path cannot be empty.') + return 1 + + repos_path = pathlib.Path(repos_path).resolve() + if not repos_path.is_dir(): + logger.error(f'Repos path is not dir.') + return 1 + + repo_set = set() + + ret_val = 0 + for root, dirs, files in os.walk(repos_path): + for name in files: + if name == 'repo.json': + repo_set.add(root) + + for repo in sorted(repo_set, reverse=True): + error_code = register(engine_path=engine_path, repo_uri=repo, remove=remove) + if error_code: + ret_val = error_code + + return ret_val + + +def get_o3de_manifest() -> pathlib.Path: + manifest_path = get_o3de_folder() / 'o3de_manifest.json' + if not manifest_path.is_file(): username = os.path.split(get_home_folder())[-1] + o3de_folder = get_o3de_folder() + default_registry_folder = get_o3de_registry_folder() + default_cache_folder = get_o3de_cache_folder() + default_downloads_folder = get_o3de_download_folder() + default_logs_folder = get_o3de_logs_folder() + default_engines_folder = get_o3de_engines_folder() + default_projects_folder = get_o3de_projects_folder() + default_gems_folder = get_o3de_gems_folder() + default_templates_folder = get_o3de_templates_folder() + default_restricted_folder = get_o3de_restricted_folder() + + default_projects_restricted_folder = default_projects_folder / 'Restricted' + default_projects_restricted_folder.mkdir(parents=True, exist_ok=True) + default_gems_restricted_folder = default_gems_folder / 'Restricted' + default_gems_restricted_folder.mkdir(parents=True, exist_ok=True) + default_templates_restricted_folder = default_templates_folder / 'Restricted' + default_templates_restricted_folder.mkdir(parents=True, exist_ok=True) + json_data = {} - json_data.update({'repo_name': f'{username}'}) - json_data.update({'origin': get_o3de_folder().as_posix()}) - json_data.update({'engines': []}) + json_data.update({'o3de_manifest_name': f'{username}'}) + json_data.update({'origin': o3de_folder.as_posix()}) + json_data.update({'default_engines_folder': default_engines_folder.as_posix()}) + json_data.update({'default_projects_folder': default_projects_folder.as_posix()}) + json_data.update({'default_gems_folder': default_gems_folder.as_posix()}) + json_data.update({'default_templates_folder': default_templates_folder.as_posix()}) + json_data.update({'default_restricted_folder': default_restricted_folder.as_posix()}) + json_data.update({'projects': []}) json_data.update({'gems': []}) json_data.update({'templates': []}) + json_data.update({'restricted': []}) json_data.update({'repos': []}) - default_projects_folder = get_home_folder() / 'my_o3de/projects' - default_projects_folder.mkdir(parents=True, exist_ok=True) - json_data.update({'default_projects_folder': default_projects_folder.as_posix()}) - default_gems_folder = get_home_folder() / 'my_o3de/gems' - default_gems_folder.mkdir(parents=True, exist_ok=True) - json_data.update({'default_gems_folder': default_gems_folder.as_posix()}) - default_templates_folder = get_home_folder() / 'my_o3de/templates' - default_templates_folder.mkdir(parents=True, exist_ok=True) - json_data.update({'default_templates_folder': default_templates_folder.as_posix()}) - with registry_path.open('w') as s: + json_data.update({'engines': []}) + + default_restricted_folder_json = default_restricted_folder / 'restricted.json' + if not default_restricted_folder_json.is_file(): + with default_restricted_folder_json.open('w') as s: + restricted_json_data = {} + restricted_json_data.update({'restricted_name': 'o3de'}) + s.write(json.dumps(restricted_json_data, indent=4)) + json_data.update({'default_restricted_folder': default_restricted_folder.as_posix()}) + + default_projects_restricted_folder_json = default_projects_restricted_folder / 'restricted.json' + if not default_projects_restricted_folder_json.is_file(): + with default_projects_restricted_folder_json.open('w') as s: + restricted_json_data = {} + restricted_json_data.update({'restricted_name': 'projects'}) + s.write(json.dumps(restricted_json_data, indent=4)) + + default_gems_restricted_folder_json = default_gems_restricted_folder / 'restricted.json' + if not default_gems_restricted_folder_json.is_file(): + with default_gems_restricted_folder_json.open('w') as s: + restricted_json_data = {} + restricted_json_data.update({'restricted_name': 'gems'}) + s.write(json.dumps(restricted_json_data, indent=4)) + + default_templates_restricted_folder_json = default_templates_restricted_folder / 'restricted.json' + if not default_templates_restricted_folder_json.is_file(): + with default_templates_restricted_folder_json.open('w') as s: + restricted_json_data = {} + restricted_json_data.update({'restricted_name': 'templates'}) + s.write(json.dumps(restricted_json_data, indent=4)) + + with manifest_path.open('w') as s: s.write(json.dumps(json_data, indent=4)) - return registry_path + return manifest_path -def load_o3de_registry(): - with get_o3de_registry().open('r') as f: - return json.load(f) +def load_o3de_manifest() -> dict: + with get_o3de_manifest().open('r') as f: + try: + json_data = json.load(f) + except Exception as e: + logger.error(f'Manifest json failed to load: {str(e)}') + else: + return json_data -def save_o3de_registry(json_data): - with get_o3de_registry().open('w') as s: - s.write(json.dumps(json_data, indent=4)) +def save_o3de_manifest(json_data: dict) -> None: + with get_o3de_manifest().open('w') as s: + try: + s.write(json.dumps(json_data, indent=4)) + except Exception as e: + logger.error(f'Manifest json failed to save: {str(e)}') -def register_engine_path(json_data, - engine_path: str, +def register_engine_path(json_data: dict, + engine_path: str or pathlib.Path, remove: bool = False) -> int: if not engine_path: logger.error(f'Engine path cannot be empty.') return 1 + engine_path = pathlib.Path(engine_path).resolve() - while engine_path in json_data['engines']: - json_data['engines'].remove(engine_path) - engine_path = pathlib.Path(engine_path) - while engine_path.as_posix() in json_data['engines']: - json_data['engines'].remove(engine_path.as_posix()) + for engine_object in json_data['engines']: + engine_object_path = pathlib.Path(engine_object['path']).resolve() + if engine_object_path == engine_path: + json_data['engines'].remove(engine_object) if remove: - logger.warn(f'Removing Engine path {engine_path}.') return 0 if not engine_path.is_dir(): @@ -157,27 +636,53 @@ def register_engine_path(json_data, logger.error(f'Engine json {engine_json} is not valid.') return 1 - json_data['engines'].insert(0, engine_path.as_posix()) + engine_object = {} + engine_object.update({'path': engine_path.as_posix()}) + engine_object.update({'projects': []}) + engine_object.update({'gems': []}) + engine_object.update({'templates': []}) + engine_object.update({'restricted': []}) + engine_object.update({'external_subdirectories': []}) + + json_data['engines'].insert(0, engine_object) return 0 -def register_gem_path(json_data, - gem_path: str, - remove: bool = False) -> int: +def register_gem_path(json_data: dict, + gem_path: str or pathlib.Path, + remove: bool = False, + engine_path: str or pathlib.Path = None) -> int: if not gem_path: logger.error(f'Gem path cannot be empty.') return 1 + gem_path = pathlib.Path(gem_path).resolve() - while gem_path in json_data['gems']: - json_data['gems'].remove(gem_path) - gem_path = pathlib.Path(gem_path) - while gem_path.as_posix() in json_data['gems']: - json_data['gems'].remove(gem_path.as_posix()) + if engine_path: + engine_data = find_engine_data(json_data, engine_path) + if not engine_data: + logger.error(f'Engine path {engine_path} is not registered.') + return 1 - if remove: - logger.warn(f'Removing Gem path {gem_path}.') - return 0 + while gem_path in engine_data['gems']: + engine_data['gems'].remove(gem_path) + + while gem_path.as_posix() in engine_data['gems']: + engine_data['gems'].remove(gem_path.as_posix()) + + if remove: + logger.warn(f'Removing Gem path {gem_path}.') + return 0 + else: + while gem_path in json_data['gems']: + json_data['gems'].remove(gem_path) + + while gem_path.as_posix() in json_data['gems']: + json_data['gems'].remove(gem_path.as_posix()) + + if remove: + logger.warn(f'Removing Gem path {gem_path}.') + return 0 if not gem_path.is_dir(): logger.error(f'Gem path {gem_path} does not exist.') @@ -188,27 +693,48 @@ def register_gem_path(json_data, logger.error(f'Gem json {gem_json} is not valid.') return 1 - json_data['gems'].insert(0, gem_path.as_posix()) + if engine_path: + engine_data['gems'].insert(0, gem_path.as_posix()) + else: + json_data['gems'].insert(0, gem_path.as_posix()) return 0 -def register_project_path(json_data, - project_path: str, - remove: bool = False) -> int: +def register_project_path(json_data: dict, + project_path: str or pathlib.Path, + remove: bool = False, + engine_path: str or pathlib.Path = None) -> int: if not project_path: logger.error(f'Project path cannot be empty.') return 1 + project_path = pathlib.Path(project_path).resolve() - while project_path in json_data['projects']: - json_data['projects'].remove(project_path) - project_path = pathlib.Path(project_path) - while project_path.as_posix() in json_data['projects']: - json_data['projects'].remove(project_path.as_posix()) + if engine_path: + engine_data = find_engine_data(json_data, engine_path) + if not engine_data: + logger.error(f'Engine path {engine_path} is not registered.') + return 1 - if remove: - logger.warn(f'Removing Project path {project_path}.') - return 0 + while project_path in engine_data['projects']: + engine_data['projects'].remove(project_path) + + while project_path.as_posix() in engine_data['projects']: + engine_data['projects'].remove(project_path.as_posix()) + + if remove: + logger.warn(f'Engine {engine_path} removing Project path {project_path}.') + return 0 + else: + while project_path in json_data['projects']: + json_data['projects'].remove(project_path) + + while project_path.as_posix() in json_data['projects']: + json_data['projects'].remove(project_path.as_posix()) + + if remove: + logger.warn(f'Removing Project path {project_path}.') + return 0 if not project_path.is_dir(): logger.error(f'Project path {project_path} does not exist.') @@ -219,14 +745,25 @@ def register_project_path(json_data, logger.error(f'Project json {project_json} is not valid.') return 1 - json_data['projects'].insert(0, project_path.as_posix()) + if engine_path: + engine_data['projects'].insert(0, project_path.as_posix()) + else: + json_data['projects'].insert(0, project_path.as_posix()) # registering a project has the additional step of setting the project.json 'engine' field this_engine_json = get_this_engine_path() / 'engine.json' with this_engine_json.open('r') as f: - this_engine_json = json.load(f) + try: + this_engine_json = json.load(f) + except Exception as e: + logger.error(f'Engine json failed to load: {str(e)}') + return 1 with project_json.open('r') as f: - project_json_data = json.load(f) + try: + project_json_data = json.load(f) + except Exception as e: + logger.error(f'Project json failed to load: {str(e)}') + return 1 update_project_json = False try: @@ -236,29 +773,51 @@ def register_project_path(json_data, if update_project_json: project_json_data['engine'] = this_engine_json['engine_name'] - backup(project_json) + backup_file(project_json) with project_json.open('w') as s: - s.write(json.dumps(project_json_data, indent=4)) + try: + s.write(json.dumps(project_json_data, indent=4)) + except Exception as e: + logger.error(f'Project json failed to save: {str(e)}') + return 1 return 0 -def register_template_path(json_data, - template_path: str, - remove: bool = False) -> int: +def register_template_path(json_data: dict, + template_path: str or pathlib.Path, + remove: bool = False, + engine_path: str or pathlib.Path = None) -> int: if not template_path: logger.error(f'Template path cannot be empty.') return 1 + template_path = pathlib.Path(template_path).resolve() - while template_path in json_data['templates']: - json_data['templates'].remove(template_path) - template_path = pathlib.Path(template_path) - while template_path.as_posix() in json_data['templates']: - json_data['templates'].remove(template_path.as_posix()) + if engine_path: + engine_data = find_engine_data(json_data, engine_path) + if not engine_data: + logger.error(f'Engine path {engine_path} is not registered.') + return 1 - if remove: - logger.warn(f'Removing Template path {template_path}.') - return 0 + while template_path in engine_data['templates']: + engine_data['templates'].remove(template_path) + + while template_path.as_posix() in engine_data['templates']: + engine_data['templates'].remove(template_path.as_posix()) + + if remove: + logger.warn(f'Engine {engine_path} removing Template path {template_path}.') + return 0 + else: + while template_path in json_data['templates']: + json_data['templates'].remove(template_path) + + while template_path.as_posix() in json_data['templates']: + json_data['templates'].remove(template_path.as_posix()) + + if remove: + logger.warn(f'Removing Template path {template_path}.') + return 0 if not template_path.is_dir(): logger.error(f'Template path {template_path} does not exist.') @@ -269,223 +828,470 @@ def register_template_path(json_data, logger.error(f'Template json {template_json} is not valid.') return 1 - json_data['templates'].insert(0, template_path.as_posix()) + if engine_path: + engine_data['templates'].insert(0, template_path.as_posix()) + else: + json_data['templates'].insert(0, template_path.as_posix()) return 0 -def register_repo(json_data, - repo_uri: str, +def register_restricted_path(json_data: dict, + restricted_path: str or pathlib.Path, + remove: bool = False, + engine_path: str or pathlib.Path = None) -> int: + if not restricted_path: + logger.error(f'Restricted path cannot be empty.') + return 1 + restricted_path = pathlib.Path(restricted_path).resolve() + + if engine_path: + engine_data = find_engine_data(json_data, engine_path) + if not engine_data: + logger.error(f'Engine path {engine_path} is not registered.') + return 1 + + while restricted_path in engine_data['restricted']: + engine_data['restricted'].remove(restricted_path) + + while restricted_path.as_posix() in engine_data['restricted']: + engine_data['restricted'].remove(restricted_path.as_posix()) + + if remove: + logger.warn(f'Engine {engine_path} removing Restricted path {restricted_path}.') + return 0 + else: + while restricted_path in json_data['restricted']: + json_data['restricted'].remove(restricted_path) + + while restricted_path.as_posix() in json_data['restricted']: + json_data['restricted'].remove(restricted_path.as_posix()) + + if remove: + logger.warn(f'Removing Restricted path {restricted_path}.') + return 0 + + if not restricted_path.is_dir(): + logger.error(f'Restricted path {restricted_path} does not exist.') + return 1 + + restricted_json = restricted_path / 'restricted.json' + if not valid_o3de_restricted_json(restricted_json): + logger.error(f'Restricted json {restricted_json} is not valid.') + return 1 + + if engine_path: + engine_data['restricted'].insert(0, restricted_path.as_posix()) + else: + json_data['restricted'].insert(0, restricted_path.as_posix()) + + return 0 + + +def valid_o3de_repo_json(file_name: str or pathlib.Path) -> bool: + file_name = pathlib.Path(file_name).resolve() + if not file_name.is_file(): + return False + + with file_name.open('r') as f: + try: + json_data = json.load(f) + test = json_data['repo_name'] + test = json_data['origin'] + except Exception as e: + return False + + return True + + +def valid_o3de_engine_json(file_name: str or pathlib.Path) -> bool: + file_name = pathlib.Path(file_name).resolve() + if not file_name.is_file(): + return False + + with file_name.open('r') as f: + try: + json_data = json.load(f) + test = json_data['engine_name'] + # test = json_data['origin'] # will be required soon + except Exception as e: + return False + return True + + +def valid_o3de_project_json(file_name: str or pathlib.Path) -> bool: + file_name = pathlib.Path(file_name).resolve() + if not file_name.is_file(): + return False + + with file_name.open('r') as f: + try: + json_data = json.load(f) + test = json_data['project_name'] + # test = json_data['origin'] # will be required soon + except Exception as e: + return False + return True + + +def valid_o3de_gem_json(file_name: str or pathlib.Path) -> bool: + file_name = pathlib.Path(file_name).resolve() + if not file_name.is_file(): + return False + + with file_name.open('r') as f: + try: + json_data = json.load(f) + test = json_data['gem_name'] + # test = json_data['origin'] # will be required soon + except Exception as e: + return False + return True + + +def valid_o3de_template_json(file_name: str or pathlib.Path) -> bool: + file_name = pathlib.Path(file_name).resolve() + if not file_name.is_file(): + return False + with file_name.open('r') as f: + try: + json_data = json.load(f) + test = json_data['template_name'] + # test = json_data['origin'] # will be required soon + except Exception as e: + return False + return True + + +def valid_o3de_restricted_json(file_name: str or pathlib.Path) -> bool: + file_name = pathlib.Path(file_name).resolve() + if not file_name.is_file(): + return False + with file_name.open('r') as f: + try: + json_data = json.load(f) + test = json_data['restricted_name'] + # test = json_data['origin'] # will be required soon + except Exception as e: + return False + return True + + +def process_add_o3de_repo(file_name: str or pathlib.Path, + repo_set: set) -> int: + file_name = pathlib.Path(file_name).resolve() + if not valid_o3de_repo_json(file_name): + return 1 + + cache_folder = get_o3de_cache_folder() + + with file_name.open('r') as f: + try: + repo_data = json.load(f) + except Exception as e: + logger.error(f'{file_name} failed to load: {str(e)}') + return 1 + + for engine_uri in repo_data['engines']: + engine_uri = f'{engine_uri}/engine.json' + engine_sha256 = hashlib.sha256(engine_uri.encode()) + cache_file = cache_folder / str(engine_sha256.hexdigest() + '.json') + if not cache_file.is_file(): + parsed_uri = urllib.parse.urlparse(engine_uri) + if parsed_uri.scheme == 'http' or \ + parsed_uri.scheme == 'https' or \ + parsed_uri.scheme == 'ftp' or \ + parsed_uri.scheme == 'ftps': + with urllib.request.urlopen(engine_uri) as s: + with cache_file.open('wb') as f: + shutil.copyfileobj(s, f) + else: + engine_json = pathlib.Path(engine_uri).resolve() + if not engine_json.is_file(): + return 1 + shutil.copy(engine_json, cache_file) + + for project_uri in repo_data['projects']: + project_uri = f'{project_uri}/project.json' + project_sha256 = hashlib.sha256(project_uri.encode()) + cache_file = cache_folder / str(project_sha256.hexdigest() + '.json') + if not cache_file.is_file(): + parsed_uri = urllib.parse.urlparse(project_uri) + if parsed_uri.scheme == 'http' or \ + parsed_uri.scheme == 'https' or \ + parsed_uri.scheme == 'ftp' or \ + parsed_uri.scheme == 'ftps': + with urllib.request.urlopen(project_uri) as s: + with cache_file.open('wb') as f: + shutil.copyfileobj(s, f) + else: + project_json = pathlib.Path(project_uri).resolve() + if not project_json.is_file(): + return 1 + shutil.copy(project_json, cache_file) + + for gem_uri in repo_data['gems']: + gem_uri = f'{gem_uri}/gem.json' + gem_sha256 = hashlib.sha256(gem_uri.encode()) + cache_file = cache_folder / str(gem_sha256.hexdigest() + '.json') + if not cache_file.is_file(): + parsed_uri = urllib.parse.urlparse(gem_uri) + if parsed_uri.scheme == 'http' or \ + parsed_uri.scheme == 'https' or \ + parsed_uri.scheme == 'ftp' or \ + parsed_uri.scheme == 'ftps': + with urllib.request.urlopen(gem_uri) as s: + with cache_file.open('wb') as f: + shutil.copyfileobj(s, f) + else: + gem_json = pathlib.Path(gem_uri).resolve() + if not gem_json.is_file(): + return 1 + shutil.copy(gem_json, cache_file) + + for template_uri in repo_data['templates']: + template_uri = f'{template_uri}/template.json' + template_sha256 = hashlib.sha256(template_uri.encode()) + cache_file = cache_folder / str(template_sha256.hexdigest() + '.json') + if not cache_file.is_file(): + parsed_uri = urllib.parse.urlparse(template_uri) + if parsed_uri.scheme == 'http' or \ + parsed_uri.scheme == 'https' or \ + parsed_uri.scheme == 'ftp' or \ + parsed_uri.scheme == 'ftps': + with urllib.request.urlopen(template_uri) as s: + with cache_file.open('wb') as f: + shutil.copyfileobj(s, f) + else: + template_json = pathlib.Path(template_uri).resolve() + if not template_json.is_file(): + return 1 + shutil.copy(template_json, cache_file) + + for repo_uri in repo_data['repos']: + if repo_uri not in repo_set: + repo_set.add(repo_uri) + repo_uri = f'{repo_uri}/repo.json' + repo_sha256 = hashlib.sha256(repo_uri.encode()) + cache_file = cache_folder / str(repo_sha256.hexdigest() + '.json') + if not cache_file.is_file(): + if parsed_uri.scheme == 'http' or \ + parsed_uri.scheme == 'https' or \ + parsed_uri.scheme == 'ftp' or \ + parsed_uri.scheme == 'ftps': + with urllib.request.urlopen(repo_uri) as s: + with cache_file.open('wb') as f: + shutil.copyfileobj(s, f) + else: + repo_json = pathlib.Path(repo_uri).resolve() + if not repo_json.is_file(): + return 1 + shutil.copy(repo_json, cache_file) + return 0 + + +def register_repo(json_data: dict, + repo_uri: str or pathlib.Path, remove: bool = False) -> int: if not repo_uri: logger.error(f'Repo URI cannot be empty.') return 1 - while repo_uri in json_data['repos']: - json_data['repos'].remove(repo_uri) + url = f'{repo_uri}/repo.json' + parsed_uri = urllib.parse.urlparse(url) + + if parsed_uri.scheme == 'http' or \ + parsed_uri.scheme == 'https' or \ + parsed_uri.scheme == 'ftp' or \ + parsed_uri.scheme == 'ftps': + while repo_uri in json_data['repos']: + json_data['repos'].remove(repo_uri) + else: + repo_uri = pathlib.Path(repo_uri).resolve() + while repo_uri.as_posix() in json_data['repos']: + json_data['repos'].remove(repo_uri.as_posix()) if remove: logger.warn(f'Removing repo uri {repo_uri}.') + return 0 - if remove: - result = refresh_repos() + repo_sha256 = hashlib.sha256(url.encode()) + cache_file = get_o3de_cache_folder() / str(repo_sha256.hexdigest() + '.json') + + result = 0 + if parsed_uri.scheme == 'http' or \ + parsed_uri.scheme == 'https' or \ + parsed_uri.scheme == 'ftp' or \ + parsed_uri.scheme == 'ftps': + if not cache_file.is_file(): + with urllib.request.urlopen(url) as s: + with cache_file.open('wb') as f: + shutil.copyfileobj(s, f) + json_data['repos'].insert(0, repo_uri) else: - repo_hash = hashlib.md5(repo_uri.encode()) - cache_folder = get_o3de_cache() - cache_file = cache_folder / str(repo_hash.hexdigest() + '.json') - parsed_uri = urllib.parse.urlparse(repo_uri) + if not cache_file.is_file(): + origin_file = pathlib.Path(url).resolve() + if not origin_file.is_file(): + return 1 + shutil.copy(origin_file, origin_file) + json_data['repos'].insert(0, repo_uri.as_posix()) - if parsed_uri.scheme == 'http' or parsed_uri.scheme == 'https' or parsed_uri.scheme == 'ftp' or parsed_uri.scheme == 'ftps': - result = 0 # a function that processes the uri and returns result - if not result: - json_data['repos'].insert(0, repo_uri) - else: - repo_uri = pathlib.Path(repo_uri) - json_data['repos'].insert(0, repo_uri.as_posix()) - result = 0 + repo_set = set() + result = process_add_o3de_repo(cache_file, repo_set) return result -def valid_o3de_manifest_json(file_name: str) -> bool: - try: - file_name = pathlib.Path(file_name) - if not file_name.is_file(): - return False - with file_name.open('r') as f: - json_data = json.load(f) - test = json_data['repo_name'] - test = json_data['origin'] - test = json_data['engines'] - test = json_data['projects'] - test = json_data['gems'] - test = json_data['templates'] - test = json_data['repos'] - except Exception as e: - return False +def register_default_engines_folder(json_data: dict, + default_engines_folder: str or pathlib.Path, + remove: bool = False) -> int: + if remove: + default_engines_folder = get_o3de_engines_folder() - return True + # make sure the path exists + default_engines_folder = pathlib.Path(default_engines_folder).resolve() + if not default_engines_folder.is_dir(): + logger.error(f'Default engines folder {default_engines_folder} does not exist.') + return 1 + + default_engines_folder = default_engines_folder.as_posix() + json_data['default_engines_folder'] = default_engines_folder + + return 0 -def valid_o3de_engine_json(file_name: str) -> bool: - try: - file_name = pathlib.Path(file_name) - if not file_name.is_file(): - return False - with file_name.open('r') as f: - json_data = json.load(f) - test = json_data['engine_name'] - except Exception as e: - return False - - return True - - -def valid_o3de_project_json(file_name: str) -> bool: - try: - file_name = pathlib.Path(file_name) - if not file_name.is_file(): - return False - with file_name.open('r') as f: - json_data = json.load(f) - test = json_data['project_name'] - except Exception as e: - return False - - return True - - -def valid_o3de_gem_json(file_name: str) -> bool: - try: - file_name = pathlib.Path(file_name) - if not file_name.is_file(): - return False - with file_name.open('r') as f: - json_data = json.load(f) - test = json_data['gem_name'] - except Exception as e: - return False - - return True - - -def valid_o3de_template_json(file_name: str) -> bool: - try: - file_name = pathlib.Path(file_name) - if not file_name.is_file(): - return False - with file_name.open('r') as f: - json_data = json.load(f) - test = json_data['template_name'] - except Exception as e: - return False - - return True - - -def register_default_projects_folder(json_data, - default_projects_folder: str, +def register_default_projects_folder(json_data: dict, + default_projects_folder: str or pathlib.Path, remove: bool = False) -> int: if remove: - json_data['default_projects_folder'] = '' - else: - # make sure the path exists - default_projects_folder = pathlib.Path(default_projects_folder) - if not default_projects_folder.is_dir(): - logger.error(f'Default projects folder {default_projects_folder} does not exist.') - return 1 + default_projects_folder = get_o3de_projects_folder() - default_projects_folder = default_projects_folder.as_posix() - json_data['default_projects_folder'] = default_projects_folder + # make sure the path exists + default_projects_folder = pathlib.Path(default_projects_folder).resolve() + if not default_projects_folder.is_dir(): + logger.error(f'Default projects folder {default_projects_folder} does not exist.') + return 1 + + default_projects_folder = default_projects_folder.as_posix() + json_data['default_projects_folder'] = default_projects_folder return 0 -def register_default_gems_folder(json_data, - default_gems_folder: str, +def register_default_gems_folder(json_data: dict, + default_gems_folder: str or pathlib.Path, remove: bool = False) -> int: if remove: - json_data['default_gems_folder'] = '' - else: - # make sure the path exists - default_gems_folder = pathlib.Path(default_gems_folder) - if not default_gems_folder.is_dir(): - logger.error(f'Default gems folder {default_gems_folder} does not exist.') - return 1 + default_gems_folder = get_o3de_gems_folder() - default_gems_folder = default_gems_folder.as_posix() - json_data['default_gems_folder'] = default_gems_folder + # make sure the path exists + default_gems_folder = pathlib.Path(default_gems_folder).resolve() + if not default_gems_folder.is_dir(): + logger.error(f'Default gems folder {default_gems_folder} does not exist.') + return 1 + + default_gems_folder = default_gems_folder.as_posix() + json_data['default_gems_folder'] = default_gems_folder return 0 -def register_default_templates_folder(json_data, - default_templates_folder: str, +def register_default_templates_folder(json_data: dict, + default_templates_folder: str or pathlib.Path, remove: bool = False) -> int: if remove: - json_data['default_templates_folder'] = '' - else: - # make sure the path exists - default_templates_folder = pathlib.Path(default_templates_folder) - if not default_templates_folder.is_dir(): - logger.error(f'Default templates folder {default_templates_folder} does not exist.') - return 1 + default_templates_folder = get_o3de_templates_folder() - default_templates_folder = default_templates_folder.as_posix() - json_data['default_templates_folder'] = default_templates_folder + # make sure the path exists + default_templates_folder = pathlib.Path(default_templates_folder).resolve() + if not default_templates_folder.is_dir(): + logger.error(f'Default templates folder {default_templates_folder} does not exist.') + return 1 + + default_templates_folder = default_templates_folder.as_posix() + json_data['default_templates_folder'] = default_templates_folder return 0 -def register(engine_path: str = None, - project_path: str = None, - gem_path: str = None, - template_path: str = None, - default_projects_folder: str = None, - default_gems_folder: str = None, - default_templates_folder: str = None, - repo_uri: str = None, - remove: bool = False) -> int: +def register_default_restricted_folder(json_data: dict, + default_restricted_folder: str or pathlib.Path, + remove: bool = False) -> int: + if remove: + default_restricted_folder = get_o3de_restricted_folder() + + # make sure the path exists + default_restricted_folder = pathlib.Path(default_restricted_folder).resolve() + if not default_restricted_folder.is_dir(): + logger.error(f'Default restricted folder {default_restricted_folder} does not exist.') + return 1 + + default_restricted_folder = default_restricted_folder.as_posix() + json_data['default_restricted_folder'] = default_restricted_folder + + return 0 + + +def register(engine_path: str or pathlib.Path = None, + project_path: str or pathlib.Path = None, + gem_path: str or pathlib.Path = None, + template_path: str or pathlib.Path = None, + restricted_path: str or pathlib.Path = None, + repo_uri: str or pathlib.Path = None, + default_engines_folder: str or pathlib.Path = None, + default_projects_folder: str or pathlib.Path = None, + default_gems_folder: str or pathlib.Path = None, + default_templates_folder: str or pathlib.Path = None, + default_restricted_folder: str or pathlib.Path = None, + remove: bool = False + ) -> int: """ Adds/Updates entries to the .o3de/o3de_manifest.json - :param engine_path: engine folder + :param engine_path: if engine folder is supplied the path will be added to the engine if it can, if not global :param project_path: project folder :param gem_path: gem folder :param template_path: template folder + :param restricted_path: restricted folder + :param repo_uri: repo uri + :param default_engines_folder: default engines folder :param default_projects_folder: default projects folder :param default_gems_folder: default gems folder :param default_templates_folder: default templates folder - :param repo_uri: repo uri + :param default_restricted_folder: default restricted code folder :param remove: add/remove the entries + :return: 0 for success or non 0 failure code """ - json_data = load_o3de_registry() + json_data = load_o3de_manifest() - if isinstance(engine_path, str) or isinstance(engine_path, pathlib.PurePath): - if not engine_path: - logger.error(f'Engine path cannot be empty.') - return 1 - result = register_engine_path(json_data, engine_path, remove) + result = 0 - elif isinstance(project_path, str) or isinstance(project_path, pathlib.PurePath): + # do anything that could require a engine context first + if isinstance(project_path, str) or isinstance(project_path, pathlib.PurePath): if not project_path: logger.error(f'Project path cannot be empty.') return 1 - result = register_project_path(json_data, project_path, remove) + result = register_project_path(json_data, project_path, remove, engine_path) elif isinstance(gem_path, str) or isinstance(gem_path, pathlib.PurePath): if not gem_path: logger.error(f'Gem path cannot be empty.') return 1 - result = register_gem_path(json_data, gem_path, remove) + result = register_gem_path(json_data, gem_path, remove, engine_path) elif isinstance(template_path, str) or isinstance(template_path, pathlib.PurePath): if not template_path: logger.error(f'Template path cannot be empty.') return 1 - result = register_template_path(json_data, template_path, remove) + result = register_template_path(json_data, template_path, remove, engine_path) + + elif isinstance(restricted_path, str) or isinstance(restricted_path, pathlib.PurePath): + if not restricted_path: + logger.error(f'Restricted path cannot be empty.') + return 1 + result = register_restricted_path(json_data, restricted_path, remove, engine_path) elif isinstance(repo_uri, str) or isinstance(repo_uri, pathlib.PurePath): if not repo_uri: @@ -493,6 +1299,9 @@ def register(engine_path: str = None, return 1 result = register_repo(json_data, repo_uri, remove) + elif isinstance(default_engines_folder, str) or isinstance(default_engines_folder, pathlib.PurePath): + result = register_default_engines_folder(json_data, default_engines_folder, remove) + elif isinstance(default_projects_folder, str) or isinstance(default_projects_folder, pathlib.PurePath): result = register_default_projects_folder(json_data, default_projects_folder, remove) @@ -502,578 +1311,2746 @@ def register(engine_path: str = None, elif isinstance(default_templates_folder, str) or isinstance(default_templates_folder, pathlib.PurePath): result = register_default_templates_folder(json_data, default_templates_folder, remove) + elif isinstance(default_restricted_folder, str) or isinstance(default_restricted_folder, pathlib.PurePath): + result = register_default_restricted_folder(json_data, default_restricted_folder, remove) + + # engine is done LAST + # Now that everything that could have an engine context is done, if the engine is supplied that means this is + # registering the engine itself + elif isinstance(engine_path, str) or isinstance(engine_path, pathlib.PurePath): + if not engine_path: + logger.error(f'Engine path cannot be empty.') + return 1 + result = register_engine_path(json_data, engine_path, remove) + if not result: - save_o3de_registry(json_data) + save_o3de_manifest(json_data) - return 0 + return result -def remove_invalid_o3de_objects(): - json_data = load_o3de_registry() +def remove_invalid_o3de_objects() -> None: + json_data = load_o3de_manifest() - for engine in json_data['engines']: - if not valid_o3de_engine_json(pathlib.Path(engine) / 'engine.json'): - logger.warn(f"Engine path {engine} is invalid.") - register(engine_path=engine, remove=True) + for engine_object in json_data['engines']: + engine_path = engine_object['path'] + if not valid_o3de_engine_json(pathlib.Path(engine_path).resolve() / 'engine.json'): + logger.warn(f"Engine path {engine_path} is invalid.") + register(engine_path=engine_path, remove=True) + else: + for project in engine_object['projects']: + if not valid_o3de_project_json(pathlib.Path(project).resolve() / 'project.json'): + logger.warn(f"Project path {project} is invalid.") + register(engine_path=engine_path, project_path=project, remove=True) + + for gem_path in engine_object['gems']: + if not valid_o3de_gem_json(pathlib.Path(gem_path).resolve() / 'gem.json'): + logger.warn(f"Gem path {gem_path} is invalid.") + register(engine_path=engine_path, gem_path=gem_path, remove=True) + + for template_path in engine_object['templates']: + if not valid_o3de_template_json(pathlib.Path(template_path).resolve() / 'template.json'): + logger.warn(f"Template path {template_path} is invalid.") + register(engine_path=engine_path, template_path=template_path, remove=True) + + for restricted in engine_object['restricted']: + if not valid_o3de_restricted_json(pathlib.Path(restricted).resolve() / 'restricted.json'): + logger.warn(f"Restricted path {restricted} is invalid.") + register(engine_path=engine_path, restricted_path=restricted, remove=True) + + for external in engine_object['external_subdirectories']: + external = pathlib.Path(external).resolve() + if not external.is_dir(): + logger.warn(f"External subdirectory {external} is invalid.") + remove_external_subdirectory(external) for project in json_data['projects']: - if not valid_o3de_project_json(pathlib.Path(project) / 'project.json'): + if not valid_o3de_project_json(pathlib.Path(project).resolve() / 'project.json'): logger.warn(f"Project path {project} is invalid.") register(project_path=project, remove=True) for gem in json_data['gems']: - if not valid_o3de_gem_json(pathlib.Path(gem) / 'gem.json'): + if not valid_o3de_gem_json(pathlib.Path(gem).resolve() / 'gem.json'): logger.warn(f"Gem path {gem} is invalid.") register(gem_path=gem, remove=True) for template in json_data['templates']: - if not valid_o3de_template_json(pathlib.Path(template) / 'template.json'): + if not valid_o3de_template_json(pathlib.Path(template).resolve() / 'template.json'): logger.warn(f"Template path {template} is invalid.") register(template_path=template, remove=True) - default_projects_folder = pathlib.Path(json_data['default_projects_folder']) + for restricted in json_data['restricted']: + if not valid_o3de_restricted_json(pathlib.Path(restricted).resolve() / 'restricted.json'): + logger.warn(f"Restricted path {restricted} is invalid.") + register(restricted_path=restricted, remove=True) + + default_engines_folder = pathlib.Path(json_data['default_engines_folder']).resolve() + if not default_engines_folder.is_dir(): + new_default_engines_folder = get_o3de_folder() / 'Engines' + new_default_engines_folder.mkdir(parents=True, exist_ok=True) + logger.warn( + f"Default engines folder {default_engines_folder} is invalid. Set default {new_default_engines_folder}") + register(default_engines_folder=new_default_engines_folder.as_posix()) + + default_projects_folder = pathlib.Path(json_data['default_projects_folder']).resolve() if not default_projects_folder.is_dir(): - new_default_projects_folder = get_home_folder() / 'my_o3de/projects' + new_default_projects_folder = get_o3de_folder() / 'Projects' new_default_projects_folder.mkdir(parents=True, exist_ok=True) - logger.warn(f"Default projects folder {default_projects_folder} is invalid. Set default {new_default_projects_folder}") + logger.warn( + f"Default projects folder {default_projects_folder} is invalid. Set default {new_default_projects_folder}") register(default_projects_folder=new_default_projects_folder.as_posix()) - default_gems_folder = pathlib.Path(json_data['default_gems_folder']) + default_gems_folder = pathlib.Path(json_data['default_gems_folder']).resolve() if not default_gems_folder.is_dir(): - new_default_gems_folder = get_home_folder() / 'my_o3de/gems' + new_default_gems_folder = get_o3de_folder() / 'Gems' new_default_gems_folder.mkdir(parents=True, exist_ok=True) - logger.warn(f"Default gems folder {default_gems_folder} is invalid. Set default {new_default_gems_folder}") + logger.warn(f"Default gems folder {default_gems_folder} is invalid." + f" Set default {new_default_gems_folder}") register(default_gems_folder=new_default_gems_folder.as_posix()) - default_templates_folder = pathlib.Path(json_data['default_templates_folder']) + default_templates_folder = pathlib.Path(json_data['default_templates_folder']).resolve() if not default_templates_folder.is_dir(): - new_default_templates_folder = get_home_folder() / 'my_o3de/templates' + new_default_templates_folder = get_o3de_folder() / 'Templates' new_default_templates_folder.mkdir(parents=True, exist_ok=True) - logger.warn(f"Default templates folder {default_templates_folder} is invalid. Set default {new_default_templates_folder}") + logger.warn( + f"Default templates folder {default_templates_folder} is invalid." + f" Set default {new_default_templates_folder}") register(default_templates_folder=new_default_templates_folder.as_posix()) + default_restricted_folder = pathlib.Path(json_data['default_restricted_folder']).resolve() + if not default_restricted_folder.is_dir(): + default_restricted_folder = get_o3de_folder() / 'Restricted' + default_restricted_folder.mkdir(parents=True, exist_ok=True) + logger.warn( + f"Default restricted folder {default_restricted_folder} is invalid." + f" Set default {default_restricted_folder}") + register(default_restricted_folder=default_restricted_folder.as_posix()) + def refresh_repos() -> int: - json_data = load_o3de_registry() - cache_folder = get_o3de_cache() + json_data = load_o3de_manifest() + + # clear the cache + cache_folder = get_o3de_cache_folder() shutil.rmtree(cache_folder) - cache_folder.mkdir(parents=True, exist_ok=True) - if len(json_data['repos']) == 0: - return 0 + cache_folder = get_o3de_cache_folder() # will recreate it result = 0 - last_failure = 0 - for repo_uri in json_data['repos']: - repo_hash = hashlib.md5(repo_uri.encode()) - cache_file = cache_folder / str(repo_hash.hexdigest() + '.json') - parsed_uri = urllib.parse.urlparse(repo_uri) - last_failure = 0 # download and validate the repo_uri - if not last_failure: - result = 1 + # set will stop circular references + repo_set = set() + + for repo_uri in json_data['repos']: + if repo_uri not in repo_set: + repo_set.add(repo_uri) + + repo_uri = f'{repo_uri}/repo.json' + repo_sha256 = hashlib.sha256(repo_uri.encode()) + cache_file = cache_folder / str(repo_sha256.hexdigest() + '.json') + if not cache_file.is_file(): + parsed_uri = urllib.parse.urlparse(repo_uri) + if parsed_uri.scheme == 'http' or \ + parsed_uri.scheme == 'https' or \ + parsed_uri.scheme == 'ftp' or \ + parsed_uri.scheme == 'ftps': + with urllib.request.urlopen(repo_uri) as s: + with cache_file.open('wb') as f: + shutil.copyfileobj(s, f) + else: + origin_file = pathlib.Path(repo_uri).resolve() + if not origin_file.is_file(): + return 1 + shutil.copy(origin_file, cache_file) + + if not valid_o3de_repo_json(cache_file): + logger.error(f'Repo json {repo_uri} is not valid.') + cache_file.unlink() + return 1 + + last_failure = process_add_o3de_repo(cache_file, repo_set) + if last_failure: + result = last_failure return result +def search_repo(repo_set: set, + repo_json_data: dict, + engine_name: str = None, + project_name: str = None, + gem_name: str = None, + template_name: str = None, + restricted_name: str = None) -> dict or None: + cache_folder = get_o3de_cache_folder() + + if isinstance(engine_name, str) or isinstance(engine_name, pathlib.PurePath): + for engine_uri in repo_json_data['engines']: + engine_uri = f'{engine_uri}/engine.json' + engine_sha256 = hashlib.sha256(engine_uri.encode()) + engine_cache_file = cache_folder / str(engine_sha256.hexdigest() + '.json') + if engine_cache_file.is_file(): + with engine_cache_file.open('r') as f: + try: + engine_json_data = json.load(f) + except Exception as e: + logger.warn(f'{engine_cache_file} failed to load: {str(e)}') + else: + if engine_json_data['engine_name'] == engine_name: + return engine_json_data + + elif isinstance(project_name, str) or isinstance(project_name, pathlib.PurePath): + for project_uri in repo_json_data['projects']: + project_uri = f'{project_uri}/project.json' + project_sha256 = hashlib.sha256(project_uri.encode()) + project_cache_file = cache_folder / str(project_sha256.hexdigest() + '.json') + if project_cache_file.is_file(): + with project_cache_file.open('r') as f: + try: + project_json_data = json.load(f) + except Exception as e: + logger.warn(f'{project_cache_file} failed to load: {str(e)}') + else: + if project_json_data['project_name'] == project_name: + return project_json_data + + elif isinstance(gem_name, str) or isinstance(gem_name, pathlib.PurePath): + for gem_uri in repo_json_data['gems']: + gem_uri = f'{gem_uri}/gem.json' + gem_sha256 = hashlib.sha256(gem_uri.encode()) + gem_cache_file = cache_folder / str(gem_sha256.hexdigest() + '.json') + if gem_cache_file.is_file(): + with gem_cache_file.open('r') as f: + try: + gem_json_data = json.load(f) + except Exception as e: + logger.warn(f'{gem_cache_file} failed to load: {str(e)}') + else: + if gem_json_data['gem_name'] == gem_name: + return gem_json_data + + elif isinstance(template_name, str) or isinstance(template_name, pathlib.PurePath): + for template_uri in repo_json_data['templates']: + template_uri = f'{template_uri}/template.json' + template_sha256 = hashlib.sha256(template_uri.encode()) + template_cache_file = cache_folder / str(template_sha256.hexdigest() + '.json') + if template_cache_file.is_file(): + with template_cache_file.open('r') as f: + try: + template_json_data = json.load(f) + except Exception as e: + logger.warn(f'{template_cache_file} failed to load: {str(e)}') + else: + if template_json_data['template_name'] == template_name: + return template_json_data + + elif isinstance(restricted_name, str) or isinstance(restricted_name, pathlib.PurePath): + for restricted_uri in repo_json_data['restricted']: + restricted_uri = f'{restricted_uri}/restricted.json' + restricted_sha256 = hashlib.sha256(restricted_uri.encode()) + restricted_cache_file = cache_folder / str(restricted_sha256.hexdigest() + '.json') + if restricted_cache_file.is_file(): + with restricted_cache_file.open('r') as f: + try: + restricted_json_data = json.load(f) + except Exception as e: + logger.warn(f'{restricted_cache_file} failed to load: {str(e)}') + else: + if restricted_json_data['restricted_name'] == restricted_name: + return restricted_json_data + # recurse + else: + for repo_repo_uri in repo_json_data['repos']: + if repo_repo_uri not in repo_set: + repo_set.add(repo_repo_uri) + repo_repo_uri = f'{repo_repo_uri}/repo.json' + repo_repo_sha256 = hashlib.sha256(repo_repo_uri.encode()) + repo_repo_cache_file = cache_folder / str(repo_repo_sha256.hexdigest() + '.json') + if repo_repo_cache_file.is_file(): + with repo_repo_cache_file.open('r') as f: + try: + repo_repo_json_data = json.load(f) + except Exception as e: + logger.warn(f'{repo_repo_cache_file} failed to load: {str(e)}') + else: + item = search_repo(repo_set, + repo_repo_json_data, + engine_name, + project_name, + gem_name, + template_name) + if item: + return item + return None + + +def get_downloadable(engine_name: str = None, + project_name: str = None, + gem_name: str = None, + template_name: str = None, + restricted_name: str = None) -> dict or None: + json_data = load_o3de_manifest() + cache_folder = get_o3de_cache_folder() + repo_set = set() + for repo_uri in json_data['repos']: + if repo_uri not in repo_set: + repo_set.add(repo_uri) + repo_uri = f'{repo_uri}/repo.json' + repo_sha256 = hashlib.sha256(repo_uri.encode()) + repo_cache_file = cache_folder / str(repo_sha256.hexdigest() + '.json') + if repo_cache_file.is_file(): + with repo_cache_file.open('r') as f: + try: + repo_json_data = json.load(f) + except Exception as e: + logger.warn(f'{repo_cache_file} failed to load: {str(e)}') + else: + item = search_repo(repo_set, + repo_json_data, + engine_name, + project_name, + gem_name, + template_name, + restricted_name) + if item: + return item + return None + + def get_registered(engine_name: str = None, project_name: str = None, gem_name: str = None, template_name: str = None, default_folder: str = None, - repo_name: str = None): - json_data = load_o3de_registry() + repo_name: str = None, + restricted_name: str = None) -> pathlib.Path or None: + json_data = load_o3de_manifest() - if type(engine_name) == str: + # check global first then this engine + if isinstance(engine_name, str): for engine in json_data['engines']: - engine = pathlib.Path(engine) / 'engine.json' - with engine.open('r') as f: - engine_json_data = json.load(f) - this_engines_name = engine_json_data['engine_name'] - if this_engines_name == engine_name: - engine = engine.parent.as_posix() - return engine + engine_path = pathlib.Path(engine['path']).resolve() + engine_json = engine_path / 'engine.json' + with engine_json.open('r') as f: + try: + engine_json_data = json.load(f) + except Exception as e: + logger.warn(f'{engine_json} failed to load: {str(e)}') + else: + this_engines_name = engine_json_data['engine_name'] + if this_engines_name == engine_name: + return engine_path - elif type(project_name) == str: - for project in json_data['projects']: - project = pathlib.Path(project) / 'project.json' - with project.open('r') as f: - project_json_data = json.load(f) - this_projects_name = project_json_data['project_name'] - if this_projects_name == project_name: - project = project.parent.as_posix() - return project + elif isinstance(project_name, str): + engine_object = find_engine_data(json_data) + projects = json_data['projects'].copy() + projects.extend(engine_object['projects']) + for project_path in projects: + project_path = pathlib.Path(project_path).resolve() + project_json = project_path / 'project.json' + with project_json.open('r') as f: + try: + project_json_data = json.load(f) + except Exception as e: + logger.warn(f'{project_json} failed to load: {str(e)}') + else: + this_projects_name = project_json_data['project_name'] + if this_projects_name == project_name: + return project_path - elif type(gem_name) == str: - for gem in json_data['gems']: - gem = pathlib.Path(gem) / 'gem.json' - with gem.open('r') as f: - gem_json_data = json.load(f) - this_gems_name = gem_json_data['gem_name'] - if this_gems_name == gem_name: - gem = gem.parent.as_posix() - return gem + elif isinstance(gem_name, str): + engine_object = find_engine_data(json_data) + gems = json_data['gems'].copy() + gems.extend(engine_object['gems']) + for gem_path in gems: + gem_path = pathlib.Path(gem_path).resolve() + gem_json = gem_path / 'gem.json' + with gem_json.open('r') as f: + try: + gem_json_data = json.load(f) + except Exception as e: + logger.warn(f'{gem_json} failed to load: {str(e)}') + else: + this_gems_name = gem_json_data['gem_name'] + if this_gems_name == gem_name: + return gem_path - elif type(template_name) == str: - for template in json_data['templates']: - template = pathlib.Path(template) / 'template.json' - with template.open('r') as f: - template_json_data = json.load(f) - this_templates_name = template_json_data['template_name'] - if this_templates_name == template_name: - template = template.parent.as_posix() - return template + elif isinstance(template_name, str): + engine_object = find_engine_data(json_data) + templates = json_data['templates'].copy() + templates.extend(engine_object['templates']) + for template_path in templates: + template_path = pathlib.Path(template_path).resolve() + template_json = template_path / 'template.json' + with template_json.open('r') as f: + try: + template_json_data = json.load(f) + except Exception as e: + logger.warn(f'{template_path} failed to load: {str(e)}') + else: + this_templates_name = template_json_data['template_name'] + if this_templates_name == template_name: + return template_path - elif type(default_folder) == str: - if default_folder == 'project': - return json_data['default_projects_folder'] - elif default_folder == 'gem': - return json_data['default_gems_folder'] - elif default_folder == 'template': - return json_data['default_templates_folder'] + elif isinstance(restricted_name, str): + engine_object = find_engine_data(json_data) + restricted = json_data['restricted'].copy() + restricted.extend(engine_object['restricted']) + for restricted_path in restricted: + restricted_path = pathlib.Path(restricted_path).resolve() + restricted_json = restricted_path / 'restricted.json' + with restricted_json.open('r') as f: + try: + restricted_json_data = json.load(f) + except Exception as e: + logger.warn(f'{restricted_json} failed to load: {str(e)}') + else: + this_restricted_name = restricted_json_data['restricted_name'] + if this_restricted_name == restricted_name: + return restricted_path - elif type(repo_name) == str: - cache_folder = get_o3de_cache() - cache_folder.mkdir(parents=True, exist_ok=True) + elif isinstance(default_folder, str): + if default_folder == 'engines': + default_engines_folder = pathlib.Path(json_data['default_engines_folder']).resolve() + return default_engines_folder + elif default_folder == 'projects': + default_projects_folder = pathlib.Path(json_data['default_projects_folder']).resolve() + return default_projects_folder + elif default_folder == 'gems': + default_gems_folder = pathlib.Path(json_data['default_gems_folder']).resolve() + return default_gems_folder + elif default_folder == 'templates': + default_templates_folder = pathlib.Path(json_data['default_templates_folder']).resolve() + return default_templates_folder + elif default_folder == 'restricted': + default_restricted_folder = pathlib.Path(json_data['default_restricted_folder']).resolve() + return default_restricted_folder + + elif isinstance(repo_name, str): + cache_folder = get_o3de_cache_folder() for repo_uri in json_data['repos']: - repo_hash = hashlib.md5(repo_uri.encode()) - cache_file = cache_folder / str(repo_hash.hexdigest() + '.json') + repo_uri = pathlib.Path(repo_uri).resolve() + repo_sha256 = hashlib.sha256(repo_uri.encode()) + cache_file = cache_folder / str(repo_sha256.hexdigest() + '.json') if cache_file.is_file(): - repo = pathlib.Path(cache_file) + repo = pathlib.Path(cache_file).resolve() with repo.open('r') as f: - repo_json_data = json.load(f) - this_repos_name = repo_json_data['repo_name'] - if this_repos_name == repo_name: - repo = repo.parent.as_posix() - return repo + try: + repo_json_data = json.load(f) + except Exception as e: + logger.warn(f'{cache_file} failed to load: {str(e)}') + else: + this_repos_name = repo_json_data['repo_name'] + if this_repos_name == repo_name: + return repo_uri return None -def print_engines(json_data, - verbose: int): - if verbose > 0: - print('\n') - print("Engines================================================") - for engine in json_data['engines']: - engine = pathlib.Path(engine) / 'engine.json' - with engine.open('r') as f: - engine_json_data = json.load(f) - print(engine) - print(json.dumps(engine_json_data, indent=4)) - print('\n') - - -def print_projects(json_data, - verbose: int): - if verbose > 0: - print('\n') - print("Projects================================================") - for project in json_data['projects']: - project = pathlib.Path(project) / 'project.json' - with project.open('r') as f: - project_json_data = json.load(f) - print(project) - print(json.dumps(project_json_data, indent=4)) - print('\n') - - -def print_gems(json_data, - verbose: int): - if verbose > 0: - print('\n') - print("Gems================================================") - for gem in json_data['gems']: - gem = pathlib.Path(gem) / 'gem.json' - with gem.open('r') as f: - gem_json_data = json.load(f) - print(gem) - print(json.dumps(gem_json_data, indent=4)) - print('\n') - - -def print_templates(json_data, - verbose: int): - if verbose > 0: - print("Templates================================================") - for template in json_data['templates']: - template = pathlib.Path(template) / 'template.json' - with template.open('r') as f: - template_json_data = json.load(f) - print(template) - print(json.dumps(template_json_data, indent=4)) - print('\n') - - -def print_repos(json_data: str, - verbose: int): - if verbose > 0: - print("Repos================================================") - cache_folder = get_o3de_cache() - cache_folder.mkdir(parents=True, exist_ok=True) - for repo in json_data['repos']: - repo_hash = hashlib.md5(repo.encode()) - cache_file = cache_folder / str(repo_hash.hexdigest() + '.json') - if valid_o3de_manifest_json(cache_file): - with cache_file.open('r') as s: - repo_json_data = json.load(s) - print(repo) - print(json.dumps(repo_json_data, indent=4)) - print('\n') - - -def register_show_engines(verbose: int): - json_data = load_o3de_registry() - - del json_data['repo_name'] - del json_data['origin'] - del json_data['projects'] - del json_data['gems'] - del json_data['templates'] - del json_data['repos'] - del json_data['default_projects_folder'] - del json_data['default_gems_folder'] - del json_data['default_templates_folder'] - - print(json.dumps(json_data, indent=4)) - print_engines(json_data, - verbose) - - -def register_show_projects(verbose: int): - json_data = load_o3de_registry() - - del json_data['repo_name'] - del json_data['origin'] - del json_data['engines'] - del json_data['gems'] - del json_data['templates'] - del json_data['repos'] - del json_data['default_projects_folder'] - del json_data['default_gems_folder'] - del json_data['default_templates_folder'] - - print(json.dumps(json_data, indent=4)) - print_projects(json_data, - verbose) - - -def register_show_gems(verbose: int): - json_data = load_o3de_registry() - - del json_data['repo_name'] - del json_data['origin'] - del json_data['engines'] - del json_data['projects'] - del json_data['templates'] - del json_data['repos'] - del json_data['default_projects_folder'] - del json_data['default_gems_folder'] - del json_data['default_templates_folder'] - - print(json.dumps(json_data, indent=4)) - print_gems(json_data, - verbose) - - -def register_show_templates(verbose: int): - json_data = load_o3de_registry() - - del json_data['repo_name'] - del json_data['origin'] - del json_data['engines'] - del json_data['projects'] - del json_data['gems'] - del json_data['repos'] - del json_data['default_projects_folder'] - del json_data['default_gems_folder'] - del json_data['default_templates_folder'] - - print(json.dumps(json_data, indent=4)) - print_templates(json_data, - verbose) - - -def register_show_repos(verbose: int): - json_data = load_o3de_registry() - - del json_data['repo_name'] - del json_data['origin'] - del json_data['engines'] - del json_data['projects'] - del json_data['gems'] - del json_data['templates'] - del json_data['default_projects_folder'] - del json_data['default_gems_folder'] - del json_data['default_templates_folder'] - - print(json.dumps(json_data, indent=4)) - print_repos(json_data, - verbose) - - -def register_show(verbose: int): - json_data = load_o3de_registry() - if verbose > 0: - print(f"{get_o3de_registry()}:") - - print(json.dumps(json_data, indent=4)) - - print_engines(json_data, - verbose) - print_projects(json_data, - verbose) - print_gems(json_data, - verbose) - print_templates(json_data, - verbose) - print_repos(json_data, - verbose) - - if verbose > 0: - print("Default Folders================================================") - print(f"Default projects folder: {json_data['default_projects_folder']}") - print(os.listdir(json_data['default_projects_folder'])) - print('\n') - print(f"Default gems folder: {json_data['default_gems_folder']}") - print(os.listdir(json_data['default_gems_folder'])) - print('\n') - print(f"Default templates folder: {json_data['default_templates_folder']}") - print(os.listdir(json_data['default_templates_folder'])) - - -def aggregate_repo(json_data, repo_uri: str): - cache_folder = get_o3de_cache() - cache_folder.mkdir(parents=True, exist_ok=True) - repo_hash = hashlib.md5(repo_uri.encode()) - cache_file = cache_folder / str(repo_hash.hexdigest() + '.json') - if valid_o3de_manifest_json(cache_file): - with cache_file.open('r') as s: - repo_json_data = json.load(s) - for engine in repo_json_data['engines']: - if engine not in json_data['engines']: - json_data['engines'].append(engine) - - for project in repo_json_data['projects']: - if project not in json_data['projects']: - json_data['projects'].append(project) - - for gem in repo_json_data['gems']: - if gem not in json_data['gems']: - json_data['gems'].append(gem) - - for template in repo_json_data['templates']: - if template not in json_data['templates']: - json_data['templates'].append(template) - - for repo in repo_json_data['repos']: - if repo not in json_data['repos']: - json_data['repos'].append(repo) - - for repo_uri in repo_json_data['repos']: - aggregate_repo(json_data, repo_uri) - - -def register_show_aggregate_engines(verbose: int): - json_data = load_o3de_registry() - repos = json_data['repos'].copy() - for repo_uri in repos: - aggregate_repo(json_data, repo_uri) - - del json_data['projects'] - del json_data['gems'] - del json_data['templates'] - del json_data['repos'] - del json_data['default_projects_folder'] - del json_data['default_gems_folder'] - del json_data['default_templates_folder'] - - print(json.dumps(json_data, indent=4)) - print_engines(json_data, - verbose) - - -def register_show_aggregate_projects(verbose: int): - json_data = load_o3de_registry() - repos = json_data['repos'].copy() - for repo_uri in repos: - aggregate_repo(json_data, repo_uri) - - del json_data['engines'] - del json_data['gems'] - del json_data['templates'] - del json_data['repos'] - del json_data['default_projects_folder'] - del json_data['default_gems_folder'] - del json_data['default_templates_folder'] - - print(json.dumps(json_data, indent=4)) - print_projects(json_data, - verbose) - - -def register_show_aggregate_gems(verbose: int): - json_data = load_o3de_registry() - repos = json_data['repos'].copy() - for repo_uri in repos: - aggregate_repo(json_data, repo_uri) - - del json_data['engines'] - del json_data['projects'] - del json_data['templates'] - del json_data['repos'] - del json_data['default_projects_folder'] - del json_data['default_gems_folder'] - del json_data['default_templates_folder'] - - print(json.dumps(json_data, indent=4)) - print_gems(json_data, - verbose) - - -def register_show_aggregate_templates(verbose: int): - json_data = load_o3de_registry() - repos = json_data['repos'].copy() - for repo_uri in repos: - aggregate_repo(json_data, repo_uri) - - del json_data['engines'] - del json_data['projects'] - del json_data['gems'] - del json_data['repos'] - del json_data['default_projects_folder'] - del json_data['default_gems_folder'] - del json_data['default_templates_folder'] - - print(json.dumps(json_data, indent=4)) - print_templates(json_data, - verbose) - - -def register_show_aggregate_repos(verbose: int): - json_data = load_o3de_registry() - repos = json_data['repos'].copy() - for repo_uri in repos: - aggregate_repo(json_data, repo_uri) - - del json_data['engines'] - del json_data['projects'] - del json_data['gems'] - del json_data['templates'] - del json_data['default_projects_folder'] - del json_data['default_gems_folder'] - del json_data['default_templates_folder'] - - print(json.dumps(json_data, indent=4)) - print_repos(json_data, - verbose) - - -def register_show_aggregate(verbose: int): - json_data = load_o3de_registry() - repos = json_data['repos'].copy() - for repo_uri in repos: - aggregate_repo(json_data, repo_uri) - - print(json.dumps(json_data, indent=4)) - - print_engines(json_data, - verbose) - print_projects(json_data, - verbose) - print_gems(json_data, - verbose) - print_templates(json_data, - verbose) - print_repos(json_data, - verbose) - - if verbose > 0: - print("Default Folders================================================") - print(f"Default projects folder: {json_data['default_projects_folder']}") - print(os.listdir(json_data['default_projects_folder'])) - print('\n') - print(f"Default gems folder: {json_data['default_gems_folder']}") - print(os.listdir(json_data['default_gems_folder'])) - print('\n') - print(f"Default templates folder: {json_data['default_templates_folder']}") - print(os.listdir(json_data['default_templates_folder'])) - - -def _run_register(args: argparse) -> int: - if args.update: - remove_invalid_o3de_objects() - return refresh_repos() - else: - if args.this_engine: - register(engine_path=get_this_engine_path()) - register_shipped_engine_o3de_objects() +def print_engines_data(engines_data: dict) -> None: + print('\n') + print("Engines================================================") + for engine_object in engines_data: + # if it's not local it should be in the cache + engine_uri = engine_object['path'] + parsed_uri = urllib.parse.urlparse(engine_uri) + if parsed_uri.scheme == 'http' or \ + parsed_uri.scheme == 'https' or \ + parsed_uri.scheme == 'ftp' or \ + parsed_uri.scheme == 'ftps': + repo_sha256 = hashlib.sha256(engine_uri.encode()) + cache_folder = get_o3de_cache_folder() + engine = cache_folder / str(repo_sha256.hexdigest() + '.json') + print(f'{engine_uri}/engine.json cached as:') else: - return register(args.engine_path, - args.project_path, - args.gem_path, - args.template_path, - args.default_projects_folder, - args.default_gems_folder, - args.default_templates_folder, - args.repo_uri, - args.remove) + engine_json = pathlib.Path(engine_uri).resolve() / 'engine.json' + + with engine_json.open('r') as f: + try: + engine_json_data = json.load(f) + except Exception as e: + logger.warn(f'{engine_json} failed to load: {str(e)}') + else: + print(engine_json) + print(json.dumps(engine_json_data, indent=4)) + print('\n') -def _run_get_registered(args: argparse) -> int: +def print_projects_data(projects_data: dict) -> None: + print('\n') + print("Projects================================================") + for project_uri in projects_data: + # if it's not local it should be in the cache + parsed_uri = urllib.parse.urlparse(project_uri) + if parsed_uri.scheme == 'http' or \ + parsed_uri.scheme == 'https' or \ + parsed_uri.scheme == 'ftp' or \ + parsed_uri.scheme == 'ftps': + repo_sha256 = hashlib.sha256(project_uri.encode()) + cache_folder = get_o3de_cache_folder() + project_json = cache_folder / str(repo_sha256.hexdigest() + '.json') + else: + project_json = pathlib.Path(project_uri).resolve() / 'project.json' + + with project_json.open('r') as f: + try: + project_json_data = json.load(f) + except Exception as e: + logger.warn(f'{project_json} failed to load: {str(e)}') + else: + print(project_json) + print(json.dumps(project_json_data, indent=4)) + print('\n') + + +def print_gems_data(gems_data: dict) -> None: + print('\n') + print("Gems================================================") + for gem_uri in gems_data: + # if it's not local it should be in the cache + parsed_uri = urllib.parse.urlparse(gem_uri) + if parsed_uri.scheme == 'http' or \ + parsed_uri.scheme == 'https' or \ + parsed_uri.scheme == 'ftp' or \ + parsed_uri.scheme == 'ftps': + repo_sha256 = hashlib.sha256(gem_uri.encode()) + cache_folder = get_o3de_cache_folder() + gem_json = cache_folder / str(repo_sha256.hexdigest() + '.json') + else: + gem_json = pathlib.Path(gem_uri).resolve() / 'gem.json' + + with gem_json.open('r') as f: + try: + gem_json_data = json.load(f) + except Exception as e: + logger.warn(f'{gem_json} failed to load: {str(e)}') + else: + print(gem_json) + print(json.dumps(gem_json_data, indent=4)) + print('\n') + + +def print_templates_data(templates_data: dict) -> None: + print('\n') + print("Templates================================================") + for template_uri in templates_data: + # if it's not local it should be in the cache + parsed_uri = urllib.parse.urlparse(template_uri) + if parsed_uri.scheme == 'http' or \ + parsed_uri.scheme == 'https' or \ + parsed_uri.scheme == 'ftp' or \ + parsed_uri.scheme == 'ftps': + repo_sha256 = hashlib.sha256(template_uri.encode()) + cache_folder = get_o3de_cache_folder() + template_json = cache_folder / str(repo_sha256.hexdigest() + '.json') + else: + template_json = pathlib.Path(template_uri).resolve() / 'template.json' + + with template_json.open('r') as f: + try: + template_json_data = json.load(f) + except Exception as e: + logger.warn(f'{template_json} failed to load: {str(e)}') + else: + print(template_json) + print(json.dumps(template_json_data, indent=4)) + print('\n') + + +def print_repos_data(repos_data: dict) -> None: + print('\n') + print("Repos================================================") + cache_folder = get_o3de_cache_folder() + for repo_uri in repos_data: + repo_sha256 = hashlib.sha256(repo_uri.encode()) + cache_file = cache_folder / str(repo_sha256.hexdigest() + '.json') + if valid_o3de_repo_json(cache_file): + with cache_file.open('r') as s: + try: + repo_json_data = json.load(s) + except Exception as e: + logger.warn(f'{cache_file} failed to load: {str(e)}') + else: + print(f'{repo_uri}/repo.json cached as:') + print(cache_file) + print(json.dumps(repo_json_data, indent=4)) + print('\n') + + +def print_restricted_data(restricted_data: dict) -> None: + print('\n') + print("Restricted================================================") + for restricted_path in restricted_data: + restricted_json = pathlib.Path(restricted_path).resolve() / 'restricted.json' + with restricted_json.open('r') as f: + try: + restricted_json_data = json.load(f) + except Exception as e: + logger.warn(f'{restricted_json} failed to load: {str(e)}') + else: + print(restricted_json) + print(json.dumps(restricted_json_data, indent=4)) + print('\n') + + +def get_this_engine() -> dict: + json_data = load_o3de_manifest() + engine_data = find_engine_data(json_data) + return engine_data + + +def get_engines() -> dict: + json_data = load_o3de_manifest() + return json_data['engines'] + + +def get_projects() -> dict: + json_data = load_o3de_manifest() + return json_data['projects'] + + +def get_gems() -> dict: + json_data = load_o3de_manifest() + return json_data['gems'] + + +def get_templates() -> dict: + json_data = load_o3de_manifest() + return json_data['templates'] + + +def get_restricted() -> dict: + json_data = load_o3de_manifest() + return json_data['restricted'] + + +def get_repos() -> dict: + json_data = load_o3de_manifest() + return json_data['repos'] + + +def get_engine_projects() -> dict: + json_data = load_o3de_manifest() + engine_object = find_engine_data(json_data) + return engine_object['projects'] + + +def get_engine_gems() -> dict: + json_data = load_o3de_manifest() + engine_object = find_engine_data(json_data) + return engine_object['gems'] + + +def get_engine_templates() -> dict: + json_data = load_o3de_manifest() + engine_object = find_engine_data(json_data) + return engine_object['templates'] + + +def get_engine_restricted() -> dict: + json_data = load_o3de_manifest() + engine_object = find_engine_data(json_data) + return engine_object['restricted'] + + +def get_external_subdirectories() -> dict: + json_data = load_o3de_manifest() + engine_object = find_engine_data(json_data) + return engine_object['external_subdirectories'] + + +def get_all_projects() -> dict: + json_data = load_o3de_manifest() + engine_object = find_engine_data(json_data) + projects_data = json_data['projects'].copy() + projects_data.extend(engine_object['projects']) + return projects_data + + +def get_all_gems() -> dict: + json_data = load_o3de_manifest() + engine_object = find_engine_data(json_data) + gems_data = json_data['gems'].copy() + gems_data.extend(engine_object['gems']) + return gems_data + + +def get_all_templates() -> dict: + json_data = load_o3de_manifest() + engine_object = find_engine_data(json_data) + templates_data = json_data['templates'].copy() + templates_data.extend(engine_object['templates']) + return templates_data + + +def get_all_restricted() -> dict: + json_data = load_o3de_manifest() + engine_object = find_engine_data(json_data) + restricted_data = json_data['restricted'].copy() + restricted_data.extend(engine_object['restricted']) + return restricted_data + + +def print_this_engine(verbose: int) -> None: + engine_data = get_this_engine() + print(json.dumps(engine_data, indent=4)) + if verbose > 0: + print_engines_data(engine_data) + + +def print_engines(verbose: int) -> None: + engines_data = get_engines() + print(json.dumps(engines_data, indent=4)) + if verbose > 0: + print_engines_data(engines_data) + + +def print_projects(verbose: int) -> None: + projects_data = get_projects() + print(json.dumps(projects_data, indent=4)) + if verbose > 0: + print_projects_data(projects_data) + + +def print_gems(verbose: int) -> None: + gems_data = get_gems() + print(json.dumps(gems_data, indent=4)) + if verbose > 0: + print_gems_data(gems_data) + + +def print_templates(verbose: int) -> None: + templates_data = get_templates() + print(json.dumps(templates_data, indent=4)) + if verbose > 0: + print_templates_data(templates_data) + + +def print_restricted(verbose: int) -> None: + restricted_data = get_restricted() + print(json.dumps(restricted_data, indent=4)) + if verbose > 0: + print_restricted_data(restricted_data) + + +def register_show_repos(verbose: int) -> None: + repos_data = get_repos() + print(json.dumps(repos_data, indent=4)) + if verbose > 0: + print_repos_data(repos_data) + + +def print_engine_projects(verbose: int) -> None: + engine_projects_data = get_engine_projects() + print(json.dumps(engine_projects_data, indent=4)) + if verbose > 0: + print_projects_data(engine_projects_data) + + +def print_engine_gems(verbose: int) -> None: + engine_gems_data = get_engine_gems() + print(json.dumps(engine_gems_data, indent=4)) + if verbose > 0: + print_gems_data(engine_gems_data) + + +def print_engine_templates(verbose: int) -> None: + engine_templates_data = get_engine_templates() + print(json.dumps(engine_templates_data, indent=4)) + if verbose > 0: + print_templates_data(engine_templates_data) + + +def print_engine_restricted(verbose: int) -> None: + engine_restricted_data = get_engine_restricted() + print(json.dumps(engine_restricted_data, indent=4)) + if verbose > 0: + print_restricted_data(engine_restricted_data) + + +def print_external_subdirectories(verbose: int) -> None: + external_subdirs_data = get_external_subdirectories() + print(json.dumps(external_subdirs_data, indent=4)) + + +def print_all_projects(verbose: int) -> None: + all_projects_data = get_all_projects() + print(json.dumps(all_projects_data, indent=4)) + if verbose > 0: + print_projects_data(all_projects_data) + + +def print_all_gems(verbose: int) -> None: + all_gems_data = get_all_gems() + print(json.dumps(all_gems_data, indent=4)) + if verbose > 0: + print_gems_data(all_gems_data) + + +def print_all_templates(verbose: int) -> None: + all_templates_data = get_all_templates() + print(json.dumps(all_templates_data, indent=4)) + if verbose > 0: + print_templates_data(all_templates_data) + + +def print_all_restricted(verbose: int) -> None: + all_restricted_data = get_all_restricted() + print(json.dumps(all_restricted_data, indent=4)) + if verbose > 0: + print_restricted_data(all_restricted_data) + + +def register_show(verbose: int) -> None: + json_data = load_o3de_manifest() + print(f"{get_o3de_manifest()}:") + print(json.dumps(json_data, indent=4)) + + if verbose > 0: + print_engines_data(get_engines()) + print_projects_data(get_all_projects()) + print_gems_data(get_gems()) + print_templates_data(get_all_templates()) + print_restricted_data(get_all_restricted()) + print_repos_data(get_repos()) + + +def find_engine_data(json_data: dict, + engine_path: str or pathlib.Path = None) -> dict or None: + if not engine_path: + engine_path = get_this_engine_path() + engine_path = pathlib.Path(engine_path).resolve() + + for engine_object in json_data['engines']: + engine_object_path = pathlib.Path(engine_object['path']).resolve() + if engine_path == engine_object_path: + return engine_object + + return None + + +def get_engine_data(engine_name: str = None, + engine_path: str or pathlib.Path = None, ) -> dict or None: + if not engine_name and not engine_path: + logger.error('Must specify either a Engine name or Engine Path.') + return 1 + + if engine_name and not engine_path: + engine_path = get_registered(engine_name=engine_name) + + if not engine_path: + logger.error(f'Engine Path {engine_path} has not been registered.') + return 1 + + engine_path = pathlib.Path(engine_path).resolve() + engine_json = engine_path / 'engine.json' + if not engine_json.is_file(): + logger.error(f'Engine json {engine_json} is not present.') + return 1 + if not valid_o3de_engine_json(engine_json): + logger.error(f'Engine json {engine_json} is not valid.') + return 1 + + with engine_json.open('r') as f: + try: + engine_json_data = json.load(f) + except Exception as e: + logger.warn(f'{engine_json} failed to load: {str(e)}') + else: + return engine_json_data + + return None + + +def get_project_data(project_name: str = None, + project_path: str or pathlib.Path = None, ) -> dict or None: + if not project_name and not project_path: + logger.error('Must specify either a Project name or Project Path.') + return 1 + + if project_name and not project_path: + project_path = get_registered(project_name=project_name) + + if not project_path: + logger.error(f'Project Path {project_path} has not been registered.') + return 1 + + project_path = pathlib.Path(project_path).resolve() + project_json = project_path / 'project.json' + if not project_json.is_file(): + logger.error(f'Project json {project_json} is not present.') + return 1 + if not valid_o3de_project_json(project_json): + logger.error(f'Project json {project_json} is not valid.') + return 1 + + with project_json.open('r') as f: + try: + project_json_data = json.load(f) + except Exception as e: + logger.warn(f'{project_json} failed to load: {str(e)}') + else: + return project_json_data + + return None + + +def get_gem_data(gem_name: str = None, + gem_path: str or pathlib.Path = None, ) -> dict or None: + if not gem_name and not gem_path: + logger.error('Must specify either a Gem name or Gem Path.') + return 1 + + if gem_name and not gem_path: + gem_path = get_registered(gem_name=gem_name) + + if not gem_path: + logger.error(f'Gem Path {gem_path} has not been registered.') + return 1 + + gem_path = pathlib.Path(gem_path).resolve() + gem_json = gem_path / 'gem.json' + if not gem_json.is_file(): + logger.error(f'Gem json {gem_json} is not present.') + return 1 + if not valid_o3de_gem_json(gem_json): + logger.error(f'Gem json {gem_json} is not valid.') + return 1 + + with gem_json.open('r') as f: + try: + gem_json_data = json.load(f) + except Exception as e: + logger.warn(f'{gem_json} failed to load: {str(e)}') + else: + return gem_json_data + + return None + + +def get_template_data(template_name: str = None, + template_path: str or pathlib.Path = None, ) -> dict or None: + if not template_name and not template_path: + logger.error('Must specify either a Template name or Template Path.') + return 1 + + if template_name and not template_path: + template_path = get_registered(template_name=template_name) + + if not template_path: + logger.error(f'Template Path {template_path} has not been registered.') + return 1 + + template_path = pathlib.Path(template_path).resolve() + template_json = template_path / 'template.json' + if not template_json.is_file(): + logger.error(f'Template json {template_json} is not present.') + return 1 + if not valid_o3de_template_json(template_json): + logger.error(f'Template json {template_json} is not valid.') + return 1 + + with template_json.open('r') as f: + try: + template_json_data = json.load(f) + except Exception as e: + logger.warn(f'{template_json} failed to load: {str(e)}') + else: + return template_json_data + + return None + + +def get_restricted_data(restricted_name: str = None, + restricted_path: str or pathlib.Path = None, ) -> dict or None: + if not restricted_name and not restricted_path: + logger.error('Must specify either a Restricted name or Restricted Path.') + return 1 + + if restricted_name and not restricted_path: + restricted_path = get_registered(restricted_name=restricted_name) + + if not restricted_path: + logger.error(f'Restricted Path {restricted_path} has not been registered.') + return 1 + + restricted_path = pathlib.Path(restricted_path).resolve() + restricted_json = restricted_path / 'restricted.json' + if not restricted_json.is_file(): + logger.error(f'Restricted json {restricted_json} is not present.') + return 1 + if not valid_o3de_restricted_json(restricted_json): + logger.error(f'Restricted json {restricted_json} is not valid.') + return 1 + + with restricted_json.open('r') as f: + try: + restricted_json_data = json.load(f) + except Exception as e: + logger.warn(f'{restricted_json} failed to load: {str(e)}') + else: + return restricted_json_data + + return None + + +def get_downloadables() -> dict: + json_data = load_o3de_manifest() + downloadable_data = {} + downloadable_data.update({'engines': []}) + downloadable_data.update({'projects': []}) + downloadable_data.update({'gems': []}) + downloadable_data.update({'templates': []}) + downloadable_data.update({'restricted': []}) + + def recurse_downloadables(repo_uri: str or pathlib.Path) -> None: + cache_folder = get_o3de_cache_folder() + repo_sha256 = hashlib.sha256(repo_uri.encode()) + cache_file = cache_folder / str(repo_sha256.hexdigest() + '.json') + if valid_o3de_repo_json(cache_file): + with cache_file.open('r') as s: + try: + repo_json_data = json.load(s) + except Exception as e: + logger.warn(f'{cache_file} failed to load: {str(e)}') + else: + for engine in repo_json_data['engines']: + if engine not in downloadable_data['engines']: + downloadable_data['engines'].append(engine) + + for project in repo_json_data['projects']: + if project not in downloadable_data['projects']: + downloadable_data['projects'].append(project) + + for gem in repo_json_data['gems']: + if gem not in downloadable_data['gems']: + downloadable_data['gems'].append(gem) + + for template in repo_json_data['templates']: + if template not in downloadable_data['templates']: + downloadable_data['templates'].append(template) + + for restricted in repo_json_data['restricted']: + if restricted not in downloadable_data['restricted']: + downloadable_data['restricted'].append(restricted) + + for repo in repo_json_data['repos']: + if repo not in downloadable_data['repos']: + downloadable_data['repos'].append(repo) + + for repo in downloadable_data['repos']: + recurse_downloadables(repo) + + for repo_entry in json_data['repos']: + recurse_downloadables(repo_entry) + return downloadable_data + + +def get_downloadable_engines() -> dict: + downloadable_data = get_downloadables() + return downloadable_data['engines'] + + +def get_downloadable_projects() -> dict: + downloadable_data = get_downloadables() + return downloadable_data['projects'] + + +def get_downloadable_gems() -> dict: + downloadable_data = get_downloadables() + return downloadable_data['gems'] + + +def get_downloadable_templates() -> dict: + downloadable_data = get_downloadables() + return downloadable_data['templates'] + + +def get_downloadable_restricted() -> dict: + downloadable_data = get_downloadables() + return downloadable_data['restricted'] + + +def print_downloadable_engines(verbose: int) -> None: + downloadable_engines = get_downloadable_engines() + for engine_data in downloadable_engines: + print(json.dumps(engine_data, indent=4)) + if verbose > 0: + print_engines_data(downloadable_engines) + + +def print_downloadable_projects(verbose: int) -> None: + downloadable_projects = get_downloadable_projects() + for projects_data in downloadable_projects: + print(json.dumps(projects_data, indent=4)) + if verbose > 0: + print_projects_data(downloadable_projects) + + +def print_downloadable_gems(verbose: int) -> None: + downloadable_gems = get_downloadable_gems() + for gem_data in downloadable_gems: + print(json.dumps(gem_data, indent=4)) + if verbose > 0: + print_gems_data(downloadable_gems) + + +def print_downloadable_templates(verbose: int) -> None: + downloadable_templates = get_downloadable_templates() + for template_data in downloadable_templates: + print(json.dumps(template_data, indent=4)) + if verbose > 0: + print_engines_data(downloadable_templates) + + +def print_downloadable_restricted(verbose: int) -> None: + downloadable_restricted = get_downloadable_restricted() + for restricted_data in downloadable_restricted: + print(json.dumps(restricted_data, indent=4)) + if verbose > 0: + print_engines_data(downloadable_restricted) + + +def print_downloadables(verbose: int) -> None: + downloadable_data = get_downloadables() + print(json.dumps(downloadable_data, indent=4)) + if verbose > 0: + print_engines_data(downloadable_data['engines']) + print_projects_data(downloadable_data['projects']) + print_gems_data(downloadable_data['gems']) + print_templates_data(downloadable_data['templates']) + print_restricted_data(downloadable_data['templates']) + + +def download_engine(engine_name: str, + dest_path: str) -> int: + if not dest_path: + dest_path = get_registered(default_folder='engines') + if not dest_path: + logger.error(f'Destination path not cannot be empty.') + return 1 + + dest_path = pathlib.Path(dest_path).resolve() + dest_path.mkdir(exist_ok=True) + + download_path = get_o3de_download_folder() / 'engines' / engine_name + download_path.mkdir(exist_ok=True) + download_zip_path = download_path / 'engine.zip' + + downloadable_engine_data = get_downloadable(engine_name=engine_name) + if not downloadable_engine_data: + logger.error(f'Downloadable engine {engine_name} not found.') + return 1 + + origin = downloadable_engine_data['origin'] + url = f'{origin}/project.zip' + parsed_uri = urllib.parse.urlparse(url) + + if download_zip_path.is_file(): + logger.warn(f'Project already downloaded to {download_zip_path}.') + elif parsed_uri.scheme == 'http' or \ + parsed_uri.scheme == 'https' or \ + parsed_uri.scheme == 'ftp' or \ + parsed_uri.scheme == 'ftps': + with urllib.request.urlopen(url) as s: + with download_zip_path.open('wb') as f: + shutil.copyfileobj(s, f) + else: + origin_file = pathlib.Path(url).resolve() + if not origin_file.is_file(): + return 1 + shutil.copy(origin_file, download_zip_path) + + if not zipfile.is_zipfile(download_zip_path): + logger.error(f"Engine zip {download_zip_path} is invalid.") + download_zip_path.unlink() + return 1 + + # if the engine.json has a sha256 check it against a sha256 of the zip + try: + sha256A = downloadable_engine_data['sha256'] + except Exception as e: + logger.warn(f'SECURITY WARNING: The advertised engine you downloaded has no "sha256"!!! Be VERY careful!!!' + f' We cannot verify this is the actually the advertised engine!!!') + else: + sha256B = hashlib.sha256(download_zip_path.open('rb').read()).hexdigest() + if sha256A != sha256B: + logger.error(f'SECURITY VIOLATION: Downloaded engine.zip sha256 {sha256B} does not match' + f' the advertised "sha256":{sha256A} in the engine.json. Deleting unzipped files!!!') + shutil.rmtree(dest_path) + return 1 + + dest_engine_folder = dest_path / engine_name + if dest_engine_folder.is_dir(): + backup_folder(dest_engine_folder) + with zipfile.ZipFile(download_zip_path, 'r') as project_zip: + try: + project_zip.extractall(dest_path) + except Exception as e: + logger.error(f'UnZip exception:{str(e)}') + shutil.rmtree(dest_path) + return 1 + + unzipped_engine_json = dest_engine_folder / 'engine.json' + if not unzipped_engine_json.is_file(): + logger.error(f'Engine json {unzipped_engine_json} is missing.') + return 1 + + if not valid_o3de_engine_json(unzipped_engine_json): + logger.error(f'Engine json {unzipped_engine_json} is invalid.') + return 1 + + # remove the sha256 if present in the advertised downloadable engine.json + # then compare it to the engine.json in the zip, they should now be identical + try: + del downloadable_engine_data['sha256'] + except Exception as e: + pass + + sha256A = hashlib.sha256(json.dumps(downloadable_engine_data, indent=4).encode('utf8')).hexdigest() + with unzipped_engine_json.open('r') as s: + try: + unzipped_engine_json_data = json.load(s) + except Exception as e: + logger.error(f'Failed to read engine json {unzipped_engine_json}. Unable to confirm this' + f' is the same template that was advertised.') + return 1 + sha256B = hashlib.sha256(json.dumps(unzipped_engine_json_data, indent=4).encode('utf8')).hexdigest() + if sha256A != sha256B: + logger.error(f'SECURITY VIOLATION: Downloaded engine.json does not match' + f' the advertised engine.json. Deleting unzipped files!!!') + shutil.rmtree(dest_path) + return 1 + + return 0 + + +def download_project(project_name: str, + dest_path: str or pathlib.Path) -> int: + if not dest_path: + dest_path = get_registered(default_folder='projects') + if not dest_path: + logger.error(f'Destination path not specified and not default projects path.') + return 1 + + dest_path = pathlib.Path(dest_path).resolve() + dest_path.mkdir(exist_ok=True, parents=True) + + download_path = get_o3de_download_folder() / 'projects' / project_name + download_path.mkdir(exist_ok=True, parents=True) + download_zip_path = download_path / 'project.zip' + + downloadable_project_data = get_downloadable(project_name=project_name) + if not downloadable_project_data: + logger.error(f'Downloadable project {project_name} not found.') + return 1 + + origin = downloadable_project_data['origin'] + url = f'{origin}/project.zip' + parsed_uri = urllib.parse.urlparse(url) + + if download_zip_path.is_file(): + logger.warn(f'Project already downloaded to {download_zip_path}.') + elif parsed_uri.scheme == 'http' or \ + parsed_uri.scheme == 'https' or \ + parsed_uri.scheme == 'ftp' or \ + parsed_uri.scheme == 'ftps': + with urllib.request.urlopen(url) as s: + with download_zip_path.open('wb') as f: + shutil.copyfileobj(s, f) + else: + origin_file = pathlib.Path(url).resolve() + if not origin_file.is_file(): + return 1 + shutil.copy(origin_file, download_zip_path) + + if not zipfile.is_zipfile(download_zip_path): + logger.error(f"Project zip {download_zip_path} is invalid.") + download_zip_path.unlink() + return 1 + + # if the project.json has a sha256 check it against a sha256 of the zip + try: + sha256A = downloadable_project_data['sha256'] + except Exception as e: + logger.warn(f'SECURITY WARNING: The advertised project you downloaded has no "sha256"!!! Be VERY careful!!!' + f' We cannot verify this is the actually the advertised project!!!') + else: + sha256B = hashlib.sha256(download_zip_path.open('rb').read()).hexdigest() + if sha256A != sha256B: + logger.error(f'SECURITY VIOLATION: Downloaded project.zip sha256 {sha256B} does not match' + f' the advertised "sha256":{sha256A} in the project.json. Deleting unzipped files!!!') + shutil.rmtree(dest_path) + return 1 + + dest_project_folder = dest_path / project_name + if dest_project_folder.is_dir(): + backup_folder(dest_project_folder) + with zipfile.ZipFile(download_zip_path, 'r') as project_zip: + try: + project_zip.extractall(dest_project_folder) + except Exception as e: + logger.error(f'UnZip exception:{str(e)}') + shutil.rmtree(dest_path) + return 1 + + unzipped_project_json = dest_project_folder / 'project.json' + if not unzipped_project_json.is_file(): + logger.error(f'Project json {unzipped_project_json} is missing.') + return 1 + + if not valid_o3de_project_json(unzipped_project_json): + logger.error(f'Project json {unzipped_project_json} is invalid.') + return 1 + + # remove the sha256 if present in the advertised downloadable project.json + # then compare it to the project.json in the zip, they should now be identical + try: + del downloadable_project_data['sha256'] + except Exception as e: + pass + + sha256A = hashlib.sha256(json.dumps(downloadable_project_data, indent=4).encode('utf8')).hexdigest() + with unzipped_project_json.open('r') as s: + try: + unzipped_project_json_data = json.load(s) + except Exception as e: + logger.error(f'Failed to read Project json {unzipped_project_json}. Unable to confirm this' + f' is the same project that was advertised.') + return 1 + sha256B = hashlib.sha256(json.dumps(unzipped_project_json_data, indent=4).encode('utf8')).hexdigest() + if sha256A != sha256B: + logger.error(f'SECURITY VIOLATION: Downloaded project.json does not match' + f' the advertised project.json. Deleting unzipped files!!!') + shutil.rmtree(dest_path) + return 1 + + return 0 + + +def download_gem(gem_name: str, + dest_path: str or pathlib.Path) -> int: + if not dest_path: + dest_path = get_registered(default_folder='gems') + if not dest_path: + logger.error(f'Destination path not cannot be empty.') + return 1 + + dest_path = pathlib.Path(dest_path).resolve() + dest_path.mkdir(exist_ok=True, parents=True) + + download_path = get_o3de_download_folder() / 'gems' / gem_name + download_path.mkdir(exist_ok=True, parents=True) + download_zip_path = download_path / 'gem.zip' + + downloadable_gem_data = get_downloadable(gem_name=gem_name) + if not downloadable_gem_data: + logger.error(f'Downloadable gem {gem_name} not found.') + return 1 + + origin = downloadable_gem_data['origin'] + url = f'{origin}/gem.zip' + parsed_uri = urllib.parse.urlparse(url) + + if download_zip_path.is_file(): + logger.warn(f'Project already downloaded to {download_zip_path}.') + elif parsed_uri.scheme == 'http' or \ + parsed_uri.scheme == 'https' or \ + parsed_uri.scheme == 'ftp' or \ + parsed_uri.scheme == 'ftps': + with urllib.request.urlopen(url) as s: + with download_zip_path.open('wb') as f: + shutil.copyfileobj(s, f) + else: + origin_file = pathlib.Path(url).resolve() + if not origin_file.is_file(): + return 1 + shutil.copy(origin_file, download_zip_path) + + if not zipfile.is_zipfile(download_zip_path): + logger.error(f"Gem zip {download_zip_path} is invalid.") + download_zip_path.unlink() + return 1 + + # if the gem.json has a sha256 check it against a sha256 of the zip + try: + sha256A = downloadable_gem_data['sha256'] + except Exception as e: + logger.warn(f'SECURITY WARNING: The advertised gem you downloaded has no "sha256"!!! Be VERY careful!!!' + f' We cannot verify this is the actually the advertised gem!!!') + else: + sha256B = hashlib.sha256(download_zip_path.open('rb').read()).hexdigest() + if sha256A != sha256B: + logger.error(f'SECURITY VIOLATION: Downloaded gem.zip sha256 {sha256B} does not match' + f' the advertised "sha256":{sha256A} in the gem.json. Deleting unzipped files!!!') + shutil.rmtree(dest_path) + return 1 + + dest_gem_folder = dest_path / gem_name + if dest_gem_folder.is_dir(): + backup_folder(dest_gem_folder) + with zipfile.ZipFile(download_zip_path, 'r') as gem_zip: + try: + gem_zip.extractall(dest_path) + except Exception as e: + logger.error(f'UnZip exception:{str(e)}') + shutil.rmtree(dest_path) + return 1 + + unzipped_gem_json = dest_gem_folder / 'gem.json' + if not unzipped_gem_json.is_file(): + logger.error(f'Engine json {unzipped_gem_json} is missing.') + return 1 + + if not valid_o3de_engine_json(unzipped_gem_json): + logger.error(f'Engine json {unzipped_gem_json} is invalid.') + return 1 + + # remove the sha256 if present in the advertised downloadable gem.json + # then compare it to the gem.json in the zip, they should now be identical + try: + del downloadable_gem_data['sha256'] + except Exception as e: + pass + + sha256A = hashlib.sha256(json.dumps(downloadable_gem_data, indent=4).encode('utf8')).hexdigest() + with unzipped_gem_json.open('r') as s: + try: + unzipped_gem_json_data = json.load(s) + except Exception as e: + logger.error(f'Failed to read gem json {unzipped_gem_json}. Unable to confirm this' + f' is the same gem that was advertised.') + return 1 + sha256B = hashlib.sha256(json.dumps(unzipped_gem_json_data, indent=4).encode('utf8')).hexdigest() + if sha256A != sha256B: + logger.error(f'SECURITY VIOLATION: Downloaded gem.json does not match' + f' the advertised gem.json. Deleting unzipped files!!!') + shutil.rmtree(dest_path) + return 1 + + return 0 + + +def download_template(template_name: str, + dest_path: str or pathlib.Path) -> int: + if not dest_path: + dest_path = get_registered(default_folder='templates') + if not dest_path: + logger.error(f'Destination path not cannot be empty.') + return 1 + + dest_path = pathlib.Path(dest_path).resolve() + dest_path.mkdir(exist_ok=True, parents=True) + + download_path = get_o3de_download_folder() / 'templates' / template_name + download_path.mkdir(exist_ok=True, parents=True) + download_zip_path = download_path / 'template.zip' + + downloadable_template_data = get_downloadable(template_name=template_name) + if not downloadable_template_data: + logger.error(f'Downloadable template {template_name} not found.') + return 1 + + origin = downloadable_template_data['origin'] + url = f'{origin}/project.zip' + parsed_uri = urllib.parse.urlparse(url) + + result = 0 + + if download_zip_path.is_file(): + logger.warn(f'Project already downloaded to {download_zip_path}.') + elif parsed_uri.scheme == 'http' or \ + parsed_uri.scheme == 'https' or \ + parsed_uri.scheme == 'ftp' or \ + parsed_uri.scheme == 'ftps': + with urllib.request.urlopen(url) as s: + with download_zip_path.open('wb') as f: + shutil.copyfileobj(s, f) + else: + origin_file = pathlib.Path(url).resolve() + if not origin_file.is_file(): + return 1 + shutil.copy(origin_file, download_zip_path) + + if not zipfile.is_zipfile(download_zip_path): + logger.error(f"Template zip {download_zip_path} is invalid.") + download_zip_path.unlink() + return 1 + + # if the template.json has a sha256 check it against a sha256 of the zip + try: + sha256A = downloadable_template_data['sha256'] + except Exception as e: + logger.warn(f'SECURITY WARNING: The advertised template you downloaded has no "sha256"!!! Be VERY careful!!!' + f' We cannot verify this is the actually the advertised template!!!') + else: + sha256B = hashlib.sha256(download_zip_path.open('rb').read()).hexdigest() + if sha256A != sha256B: + logger.error(f'SECURITY VIOLATION: Downloaded template.zip sha256 {sha256B} does not match' + f' the advertised "sha256":{sha256A} in the template.json. Deleting unzipped files!!!') + shutil.rmtree(dest_path) + return 1 + + dest_template_folder = dest_path / template_name + if dest_template_folder.is_dir(): + backup_folder(dest_template_folder) + with zipfile.ZipFile(download_zip_path, 'r') as project_zip: + try: + project_zip.extractall(dest_path) + except Exception as e: + logger.error(f'UnZip exception:{str(e)}') + shutil.rmtree(dest_path) + return 1 + + unzipped_template_json = dest_template_folder / 'template.json' + if not unzipped_template_json.is_file(): + logger.error(f'Template json {unzipped_template_json} is missing.') + return 1 + + if not valid_o3de_engine_json(unzipped_template_json): + logger.error(f'Template json {unzipped_template_json} is invalid.') + return 1 + + # remove the sha256 if present in the advertised downloadable template.json + # then compare it to the template.json in the zip, they should now be identical + try: + del downloadable_template_data['sha256'] + except Exception as e: + pass + + sha256A = hashlib.sha256(json.dumps(downloadable_template_data, indent=4).encode('utf8')).hexdigest() + with unzipped_template_json.open('r') as s: + try: + unzipped_template_json_data = json.load(s) + except Exception as e: + logger.error(f'Failed to read Template json {unzipped_template_json}. Unable to confirm this' + f' is the same template that was advertised.') + return 1 + sha256B = hashlib.sha256(json.dumps(unzipped_template_json_data, indent=4).encode('utf8')).hexdigest() + if sha256A != sha256B: + logger.error(f'SECURITY VIOLATION: Downloaded template.json does not match' + f' the advertised template.json. Deleting unzipped files!!!') + shutil.rmtree(dest_path) + return 1 + + return 0 + + +def download_restricted(restricted_name: str, + dest_path: str or pathlib.Path) -> int: + if not dest_path: + dest_path = get_registered(default_folder='restricted') + if not dest_path: + logger.error(f'Destination path not cannot be empty.') + return 1 + + dest_path = pathlib.Path(dest_path).resolve() + dest_path.mkdir(exist_ok=True, parents=True) + + download_path = get_o3de_download_folder() / 'restricted' / restricted_name + download_path.mkdir(exist_ok=True, parents=True) + download_zip_path = download_path / 'restricted.zip' + + downloadable_restricted_data = get_downloadable(restricted_name=restricted_name) + if not downloadable_restricted_data: + logger.error(f'Downloadable Restricted {restricted_name} not found.') + return 1 + + origin = downloadable_restricted_data['origin'] + url = f'{origin}/restricted.zip' + parsed_uri = urllib.parse.urlparse(url) + + if download_zip_path.is_file(): + logger.warn(f'Restricted already downloaded to {download_zip_path}.') + elif parsed_uri.scheme == 'http' or \ + parsed_uri.scheme == 'https' or \ + parsed_uri.scheme == 'ftp' or \ + parsed_uri.scheme == 'ftps': + with urllib.request.urlopen(url) as s: + with download_zip_path.open('wb') as f: + shutil.copyfileobj(s, f) + else: + origin_file = pathlib.Path(url).resolve() + if not origin_file.is_file(): + return 1 + shutil.copy(origin_file, download_zip_path) + + if not zipfile.is_zipfile(download_zip_path): + logger.error(f"Restricted zip {download_zip_path} is invalid.") + download_zip_path.unlink() + return 1 + + # if the restricted.json has a sha256 check it against a sha256 of the zip + try: + sha256A = downloadable_restricted_data['sha256'] + except Exception as e: + logger.warn(f'SECURITY WARNING: The advertised restricted you downloaded has no "sha256"!!! Be VERY careful!!!' + f' We cannot verify this is the actually the advertised restricted!!!') + else: + sha256B = hashlib.sha256(download_zip_path.open('rb').read()).hexdigest() + if sha256A != sha256B: + logger.error(f'SECURITY VIOLATION: Downloaded restricted.zip sha256 {sha256B} does not match' + f' the advertised "sha256":{sha256A} in the restricted.json. Deleting unzipped files!!!') + shutil.rmtree(dest_path) + return 1 + + dest_restricted_folder = dest_path / restricted_name + if dest_restricted_folder.is_dir(): + backup_folder(dest_restricted_folder) + with zipfile.ZipFile(download_zip_path, 'r') as project_zip: + try: + project_zip.extractall(dest_path) + except Exception as e: + logger.error(f'UnZip exception:{str(e)}') + shutil.rmtree(dest_path) + return 1 + + unzipped_restricted_json = dest_restricted_folder / 'restricted.json' + if not unzipped_restricted_json.is_file(): + logger.error(f'Restricted json {unzipped_restricted_json} is missing.') + return 1 + + if not valid_o3de_engine_json(unzipped_restricted_json): + logger.error(f'Restricted json {unzipped_restricted_json} is invalid.') + return 1 + + # remove the sha256 if present in the advertised downloadable restricted.json + # then compare it to the restricted.json in the zip, they should now be identical + try: + del downloadable_restricted_data['sha256'] + except Exception as e: + pass + + sha256A = hashlib.sha256(json.dumps(downloadable_restricted_data, indent=4).encode('utf8')).hexdigest() + with unzipped_restricted_json.open('r') as s: + try: + unzipped_restricted_json_data = json.load(s) + except Exception as e: + logger.error( + f'Failed to read Restricted json {unzipped_restricted_json}. Unable to confirm this' + f' is the same restricted that was advertised.') + return 1 + sha256B = hashlib.sha256( + json.dumps(unzipped_restricted_json_data, indent=4).encode('utf8')).hexdigest() + if sha256A != sha256B: + logger.error(f'SECURITY VIOLATION: Downloaded restricted.json does not match' + f' the advertised restricted.json. Deleting unzipped files!!!') + shutil.rmtree(dest_path) + return 1 + + return 0 + + +def add_gem_dependency(cmake_file: str or pathlib.Path, + gem_target: str) -> int: + """ + adds a gem dependency to a cmake file + :param cmake_file: path to the cmake file + :param gem_target: name of the cmake target + :return: 0 for success or non 0 failure code + """ + if not os.path.isfile(cmake_file): + logger.error(f'Failed to locate cmake file {cmake_file}') + return 1 + + # on a line by basis, see if there already is Gem::{gem_name} + # find the first occurrence of a gem, copy its formatting and replace + # the gem name with the new one and append it + # if the gem is already present fail + t_data = [] + added = False + with open(cmake_file, 'r') as s: + for line in s: + if f'Gem::{gem_target}' in line: + logger.warning(f'{gem_target} is already a gem dependency.') + return 0 + if not added and r'Gem::' in line: + new_gem = ' ' * line.find(r'Gem::') + f'Gem::{gem_target}\n' + t_data.append(new_gem) + added = True + t_data.append(line) + + # if we didn't add it the set gem dependencies could be empty so + # add a new gem, if empty the correct format is 1 tab=4spaces + if not added: + index = 0 + for line in t_data: + index = index + 1 + if r'set(GEM_DEPENDENCIES' in line: + t_data.insert(index, f' Gem::{gem_target}\n') + added = True + break + + # if we didn't add it then it's not here, add a whole new one + if not added: + t_data.append('\n') + t_data.append('set(GEM_DEPENDENCIES\n') + t_data.append(f' Gem::{gem_target}\n') + t_data.append(')\n') + + # write the cmake + os.unlink(cmake_file) + with open(cmake_file, 'w') as s: + s.writelines(t_data) + + return 0 + + +def get_project_runtime_gem_targets(project_path: str or pathlib.Path, + platform: str = 'Common') -> set: + return get_gem_targets_from_cmake_file(get_dependencies_cmake_file(project_path=project_path, dependency_type='runtime', platform=platform)) + + +def get_project_tool_gem_targets(project_path: str or pathlib.Path, + platform: str = 'Common') -> set: + return get_gem_targets_from_cmake_file(get_dependencies_cmake_file(project_path=project_path, dependency_type='tool', platform=platform)) + + +def get_project_server_gem_targets(project_path: str or pathlib.Path, + platform: str = 'Common') -> set: + return get_gem_targets_from_cmake_file(get_dependencies_cmake_file(project_path=project_path, dependency_type='server', platform=platform)) + + +def get_project_gem_targets(project_path: str or pathlib.Path, + platform: str = 'Common') -> set: + runtime_gems = get_gem_targets_from_cmake_file(get_dependencies_cmake_file(project_path=project_path, dependency_type='runtime', platform=platform)) + tool_gems = get_gem_targets_from_cmake_file(get_dependencies_cmake_file(project_path=project_path, dependency_type='tool', platform=platform)) + server_gems = get_gem_targets_from_cmake_file(get_dependencies_cmake_file(project_path=project_path, dependency_type='server', platform=platform)) + return runtime_gems.union(tool_gems.union(server_gems)) + + +def get_gem_targets_from_cmake_file(cmake_file: str or pathlib.Path) -> set: + """ + Gets a list of declared gem targets dependencies of a cmake file + :param cmake_file: path to the cmake file + :return: set of gem targets found + """ + cmake_file = pathlib.Path(cmake_file).resolve() + + if not cmake_file.is_file(): + logger.error(f'Failed to locate cmake file {cmake_file}') + return set() + + gem_target_set = set() + with cmake_file.open('r') as s: + for line in s: + gem_name = line.split('Gem::') + if len(gem_name) > 1: + # Only take the name as everything leading up to the first '.' if found + # Gem naming conventions will have GemName.Editor, GemName.Server, and GemName + # as different targets of the GemName Gem + gem_target_set.add(gem_name[1].replace('\n', '')) + return gem_target_set + + +def get_project_runtime_gem_names(project_path: str or pathlib.Path, + platform: str = 'Common') -> set: + return get_gem_names_from_cmake_file(get_dependencies_cmake_file(project_path=project_path, dependency_type='runtime', platform=platform)) + + +def get_project_tool_gem_names(project_path: str or pathlib.Path, + platform: str = 'Common') -> set: + return get_gem_names_from_cmake_file(get_dependencies_cmake_file(project_path=project_path, dependency_type='tool', platform=platform)) + + +def get_project_server_gem_names(project_path: str or pathlib.Path, + platform: str = 'Common') -> set: + return get_gem_names_from_cmake_file(get_dependencies_cmake_file(project_path=project_path, dependency_type='server', platform=platform)) + + +def get_project_gem_names(project_path: str or pathlib.Path, + platform: str = 'Common') -> set: + runtime_gem_names = get_gem_names_from_cmake_file(get_dependencies_cmake_file(project_path=project_path, dependency_type='runtime', platform=platform)) + tool_gem_names = get_gem_names_from_cmake_file(get_dependencies_cmake_file(project_path=project_path, dependency_type='tool', platform=platform)) + server_gem_names = get_gem_names_from_cmake_file(get_dependencies_cmake_file(project_path=project_path, dependency_type='server', platform=platform)) + return runtime_gem_names.union(tool_gem_names.union(server_gem_names)) + + +def get_gem_names_from_cmake_file(cmake_file: str or pathlib.Path) -> set: + """ + Gets a list of declared gem dependencies of a cmake file + :param cmake_file: path to the cmake file + :return: set of gems found + """ + cmake_file = pathlib.Path(cmake_file).resolve() + + if not cmake_file.is_file(): + logger.error(f'Failed to locate cmake file {cmake_file}') + return set() + + gem_set = set() + with cmake_file.open('r') as s: + for line in s: + gem_name = line.split('Gem::') + if len(gem_name) > 1: + # Only take the name as everything leading up to the first '.' if found + # Gem naming conventions will have GemName.Editor, GemName.Server, and GemName + # as different targets of the GemName Gem + gem_set.add(gem_name[1].split('.')[0].replace('\n', '')) + return gem_set + + +def get_project_runtime_gem_paths(project_path: str or pathlib.Path, + platform: str = 'Common') -> set: + gem_names = get_project_runtime_gem_names(project_path, platform) + gem_paths = set() + for gem_name in gem_names: + gem_paths.add(get_registered(gem_name=gem_name)) + return gem_paths + + +def get_project_tool_gem_paths(project_path: str or pathlib.Path, + platform: str = 'Common') -> set: + gem_names = get_project_tool_gem_names(project_path, platform) + gem_paths = set() + for gem_name in gem_names: + gem_paths.add(get_registered(gem_name=gem_name)) + return gem_paths + + +def get_project_server_gem_paths(project_path: str or pathlib.Path, + platform: str = 'Common') -> set: + gem_names = get_project_server_gem_names(project_path, platform) + gem_paths = set() + for gem_name in gem_names: + gem_paths.add(get_registered(gem_name=gem_name)) + return gem_paths + + +def get_project_gem_paths(project_path: str or pathlib.Path, + platform: str = 'Common') -> set: + gem_names = get_project_gem_names(project_path, platform) + gem_paths = set() + for gem_name in gem_names: + gem_paths.add(get_registered(gem_name=gem_name)) + return gem_paths + + +def remove_gem_dependency(cmake_file: str or pathlib.Path, + gem_target: str) -> int: + """ + removes a gem dependency from a cmake file + :param cmake_file: path to the cmake file + :param gem_target: cmake target name + :return: 0 for success or non 0 failure code + """ + if not os.path.isfile(cmake_file): + logger.error(f'Failed to locate cmake file {cmake_file}') + return 1 + + # on a line by basis, remove any line with Gem::{gem_name} + t_data = [] + # Remove the gem from the cmake_dependencies file by skipping the gem name entry + removed = False + with open(cmake_file, 'r') as s: + for line in s: + if f'Gem::{gem_target}' in line: + removed = True + else: + t_data.append(line) + + if not removed: + logger.error(f'Failed to remove Gem::{gem_target} from cmake file {cmake_file}') + return 1 + + # write the cmake + os.unlink(cmake_file) + with open(cmake_file, 'w') as s: + s.writelines(t_data) + + return 0 + + +def get_project_templates(): # temporary until we have a better way to do this... maybe template_type element + project_templates = [] + for template in get_all_templates(): + if 'Project' in template: + project_templates.append(template) + return project_templates + + +def get_gem_templates(): # temporary until we have a better way to do this... maybe template_type element + gem_templates = [] + for template in get_all_templates(): + if 'Gem' in template: + gem_templates.append(template) + return gem_templates + + +def get_generic_templates(): # temporary until we have a better way to do this... maybe template_type element + generic_templates = [] + for template in get_all_templates(): + if 'Project' not in template and 'Gem' not in template: + generic_templates.append(template) + return generic_templates + + +def get_dependencies_cmake_file(project_name: str = None, + project_path: str or pathlib.Path = None, + dependency_type: str = 'runtime', + platform: str = 'Common') -> str or None: + """ + get the standard cmake file name for a particular type of dependency + :param gem_name: name of the gem, resolves gem_path + :param gem_path: path of the gem + :return: list of gem targets + """ + if not project_name and not project_path: + logger.error(f'Must supply either a Project Name or Project Path.') + return None + + if project_name and not project_path: + project_path = get_registered(project_name=project_name) + + project_path = pathlib.Path(project_path).resolve() + + if platform == 'Common': + dependencies_file = f'{dependency_type}_dependencies.cmake' + dependencies_file_path = project_path / 'Gem/Code' / dependencies_file + if dependencies_file_path.is_file(): + return dependencies_file_path + return project_path / 'Code' / dependencies_file + else: + dependencies_file = f'{platform.lower()}_{dependency_type}_dependencies.cmake' + dependencies_file_path = project_path / 'Gem/Code/Platform' / platform / dependencies_file + if dependencies_file_path.is_file(): + return dependencies_file_path + return project_path / 'Code/Platform' / platform / dependencies_file + + +def get_all_gem_targets() -> list: + modules = [] + for gem_path in get_all_gems(): + this_gems_targets = get_gem_targets(gem_path=gem_path) + modules.extend(this_gems_targets) + return modules + + +def get_gem_targets(gem_name: str = None, + gem_path: str or pathlib.Path = None) -> list: + """ + Finds gem targets in a gem + :param gem_name: name of the gem, resolves gem_path + :param gem_path: path of the gem + :return: list of gem targets + """ + if not gem_name and not gem_path: + return [] + + if gem_name and not gem_path: + gem_path = get_registered(gem_name=gem_name) + + if not gem_path: + return [] + + gem_path = pathlib.Path(gem_path).resolve() + gem_json = gem_path / 'gem.json' + if not valid_o3de_gem_json(gem_json): + return [] + + module_identifiers = [ + 'MODULE', + 'GEM_MODULE', + '${PAL_TRAIT_MONOLITHIC_DRIVEN_MODULE_TYPE}' + ] + modules = [] + for root, dirs, files in os.walk(gem_path): + for file in files: + if file == 'CMakeLists.txt': + with open(os.path.join(root, file), 'r') as s: + for line in s: + trimmed = line.lstrip() + if trimmed.startswith('NAME '): + trimmed = trimmed.rstrip(' \n') + split_trimmed = trimmed.split(' ') + if len(split_trimmed) == 3 and split_trimmed[2] in module_identifiers: + modules.append(split_trimmed[1]) + return modules + + +def add_external_subdirectory(external_subdir: str or pathlib.Path, + engine_path: str or pathlib.Path = None, + supress_errors: bool = False) -> int: + """ + add external subdirectory to a cmake + :param external_subdir: external subdirectory to add to cmake + :param engine_path: optional engine path, defaults to this engine + :param supress_errors: optional silence errors + :return: 0 for success or non 0 failure code + """ + external_subdir = pathlib.Path(external_subdir).resolve() + if not external_subdir.is_dir(): + if not supress_errors: + logger.error(f'Add External Subdirectory Failed: {external_subdir} does not exist.') + return 1 + + external_subdir_cmake = external_subdir / 'CMakeLists.txt' + if not external_subdir_cmake.is_file(): + if not supress_errors: + logger.error(f'Add External Subdirectory Failed: {external_subdir} does not contain a CMakeLists.txt.') + return 1 + + json_data = load_o3de_manifest() + engine_object = find_engine_data(json_data, engine_path) + if not engine_object: + if not supress_errors: + logger.error(f'Add External Subdirectory Failed: {engine_path} not registered.') + return 1 + + while external_subdir.as_posix() in engine_object['external_subdirectories']: + engine_object['external_subdirectories'].remove(external_subdir.as_posix()) + + def parse_cmake_file(cmake: str or pathlib.Path, + files: set()): + cmake_path = pathlib.Path(cmake).resolve() + cmake_file = cmake_path + if cmake_path.is_dir(): + files.add(cmake_path) + cmake_file = cmake_path / 'CMakeLists.txt' + elif cmake_path.is_file(): + cmake_path = cmake_path.parent + else: + return + + with cmake_file.open('r') as s: + lines = s.readlines() + for line in lines: + line = line.strip() + start = line.find('include(') + if start == 0: + end = line.find(')', start) + if end > start + len('include('): + try: + include_cmake_file = pathlib.Path(engine_path / line[start + len('include('): end]).resolve() + except Exception as e: + pass + else: + parse_cmake_file(include_cmake_file, files) + else: + start = line.find('add_subdirectory(') + if start == 0: + end = line.find(')', start) + if end > start + len('add_subdirectory('): + try: + include_cmake_file = pathlib.Path( + cmake_path / line[start + len('add_subdirectory('): end]).resolve() + except Exception as e: + pass + else: + parse_cmake_file(include_cmake_file, files) + + cmake_files = set() + parse_cmake_file(engine_path, cmake_files) + for external in engine_object["external_subdirectories"]: + parse_cmake_file(external, cmake_files) + + if external_subdir in cmake_files: + save_o3de_manifest(json_data) + if not supress_errors: + logger.error(f'External subdirectory {external_subdir.as_posix()} already included by add_subdirectory().') + return 1 + + engine_object['external_subdirectories'].insert(0, external_subdir.as_posix()) + engine_object['external_subdirectories'] = sorted(engine_object['external_subdirectories']) + + save_o3de_manifest(json_data) + + return 0 + + +def remove_external_subdirectory(external_subdir: str or pathlib.Path, + engine_path: str or pathlib.Path = None) -> int: + """ + remove external subdirectory from cmake + :param external_subdir: external subdirectory to add to cmake + :param engine_path: optional engine path, defaults to this engine + :return: 0 for success or non 0 failure code + """ + json_data = load_o3de_manifest() + engine_object = find_engine_data(json_data, engine_path) + if not engine_object: + logger.error(f'Remove External Subdirectory Failed: {engine_path} not registered.') + return 1 + + external_subdir = pathlib.Path(external_subdir).resolve() + while external_subdir.as_posix() in engine_object['external_subdirectories']: + engine_object['external_subdirectories'].remove(external_subdir.as_posix()) + + save_o3de_manifest(json_data) + + return 0 + + +def add_gem_to_cmake(gem_name: str = None, + gem_path: str or pathlib.Path = None, + engine_name: str = None, + engine_path: str or pathlib.Path = None, + supress_errors: bool = False) -> int: + """ + add a gem to a cmake as an external subdirectory for an engine + :param gem_name: name of the gem to add to cmake + :param gem_path: the path of the gem to add to cmake + :param engine_name: name of the engine to add to cmake + :param engine_path: the path of the engine to add external subdirectory to, default to this engine + :param supress_errors: optional silence errors + :return: 0 for success or non 0 failure code + """ + if not gem_name and not gem_path: + if not supress_errors: + logger.error('Must specify either a Gem name or Gem Path.') + return 1 + + if gem_name and not gem_path: + gem_path = get_registered(gem_name=gem_name) + + if not gem_path: + if not supress_errors: + logger.error(f'Gem Path {gem_path} has not been registered.') + return 1 + + gem_path = pathlib.Path(gem_path).resolve() + gem_json = gem_path / 'gem.json' + if not gem_json.is_file(): + if not supress_errors: + logger.error(f'Gem json {gem_json} is not present.') + return 1 + if not valid_o3de_gem_json(gem_json): + if not supress_errors: + logger.error(f'Gem json {gem_json} is not valid.') + return 1 + + if not engine_name and not engine_path: + engine_path = get_this_engine_path() + + if engine_name and not engine_path: + engine_path = get_registered(engine_name=engine_name) + + if not engine_path: + if not supress_errors: + logger.error(f'Engine Path {engine_path} has not been registered.') + return 1 + + engine_json = engine_path / 'engine.json' + if not engine_json.is_file(): + if not supress_errors: + logger.error(f'Engine json {engine_json} is not present.') + return 1 + if not valid_o3de_engine_json(engine_json): + if not supress_errors: + logger.error(f'Engine json {engine_json} is not valid.') + return 1 + + return add_external_subdirectory(external_subdir=gem_path, engine_path=engine_path, supress_errors=supress_errors) + + +def remove_gem_from_cmake(gem_name: str = None, + gem_path: str or pathlib.Path = None, + engine_name: str = None, + engine_path: str or pathlib.Path = None) -> int: + """ + remove a gem to cmake as an external subdirectory + :param gem_name: name of the gem to remove from cmake + :param gem_path: the path of the gem to add to cmake + :param engine_name: optional name of the engine to remove from cmake + :param engine_path: the path of the engine to remove external subdirectory from, defaults to this engine + :return: 0 for success or non 0 failure code + """ + if not gem_name and not gem_path: + logger.error('Must specify either a Gem name or Gem Path.') + return 1 + + if gem_name and not gem_path: + gem_path = get_registered(gem_name=gem_name) + + if not gem_path: + logger.error(f'Gem Path {gem_path} has not been registered.') + return 1 + + if not engine_name and not engine_path: + engine_path = get_this_engine_path() + + if engine_name and not engine_path: + engine_path = get_registered(engine_name=engine_name) + + if not engine_path: + logger.error(f'Engine Path {engine_path} is not registered.') + return 1 + + return remove_external_subdirectory(external_subdir=gem_path, engine_path=engine_path) + + +def add_gem_to_project(gem_name: str = None, + gem_path: str or pathlib.Path = None, + gem_target: str = None, + project_name: str = None, + project_path: str or pathlib.Path = None, + dependencies_file: str or pathlib.Path = None, + runtime_dependency: bool = False, + tool_dependency: bool = False, + server_dependency: bool = False, + platforms: str = 'Common', + add_to_cmake: bool = True) -> int: + """ + add a gem to a project + :param gem_name: name of the gem to add + :param gem_path: path to the gem to add + :param gem_target: the name of the cmake gem module + :param project_name: name of to the project to add the gem to + :param project_path: path to the project to add the gem to + :param dependencies_file: if this dependency goes/is in a specific file + :param runtime_dependency: bool to specify this is a runtime gem for the game + :param tool_dependency: bool to specify this is a tool gem for the editor + :param server_dependency: bool to specify this is a server gem for the server + :param platforms: str to specify common or which specific platforms + :param add_to_cmake: bool to specify that this gem should be added to cmake + :return: 0 for success or non 0 failure code + """ + # we need either a project name or path + if not project_name and not project_path: + logger.error(f'Must either specify a Project path or Project Name.') + return 1 + + # if project name resolve it into a path + if project_name and not project_path: + project_path = get_registered(project_name=project_name) + project_path = pathlib.Path(project_path).resolve() + if not project_path.is_dir(): + logger.error(f'Project path {project_path} is not a folder.') + return 1 + + # get the engine name this project is associated with + # and resolve that engines path + project_json = project_path / 'project.json' + if not valid_o3de_project_json(project_json): + logger.error(f'Project json {project_json} is not valid.') + return 1 + with project_json.open('r') as s: + try: + project_json_data = json.load(s) + except Exception as e: + logger.error(f'Error loading Project json {project_json}: {str(e)}') + return 1 + else: + try: + engine_name = project_json_data['engine'] + except Exception as e: + logger.error(f'Project json {project_json} "engine" not found: {str(e)}') + return 1 + else: + engine_path = get_registered(engine_name=engine_name) + if not engine_path: + logger.error(f'Engine {engine_name} is not registered.') + return 1 + + # we need either a gem name or path + if not gem_name and not gem_path: + logger.error(f'Must either specify a Gem path or Gem Name.') + return 1 + + # if gem name resolve it into a path + if gem_name and not gem_path: + gem_path = get_registered(gem_name=gem_name) + gem_path = pathlib.Path(gem_path).resolve() + # make sure this gem already exists if we're adding. We can always remove a gem. + if not gem_path.is_dir(): + logger.error(f'Gem Path {gem_path} does not exist.') + return 1 + + # if add to cmake, make sure the gem.json exists and valid before we proceed + if add_to_cmake: + gem_json = gem_path / 'gem.json' + if not gem_json.is_file(): + logger.error(f'Gem json {gem_json} is not present.') + return 1 + if not valid_o3de_gem_json(gem_json): + logger.error(f'Gem json {gem_json} is not valid.') + return 1 + + # find all available modules in this gem_path + modules = get_gem_targets(gem_path=gem_path) + if len(modules) == 0: + logger.error(f'No gem modules found under {gem_path}.') + return 1 + + # if the gem has no modules and the user has specified a target fail + if gem_target and not modules: + logger.error(f'Gem has no targets, but gem target {gem_target} was specified.') + return 1 + + # if the gem target is not in the modules + if gem_target not in modules: + logger.error(f'Gem target not in gem modules: {modules}') + return 1 + + if gem_target: + # if the user has not specified either we will assume they meant the most common which is runtime + if not runtime_dependency and not tool_dependency and not server_dependency and not dependencies_file: + logger.warning("Dependency type not specified: Assuming '--runtime-dependency'") + runtime_dependency = True + + ret_val = 0 + + # if the user has specified the dependencies file then ignore the runtime_dependency and tool_dependency flags + if dependencies_file: + dependencies_file = pathlib.Path(dependencies_file).resolve() + # make sure this is a project has a dependencies_file + if not dependencies_file.is_file(): + logger.error(f'Dependencies file {dependencies_file} is not present.') + return 1 + # add the dependency + ret_val = add_gem_dependency(dependencies_file, gem_target) + + else: + if ',' in platforms: + platforms = platforms.split(',') + else: + platforms = [platforms] + for platform in platforms: + if runtime_dependency: + # make sure this is a project has a runtime_dependencies.cmake file + project_runtime_dependencies_file = pathlib.Path( + get_dependencies_cmake_file(project_path=project_path, dependency_type='runtime', platform=platform)).resolve() + if not project_runtime_dependencies_file.is_file(): + logger.error(f'Runtime dependencies file {project_runtime_dependencies_file} is not present.') + return 1 + # add the dependency + ret_val = add_gem_dependency(project_runtime_dependencies_file, gem_target) + + if (ret_val == 0) and tool_dependency: + # make sure this is a project has a tool_dependencies.cmake file + project_tool_dependencies_file = pathlib.Path( + get_dependencies_cmake_file(project_path=project_path, dependency_type='tool', platform=platform)).resolve() + if not project_tool_dependencies_file.is_file(): + logger.error(f'Tool dependencies file {project_tool_dependencies_file} is not present.') + return 1 + # add the dependency + ret_val = add_gem_dependency(project_tool_dependencies_file, gem_target) + + if (ret_val == 0) and server_dependency: + # make sure this is a project has a tool_dependencies.cmake file + project_server_dependencies_file = pathlib.Path( + get_dependencies_cmake_file(project_path=project_path, dependency_type='server', platform=platform)).resolve() + if not project_server_dependencies_file.is_file(): + logger.error(f'Server dependencies file {project_server_dependencies_file} is not present.') + return 1 + # add the dependency + ret_val = add_gem_dependency(project_server_dependencies_file, gem_target) + + if not ret_val and add_to_cmake: + ret_val = add_gem_to_cmake(gem_path=gem_path, engine_path=engine_path) + + return ret_val + + +def remove_gem_from_project(gem_name: str = None, + gem_path: str or pathlib.Path = None, + gem_target: str = None, + project_name: str = None, + project_path: str or pathlib.Path = None, + dependencies_file: str or pathlib.Path = None, + runtime_dependency: bool = False, + tool_dependency: bool = False, + server_dependency: bool = False, + platforms: str = 'Common', + remove_from_cmake: bool = False) -> int: + """ + remove a gem from a project + :param gem_name: name of the gem to add + :param gem_path: path to the gem to add + :param gem_target: the name of teh cmake gem module + :param project_name: name of the project to add the gem to + :param project_path: path to the project to add the gem to + :param dependencies_file: if this dependency goes/is in a specific file + :param runtime_dependency: bool to specify this is a runtime gem for the game + :param tool_dependency: bool to specify this is a tool gem for the editor + :param server_dependency: bool to specify this is a server gem for the server + :param platforms: str to specify common or which specific platforms + :param remove_from_cmake: bool to specify that this gem should be removed from cmake + :return: 0 for success or non 0 failure code + """ + + # we need either a project name or path + if not project_name and not project_path: + logger.error(f'Must either specify a Project path or Project Name.') + return 1 + + # if project name resolve it into a path + if project_name and not project_path: + project_path = get_registered(project_name=project_name) + project_path = pathlib.Path(project_path).resolve() + if not project_path.is_dir(): + logger.error(f'Project path {project_path} is not a folder.') + return 1 + + # We need either a gem name or path + if not gem_name and not gem_path: + logger.error(f'Must either specify a Gem path or Gem Name.') + return 1 + + # if gem name resolve it into a path + if gem_name and not gem_path: + gem_path = get_registered(gem_name=gem_name) + gem_path = pathlib.Path(gem_path).resolve() + # make sure this gem already exists if we're adding. We can always remove a gem. + if not gem_path.is_dir(): + logger.error(f'Gem Path {gem_path} does not exist.') + return 1 + + # find all available modules in this gem_path + modules = get_gem_targets(gem_path=gem_path) + if len(modules) == 0: + logger.error(f'No gem modules found.') + return 1 + + # if the user has not set a specific gem target remove all of them + + # if gem target not specified, see if there is only 1 module + if not gem_target: + if len(modules) == 1: + gem_target = modules[0] + else: + logger.error(f'Gem target not specified: {modules}') + return 1 + elif gem_target not in modules: + logger.error(f'Gem target not in gem modules: {modules}') + return 1 + + # if the user has not specified either we will assume they meant the most common which is runtime + if not runtime_dependency and not tool_dependency and not server_dependency and not dependencies_file: + logger.warning("Dependency type not specified: Assuming '--runtime-dependency'") + runtime_dependency = True + + # when removing we will try to do as much as possible even with failures so ret_val will be the last error code + ret_val = 0 + + # if the user has specified the dependencies file then ignore the runtime_dependency and tool_dependency flags + if dependencies_file: + dependencies_file = pathlib.Path(dependencies_file).resolve() + # make sure this is a project has a dependencies_file + if not dependencies_file.is_file(): + logger.error(f'Dependencies file {dependencies_file} is not present.') + return 1 + # remove the dependency + error_code = remove_gem_dependency(dependencies_file, gem_target) + if error_code: + ret_val = error_code + else: + if ',' in platforms: + platforms = platforms.split(',') + else: + platforms = [platforms] + for platform in platforms: + if runtime_dependency: + # make sure this is a project has a runtime_dependencies.cmake file + project_runtime_dependencies_file = pathlib.Path( + get_dependencies_cmake_file(project_path=project_path, dependency_type='runtime', platform=platform)).resolve() + if not project_runtime_dependencies_file.is_file(): + logger.error(f'Runtime dependencies file {project_runtime_dependencies_file} is not present.') + else: + # remove the dependency + error_code = remove_gem_dependency(project_runtime_dependencies_file, gem_target) + if error_code: + ret_val = error_code + + if tool_dependency: + # make sure this is a project has a tool_dependencies.cmake file + project_tool_dependencies_file = pathlib.Path( + get_dependencies_cmake_file(project_path=project_path, dependency_type='tool', platform=platform)).resolve() + if not project_tool_dependencies_file.is_file(): + logger.error(f'Tool dependencies file {project_tool_dependencies_file} is not present.') + else: + # remove the dependency + error_code = remove_gem_dependency(project_tool_dependencies_file, gem_target) + if error_code: + ret_val = error_code + + if server_dependency: + # make sure this is a project has a tool_dependencies.cmake file + project_server_dependencies_file = pathlib.Path( + get_dependencies_cmake_file(project_path=project_path, dependency_type='server', platform=platform)).resolve() + if not project_server_dependencies_file.is_file(): + logger.error(f'Server dependencies file {project_server_dependencies_file} is not present.') + else: + # remove the dependency + error_code = remove_gem_dependency(project_server_dependencies_file, gem_target) + if error_code: + ret_val = error_code + + if remove_from_cmake: + error_code = remove_gem_from_cmake(gem_path=gem_path) + if error_code: + ret_val = error_code + + return ret_val + + +def sha256(file_path: str or pathlib.Path, + json_path: str or pathlib.Path = None) -> int: + if not file_path: + logger.error(f'File path cannot be empty.') + return 1 + file_path = pathlib.Path(file_path).resolve() + if not file_path.is_file(): + logger.error(f'File path {file_path} does not exist.') + return 1 + + if json_path: + json_path = pathlib.Path(json_path).resolve() + if not json_path.is_file(): + logger.error(f'Json path {json_path} does not exist.') + return 1 + + sha256 = hashlib.sha256(file_path.open('rb').read()).hexdigest() + + if json_path: + with json_path.open('r') as s: + try: + json_data = json.load(s) + except Exception as e: + logger.error(f'Failed to read Json path {json_path}: {str(e)}') + return 1 + json_data.update({"sha256": sha256}) + backup_file(json_path) + with json_path.open('w') as s: + try: + s.write(json.dumps(json_data, indent=4)) + except Exception as e: + logger.error(f'Failed to write Json path {json_path}: {str(e)}') + return 1 + else: + print(sha256) + return 0 + + +def _run_get_registered(args: argparse) -> str or pathlib.Path: + if args.override_home_folder: + global override_home_folder + override_home_folder = args.override_home_folder + return get_registered(args.engine_name, args.project_name, args.gem_name, args.template_name, args.default_folder, - args.repo_name) + args.repo_name, + args.restricted_name) def _run_register_show(args: argparse) -> int: + if args.override_home_folder: + global override_home_folder + override_home_folder = args.override_home_folder - if args.aggregate: - register_show_aggregate(args.verbose) - return 0 - if args.aggregate_engines: - register_show_aggregate_engines(args.verbose) - return 0 - elif args.aggregate_projects: - register_show_aggregate_projects(args.verbose) - return 0 - elif args.aggregate_gems: - register_show_aggregate_gems(args.verbose) - return 0 - elif args.aggregate_templates: - register_show_aggregate_templates(args.verbose) - return 0 - elif args.aggregate_repos: - register_show_aggregate_repos(args.verbose) + if args.this_engine: + print_this_engine(args.verbose) return 0 + elif args.engines: - register_show_engines(args.verbose) + print_engines(args.verbose) return 0 elif args.projects: - register_show_projects(args.verbose) + print_projects(args.verbose) return 0 elif args.gems: - register_show_gems(args.verbose) + print_gems(args.verbose) return 0 elif args.templates: - register_show_templates(args.verbose) + print_templates(args.verbose) return 0 elif args.repos: register_show_repos(args.verbose) return 0 + elif args.restricted: + print_restricted(args.verbose) + return 0 + + elif args.engine_projects: + print_engine_projects(args.verbose) + return 0 + elif args.engine_gems: + print_engine_gems(args.verbose) + return 0 + elif args.engine_templates: + print_engine_templates(args.verbose) + return 0 + elif args.engine_restricted: + print_engine_restricted(args.verbose) + return 0 + elif args.external_subdirectories: + print_external_subdirectories(args.verbose) + return 0 + + elif args.all_projects: + print_all_projects(args.verbose) + return 0 + elif args.all_gems: + print_all_gems(args.verbose) + return 0 + elif args.all_templates: + print_all_templates(args.verbose) + return 0 + elif args.all_restricted: + print_all_restricted(args.verbose) + return 0 + + elif args.downloadables: + print_downloadables(args.verbose) + return 0 + if args.downloadable_engines: + print_downloadable_engines(args.verbose) + return 0 + elif args.downloadable_projects: + print_downloadable_projects(args.verbose) + return 0 + elif args.downloadable_gems: + print_downloadable_gems(args.verbose) + return 0 + elif args.downloadable_templates: + print_downloadable_templates(args.verbose) + return 0 else: register_show(args.verbose) return 0 +def _run_download(args: argparse) -> int: + if args.override_home_folder: + global override_home_folder + override_home_folder = args.override_home_folder + + if args.engine_name: + return download_engine(args.engine_name, + args.dest_path) + elif args.project_name: + return download_project(args.project_name, + args.dest_path) + elif args.gem_nanme: + return download_gem(args.gem_name, + args.dest_path) + elif args.template_name: + return download_template(args.template_name, + args.dest_path) + + +def _run_register(args: argparse) -> int: + if args.override_home_folder: + global override_home_folder + override_home_folder = args.override_home_folder + + if args.update: + remove_invalid_o3de_objects() + return refresh_repos() + elif args.this_engine: + ret_val = register(engine_path=get_this_engine_path()) + error_code = register_shipped_engine_o3de_objects() + if error_code: + ret_val = error_code + return ret_val + elif args.all_engines_path: + return register_all_engines_in_folder(args.all_engines_path, args.remove) + elif args.all_projects_path: + return register_all_projects_in_folder(args.all_projects_path, args.remove) + elif args.all_gems_path: + return register_all_gems_in_folder(args.all_gems_path, args.remove) + elif args.all_templates_path: + return register_all_templates_in_folder(args.all_templates_path, args.remove) + elif args.all_restricted_path: + return register_all_restricted_in_folder(args.all_restricted_path, args.remove) + elif args.all_repo_uri: + return register_all_repos_in_folder(args.all_restricted_path, args.remove) + else: + return register(engine_path=args.engine_path, + project_path=args.project_path, + gem_path=args.gem_path, + template_path=args.template_path, + restricted_path=args.restricted_path, + repo_uri=args.repo_uri, + default_engines_folder=args.default_engines_folder, + default_projects_folder=args.default_projects_folder, + default_gems_folder=args.default_gems_folder, + default_templates_folder=args.default_templates_folder, + default_restricted_folder=args.default_restricted_folder, + remove=args.remove) + + +def _run_add_external_subdirectory(args: argparse) -> int: + if args.override_home_folder: + global override_home_folder + override_home_folder = args.override_home_folder + + return add_external_subdirectory(args.external_subdirectory) + + +def _run_remove_external_subdirectory(args: argparse) -> int: + if args.override_home_folder: + global override_home_folder + override_home_folder = args.override_home_folder + + return remove_external_subdirectory(args.external_subdirectory) + + +def _run_add_gem_to_cmake(args: argparse) -> int: + if args.override_home_folder: + global override_home_folder + override_home_folder = args.override_home_folder + + return add_gem_to_cmake(gem_name=args.gem_name, gem_path=args.gem_path) + + +def _run_remove_gem_from_cmake(args: argparse) -> int: + if args.override_home_folder: + global override_home_folder + override_home_folder = args.override_home_folder + + return remove_gem_from_cmake(args.gem_name, args.gem_path) + + +def _run_add_gem_to_project(args: argparse) -> int: + if args.override_home_folder: + global override_home_folder + override_home_folder = args.override_home_folder + + return add_gem_to_project(args.gem_name, + args.gem_path, + args.gem_target, + args.project_name, + args.project_path, + args.dependencies_file, + args.runtime_dependency, + args.tool_dependency, + args.server_dependency, + args.platforms, + args.add_to_cmake) + + +def _run_remove_gem_from_project(args: argparse) -> int: + if args.override_home_folder: + global override_home_folder + override_home_folder = args.override_home_folder + + return remove_gem_from_project(args.gem_name, + args.gem_path, + args.gem_target, + args.project_path, + args.project_name, + args.dependencies_file, + args.runtime_dependency, + args.tool_dependency, + args.server_dependency, + args.platforms, + args.remove_from_cmake) + + +def _run_sha256(args: argparse) -> int: + return sha256(args.file_path, + args.json_path) + + def add_args(parser, subparsers) -> None: """ add_args is called to add expected parser arguments and subparsers arguments to each command such that it can be - invoked locally or aggregated by a central python file. + invoked locally or added by a central python file. Ex. Directly run from this file alone with: python register.py register --gem-path "C:/TestGem" OR - o3de.py can aggregate commands by importing engine_template, + o3de.py can downloadable commands by importing engine_template, call add_args and execute: python o3de.py register --gem-path "C:/TestGem" :param parser: the caller instantiates a parser and passes it in here :param subparsers: the caller instantiates subparsers and passes it in here @@ -1081,98 +4058,317 @@ def add_args(parser, subparsers) -> None: # register register_subparser = subparsers.add_parser('register') group = register_subparser.add_mutually_exclusive_group(required=True) - group.add_argument('--this-engine', action = 'store_true', required=False, - default = False, + group.add_argument('--this-engine', action='store_true', required=False, + default=False, help='Registers the engine this script is running from.') - group.add_argument('-e', '--engine-path', type=str, required=False, + group.add_argument('-ep', '--engine-path', type=str, required=False, help='Engine path to register/remove.') - group.add_argument('-p', '--project-path', type=str, required=False, + group.add_argument('-pp', '--project-path', type=str, required=False, help='Project path to register/remove.') - group.add_argument('-g', '--gem-path', type=str, required=False, + group.add_argument('-gp', '--gem-path', type=str, required=False, help='Gem path to register/remove.') - group.add_argument('-t', '--template-path', type=str, required=False, + group.add_argument('-tp', '--template-path', type=str, required=False, help='Template path to register/remove.') - group.add_argument('-dp', '--default-projects-folder', type=str, required=False, - help='The default projects folder to register/remove.') - group.add_argument('-dg', '--default-gems-folder', type=str, required=False, - help='The default gems folder to register/remove.') - group.add_argument('-dt', '--default-templates-folder', type=str, required=False, - help='The default templates folder to register/remove.') + group.add_argument('-rp', '--restricted-path', type=str, required=False, + help='A restricted folder to register/remove.') group.add_argument('-ru', '--repo-uri', type=str, required=False, help='A repo uri to register/remove.') + group.add_argument('-aep', '--all-engines-path', type=str, required=False, + help='All engines under this folder to register/remove.') + group.add_argument('-app', '--all-projects-path', type=str, required=False, + help='All projects under this folder to register/remove.') + group.add_argument('-agp', '--all-gems-path', type=str, required=False, + help='All gems under this folder to register/remove.') + group.add_argument('-atp', '--all-templates-path', type=str, required=False, + help='All templates under this folder to register/remove.') + group.add_argument('-arp', '--all-restricted-path', type=str, required=False, + help='All templates under this folder to register/remove.') + group.add_argument('-aru', '--all-repo-uri', type=str, required=False, + help='All repos under this folder to register/remove.') + group.add_argument('-def', '--default-engines-folder', type=str, required=False, + help='The default engines folder to register/remove.') + group.add_argument('-dpf', '--default-projects-folder', type=str, required=False, + help='The default projects folder to register/remove.') + group.add_argument('-dgf', '--default-gems-folder', type=str, required=False, + help='The default gems folder to register/remove.') + group.add_argument('-dtf', '--default-templates-folder', type=str, required=False, + help='The default templates folder to register/remove.') + group.add_argument('-drf', '--default-restricted-folder', type=str, required=False, + help='The default restricted folder to register/remove.') group.add_argument('-u', '--update', action='store_true', required=False, default=False, help='Refresh the repo cache.') + + register_subparser.add_argument('-ohf', '--override-home-folder', type=str, required=False, + help='By default the home folder is the user folder, override it to this folder.') + register_subparser.add_argument('-r', '--remove', action='store_true', required=False, default=False, help='Remove entry.') - register_subparser.set_defaults(func=_run_register) # show register_show_subparser = subparsers.add_parser('register-show') group = register_show_subparser.add_mutually_exclusive_group(required=False) + group.add_argument('-te', '--this-engine', action='store_true', required=False, + default=False, + help='Just the local engines.') group.add_argument('-e', '--engines', action='store_true', required=False, default=False, - help='Just the local engines. Ignores repos') + help='Just the local engines.') group.add_argument('-p', '--projects', action='store_true', required=False, default=False, - help='Just the local projects. Ignores repos.') + help='Just the local projects.') group.add_argument('-g', '--gems', action='store_true', required=False, default=False, - help='Just the local gems. Ignores repos') + help='Just the local gems.') group.add_argument('-t', '--templates', action='store_true', required=False, default=False, - help='Just the local templates. Ignores repos.') + help='Just the local templates.') group.add_argument('-r', '--repos', action='store_true', required=False, default=False, help='Just the local repos. Ignores repos.') - group.add_argument('-a', '--aggregate', action='store_true', required=False, + group.add_argument('-rs', '--restricted', action='store_true', required=False, + default=False, + help='The local restricted folders.') + + group.add_argument('-ep', '--engine-projects', action='store_true', required=False, + default=False, + help='Just the local projects. Ignores repos.') + group.add_argument('-eg', '--engine-gems', action='store_true', required=False, + default=False, + help='Just the local gems. Ignores repos') + group.add_argument('-et', '--engine-templates', action='store_true', required=False, + default=False, + help='Just the local templates. Ignores repos.') + group.add_argument('-ers', '--engine-restricted', action='store_true', required=False, + default=False, + help='The restricted folders.') + group.add_argument('-x', '--external-subdirectories', action='store_true', required=False, + default=False, + help='The external subdirectories.') + + group.add_argument('-ap', '--all-projects', action='store_true', required=False, + default=False, + help='Just the local projects. Ignores repos.') + group.add_argument('-ag', '--all-gems', action='store_true', required=False, + default=False, + help='Just the local gems. Ignores repos') + group.add_argument('-at', '--all-templates', action='store_true', required=False, + default=False, + help='Just the local templates. Ignores repos.') + group.add_argument('-ars', '--all-restricted', action='store_true', required=False, + default=False, + help='The restricted folders.') + + group.add_argument('-d', '--downloadables', action='store_true', required=False, default=False, help='Combine all repos into a single list of resources.') - group.add_argument('-ae', '--aggregate-engines', action='store_true', required=False, + group.add_argument('-de', '--downloadable-engines', action='store_true', required=False, default=False, help='Combine all repos engines into a single list of resources.') - group.add_argument('-ap', '--aggregate-projects', action='store_true', required=False, + group.add_argument('-dp', '--downloadable-projects', action='store_true', required=False, default=False, help='Combine all repos projects into a single list of resources.') - group.add_argument('-ag', '--aggregate-gems', action='store_true', required=False, + group.add_argument('-dg', '--downloadable-gems', action='store_true', required=False, default=False, help='Combine all repos gems into a single list of resources.') - group.add_argument('-at', '--aggregate-templates', action='store_true', required=False, + group.add_argument('-dt', '--downloadable-templates', action='store_true', required=False, default=False, help='Combine all repos templates into a single list of resources.') - group.add_argument('-ar', '--aggregate-repos', action='store_true', required=False, - default=False, - help='Combine all repos into a single list of resources.') - group = register_show_subparser.add_mutually_exclusive_group(required=False) - group.add_argument('-v', '--verbose', action='count', required=False, - default=0, - help='How verbose do you want the output to be.') + register_show_subparser.add_argument('-v', '--verbose', action='count', required=False, + default=0, + help='How verbose do you want the output to be.') + + register_show_subparser.add_argument('-ohf', '--override-home-folder', type=str, required=False, + help='By default the home folder is the user folder, override it to this folder.') register_show_subparser.set_defaults(func=_run_register_show) # get-registered get_registered_subparser = subparsers.add_parser('get-registered') group = get_registered_subparser.add_mutually_exclusive_group(required=True) - group.add_argument('-e', '--engine-name', type=str, required=False, + group.add_argument('-en', '--engine-name', type=str, required=False, help='Engine name.') - group.add_argument('-p', '--project-name', type=str, required=False, + group.add_argument('-pn', '--project-name', type=str, required=False, help='Project name.') - group.add_argument('-g', '--gem-name', type=str, required=False, + group.add_argument('-gn', '--gem-name', type=str, required=False, help='Gem name.') - group.add_argument('-t', '--template-name', type=str, required=False, + group.add_argument('-tn', '--template-name', type=str, required=False, help='Template name.') - group.add_argument('-f', '--default-folder', type=str, required=False, - choices=['projects', 'gems', 'templates'], - help='The default folder.') - group.add_argument('-r', '--repo-name', type=str, required=False, - help='A repo uri to register/remove.') + group.add_argument('-df', '--default-folder', type=str, required=False, + choices=['engines', 'projects', 'gems', 'templates', 'restricted'], + help='The default folders for o3de.') + group.add_argument('-rn', '--repo-name', type=str, required=False, + help='Repo name.') + group.add_argument('-rsn', '--restricted-name', type=str, required=False, + help='Restricted name.') + + get_registered_subparser.add_argument('-ohf', '--override-home-folder', type=str, required=False, + help='By default the home folder is the user folder, override it to this folder.') get_registered_subparser.set_defaults(func=_run_get_registered) + # download + download_subparser = subparsers.add_parser('download') + group = download_subparser.add_mutually_exclusive_group(required=True) + group.add_argument('-e', '--engine-name', type=str, required=False, + help='Downloadable engine name.') + group.add_argument('-p', '--project-name', type=str, required=False, + help='Downloadable project name.') + group.add_argument('-g', '--gem-name', type=str, required=False, + help='Downloadable gem name.') + group.add_argument('-t', '--template-name', type=str, required=False, + help='Downloadable template name.') + download_subparser.add_argument('-dp', '--dest-path', type=str, required=False, + default=None, + help='Optional destination folder to download into.' + ' i.e. download --project-name "StarterGame" --dest-path "C:/projects"' + ' will result in C:/projects/StarterGame' + ' If blank will download to default object type folder') + + download_subparser.add_argument('-ohf', '--override-home-folder', type=str, required=False, + help='By default the home folder is the user folder, override it to this folder.') + + download_subparser.set_defaults(func=_run_download) + + # add external subdirectories + add_external_subdirectory_subparser = subparsers.add_parser('add-external-subdirectory') + add_external_subdirectory_subparser.add_argument('external_subdirectory', metavar='external_subdirectory', type=str, + help='add an external subdirectory to cmake') + + add_external_subdirectory_subparser.add_argument('-ohf', '--override-home-folder', type=str, required=False, + help='By default the home folder is the user folder, override it to this folder.') + + add_external_subdirectory_subparser.set_defaults(func=_run_add_external_subdirectory) + + # remove external subdirectories + remove_external_subdirectory_subparser = subparsers.add_parser('remove-external-subdirectory') + remove_external_subdirectory_subparser.add_argument('external_subdirectory', metavar='external_subdirectory', + type=str, + help='remove external subdirectory from cmake') + + remove_external_subdirectory_subparser.add_argument('-ohf', '--override-home-folder', type=str, required=False, + help='By default the home folder is the user folder, override it to this folder.') + + remove_external_subdirectory_subparser.set_defaults(func=_run_remove_external_subdirectory) + + # add gems to cmake + # convenience functions to disambiguate the gem name -> gem_path and call add-external-subdirectory on gem_path + add_gem_to_cmake_subparser = subparsers.add_parser('add-gem-to-cmake') + group = add_gem_to_cmake_subparser.add_mutually_exclusive_group(required=True) + group.add_argument('-gp', '--gem-path', type=str, required=False, + help='The path to the gem.') + group.add_argument('-gn', '--gem-name', type=str, required=False, + help='The name of the gem.') + + add_gem_to_cmake_subparser.add_argument('-ohf', '--override-home-folder', type=str, required=False, + help='By default the home folder is the user folder, override it to this folder.') + + add_gem_to_cmake_subparser.set_defaults(func=_run_add_gem_to_cmake) + + # remove gems from cmake + # convenience functions to disambiguate the gem name -> gem_path and call remove-external-subdirectory on gem_path + remove_gem_from_cmake_subparser = subparsers.add_parser('remove-gem-from-cmake') + group = remove_gem_from_cmake_subparser.add_mutually_exclusive_group(required=True) + group.add_argument('-gp', '--gem-path', type=str, required=False, + help='The path to the gem.') + group.add_argument('-gn', '--gem-name', type=str, required=False, + help='The name of the gem.') + + remove_gem_from_cmake_subparser.add_argument('-ohf', '--override-home-folder', type=str, required=False, + help='By default the home folder is the user folder, override it to this folder.') + + remove_gem_from_cmake_subparser.set_defaults(func=_run_remove_gem_from_cmake) + + # add a gem to a project + add_gem_subparser = subparsers.add_parser('add-gem-to-project') + group = add_gem_subparser.add_mutually_exclusive_group(required=True) + group.add_argument('-pp', '--project-path', type=str, required=False, + help='The path to the project.') + group.add_argument('-pn', '--project-name', type=str, required=False, + help='The name of the project.') + group = add_gem_subparser.add_mutually_exclusive_group(required=True) + group.add_argument('-gp', '--gem-path', type=str, required=False, + help='The path to the gem.') + group.add_argument('-gn', '--gem-name', type=str, required=False, + help='The name of the gem.') + add_gem_subparser.add_argument('-gt', '--gem-target', type=str, required=False, + help='The cmake target name to add. If not specified it will assume gem_name') + add_gem_subparser.add_argument('-df', '--dependencies-file', type=str, required=False, + help='The cmake dependencies file in which the gem dependencies are specified.' + 'If not specified it will assume ') + add_gem_subparser.add_argument('-rd', '--runtime-dependency', action='store_true', required=False, + default=False, + help='Optional toggle if this gem should be added as a runtime dependency') + add_gem_subparser.add_argument('-td', '--tool-dependency', action='store_true', required=False, + default=False, + help='Optional toggle if this gem should be added as a tool dependency') + add_gem_subparser.add_argument('-sd', '--server-dependency', action='store_true', required=False, + default=False, + help='Optional toggle if this gem should be added as a server dependency') + add_gem_subparser.add_argument('-pl', '--platforms', type=str, required=False, + default='Common', + help='Optional list of platforms this gem should be added to.' + ' Ex. --platforms Mac,Windows,Linux') + add_gem_subparser.add_argument('-a', '--add-to-cmake', type=bool, required=False, + default=True, + help='Automatically call add-gem-to-cmake.') + + add_gem_subparser.add_argument('-ohf', '--override-home-folder', type=str, required=False, + help='By default the home folder is the user folder, override it to this folder.') + + add_gem_subparser.set_defaults(func=_run_add_gem_to_project) + + # remove a gem from a project + remove_gem_subparser = subparsers.add_parser('remove-gem-from-project') + group = remove_gem_subparser.add_mutually_exclusive_group(required=True) + group.add_argument('-pp', '--project-path', type=str, required=False, + help='The path to the project.') + group.add_argument('-pn', '--project-name', type=str, required=False, + help='The name of the project.') + group = remove_gem_subparser.add_mutually_exclusive_group(required=True) + group.add_argument('-gp', '--gem-path', type=str, required=False, + help='The path to the gem.') + group.add_argument('-gn', '--gem-name', type=str, required=False, + help='The name of the gem.') + remove_gem_subparser.add_argument('-gt', '--gem-target', type=str, required=False, + help='The cmake target name to add. If not specified it will assume gem_name') + remove_gem_subparser.add_argument('-df', '--dependencies-file', type=str, required=False, + help='The cmake dependencies file in which the gem dependencies are specified.' + 'If not specified it will assume ') + remove_gem_subparser.add_argument('-rd', '--runtime-dependency', action='store_true', required=False, + default=False, + help='Optional toggle if this gem should be removed as a runtime dependency') + remove_gem_subparser.add_argument('-td', '--tool-dependency', action='store_true', required=False, + default=False, + help='Optional toggle if this gem should be removed as a server dependency') + remove_gem_subparser.add_argument('-sd', '--server-dependency', action='store_true', required=False, + default=False, + help='Optional toggle if this gem should be removed as a server dependency') + remove_gem_subparser.add_argument('-pl', '--platforms', type=str, required=False, + default='Common', + help='Optional list of platforms this gem should be removed from' + ' Ex. --platforms Mac,Windows,Linux') + remove_gem_subparser.add_argument('-r', '--remove-from-cmake', type=bool, required=False, + default=False, + help='Automatically call remove-from-cmake.') + + remove_gem_subparser.add_argument('-ohf', '--override-home-folder', type=str, required=False, + help='By default the home folder is the user folder, override it to this folder.') + + remove_gem_subparser.set_defaults(func=_run_remove_gem_from_project) + + # sha256 + sha256_subparser = subparsers.add_parser('sha256') + sha256_subparser.add_argument('-f', '--file-path', type=str, required=True, + help='The path to the file you want to sha256.') + sha256_subparser.add_argument('-j', '--json-path', type=str, required=False, + help='optional path to an o3de json file to add the "sha256" element to.') + sha256_subparser.set_defaults(func=_run_sha256) + if __name__ == "__main__": # parse the command line args diff --git a/cmake/o3de_manifest.cmake b/cmake/o3de_manifest.cmake new file mode 100644 index 0000000000..1585ec2d2f --- /dev/null +++ b/cmake/o3de_manifest.cmake @@ -0,0 +1,986 @@ +# +# All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or +# its licensors. +# +# For complete copyright and license terms please see the LICENSE at the root of this +# distribution (the "License"). All use of this software is governed by the License, +# or, if provided, by the license below or the license accompanying this file. Do not +# remove or 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 the user home directory +set(O3DE_HOME_PATH "" CACHE PATH "Override the user home to this path") +if(O3DE_HOME_PATH) + set(home_directory ${O3DE_HOME_PATH}) +elseif(CMAKE_HOST_WIN32) + file(TO_CMAKE_PATH "$ENV{USERPROFILE}" home_directory) +else() + file(TO_CMAKE_PATH "$ENV{HOME}" home_directory) +endif() +if (NOT home_directory) + message(FATAL_ERROR "Cannot find user home directory, without the user home directory the o3de manifest cannot be found") +endif() + +# Optionally delete the home directory +if(O3DE_DELETE_HOME_PATH) + message(STATUS "O3DE_DELETE_HOME_PATH=${O3DE_DELETE_HOME_PATH}") + if(EXISTS ${home_directory}/.o3de) + message(STATUS "Deleting ${home_directory}/.o3de") + file(REMOVE_RECURSE ${home_directory}/.o3de) + else() + message(STATUS "Home path ${home_directory}/.o3de doesnt exist.") + endif() +endif() + +######################################################################################################################## +# If O3DE_REGISTER_ENGINE_PATH variable is set on the commandline this will allow registration of anything using +# O3DE_REGISTER_ENGINE_PATH o3de script. This is handy for situations like build servers which download the code and +# are expected to build without the need for someone to register o3de objects like this engine by manually typing it in. +# If O3DE_REGISTER_THIS_ENGINE=TRUE is set on the commandline when O3DE_REGISTER_ENGINE_PATH is also set this will call: +# O3DE_REGISTER_ENGINE_PATH/scripts>o3de register --this-engine --override-home-folder +# Note: register --this-engine will automatically register anything it finds in known folders, so if you put your +# o3de objects like projects/gems/templates/restricted/etc... in known folders for those types they will get registered +# automatically. Known folders for types are your .o3de/Projects and .o3de/Gems etc. So if I wanted my project to be +# registered and built by this build server I could simply put them in those known folders on the build server and they +# would get registered automatically by this call. +# OR +# I could put them on the commandline as well. This would be the way if the o3de objects we need to regiater are NOT +# in known folders or you do not intend to call with O3DE_REGISTER_THIS_ENGINE=TRUE Ex. +# -DO3DE_REGISTER_ENGINE_PATH=C:\this\engine +# -DO3DE_REGISTER_PROJECT_PATHS=C:\ThisGame;C:\ThatGame +# -DO3DE_REGISTER_GEM_PATHS=C:\ThisGem;C:\ThatGem;C:\And\Some\Other\Gem +# -DO3DE_REGISTER_RESTRICTED_PATHS=C:\this\engine\Restricted;C:\ThisGame\Restricted;C:\ThisGem\Restricted +######################################################################################################################## +if(O3DE_REGISTER_ENGINE_PATH) + message(STATUS "O3DE_REGISTER_ENGINE_PATH=${O3DE_REGISTER_ENGINE_PATH}") + + if(O3DE_REGISTER_THIS_ENGINE) + message(STATUS "O3DE_REGISTER_THIS_ENGINE=${O3DE_REGISTER_THIS_ENGINE}") + message(STATUS "register --this-engine") + if(CMAKE_HOST_WIN32) + execute_process( + COMMAND cmd /c ${O3DE_REGISTER_ENGINE_PATH}/scripts/o3de.bat register --this-engine --override-home-folder ${home_directory} + RESULT_VARIABLE o3de_register_this_engine_cmd_result + ) + else() + execute_process( + COMMAND sh ${O3DE_REGISTER_ENGINE_PATH}/scripts/o3de.sh register --this-engine --override-home-folder ${home_directory} + RESULT_VARIABLE o3de_register_this_engine_cmd_result + ) + endif() + if(o3de_register_this_engine_cmd_result) + message(FATAL_ERROR "An error occured trying to register --this-engine: ${o3de_register_this_engine_cmd_result}") + else() + message(STATUS "Engine ${O3DE_REGISTER_ENGINE_PATH} registration successfull.") + endif() + endif() + + if(O3DE_REGISTER_RESTRICTED_PATHS) + message(STATUS "O3DE_REGISTER_RESTRICTED_PATHS=${O3DE_REGISTER_RESTRICTED_PATHS}") + foreach(restricted_path ${O3DE_REGISTER_RESTRICTED_PATHS}) + if(CMAKE_HOST_WIN32) + execute_process( + COMMAND cmd /c ${O3DE_REGISTER_ENGINE_PATH}/scripts/o3de.bat register --restricted-path ${restricted_path} --override-home-folder ${home_directory} + RESULT_VARIABLE o3de_register_restricted_cmd_result + ) + else() + execute_process( + COMMAND sh ${O3DE_REGISTER_ENGINE_PATH}/scripts/o3de.sh register --restricted-path ${restricted_path} --override-home-folder ${home_directory} + RESULT_VARIABLE o3de_register_restricted_cmd_result + ) + endif() + if(o3de_register_restricted_cmd_result) + message(FATAL_ERROR "An error occured trying to ${O3DE_REGISTER_ENGINE_PATH}/scripts>o3de register --restricted-path ${restricted_path} --override-home-folder ${home_directory}: ${o3de_register_restricted_cmd_result}") + else() + message(STATUS "Restricted ${restricted_path} registration successfull.") + endif() + endforeach() + endif() + + if(O3DE_REGISTER_PROJECT_PATHS) + message(STATUS "O3DE_REGISTER_PROJECT_PATHS=${O3DE_REGISTER_PROJECT_PATHS}") + foreach(project_path ${O3DE_REGISTER_PROJECT_PATHS}) + if(CMAKE_HOST_WIN32) + execute_process( + COMMAND cmd /c ${O3DE_REGISTER_ENGINE_PATH}/scripts/o3de.bat register --project-path ${project_path} --override-home-folder ${home_directory} + RESULT_VARIABLE o3de_register_project_cmd_result + ) + else() + execute_process( + COMMAND sh ${O3DE_REGISTER_ENGINE_PATH}/scripts/o3de.sh register --project-path ${project_path} --override-home-folder ${home_directory} + RESULT_VARIABLE o3de_register_project_cmd_result + ) + endif() + if(o3de_register_project_cmd_result) + message(FATAL_ERROR "An error occured trying to ${O3DE_REGISTER_ENGINE_PATH}/scripts>o3de register --project-path ${project_path} --override-home-folder ${home_directory}") + else() + message(STATUS "Project ${project_path} registration successfull.") + endif() + endforeach() + endif() + + if(O3DE_REGISTER_GEM_PATHS) + message(STATUS "O3DE_REGISTER_GEM_PATHS=${O3DE_REGISTER_GEM_PATHS}") + foreach(gem_path ${O3DE_REGISTER_GEM_PATHS}) + if(CMAKE_HOST_WIN32) + execute_process( + COMMAND cmd /c ${O3DE_REGISTER_ENGINE_PATH}/scripts/o3de.bat register --gem-path ${gem_path} --override-home-folder ${home_directory} + RESULT_VARIABLE o3de_register_gem_cmd_result + ) + else() + execute_process( + COMMAND sh ${O3DE_REGISTER_ENGINE_PATH}/scripts/o3de.sh register --gem-path ${gem_path} --override-home-folder ${home_directory} + RESULT_VARIABLE o3de_register_gem_cmd_result + ) + endif() + if(o3de_register_gem_cmd_result) + message(FATAL_ERROR "An error occured trying to ${O3DE_REGISTER_ENGINE_PATH}/scripts>o3de register --gem-path ${gem_path} --override-home-folder ${home_directory}") + else() + message(STATUS "Gem ${gem_path} registration successfull.") + endif() + endforeach() + endif() + + if(O3DE_REGISTER_TEMPLATE_PATHS) + message(STATUS "O3DE_REGISTER_TEMPLATE_PATHS=${O3DE_REGISTER_TEMPLATE_PATHS}") + foreach(template_path ${O3DE_REGISTER_TEMPLATE_PATHS}) + if(CMAKE_HOST_WIN32) + execute_process( + COMMAND cmd /c ${O3DE_REGISTER_ENGINE_PATH}/scripts/o3de.bat register --template-path ${template_path} --override-home-folder ${home_directory} + RESULT_VARIABLE o3de_register_template_cmd_result + ) + else() + execute_process( + COMMAND sh ${O3DE_REGISTER_ENGINE_PATH}/scripts/o3de.sh register --template-path ${template_path} --override-home-folder ${home_directory} + RESULT_VARIABLE o3de_register_template_cmd_result + ) + endif() + if(o3de_register_template_cmd_result) + message(FATAL_ERROR "An error occured trying to ${O3DE_REGISTER_ENGINE_PATH}/scripts>o3de register --template-path ${template_path} --override-home-folder ${home_directory}") + else() + message(STATUS "Template ${template_path} registration successfull.") + endif() + endforeach() + endif() + + if(O3DE_REGISTER_REPO_URIS) + message(STATUS "O3DE_REGISTER_REPO_URIS=${O3DE_REGISTER_REPO_URIS}") + foreach(repo_uri ${O3DE_REGISTER_REPO_URIS}) + if(CMAKE_HOST_WIN32) + execute_process( + COMMAND cmd /c ${O3DE_REGISTER_ENGINE_PATH}/scripts/o3de.bat register --repo-uri ${repo_uri} --override-home-folder ${home_directory} + RESULT_VARIABLE o3de_register_repo_cmd_result + ) + else() + execute_process( + COMMAND sh ${O3DE_REGISTER_ENGINE_PATH}/scripts/o3de.sh register --repo-uri ${repo_uri} --override-home-folder ${home_directory} + RESULT_VARIABLE o3de_register_repo_cmd_result + ) + endif() + if(o3de_register_repo_cmd_result) + message(FATAL_ERROR "An error occured trying to ${O3DE_REGISTER_ENGINE_PATH}/scripts>o3de register --repo-uri ${repo_uri} --override-home-folder ${home_directory}") + else() + message(STATUS "Repo ${repo_uri} registration successfull.") + endif() + endforeach() + endif() +endif() + +################################################################################ +# o3de manifest +################################################################################ +# Set manifest json path to the /.o3de/o3de_manifest.json +set(o3de_manifest_json_path ${home_directory}/.o3de/o3de_manifest.json) +if(NOT EXISTS ${o3de_manifest_json_path}) + message(FATAL_ERROR "${o3de_manifest_json_path} not found. You must o3de register --this-engine.") +endif() +file(READ ${o3de_manifest_json_path} manifest_json_data) + +################################################################################ +# o3de manifest name +################################################################################ +string(JSON o3de_manifest_name ERROR_VARIABLE json_error GET ${manifest_json_data} o3de_manifest_name) +message(STATUS "o3de_manifest_name: ${o3de_manifest_name}") +if(json_error) + message(FATAL_ERROR "Unable to read repo_name from '${o3de_manifest_json_path}', error: ${json_error}") +endif() + +################################################################################ +# o3de origin +################################################################################ +string(JSON o3de_origin ERROR_VARIABLE json_error GET ${manifest_json_data} origin) +if(json_error) + message(FATAL_ERROR "Unable to read origin from '${o3de_manifest_json_path}', error: ${json_error}") +endif() + +################################################################################ +# o3de default engines folder +################################################################################ +string(JSON o3de_default_engines_folder ERROR_VARIABLE json_error GET ${manifest_json_data} default_engines_folder) +message(STATUS "default_engines_folder: ${o3de_default_engines_folder}") +if(json_error) + message(FATAL_ERROR "Unable to read default_engines_folder from '${o3de_manifest_json_path}', error: ${json_error}") +endif() + +################################################################################ +# o3de default projects folder +################################################################################ +string(JSON o3de_default_projects_folder ERROR_VARIABLE json_error GET ${manifest_json_data} default_projects_folder) +message(STATUS "default_projects_folder: ${o3de_default_projects_folder}") +if(json_error) + message(FATAL_ERROR "Unable to read default_projects_folder from '${o3de_manifest_json_path}', error: ${json_error}") +endif() + +################################################################################ +# o3de default gems folder +################################################################################ +string(JSON o3de_default_gems_folder ERROR_VARIABLE json_error GET ${manifest_json_data} default_gems_folder) +message(STATUS "default_gems_folder: ${o3de_default_gems_folder}") +if(json_error) + message(FATAL_ERROR "Unable to read default_gems_folder from '${o3de_manifest_json_path}', error: ${json_error}") +endif() + +################################################################################ +# o3de default templates folder +################################################################################ +string(JSON o3de_default_templates_folder ERROR_VARIABLE json_error GET ${manifest_json_data} default_templates_folder) +message(STATUS "default_templates_folder: ${o3de_default_templates_folder}") +if(json_error) + message(FATAL_ERROR "Unable to read default_templates_folder from '${o3de_manifest_json_path}', error: ${json_error}") +endif() + +################################################################################ +# o3de default restricted folder +################################################################################ +string(JSON o3de_default_restricted_folder ERROR_VARIABLE json_error GET ${manifest_json_data} default_restricted_folder) +message(STATUS "default_restricted_folder: ${o3de_default_restricted_folder}") +if(json_error) + message(FATAL_ERROR "Unable to read default_restricted_folder from '${o3de_manifest_json_path}', error: ${json_error}") +endif() + +################################################################################ +# o3de projects +################################################################################ +string(JSON o3de_projects_count ERROR_VARIABLE json_error LENGTH ${manifest_json_data} projects) +if(json_error) + message(FATAL_ERROR "Unable to read key 'projects' from '${o3de_manifest_json_path}', error: ${json_error}") +endif() +if(${o3de_projects_count} GREATER 0) + math(EXPR o3de_projects_count "${o3de_projects_count}-1") + foreach(projects_index RANGE ${o3de_projects_count}) + string(JSON projects_path ERROR_VARIABLE json_error GET ${manifest_json_data} projects ${projects_index}) + if(json_error) + message(FATAL_ERROR "Unable to read projects[${projects_index}] '${o3de_manifest_json_path}', error: ${json_error}") + endif() + list(APPEND o3de_projects ${projects_path}) + list(APPEND o3de_global_projects ${projects_path}) + endforeach() +endif() + +################################################################################ +# o3de gems +################################################################################ +string(JSON o3de_gems_count ERROR_VARIABLE json_error LENGTH ${manifest_json_data} gems) +if(json_error) + message(FATAL_ERROR "Unable to read key 'gems' from '${o3de_manifest_json_path}', error: ${json_error}") +endif() +if(${o3de_gems_count} GREATER 0) + math(EXPR o3de_gems_count "${o3de_gems_count}-1") + foreach(gems_index RANGE ${o3de_gems_count}) + string(JSON gems_path ERROR_VARIABLE json_error GET ${manifest_json_data} gems ${gems_index}) + if(json_error) + message(FATAL_ERROR "Unable to read gems[${gems_index}] '${o3de_manifest_json_path}', error: ${json_error}") + endif() + list(APPEND o3de_gems ${gems_path}) + list(APPEND o3de_global_gems ${gems_path}) + endforeach() +endif() + +################################################################################ +# o3de templates +################################################################################ +string(JSON o3de_templates_count ERROR_VARIABLE json_error LENGTH ${manifest_json_data} templates) +if(json_error) + message(FATAL_ERROR "Unable to read key 'templates' from '${o3de_manifest_json_path}', error: ${json_error}") +endif() +if(${o3de_templates_count} GREATER 0) + math(EXPR o3de_templates_count "${o3de_templates_count}-1") + foreach(templates_index RANGE ${o3de_templates_count}) + string(JSON templates_path ERROR_VARIABLE json_error GET ${manifest_json_data} templates ${templates_index}) + if(json_error) + message(FATAL_ERROR "Unable to read templates[${templates_index}] '${o3de_manifest_json_path}', error: ${json_error}") + endif() + list(APPEND o3de_templates ${templates_path}) + list(APPEND o3de_global_templates ${templates_path}) + endforeach() +endif() + +################################################################################ +# o3de repos +################################################################################ +string(JSON o3de_repos_count ERROR_VARIABLE json_error LENGTH ${manifest_json_data} repos) +if(json_error) + message(FATAL_ERROR "Unable to read key 'repos' from '${o3de_manifest_json_path}', error: ${json_error}") +endif() +if(${o3de_repos_count} GREATER 0) + math(EXPR o3de_repos_count "${o3de_repos_count}-1") + foreach(repos_index RANGE ${o3de_repos_count}) + string(JSON repo_uri ERROR_VARIABLE json_error GET ${manifest_json_data} repos ${repos_index}) + if(json_error) + message(FATAL_ERROR "Unable to read repos[${repos_index}] '${o3de_manifest_json_path}', error: ${json_error}") + endif() + list(APPEND o3de_repos ${repo_uri}) + list(APPEND o3de_global_repos ${repo_uri}) + endforeach() +endif() + +################################################################################ +# o3de restricted +################################################################################ +string(JSON o3de_restricted_count ERROR_VARIABLE json_error LENGTH ${manifest_json_data} restricted) +if(json_error) + message(FATAL_ERROR "Unable to read key 'restricted' from '${o3de_manifest_json_path}', error: ${json_error}") +endif() +if(${o3de_restricted_count} GREATER 0) + math(EXPR o3de_restricted_count "${o3de_restricted_count}-1") + foreach(restricted_index RANGE ${o3de_restricted_count}) + string(JSON restricted_path ERROR_VARIABLE json_error GET ${manifest_json_data} restricted ${restricted_index}) + if(json_error) + message(FATAL_ERROR "Unable to read restricted[${restricted_index}] '${o3de_manifest_json_path}', error: ${json_error}") + endif() + list(APPEND o3de_restricted ${restricted_path}) + list(APPEND o3de_global_restricted ${restricted_path}) + endforeach() +endif() + +################################################################################ +# o3de engines +################################################################################ +string(JSON o3de_engines_count ERROR_VARIABLE json_error LENGTH ${manifest_json_data} engines) +if(json_error) + message(FATAL_ERROR "Unable to read key 'engines' from '${o3de_manifest_json_path}', error: ${json_error}") +endif() + +if(${o3de_engines_count} GREATER 0) + math(EXPR o3de_engines_count "${o3de_engines_count}-1") + # Either the engine_path and engine_json are set in which case the user is configuring from the engine + # or project_path and project_json are set in which case the user is configuring from the project. + # We need to know which engine_path the user is using so if the project_json is set then we need + # to read the project_json and disambiguate the engine_path. + if(NOT o3de_engine_path) + if(NOT o3de_project_json) + message(FATAL_ERROR "Neither o3de_engine_path nor o3de_project_json defined. Cannot determine engine!") + endif() + + # get the name of the engine this project uses + file(READ ${o3de_project_json} project_json_data) + string(JSON project_engine_name ERROR_VARIABLE json_error GET ${project_json_data} engine) + if(json_error) + message(FATAL_ERROR "Unable to read 'engine' from '${o3de_project_json}', error: ${json_error}") + endif() + + # search each engine in order from the manifest to find the matching engine name + foreach(engines_index RANGE ${o3de_engines_count}) + string(JSON engine_data ERROR_VARIABLE json_error GET ${manifest_json_data} engines ${engines_index}) + if(json_error) + message(FATAL_ERROR "Unable to read engines[${engines_index}] '${o3de_manifest_json_path}', error: ${json_error}") + endif() + + # get this engines path + string(JSON this_engine_path ERROR_VARIABLE json_error GET ${engine_data} path) + if(json_error) + message(FATAL_ERROR "Unable to read engine path from '${o3de_manifest_json_path}', error: ${json_error}") + endif() + + # add this engine to the engines list + list(APPEND o3de_engines ${this_engine_path}) + + # use path to get the engine.json + set(this_engine_json ${this_engine_path}/engine.json) + + # read the name of this engine + file(READ ${this_engine_json} this_engine_json_data) + string(JSON this_engine_name ERROR_VARIABLE json_error GET ${this_engine_json_data} engine_name) + if(json_error) + message(FATAL_ERROR "Unable to read engine_name from '${this_engine_json}', error: ${json_error}") + endif() + + # see if this engines name is the same as the one this projects should use + if(${this_engine_name} STREQUAL ${project_engine_name}) + message(STATUS "Found engine: '${project_engine_name}' at ${this_engine_path}") + set(o3de_engine_path ${this_engine_path}) + break() + endif() + endforeach() + endif() +endif() + +#we should have an engine_path at this point +if(NOT o3de_engine_path) + message(FATAL_ERROR "o3de_engine_path not defined. Cannot determine engine!") +endif() + +# now that we have an engine_path read in that engines o3de resources +if(${o3de_engines_count} GREATER -1) + foreach(engines_index RANGE ${o3de_engines_count}) + string(JSON engine_data ERROR_VARIABLE json_error GET ${manifest_json_data} engines ${engines_index}) + if(json_error) + message(FATAL_ERROR "Unable to read engines[${engines_index}] '${o3de_manifest_json_path}', error: ${json_error}") + endif() + + # get this engines path + string(JSON this_engine_path ERROR_VARIABLE json_error GET ${engine_data} path) + if(json_error) + message(FATAL_ERROR "Unable to read engine path from '${o3de_manifest_json_path}', error: ${json_error}") + endif() + + if(${o3de_engine_path} STREQUAL ${this_engine_path}) + ################################################################################ + # o3de engine projects + ################################################################################ + string(JSON o3de_engine_projects_count ERROR_VARIABLE json_error LENGTH ${engine_data} projects) + if(json_error) + message(FATAL_ERROR "Unable to read key 'projects' from '${engine_data}', error: ${json_error}") + endif() + if(${o3de_engine_projects_count} GREATER 0) + math(EXPR o3de_engine_projects_count "${o3de_engine_projects_count}-1") + foreach(engine_projects_index RANGE ${o3de_engine_projects_count}) + string(JSON engine_projects_path ERROR_VARIABLE json_error GET ${engine_data} projects ${engine_projects_index}) + if(json_error) + message(FATAL_ERROR "Unable to read engine projects[${projects_index}] '${o3de_manifest_json_path}', error: ${json_error}") + endif() + list(APPEND o3de_projects ${engine_projects_path}) + list(APPEND o3de_engine_projects ${engine_projects_path}) + endforeach() + endif() + + ################################################################################ + # o3de engine gems + ################################################################################ + string(JSON o3de_engine_gems_count ERROR_VARIABLE json_error LENGTH ${engine_data} gems) + if(json_error) + message(FATAL_ERROR "Unable to read key 'gems' from '${engine_data}', error: ${json_error}") + endif() + if(${o3de_engine_gems_count} GREATER 0) + math(EXPR o3de_engine_gems_count "${o3de_engine_gems_count}-1") + foreach(engine_gems_index RANGE ${o3de_engine_gems_count}) + string(JSON engine_gems_path ERROR_VARIABLE json_error GET ${engine_data} gems ${engine_gems_index}) + if(json_error) + message(FATAL_ERROR "Unable to read engine gems[${gems_index}] '${o3de_manifest_json_path}', error: ${json_error}") + endif() + list(APPEND o3de_gems ${engine_gems_path}) + list(APPEND o3de_engine_gems ${engine_gems_path}) + endforeach() + endif() + + ################################################################################ + # o3de engine templates + ################################################################################ + string(JSON o3de_engine_templates_count ERROR_VARIABLE json_error LENGTH ${engine_data} templates) + if(json_error) + message(FATAL_ERROR "Unable to read key 'templates' from '${o3de_manifest_json_path}', error: ${json_error}") + endif() + if(${o3de_engine_gems_count} GREATER 0) + math(EXPR o3de_engine_templates_count "${o3de_engine_templates_count}-1") + foreach(engine_templates_index RANGE ${o3de_engine_templates_count}) + string(JSON engine_templates_path ERROR_VARIABLE json_error GET ${engine_data} templates ${engine_templates_index}) + if(json_error) + message(FATAL_ERROR "Unable to read engine templates[${templates_index}] '${o3de_manifest_json_path}', error: ${json_error}") + endif() + list(APPEND o3de_templates ${engine_templates_path}) + list(APPEND o3de_engine_templates ${engine_templates_path}) + endforeach() + endif() + + ################################################################################ + # o3de engine restricted + ################################################################################ + string(JSON o3de_engine_restricted_count ERROR_VARIABLE json_error LENGTH ${engine_data} restricted) + if(json_error) + message(FATAL_ERROR "Unable to read key 'restricted' from '${o3de_manifest_json_path}', error: ${json_error}") + endif() + if(${o3de_engine_restricted_count} GREATER 0) + math(EXPR o3de_engine_restricted_count "${o3de_engine_restricted_count}-1") + foreach(engine_restricted_index RANGE ${o3de_engine_restricted_count}) + string(JSON engine_restricted_path ERROR_VARIABLE json_error GET ${engine_data} restricted ${engine_restricted_index}) + if(json_error) + message(FATAL_ERROR "Unable to read engine restricted[${engine_restricted_index}] '${o3de_manifest_json_path}', error: ${json_error}") + endif() + list(APPEND o3de_restricted ${engine_restricted_path}) + list(APPEND o3de_engine_restricted ${engine_restricted_path}) + endforeach() + endif() + + ################################################################################ + # o3de engine external_subdirectories + ################################################################################ + string(JSON o3de_external_subdirectories_count ERROR_VARIABLE json_error LENGTH ${engine_data} external_subdirectories) + if(json_error) + message(FATAL_ERROR "Unable to read key 'external_subdirectories' from '${o3de_manifest_json_path}', error: ${json_error}") + endif() + if(${o3de_external_subdirectories_count} GREATER 0) + math(EXPR o3de_external_subdirectories_count "${o3de_external_subdirectories_count}-1") + foreach(external_subdirectories_index RANGE ${o3de_external_subdirectories_count}) + string(JSON external_subdirectories_path ERROR_VARIABLE json_error GET ${engine_data} external_subdirectories ${external_subdirectories_index}) + if(json_error) + message(FATAL_ERROR "Unable to read engine external_subdirectories[${gems_index}] '${o3de_manifest_json_path}', error: ${json_error}") + endif() + list(APPEND o3de_engine_external_subdirectories ${external_subdirectories_path}) + endforeach() + endif() + + break() + + endif() + endforeach() +endif() + + +################################################################################ +#! o3de_engine_id: +# +# \arg:engine returns the engine association element from an o3de json +# \arg:o3de_json_file name of the o3de json file +################################################################################ +function(o3de_engine_id o3de_json_file engine) + file(READ ${o3de_json_file} json_data) + string(JSON engine_entry ERROR_VARIABLE json_error GET ${json_data} engine) + if(json_error) + message(WARNING "Unable to read engine from '${o3de_json_file}', error: ${json_error}") + message(WARNING "Setting engine to engine default 'o3de'") + set(engine_entry "o3de") + endif() + if(engine_entry) + set(${engine} ${engine_entry} PARENT_SCOPE) + endif() +endfunction() + + +################################################################################ +#! o3de_project_id: +# +# \arg:project returns the project association element from an o3de json +# \arg:o3de_json_file name of the o3de json file +################################################################################ +function(o3de_project_id o3de_json_file project) + file(READ ${o3de_json_file} json_data) + string(JSON project_entry ERROR_VARIABLE json_error GET ${json_data} project) + if(json_error) + message(FATAL_ERROR "Unable to read project from '${o3de_json_file}', error: ${json_error}") + endif() + if(project_entry) + set(${project} ${project_entry} PARENT_SCOPE) + endif() +endfunction() + + +################################################################################ +#! o3de_gem_id: +# +# \arg:gem returns the gem association element from an o3de json +# \arg:o3de_json_file name of the o3de json file +################################################################################ +function(o3de_gem_id o3de_json_file gem) + file(READ ${o3de_json_file} json_data) + string(JSON gem_entry ERROR_VARIABLE json_error GET ${json_data} gem) + if(json_error) + message(FATAL_ERROR "Unable to read gem from '${o3de_json_file}', error: ${json_error}") + endif() + if(gem_entry) + set(${gem} ${gem_entry} PARENT_SCOPE) + endif() +endfunction() + + +################################################################################ +#! o3de_template_id: +# +# \arg:template returns the template association element from an o3de json +# \arg:o3de_json_file name of the o3de json file +################################################################################ +function(o3de_template_id o3de_json_file template) + file(READ ${o3de_json_file} json_data) + string(JSON template_entry ERROR_VARIABLE json_error GET ${json_data} template) + if(json_error) + message(FATAL_ERROR "Unable to read template from '${o3de_json_file}', error: ${json_error}") + endif() + if(template_entry) + set(${template} ${template_entry} PARENT_SCOPE) + endif() +endfunction() + + +################################################################################ +#! o3de_repo_id: +# +# \arg:repo returns the repo association element from an o3de json +# \arg:o3de_json_file name of the o3de json file +################################################################################ +function(o3de_repo_id o3de_json_file repo) + file(READ ${o3de_json_file} json_data) + string(JSON repo_entry ERROR_VARIABLE json_error GET ${json_data} repo) + if(json_error) + message(FATAL_ERROR "Unable to read repo from '${o3de_json_file}', error: ${json_error}") + endif() + if(repo_entry) + set(${repo} ${repo_entry} PARENT_SCOPE) + endif() +endfunction() + + +################################################################################ +#! o3de_restricted_id: +# +# \arg:restricted returns the restricted association element from an o3de json, otherwise engine 'o3de' is assumed +# \arg:o3de_json_file name of the o3de json file +################################################################################ +function(o3de_restricted_id o3de_json_file restricted) + file(READ ${o3de_json_file} json_data) + string(JSON restricted_entry ERROR_VARIABLE json_error GET ${json_data} restricted) + if(json_error) + message(WARNING "Unable to read restricted from '${o3de_json_file}', error: ${json_error}") + message(WARNING "Setting restricted to engine default 'o3de'") + set(restricted_entry "o3de") + endif() + if(restricted_entry) + set(${restricted} ${restricted_entry} PARENT_SCOPE) + endif() +endfunction() + + +################################################################################ +#! o3de_find_engine_folder: +# +# \arg:engine_path returns the path of the o3de engine folder with name engine_name +# \arg:engine_name name of the engine +################################################################################ +function(o3de_find_engine_folder engine_name engine_path) + foreach(engine_entry ${o3de_engines}) + set(engine_json_file ${engine_entry}/engine.json) + file(READ ${engine_json_file} engine_json) + string(JSON this_engine_name ERROR_VARIABLE json_error GET ${engine_json} engine_name) + if(json_error) + message(WARNING "Unable to read engine_name from '${engine_json_file}', error: ${json_error}") + else() + if(this_engine_name STREQUAL engine_name) + set(${engine_path} ${engine_entry} PARENT_SCOPE) + return() + endif() + endif() + endforeach() + message(FATAL_ERROR "Unable to find repo_name: '${engine_name}'") +endfunction() + + +################################################################################ +#! o3de_find_project_folder: +# +# \arg:project_path returns the path of the o3de project folder with name project_name +# \arg:project_name name of the project +################################################################################ +function(o3de_find_project_folder project_name project_path) + foreach(project_entry ${o3de_projects}) + set(project_json_file ${project_entry}/project.json) + file(READ ${project_json_file} project_json) + string(JSON this_project_name ERROR_VARIABLE json_error GET ${project_json} project_name) + if(json_error) + message(WARNING "Unable to read project_name from '${project_json_file}', error: ${json_error}") + else() + if(this_project_name STREQUAL project_name) + set(${project_path} ${project_entry} PARENT_SCOPE) + return() + endif() + endif() + endforeach() + message(FATAL_ERROR "Unable to find project_name: '${project_name}'") +endfunction() + + +################################################################################ +#! o3de_find_gem_folder: +# +# \arg:gem_path returns the path of the o3de gem folder with name gem_name +# \arg:gem_name name of the gem +################################################################################ +function(o3de_find_gem_folder gem_name gem_path) + foreach(gem_entry ${o3de_gems}) + set(gem_json_file ${gem_entry}/gem.json) + file(READ ${gem_json_file} gem_json) + string(JSON this_gem_name ERROR_VARIABLE json_error GET ${gem_json} gem_name) + if(json_error) + message(WARNING "Unable to read gem_name from '${gem_json_file}', error: ${json_error}") + else() + if(this_gem_name STREQUAL gem_name) + set(${gem_path} ${gem_entry} PARENT_SCOPE) + return() + endif() + endif() + endforeach() + message(FATAL_ERROR "Unable to find gem_name: '${gem_name}'") +endfunction() + + +################################################################################ +#! o3de_find_template_folder: +# +# \arg:template_path returns the path of the o3de template folder with name template_name +# \arg:template_name name of the template +################################################################################ +function(o3de_find_template_folder template_name template_path) + foreach(template_entry ${o3de_templates}) + set(template_json_file ${template_entry}/template.json) + file(READ ${template_json_file} template_json) + string(JSON this_template_name ERROR_VARIABLE json_error GET ${template_json} template_name) + if(json_error) + message(WARNING "Unable to read template_name from '${template_json_file}', error: ${json_error}") + else() + if(this_template_name STREQUAL template_name) + set(${template_path} ${template_entry} PARENT_SCOPE) + return() + endif() + endif() + endforeach() + message(FATAL_ERROR "Unable to find template_name: '${template_name}'") +endfunction() + + +################################################################################ +#! o3de_find_repo_folder: +# +# \arg:repo_path returns the path of the o3de repo folder with name repo_name +# \arg:repo_name name of the repo +################################################################################ +function(o3de_find_repo_folder repo_name repo_path) + foreach(repo_entry ${o3de_repos}) + set(repo_json_file ${repo_entry}/repo.json) + file(READ ${repo_json_file} repo_json) + string(JSON this_repo_name ERROR_VARIABLE json_error GET ${repo_json} repo_name) + if(json_error) + message(WARNING "Unable to read repo_name from '${repo_json_file}', error: ${json_error}") + else() + if(this_repo_name STREQUAL repo_name) + set(${repo_path} ${repo_entry} PARENT_SCOPE) + return() + endif() + endif() + endforeach() + message(FATAL_ERROR "Unable to find repo_name: '${repo_name}'") +endfunction() + + +################################################################################ +#! o3de_find_restricted_folder: +# +# \arg:restricted_path returns the path of the o3de restricted folder with name restricted_name +# \arg:restricted_name name of the restricted +################################################################################ +function(o3de_find_restricted_folder restricted_name restricted_path) + foreach(restricted_entry ${o3de_restricted}) + set(restricted_json_file ${restricted_entry}/restricted.json) + file(READ ${restricted_json_file} restricted_json) + string(JSON this_restricted_name ERROR_VARIABLE json_error GET ${restricted_json} restricted_name) + if(json_error) + message(WARNING "Unable to read restricted_name from '${restricted_json_file}', error: ${json_error}") + else() + if(this_restricted_name STREQUAL restricted_name) + set(${restricted_path} ${restricted_entry} PARENT_SCOPE) + return() + endif() + endif() + endforeach() + message(FATAL_ERROR "Unable to find restricted_name: '${restricted_name}'") +endfunction() + + +################################################################################ +#! o3de_engine_name: +# +# \arg:engine returns the engine_name element from an engine.json +# \arg:o3de_engine_json_file name of the o3de json file +################################################################################ +function(o3de_engine_name o3de_engine_json_file engine) + file(READ ${o3de_engine_json_file} json_data) + string(JSON engine_entry ERROR_VARIABLE json_error GET ${json_data} engine_name) + if(json_error) + message(FATAL_ERROR "Unable to read engine_name from '${o3de_json_file}', error: ${json_error}") + endif() + if(engine_entry) + set(${engine} ${engine_entry} PARENT_SCOPE) + endif() +endfunction() + + +################################################################################ +#! o3de_project_name: +# +# \arg:project returns the project_name element from an project.json +# \arg:o3de_project_json_file name of the o3de json file +################################################################################ +function(o3de_project_name o3de_project_json_file project) + file(READ ${o3de_project_json_file} json_data) + string(JSON project_entry ERROR_VARIABLE json_error GET ${json_data} project_name) + if(json_error) + message(FATAL_ERROR "Unable to read project_name from '${o3de_json_file}', error: ${json_error}") + endif() + if(project_entry) + set(${project} ${project_entry} PARENT_SCOPE) + endif() +endfunction() + + +################################################################################ +#! o3de_gem_name: +# +# \arg:gem returns the gem_name element from an gem.json +# \arg:o3de_gem_json_file name of the o3de json file +################################################################################ +function(o3de_gem_name o3de_gem_json_file gem) + file(READ ${o3de_gem_json_file} json_data) + string(JSON gem_entry ERROR_VARIABLE json_error GET ${json_data} gem_name) + if(json_error) + message(FATAL_ERROR "Unable to read gem_name from '${o3de_json_file}', error: ${json_error}") + endif() + if(gem_entry) + set(${gem} ${gem_entry} PARENT_SCOPE) + endif() +endfunction() + + +################################################################################ +#! o3de_template_name: +# +# \arg:template returns the template_name element from an template json +# \arg:o3de_template_json_file name of the o3de json file +################################################################################ +function(o3de_template_name o3de_template_json_file template) + file(READ ${o3de_template_json_file} json_data) + string(JSON template_entry ERROR_VARIABLE json_error GET ${json_data} template_name) + if(json_error) + message(FATAL_ERROR "Unable to read template_name from '${o3de_json_file}', error: ${json_error}") + endif() + if(template_entry) + set(${template} ${template_entry} PARENT_SCOPE) + endif() +endfunction() + + +################################################################################ +#! o3de_repo_name: +# +# \arg:repo returns the repo_name element from an repo.json or o3de_manifest.json +# \arg:o3de_repo_json_file name of the o3de json file +################################################################################ +function(o3de_repo_name o3de_repo_json_file repo) + file(READ ${o3de_repo_json_file} json_data) + string(JSON repo_entry ERROR_VARIABLE json_error GET ${json_data} repo_name) + if(json_error) + message(FATAL_ERROR "Unable to read repo_name from '${o3de_json_file}', error: ${json_error}") + endif() + if(repo_entry) + set(${repo} ${repo_entry} PARENT_SCOPE) + endif() +endfunction() + + +################################################################################ +#! o3de_restricted_name: +# +# \arg:restricted returns the restricted association element from an o3de json +# \arg:o3de_json_file name of the o3de json file +################################################################################ +function(o3de_restricted_name o3de_json_file restricted) + file(READ ${o3de_json_file} json_data) + string(JSON restricted_entry ERROR_VARIABLE json_error GET ${json_data} restricted_name) + if(json_error) + message(WARNING "FATAL_ERROR to read restricted_name from '${o3de_json_file}', error: ${json_error}") + endif() + if(restricted_entry) + set(${restricted} ${restricted_entry} PARENT_SCOPE) + endif() +endfunction() + + +################################################################################ +#! o3de_engine_path: +# +# \arg:engine_path returns the path of the o3de engine folder with name engine_name +# \arg:engine_name name of the engine +################################################################################ +function(o3de_engine_path o3de_json_file engine_path) + o3de_engine_id(${o3de_json_file} engine_name) + if(engine_name) + o3de_find_engine_folder(${engine_name} engine_folder) + if(engine_folder) + set(${engine_path} ${engine_folder} PARENT_SCOPE) + endif() + endif() +endfunction() + + +################################################################################ +#! o3de_project_path: +# +# \arg:project_path returns the path of the o3de project folder with name project_name +# \arg:project_name name of the project +################################################################################ +function(o3de_project_path o3de_json_file project_path) + o3de_project_id(${o3de_json_file} project_name) + if(project_name) + o3de_find_project_folder(${project_name} project_folder) + if(project_folder) + set(${project_path} ${project_folder} PARENT_SCOPE) + endif() + endif() +endfunction() + + +################################################################################ +#! o3de_template_path: +# +# \arg:template_path returns the path of the o3de template folder with name template_name +# \arg:template_name name of the template +################################################################################ +function(o3de_template_path o3de_json_file template_path) + o3de_template_id(${o3de_json_file} template_name) + if(template_name) + o3de_find_template_folder(${template_name} template_folder) + if(template_folder) + set(${template_path} ${template_folder} PARENT_SCOPE) + endif() + endif() +endfunction() + + +################################################################################ +#! o3de_repo_path: +# +# \arg:repo_path returns the path of the o3de repo folder with name repo_name +# \arg:repo_name name of the repo +################################################################################ +function(o3de_repo_path o3de_json_file repo_path) + o3de_repo_id(${o3de_json_file} repo_name) + if(repo_name) + o3de_find_repo_folder(${repo_name} repo_folder) + if(repo_folder) + set(${repo_path} ${repo_folder} PARENT_SCOPE) + endif() + endif() +endfunction() + + +################################################################################ +#! o3de_restricted_path: +# +# \arg:restricted_path returns the path of the o3de restricted folder with name restricted_name +# \arg:restricted_name name of the restricted +################################################################################ +function(o3de_restricted_path o3de_json_file restricted_path) + o3de_restricted_id(${o3de_json_file} restricted_name) + if(restricted_name) + o3de_find_restricted_folder(${restricted_name} restricted_folder) + if(restricted_folder) + set(${restricted_path} ${restricted_folder} PARENT_SCOPE) + endif() + endif() +endfunction() diff --git a/engine.json b/engine.json index 5091605f4c..22ac2512f5 100644 --- a/engine.json +++ b/engine.json @@ -1,5 +1,6 @@ { "engine_name": "o3de", + "restricted": "o3de", "FileVersion": 1, "O3DEVersion": "0.0.0.0", "O3DECopyrightYear": 2021 diff --git a/scripts/build/Jenkins/Jenkinsfile b/scripts/build/Jenkins/Jenkinsfile index f85b0b5ef4..ae2779eba8 100644 --- a/scripts/build/Jenkins/Jenkinsfile +++ b/scripts/build/Jenkins/Jenkinsfile @@ -60,7 +60,7 @@ def palRm(path) { } else { def win_path = path.replace('/','\\') bat label: "Removing ${win_path}", - script: "del ${win_path}" + script: "del /Q ${win_path}" } } @@ -354,6 +354,16 @@ def TestMetrics(Map pipelineConfig, String workspace, String branchName, String } } +def ExportTestResults(Map options, String platform, String type, String workspace, Map params) { + catchError(message: "Error exporting tests results (this won't fail the build)", buildResult: 'SUCCESS', stageResult: 'FAILURE') { + def o3deroot = "${workspace}/${ENGINE_REPOSITORY_NAME}" + dir("${o3deroot}/${params.OUTPUT_DIRECTORY}") { + junit testResults: "Testing/**/*.xml" + palRmDir("Testing") + } + } +} + def PostBuildCommonSteps(String workspace, boolean mount = true) { echo 'Starting post-build common steps...' @@ -396,6 +406,14 @@ def CreateTestMetricsStage(Map pipelineConfig, String branchName, Map environmen } } +def CreateExportTestResultsStage(Map pipelineConfig, String platformName, String jobName, Map environmentVars, Map params) { + return { + stage("${jobName}_results") { + ExportTestResults(pipelineConfig, platformName, jobName, environmentVars['WORKSPACE'], params) + } + } +} + def CreateTeardownStage(Map environmentVars) { return { stage('Teardown') { @@ -511,11 +529,15 @@ try { } } finally { - if (env.MARS_REPO && platform.value.build_types[build_job_name].PARAMETERS.containsKey('TEST_METRICS') && platform.value.build_types[build_job_name].PARAMETERS.TEST_METRICS == 'True') { - def output_directory = platform.value.build_types[build_job_name].PARAMETERS.OUTPUT_DIRECTORY - def configuration = platform.value.build_types[build_job_name].PARAMETERS.CONFIGURATION + def params = platform.value.build_types[build_job_name].PARAMETERS + if (env.MARS_REPO && params && params.containsKey('TEST_METRICS') && params.TEST_METRICS == 'True') { + def output_directory = params.OUTPUT_DIRECTORY + def configuration = params.CONFIGURATION CreateTestMetricsStage(pipelineConfig, branchName, envVars, build_job_name, output_directory, configuration).call() } + if (params && params.containsKey('TEST_RESULTS') && params.TEST_RESULTS == 'True') { + CreateExportTestResultsStage(pipelineConfig, platform.key, build_job_name, envVars, params).call() + } CreateTeardownStage(envVars).call() } } diff --git a/scripts/build/Platform/Android/build_config.json b/scripts/build/Platform/Android/build_config.json index 07dc363296..d0fce80964 100644 --- a/scripts/build/Platform/Android/build_config.json +++ b/scripts/build/Platform/Android/build_config.json @@ -27,14 +27,15 @@ }, "debug": { "TAGS":[ - "nightly", + "nightly-incremental", + "nightly-clean", "weekly-build-metrics" ], "COMMAND":"../Windows/build_ninja_windows.cmd", "PARAMETERS": { "CONFIGURATION":"debug", "OUTPUT_DIRECTORY":"build\\android", - "CMAKE_OPTIONS":"-G \"Ninja Multi-Config\" -DCMAKE_TOOLCHAIN_FILE=cmake\\Platform\\Android\\Toolchain_android.cmake -DANDROID_ABI=arm64-v8a -DANDROID_ARM_MODE=arm -DANDROID_ARM_NEON=FALSE -DANDROID_NATIVE_API_LEVEL=21 -DLY_NDK_DIR=\"!LY_3RDPARTY_PATH!\\android-ndk\\r21d\" -DLY_UNITY_BUILD=TRUE", + "CMAKE_OPTIONS":"-G \"Ninja Multi-Config\" -DCMAKE_TOOLCHAIN_FILE=cmake\\Platform\\Android\\Toolchain_android.cmake -DANDROID_ABI=arm64-v8a -DANDROID_ARM_MODE=arm -DANDROID_ARM_NEON=FALSE -DANDROID_NATIVE_API_LEVEL=21 -DLY_NDK_DIR=\"!LY_3RDPARTY_PATH!\\android-ndk\\r21d\" -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", "CMAKE_BUILD_ARGS":"-j!NUMBER_OF_PROCESSORS!" @@ -59,7 +60,7 @@ "PARAMETERS": { "CONFIGURATION":"profile", "OUTPUT_DIRECTORY":"build\\android", - "CMAKE_OPTIONS":"-G \"Ninja Multi-Config\" -DCMAKE_TOOLCHAIN_FILE=cmake\\Platform\\Android\\Toolchain_android.cmake -DANDROID_ABI=arm64-v8a -DANDROID_ARM_MODE=arm -DANDROID_ARM_NEON=FALSE -DANDROID_NATIVE_API_LEVEL=21 -DLY_NDK_DIR=\"!LY_3RDPARTY_PATH!\\android-ndk\\r21d\" -DLY_UNITY_BUILD=TRUE", + "CMAKE_OPTIONS":"-G \"Ninja Multi-Config\" -DCMAKE_TOOLCHAIN_FILE=cmake\\Platform\\Android\\Toolchain_android.cmake -DANDROID_ABI=arm64-v8a -DANDROID_ARM_MODE=arm -DANDROID_ARM_NEON=FALSE -DANDROID_NATIVE_API_LEVEL=21 -DLY_NDK_DIR=\"!LY_3RDPARTY_PATH!\\android-ndk\\r21d\" -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", "CMAKE_BUILD_ARGS":"-j!NUMBER_OF_PROCESSORS!" @@ -67,14 +68,15 @@ }, "profile_nounity": { "TAGS":[ - "nightly", + "nightly-incremental", + "nightly-clean", "weekly-build-metrics" ], "COMMAND":"../Windows/build_ninja_windows.cmd", "PARAMETERS": { "CONFIGURATION":"profile", "OUTPUT_DIRECTORY":"build\\android", - "CMAKE_OPTIONS":"-G \"Ninja Multi-Config\" -DCMAKE_TOOLCHAIN_FILE=cmake\\Platform\\Android\\Toolchain_android.cmake -DANDROID_ABI=arm64-v8a -DANDROID_ARM_MODE=arm -DANDROID_ARM_NEON=FALSE -DANDROID_NATIVE_API_LEVEL=21 -DLY_NDK_DIR=\"!LY_3RDPARTY_PATH!\\android-ndk\\r21d\" -DLY_UNITY_BUILD=FALSE", + "CMAKE_OPTIONS":"-G \"Ninja Multi-Config\" -DCMAKE_TOOLCHAIN_FILE=cmake\\Platform\\Android\\Toolchain_android.cmake -DANDROID_ABI=arm64-v8a -DANDROID_ARM_MODE=arm -DANDROID_ARM_NEON=FALSE -DANDROID_NATIVE_API_LEVEL=21 -DLY_NDK_DIR=\"!LY_3RDPARTY_PATH!\\android-ndk\\r21d\" -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", "CMAKE_BUILD_ARGS":"-j!NUMBER_OF_PROCESSORS!" @@ -83,13 +85,15 @@ "asset_profile": { "TAGS":[ "default", - "weekly-build-metrics" + "weekly-build-metrics", + "nightly-incremental", + "nightly-clean" ], "COMMAND":"../Windows/build_asset_windows.cmd", "PARAMETERS": { "CONFIGURATION":"profile", "OUTPUT_DIRECTORY":"build\\windows_vs2019", - "CMAKE_OPTIONS":"-G \"Visual Studio 16 2019\" -DCMAKE_SYSTEM_VERSION=10.0 -DLY_UNITY_BUILD=TRUE", + "CMAKE_OPTIONS":"-G \"Visual Studio 16 2019\" -DCMAKE_SYSTEM_VERSION=10.0 -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":"AssetProcessorBatch", "CMAKE_NATIVE_BUILD_ARGS": "/m /nologo", @@ -98,28 +102,17 @@ "ASSET_PROCESSOR_PLATFORMS":"es3" } }, - "asset_clean_profile": { - "TAGS":[ - "nightly" - ], - "PIPELINE_ENV": { - "CLEAN_ASSETS": "1" - }, - "steps": [ - "clean", - "asset_profile" - ] - }, "release": { "TAGS":[ - "nightly", + "nightly-incremental", + "nightly-clean", "weekly-build-metrics" ], "COMMAND":"../Windows/build_ninja_windows.cmd", "PARAMETERS": { "CONFIGURATION":"release", "OUTPUT_DIRECTORY":"build\\android", - "CMAKE_OPTIONS":"-G \"Ninja Multi-Config\" -DCMAKE_TOOLCHAIN_FILE=cmake\\Platform\\Android\\Toolchain_android.cmake -DANDROID_ABI=arm64-v8a -DANDROID_ARM_MODE=arm -DANDROID_ARM_NEON=FALSE -DANDROID_NATIVE_API_LEVEL=21 -DLY_NDK_DIR=\"!LY_3RDPARTY_PATH!\\android-ndk\\r21d\" -DLY_UNITY_BUILD=TRUE", + "CMAKE_OPTIONS":"-G \"Ninja Multi-Config\" -DCMAKE_TOOLCHAIN_FILE=cmake\\Platform\\Android\\Toolchain_android.cmake -DANDROID_ABI=arm64-v8a -DANDROID_ARM_MODE=arm -DANDROID_ARM_NEON=FALSE -DANDROID_NATIVE_API_LEVEL=21 -DLY_NDK_DIR=\"!LY_3RDPARTY_PATH!\\android-ndk\\r21d\" -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", "CMAKE_BUILD_ARGS":"-j!NUMBER_OF_PROCESSORS!" @@ -127,14 +120,15 @@ }, "monolithic_release": { "TAGS":[ - "nightly", + "nightly-incremental", + "nightly-clean", "weekly-build-metrics" ], "COMMAND":"../Windows/build_ninja_windows.cmd", "PARAMETERS": { "CONFIGURATION":"release", "OUTPUT_DIRECTORY":"build\\mono_android", - "CMAKE_OPTIONS":"-G \"Ninja Multi-Config\" -DCMAKE_TOOLCHAIN_FILE=cmake\\Platform\\Android\\Toolchain_android.cmake -DANDROID_ABI=arm64-v8a -DANDROID_ARM_MODE=arm -DANDROID_ARM_NEON=FALSE -DANDROID_NATIVE_API_LEVEL=21 -DLY_NDK_DIR=\"!LY_3RDPARTY_PATH!\\android-ndk\\r21d\" -DLY_MONOLITHIC_GAME=TRUE -DLY_UNITY_BUILD=TRUE", + "CMAKE_OPTIONS":"-G \"Ninja Multi-Config\" -DCMAKE_TOOLCHAIN_FILE=cmake\\Platform\\Android\\Toolchain_android.cmake -DANDROID_ABI=arm64-v8a -DANDROID_ARM_MODE=arm -DANDROID_ARM_NEON=FALSE -DANDROID_NATIVE_API_LEVEL=21 -DLY_NDK_DIR=\"!LY_3RDPARTY_PATH!\\android-ndk\\r21d\" -DLY_MONOLITHIC_GAME=TRUE -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", "CMAKE_BUILD_ARGS":"-j!NUMBER_OF_PROCESSORS!" diff --git a/scripts/build/Platform/Android/pipeline.json b/scripts/build/Platform/Android/pipeline.json index a4a2700af0..ed10e7022d 100644 --- a/scripts/build/Platform/Android/pipeline.json +++ b/scripts/build/Platform/Android/pipeline.json @@ -13,6 +13,9 @@ }, "packaging": { "CLEAN_WORKSPACE": true + }, + "nightly-clean": { + "CLEAN_WORKSPACE": true } } } \ No newline at end of file diff --git a/scripts/build/Platform/Linux/build_config.json b/scripts/build/Platform/Linux/build_config.json index 426bf1d7ce..bbfc3e4269 100644 --- a/scripts/build/Platform/Linux/build_config.json +++ b/scripts/build/Platform/Linux/build_config.json @@ -29,29 +29,31 @@ }, "debug": { "TAGS": [ - "nightly", + "nightly-incremental", + "nightly-clean", "weekly-build-metrics" ], "COMMAND": "build_linux.sh", "PARAMETERS": { "CONFIGURATION": "debug", "OUTPUT_DIRECTORY": "build/linux", - "CMAKE_OPTIONS": "-G 'Ninja Multi-Config' -DCMAKE_C_COMPILER=clang-6.0 -DCMAKE_CXX_COMPILER=clang++-6.0 -DLY_UNITY_BUILD=TRUE -DLY_PARALLEL_LINK_JOBS=4", + "CMAKE_OPTIONS": "-G 'Ninja Multi-Config' -DCMAKE_C_COMPILER=clang-6.0 -DCMAKE_CXX_COMPILER=clang++-6.0 -DLY_UNITY_BUILD=TRUE -DLY_PARALLEL_LINK_JOBS=4 -DO3DE_HOME_PATH=\"${WORKSPACE}/home\" -DO3DE_REGISTER_ENGINE_PATH=\"${WORKSPACE}/o3de\" -DO3DE_REGISTER_THIS_ENGINE=TRUE", "CMAKE_LY_PROJECTS": "AutomatedTesting", "CMAKE_TARGET": "all" } }, "profile": { "TAGS": [ - "nightly", - "daily-pipeline-metrics", - "weekly-build-metrics" + "nightly-incremental", + "nightly-clean", + "daily-pipeline-metrics", + "weekly-build-metrics" ], "COMMAND": "build_linux.sh", "PARAMETERS": { "CONFIGURATION": "profile", "OUTPUT_DIRECTORY": "build/linux", - "CMAKE_OPTIONS": "-G 'Ninja Multi-Config' -DCMAKE_C_COMPILER=clang-6.0 -DCMAKE_CXX_COMPILER=clang++-6.0 -DLY_UNITY_BUILD=TRUE -DLY_PARALLEL_LINK_JOBS=4", + "CMAKE_OPTIONS": "-G 'Ninja Multi-Config' -DCMAKE_C_COMPILER=clang-6.0 -DCMAKE_CXX_COMPILER=clang++-6.0 -DLY_UNITY_BUILD=TRUE -DLY_PARALLEL_LINK_JOBS=4 -DO3DE_HOME_PATH=\"${WORKSPACE}/home\" -DO3DE_REGISTER_ENGINE_PATH=\"${WORKSPACE}/o3de\" -DO3DE_REGISTER_THIS_ENGINE=TRUE", "CMAKE_LY_PROJECTS": "AutomatedTesting", "CMAKE_TARGET": "all" } @@ -64,7 +66,7 @@ "PARAMETERS": { "CONFIGURATION": "profile", "OUTPUT_DIRECTORY": "build/linux", - "CMAKE_OPTIONS": "-G 'Ninja Multi-Config' -DCMAKE_C_COMPILER=clang-6.0 -DCMAKE_CXX_COMPILER=clang++-6.0 -DLY_UNITY_BUILD=FALSE -DLY_PARALLEL_LINK_JOBS=4", + "CMAKE_OPTIONS": "-G 'Ninja Multi-Config' -DCMAKE_C_COMPILER=clang-6.0 -DCMAKE_CXX_COMPILER=clang++-6.0 -DLY_UNITY_BUILD=FALSE -DLY_PARALLEL_LINK_JOBS=4 -DO3DE_HOME_PATH=\"${WORKSPACE}/home\" -DO3DE_REGISTER_ENGINE_PATH=\"${WORKSPACE}/o3de\" -DO3DE_REGISTER_THIS_ENGINE=TRUE", "CMAKE_LY_PROJECTS": "AutomatedTesting", "CMAKE_TARGET": "all" } @@ -78,7 +80,7 @@ "PARAMETERS": { "CONFIGURATION": "profile", "OUTPUT_DIRECTORY": "build/linux", - "CMAKE_OPTIONS": "-G 'Ninja Multi-Config' -DCMAKE_C_COMPILER=clang-6.0 -DCMAKE_CXX_COMPILER=clang++-6.0 -DLY_UNITY_BUILD=TRUE -DLY_PARALLEL_LINK_JOBS=4", + "CMAKE_OPTIONS": "-G 'Ninja Multi-Config' -DCMAKE_C_COMPILER=clang-6.0 -DCMAKE_CXX_COMPILER=clang++-6.0 -DLY_UNITY_BUILD=TRUE -DLY_PARALLEL_LINK_JOBS=4 -DO3DE_HOME_PATH=\"${WORKSPACE}/home\" -DO3DE_REGISTER_ENGINE_PATH=\"${WORKSPACE}/o3de\" -DO3DE_REGISTER_THIS_ENGINE=TRUE", "CMAKE_LY_PROJECTS": "AutomatedTesting", "CMAKE_TARGET": "all", "CTEST_OPTIONS": "-E (Gem::EMotionFX.Editor.Tests|Gem::AWSClientAuth.Tests|Gem::AWSCore.Editor.Tests) -L FRAMEWORK_googletest" @@ -90,7 +92,7 @@ "PARAMETERS": { "CONFIGURATION": "profile", "OUTPUT_DIRECTORY": "build/linux", - "CMAKE_OPTIONS": "-G 'Ninja Multi-Config' -DCMAKE_C_COMPILER=clang-6.0 -DCMAKE_CXX_COMPILER=clang++-6.0 -DLY_UNITY_BUILD=FALSE -DLY_PARALLEL_LINK_JOBS=4", + "CMAKE_OPTIONS": "-G 'Ninja Multi-Config' -DCMAKE_C_COMPILER=clang-6.0 -DCMAKE_CXX_COMPILER=clang++-6.0 -DLY_UNITY_BUILD=FALSE -DLY_PARALLEL_LINK_JOBS=4 -DO3DE_HOME_PATH=\"${WORKSPACE}/home\" -DO3DE_REGISTER_ENGINE_PATH=\"${WORKSPACE}/o3de\" -DO3DE_REGISTER_THIS_ENGINE=TRUE", "CMAKE_LY_PROJECTS": "AutomatedTesting", "CMAKE_TARGET": "all", "CTEST_OPTIONS": "-E (Gem::EMotionFX.Editor.Tests|Gem::AWSClientAuth.Tests|Gem::AWSCore.Editor.Tests) -L FRAMEWORK_googletest" @@ -98,13 +100,15 @@ }, "asset_profile": { "TAGS": [ - "weekly-build-metrics" + "weekly-build-metrics", + "nightly-incremental", + "nightly-clean" ], "COMMAND": "build_asset_linux.sh", "PARAMETERS": { "CONFIGURATION": "profile", "OUTPUT_DIRECTORY": "build/linux", - "CMAKE_OPTIONS": "-G 'Ninja Multi-Config' -DCMAKE_C_COMPILER=clang-6.0 -DCMAKE_CXX_COMPILER=clang++-6.0 -DLY_UNITY_BUILD=TRUE -DLY_PARALLEL_LINK_JOBS=4", + "CMAKE_OPTIONS": "-G 'Ninja Multi-Config' -DCMAKE_C_COMPILER=clang-6.0 -DCMAKE_CXX_COMPILER=clang++-6.0 -DLY_UNITY_BUILD=TRUE -DLY_PARALLEL_LINK_JOBS=4 -DO3DE_HOME_PATH=\"${WORKSPACE}/home\" -DO3DE_REGISTER_ENGINE_PATH=\"${WORKSPACE}/o3de\" -DO3DE_REGISTER_THIS_ENGINE=TRUE", "CMAKE_LY_PROJECTS": "AutomatedTesting", "CMAKE_TARGET": "AssetProcessorBatch", "ASSET_PROCESSOR_BINARY": "bin/profile/AssetProcessorBatch", @@ -118,7 +122,7 @@ "PARAMETERS": { "CONFIGURATION": "profile", "OUTPUT_DIRECTORY": "build/linux", - "CMAKE_OPTIONS": "-G 'Ninja Multi-Config' -DCMAKE_C_COMPILER=clang-6.0 -DCMAKE_CXX_COMPILER=clang++-6.0 -DLY_UNITY_BUILD=FALSE -DLY_PARALLEL_LINK_JOBS=4", + "CMAKE_OPTIONS": "-G 'Ninja Multi-Config' -DCMAKE_C_COMPILER=clang-6.0 -DCMAKE_CXX_COMPILER=clang++-6.0 -DLY_UNITY_BUILD=FALSE -DLY_PARALLEL_LINK_JOBS=4 -DO3DE_HOME_PATH=\"${WORKSPACE}/home\" -DO3DE_REGISTER_ENGINE_PATH=\"${WORKSPACE}/o3de\" -DO3DE_REGISTER_THIS_ENGINE=TRUE", "CMAKE_LY_PROJECTS": "AutomatedTesting", "CMAKE_TARGET": "AssetProcessorBatch", "ASSET_PROCESSOR_BINARY": "bin/profile/AssetProcessorBatch", @@ -126,28 +130,17 @@ "ASSET_PROCESSOR_PLATFORMS": "pc,server" } }, - "asset_clean_profile": { - "TAGS": [ - "nightly" - ], - "PIPELINE_ENV": { - "CLEAN_ASSETS": "1" - }, - "steps": [ - "clean", - "asset_profile" - ] - }, "periodic_test_profile": { "TAGS": [ - "nightly", + "nightly-incremental", + "nightly-clean", "weekly-build-metrics" ], "COMMAND": "build_test_linux.sh", "PARAMETERS": { "CONFIGURATION": "profile", "OUTPUT_DIRECTORY": "build/linux", - "CMAKE_OPTIONS": "-G 'Ninja Multi-Config' -DCMAKE_C_COMPILER=clang-6.0 -DCMAKE_CXX_COMPILER=clang++-6.0 -DLY_UNITY_BUILD=TRUE -DLY_PARALLEL_LINK_JOBS=4", + "CMAKE_OPTIONS": "-G 'Ninja Multi-Config' -DCMAKE_C_COMPILER=clang-6.0 -DCMAKE_CXX_COMPILER=clang++-6.0 -DLY_UNITY_BUILD=TRUE -DLY_PARALLEL_LINK_JOBS=4 -DO3DE_HOME_PATH=\"${WORKSPACE}/home\" -DO3DE_REGISTER_ENGINE_PATH=\"${WORKSPACE}/o3de\" -DO3DE_REGISTER_THIS_ENGINE=TRUE", "CMAKE_LY_PROJECTS": "AutomatedTesting", "CMAKE_TARGET": "TEST_SUITE_periodic", "CTEST_OPTIONS": "-L \"(SUITE_periodic)\"" @@ -155,14 +148,15 @@ }, "benchmark_test_profile": { "TAGS": [ - "nightly", + "nightly-incremental", + "nightly-clean", "weekly-build-metrics" ], "COMMAND": "build_test_linux.sh", "PARAMETERS": { "CONFIGURATION": "profile", "OUTPUT_DIRECTORY": "build/linux", - "CMAKE_OPTIONS": "-G 'Ninja Multi-Config' -DCMAKE_C_COMPILER=clang-6.0 -DCMAKE_CXX_COMPILER=clang++-6.0 -DLY_UNITY_BUILD=TRUE -DLY_PARALLEL_LINK_JOBS=4", + "CMAKE_OPTIONS": "-G 'Ninja Multi-Config' -DCMAKE_C_COMPILER=clang-6.0 -DCMAKE_CXX_COMPILER=clang++-6.0 -DLY_UNITY_BUILD=TRUE -DLY_PARALLEL_LINK_JOBS=4 -DO3DE_HOME_PATH=\"${WORKSPACE}/home\" -DO3DE_REGISTER_ENGINE_PATH=\"${WORKSPACE}/o3de\" -DO3DE_REGISTER_THIS_ENGINE=TRUE", "CMAKE_LY_PROJECTS": "AutomatedTesting", "CMAKE_TARGET": "TEST_SUITE_benchmark", "CTEST_OPTIONS": "-L \"(SUITE_benchmark)\"" @@ -170,28 +164,30 @@ }, "release": { "TAGS": [ - "nightly", + "nightly-incremental", + "nightly-clean", "weekly-build-metrics" ], "COMMAND": "build_linux.sh", "PARAMETERS": { "CONFIGURATION": "release", "OUTPUT_DIRECTORY": "build/linux", - "CMAKE_OPTIONS": "-G 'Ninja Multi-Config' -DCMAKE_C_COMPILER=clang-6.0 -DCMAKE_CXX_COMPILER=clang++-6.0 -DLY_UNITY_BUILD=TRUE -DLY_PARALLEL_LINK_JOBS=4", + "CMAKE_OPTIONS": "-G 'Ninja Multi-Config' -DCMAKE_C_COMPILER=clang-6.0 -DCMAKE_CXX_COMPILER=clang++-6.0 -DLY_UNITY_BUILD=TRUE -DLY_PARALLEL_LINK_JOBS=4 -DO3DE_HOME_PATH=\"${WORKSPACE}/home\" -DO3DE_REGISTER_ENGINE_PATH=\"${WORKSPACE}/o3de\" -DO3DE_REGISTER_THIS_ENGINE=TRUE", "CMAKE_LY_PROJECTS": "AutomatedTesting", "CMAKE_TARGET": "all" } }, "monolithic_release": { "TAGS": [ - "nightly", + "nightly-incremental", + "nightly-clean", "weekly-build-metrics" ], "COMMAND": "build_linux.sh", "PARAMETERS": { "CONFIGURATION": "release", "OUTPUT_DIRECTORY": "build/mono_linux", - "CMAKE_OPTIONS": "-G 'Ninja Multi-Config' -DCMAKE_C_COMPILER=clang-6.0 -DCMAKE_CXX_COMPILER=clang++-6.0 -DLY_MONOLITHIC_GAME=TRUE -DLY_UNITY_BUILD=TRUE -DLY_PARALLEL_LINK_JOBS=4", + "CMAKE_OPTIONS": "-G 'Ninja Multi-Config' -DCMAKE_C_COMPILER=clang-6.0 -DCMAKE_CXX_COMPILER=clang++-6.0 -DLY_MONOLITHIC_GAME=TRUE -DLY_UNITY_BUILD=TRUE -DLY_PARALLEL_LINK_JOBS=4 -DO3DE_HOME_PATH=\"${WORKSPACE}/home\" -DO3DE_REGISTER_ENGINE_PATH=\"${WORKSPACE}/o3de\" -DO3DE_REGISTER_THIS_ENGINE=TRUE", "CMAKE_LY_PROJECTS": "AutomatedTesting", "CMAKE_TARGET": "all" } diff --git a/scripts/build/Platform/Linux/pipeline.json b/scripts/build/Platform/Linux/pipeline.json index ec06dff5bf..d964a693ce 100644 --- a/scripts/build/Platform/Linux/pipeline.json +++ b/scripts/build/Platform/Linux/pipeline.json @@ -12,6 +12,9 @@ }, "packaging": { "CLEAN_WORKSPACE": true + }, + "nightly-clean": { + "CLEAN_WORKSPACE": true } } } \ No newline at end of file diff --git a/scripts/build/Platform/Mac/build_config.json b/scripts/build/Platform/Mac/build_config.json index f816117331..f312279fe6 100644 --- a/scripts/build/Platform/Mac/build_config.json +++ b/scripts/build/Platform/Mac/build_config.json @@ -9,7 +9,8 @@ }, "profile_pipe": { "TAGS": [ - "nightly" + "nightly-incremental", + "nightly-clean" ], "steps": [ "profile", @@ -28,14 +29,15 @@ }, "debug": { "TAGS": [ - "nightly", + "nightly-incremental", + "nightly-clean", "weekly-build-metrics" ], "COMMAND": "build_mac.sh", "PARAMETERS": { "CONFIGURATION": "debug", "OUTPUT_DIRECTORY": "build/mac", - "CMAKE_OPTIONS": "-G Xcode -DLY_UNITY_BUILD=TRUE", + "CMAKE_OPTIONS": "-G Xcode -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" } @@ -49,34 +51,37 @@ "PARAMETERS": { "CONFIGURATION": "profile", "OUTPUT_DIRECTORY": "build/mac", - "CMAKE_OPTIONS": "-G Xcode -DLY_UNITY_BUILD=TRUE", + "CMAKE_OPTIONS": "-G Xcode -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" } }, "profile_nounity": { "TAGS": [ - "nightly", + "nightly-incremental", + "nightly-clean", "weekly-build-metrics" ], "COMMAND": "build_mac.sh", "PARAMETERS": { "CONFIGURATION": "profile", "OUTPUT_DIRECTORY": "build/mac", - "CMAKE_OPTIONS": "-G Xcode -DLY_UNITY_BUILD=FALSE", + "CMAKE_OPTIONS": "-G Xcode -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" } }, "asset_profile": { "TAGS": [ - "weekly-build-metrics" + "weekly-build-metrics", + "nightly-incremental", + "nightly-clean" ], "COMMAND": "build_asset_mac.sh", "PARAMETERS": { "CONFIGURATION": "profile", "OUTPUT_DIRECTORY": "build/mac", - "CMAKE_OPTIONS": "-G Xcode -DLY_UNITY_BUILD=TRUE", + "CMAKE_OPTIONS": "-G Xcode -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": "AssetProcessorBatch", "ASSET_PROCESSOR_BINARY": "bin/profile/AssetProcessorBatch", @@ -84,28 +89,17 @@ "ASSET_PROCESSOR_PLATFORMS": "osx_gl" } }, - "asset_clean_profile": { - "TAGS": [ - "nightly" - ], - "PIPELINE_ENV": { - "CLEAN_ASSETS": "1" - }, - "steps": [ - "clean", - "asset_profile" - ] - }, "periodic_test_profile": { "TAGS": [ - "nightly", + "nightly-incremental", + "nightly-clean", "weekly-build-metrics" ], "COMMAND": "build_test_mac.sh", "PARAMETERS": { "CONFIGURATION": "profile", "OUTPUT_DIRECTORY": "build/mac", - "CMAKE_OPTIONS": "-G Xcode -DLY_UNITY_BUILD=TRUE", + "CMAKE_OPTIONS": "-G Xcode -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": "TEST_SUITE_periodic", "CTEST_OPTIONS": "-L \"(SUITE_periodic)\"" @@ -113,14 +107,15 @@ }, "benchmark_test_profile": { "TAGS": [ - "nightly", + "nightly-incremental", + "nightly-clean", "weekly-build-metrics" ], "COMMAND": "build_test_mac.sh", "PARAMETERS": { "CONFIGURATION": "profile", "OUTPUT_DIRECTORY": "build/mac", - "CMAKE_OPTIONS": "-G Xcode -DLY_UNITY_BUILD=TRUE", + "CMAKE_OPTIONS": "-G Xcode -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": "TEST_SUITE_benchmark", "CTEST_OPTIONS": "-L \"(SUITE_benchmark)\"" @@ -128,28 +123,30 @@ }, "release": { "TAGS": [ - "nightly", + "nightly-incremental", + "nightly-clean", "weekly-build-metrics" ], "COMMAND": "build_mac.sh", "PARAMETERS": { "CONFIGURATION": "release", "OUTPUT_DIRECTORY": "build/mac", - "CMAKE_OPTIONS": "-G Xcode -DLY_UNITY_BUILD=TRUE", + "CMAKE_OPTIONS": "-G Xcode -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" } }, "monolithic_release": { "TAGS": [ - "nightly", + "nightly-incremental", + "nightly-clean", "weekly-build-metrics" ], "COMMAND": "build_mac.sh", "PARAMETERS": { "CONFIGURATION": "release", "OUTPUT_DIRECTORY": "build/mono_mac", - "CMAKE_OPTIONS": "-G Xcode -DLY_MONOLITHIC_GAME=TRUE -DLY_UNITY_BUILD=TRUE", + "CMAKE_OPTIONS": "-G Xcode -DLY_MONOLITHIC_GAME=TRUE -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" } diff --git a/scripts/build/Platform/Mac/pipeline.json b/scripts/build/Platform/Mac/pipeline.json index bb94f33d70..58f62b421d 100644 --- a/scripts/build/Platform/Mac/pipeline.json +++ b/scripts/build/Platform/Mac/pipeline.json @@ -12,6 +12,9 @@ }, "packaging": { "CLEAN_WORKSPACE": true + }, + "nightly-clean": { + "CLEAN_WORKSPACE": true } } } \ No newline at end of file diff --git a/scripts/build/Platform/Windows/build_config.json b/scripts/build/Platform/Windows/build_config.json index bd10c9e59a..ee34bae3e3 100644 --- a/scripts/build/Platform/Windows/build_config.json +++ b/scripts/build/Platform/Windows/build_config.json @@ -17,7 +17,8 @@ }, "debug_vs2019_pipe": { "TAGS": [ - "nightly" + "nightly-incremental", + "nightly-clean" ], "steps": [ "debug_vs2019", @@ -86,7 +87,7 @@ "PARAMETERS": { "CONFIGURATION": "debug", "OUTPUT_DIRECTORY": "build\\windows_vs2019", - "CMAKE_OPTIONS": "-G \"Visual Studio 16 2019\" -DCMAKE_SYSTEM_VERSION=10.0 -DLY_UNITY_BUILD=TRUE -DLY_BUILD_WITH_INCREMENTAL_LINKING_DEBUG=FALSE", + "CMAKE_OPTIONS": "-G \"Visual Studio 16 2019\" -DCMAKE_SYSTEM_VERSION=10.0 -DLY_UNITY_BUILD=TRUE -DLY_BUILD_WITH_INCREMENTAL_LINKING_DEBUG=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": "/m /nologo" @@ -100,12 +101,13 @@ "PARAMETERS": { "CONFIGURATION": "debug", "OUTPUT_DIRECTORY": "build\\windows_vs2019", - "CMAKE_OPTIONS": "-G \"Visual Studio 16 2019\" -DCMAKE_SYSTEM_VERSION=10.0 -DLY_UNITY_BUILD=TRUE -DLY_BUILD_WITH_INCREMENTAL_LINKING_DEBUG=FALSE", + "CMAKE_OPTIONS": "-G \"Visual Studio 16 2019\" -DCMAKE_SYSTEM_VERSION=10.0 -DLY_UNITY_BUILD=TRUE -DLY_BUILD_WITH_INCREMENTAL_LINKING_DEBUG=FALSE -DO3DE_HOME_PATH=\"!WORKSPACE!/home\" -DO3DE_REGISTER_ENGINE_PATH=\"!WORKSPACE!/o3de\" -DO3DE_REGISTER_THIS_ENGINE=TRUE", "CMAKE_LY_PROJECTS": "AutomatedTesting", "CMAKE_TARGET": "TEST_SUITE_smoke TEST_SUITE_main", "CMAKE_NATIVE_BUILD_ARGS": "/m /nologo", "CTEST_OPTIONS": "-L \"(SUITE_smoke|SUITE_main)\" -LE \"(REQUIRES_gpu)\" -T Test", - "TEST_METRICS": "True" + "TEST_METRICS": "True", + "TEST_RESULTS": "True" } }, "profile_vs2019": { @@ -117,7 +119,7 @@ "PARAMETERS": { "CONFIGURATION": "profile", "OUTPUT_DIRECTORY": "build\\windows_vs2019", - "CMAKE_OPTIONS": "-G \"Visual Studio 16 2019\" -DCMAKE_SYSTEM_VERSION=10.0 -DLY_UNITY_BUILD=TRUE", + "CMAKE_OPTIONS": "-G \"Visual Studio 16 2019\" -DCMAKE_SYSTEM_VERSION=10.0 -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": "/m /nologo" @@ -125,14 +127,15 @@ }, "profile_vs2019_nounity": { "TAGS": [ - "nightly", + "nightly-incremental", + "nightly-clean", "weekly-build-metrics" ], "COMMAND": "build_windows.cmd", "PARAMETERS": { "CONFIGURATION": "profile", "OUTPUT_DIRECTORY": "build\\windows_vs2019", - "CMAKE_OPTIONS": "-G \"Visual Studio 16 2019\" -DCMAKE_SYSTEM_VERSION=10.0 -DLY_UNITY_BUILD=FALSE", + "CMAKE_OPTIONS": "-G \"Visual Studio 16 2019\" -DCMAKE_SYSTEM_VERSION=10.0 -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": "/m /nologo" @@ -147,42 +150,47 @@ "PARAMETERS": { "CONFIGURATION": "profile", "OUTPUT_DIRECTORY": "build\\windows_vs2019", - "CMAKE_OPTIONS": "-G \"Visual Studio 16 2019\" -DCMAKE_SYSTEM_VERSION=10.0 -DLY_UNITY_BUILD=TRUE", + "CMAKE_OPTIONS": "-G \"Visual Studio 16 2019\" -DCMAKE_SYSTEM_VERSION=10.0 -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": "TEST_SUITE_smoke TEST_SUITE_main", "CMAKE_NATIVE_BUILD_ARGS": "/m /nologo", "CTEST_OPTIONS": "-L \"(SUITE_smoke|SUITE_main)\" -LE \"(REQUIRES_gpu)\" -T Test", - "TEST_METRICS": "True" + "TEST_METRICS": "True", + "TEST_RESULTS": "True" } }, "test_gpu_profile_vs2019": { "TAGS":[ - "nightly" + "nightly-incremental", + "nightly-clean" ], "PIPELINE_ENV":{ - "NODE_LABEL":"windows-gpu" + "NODE_LABEL":"windows-gpu" }, "COMMAND": "build_test_windows.cmd", "PARAMETERS": { "CONFIGURATION": "profile", "OUTPUT_DIRECTORY": "build\\windows_vs2019", - "CMAKE_OPTIONS": "-G \"Visual Studio 16 2019\" -DCMAKE_SYSTEM_VERSION=10.0 -DLY_UNITY_BUILD=TRUE", + "CMAKE_OPTIONS": "-G \"Visual Studio 16 2019\" -DCMAKE_SYSTEM_VERSION=10.0 -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": "TEST_SUITE_smoke TEST_SUITE_main", "CMAKE_NATIVE_BUILD_ARGS": "/m /nologo", "CTEST_OPTIONS": "-L \"(SUITE_smoke_REQUIRES_gpu|SUITE_main_REQUIRES_gpu)\" -T Test", - "TEST_METRICS": "True" + "TEST_METRICS": "True", + "TEST_RESULTS": "True" } }, "asset_profile_vs2019": { "TAGS": [ - "weekly-build-metrics" + "weekly-build-metrics", + "nightly-incremental", + "nightly-clean" ], "COMMAND": "build_asset_windows.cmd", "PARAMETERS": { "CONFIGURATION": "profile", "OUTPUT_DIRECTORY": "build\\windows_vs2019", - "CMAKE_OPTIONS": "-G \"Visual Studio 16 2019\" -DCMAKE_SYSTEM_VERSION=10.0 -DLY_UNITY_BUILD=TRUE", + "CMAKE_OPTIONS": "-G \"Visual Studio 16 2019\" -DCMAKE_SYSTEM_VERSION=10.0 -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": "AssetProcessorBatch", "CMAKE_NATIVE_BUILD_ARGS": "/m /nologo", @@ -191,38 +199,29 @@ "ASSET_PROCESSOR_PLATFORMS": "pc,server" } }, - "asset_clean_profile_vs2019": { - "TAGS": [ - "nightly" - ], - "PIPELINE_ENV": { - "CLEAN_ASSETS": "1" - }, - "steps": [ - "clean", - "asset_profile_vs2019" - ] - }, "periodic_test_profile_vs2019": { "TAGS": [ - "nightly", + "nightly-incremental", + "nightly-clean", "weekly-build-metrics" ], "COMMAND": "build_test_windows.cmd", "PARAMETERS": { "CONFIGURATION": "profile", "OUTPUT_DIRECTORY": "build\\windows_vs2019", - "CMAKE_OPTIONS": "-G \"Visual Studio 16 2019\" -DCMAKE_SYSTEM_VERSION=10.0 -DLY_UNITY_BUILD=TRUE", + "CMAKE_OPTIONS": "-G \"Visual Studio 16 2019\" -DCMAKE_SYSTEM_VERSION=10.0 -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": "TEST_SUITE_periodic", "CMAKE_NATIVE_BUILD_ARGS": "/m /nologo", "CTEST_OPTIONS": "-L \"(SUITE_periodic)\" -T Test", - "TEST_METRICS": "True" + "TEST_METRICS": "True", + "TEST_RESULTS": "True" } }, "sandbox_test_profile_vs2019": { "TAGS": [ - "nightly", + "nightly-incremental", + "nightly-clean", "weekly-build-metrics" ], "PIPELINE_ENV": { @@ -232,41 +231,45 @@ "PARAMETERS": { "CONFIGURATION": "profile", "OUTPUT_DIRECTORY": "build\\windows_vs2019", - "CMAKE_OPTIONS": "-G \"Visual Studio 16 2019\" -DCMAKE_SYSTEM_VERSION=10.0 -DLY_UNITY_BUILD=TRUE", + "CMAKE_OPTIONS": "-G \"Visual Studio 16 2019\" -DCMAKE_SYSTEM_VERSION=10.0 -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": "TEST_SUITE_sandbox", "CMAKE_NATIVE_BUILD_ARGS": "/m /nologo", "CTEST_OPTIONS": "-L \"(SUITE_sandbox)\" -T Test", - "TEST_METRICS": "True" + "TEST_METRICS": "True", + "TEST_RESULTS": "True" } }, "benchmark_test_profile_vs2019": { "TAGS": [ - "nightly", + "nightly-incremental", + "nightly-clean", "weekly-build-metrics" ], "COMMAND": "build_test_windows.cmd", "PARAMETERS": { "CONFIGURATION": "profile", "OUTPUT_DIRECTORY": "build\\windows_vs2019", - "CMAKE_OPTIONS": "-G \"Visual Studio 16 2019\" -DCMAKE_SYSTEM_VERSION=10.0 -DLY_UNITY_BUILD=TRUE", + "CMAKE_OPTIONS": "-G \"Visual Studio 16 2019\" -DCMAKE_SYSTEM_VERSION=10.0 -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": "TEST_SUITE_benchmark", "CMAKE_NATIVE_BUILD_ARGS": "/m /nologo", "CTEST_OPTIONS": "-L \"(SUITE_benchmark)\" -T Test", - "TEST_METRICS": "True" + "TEST_METRICS": "True", + "TEST_RESULTS": "True" } }, "release_vs2019": { "TAGS": [ - "nightly", + "nightly-incremental", + "nightly-clean", "weekly-build-metrics" ], "COMMAND": "build_windows.cmd", "PARAMETERS": { "CONFIGURATION": "release", "OUTPUT_DIRECTORY": "build\\windows_vs2019", - "CMAKE_OPTIONS": "-G \"Visual Studio 16 2019\" -DCMAKE_SYSTEM_VERSION=10.0 -DLY_UNITY_BUILD=TRUE", + "CMAKE_OPTIONS": "-G \"Visual Studio 16 2019\" -DCMAKE_SYSTEM_VERSION=10.0 -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": "/m /nologo" @@ -274,14 +277,15 @@ }, "monolithic_release_vs2019": { "TAGS": [ - "nightly", + "nightly-incremental", + "nightly-clean", "weekly-build-metrics" ], "COMMAND": "build_windows.cmd", "PARAMETERS": { "CONFIGURATION": "release", "OUTPUT_DIRECTORY": "build\\mono_windows_vs2019", - "CMAKE_OPTIONS": "-G \"Visual Studio 16 2019\" -DCMAKE_SYSTEM_VERSION=10.0 -DLY_MONOLITHIC_GAME=TRUE -DLY_UNITY_BUILD=TRUE", + "CMAKE_OPTIONS": "-G \"Visual Studio 16 2019\" -DCMAKE_SYSTEM_VERSION=10.0 -DLY_MONOLITHIC_GAME=TRUE -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": "/m /nologo" @@ -289,13 +293,14 @@ }, "install_profile_vs2019": { "TAGS": [ - "nightly" + "nightly-incremental", + "nightly-clean" ], "COMMAND": "build_windows.cmd", "PARAMETERS": { "CONFIGURATION": "profile", "OUTPUT_DIRECTORY": "build\\windows_vs2019", - "CMAKE_OPTIONS": "-G \"Visual Studio 16 2019\" -DCMAKE_SYSTEM_VERSION=10.0 -DLY_UNITY_BUILD=TRUE -DLY_DISABLE_TEST_MODULES=TRUE -DCMAKE_INSTALL_PREFIX=install", + "CMAKE_OPTIONS": "-G \"Visual Studio 16 2019\" -DCMAKE_SYSTEM_VERSION=10.0 -DLY_UNITY_BUILD=TRUE -DLY_DISABLE_TEST_MODULES=TRUE -DCMAKE_INSTALL_PREFIX=install -DO3DE_HOME_PATH=\"!WORKSPACE!/home\" -DO3DE_REGISTER_ENGINE_PATH=\"!WORKSPACE!/o3de\" -DO3DE_REGISTER_THIS_ENGINE=TRUE", "CMAKE_LY_PROJECTS": "", "CMAKE_TARGET": "INSTALL", "CMAKE_NATIVE_BUILD_ARGS": "/m /nologo" diff --git a/scripts/build/Platform/Windows/package_build_config.json b/scripts/build/Platform/Windows/package_build_config.json index a5ca861377..40f479a098 100644 --- a/scripts/build/Platform/Windows/package_build_config.json +++ b/scripts/build/Platform/Windows/package_build_config.json @@ -4,7 +4,7 @@ "PARAMETERS": { "CONFIGURATION": "profile", "OUTPUT_DIRECTORY": "windows_vs2017", - "CMAKE_OPTIONS": "-G \"Visual Studio 15 2017\" -A x64 -T host=x64 -DCMAKE_SYSTEM_VERSION=10.0 -DLY_UNITY_BUILD=TRUE", + "CMAKE_OPTIONS": "-G \"Visual Studio 15 2017\" -A x64 -T host=x64 -DCMAKE_SYSTEM_VERSION=10.0 -DLY_UNITY_BUILD=TRUE -DO3DE_HOME_PATH=\"!WORKSPACE!/home\" -DO3DE_REGISTER_ENGINE_PATH=\"!WORKSPACE!/o3de\" -DO3DE_REGISTER_THIS_ENGINE=TRUE", "CMAKE_LY_PROJECTS": "AtomTest;AtomSampleViewer", "CMAKE_TARGET": "ALL_BUILD", "CMAKE_NATIVE_BUILD_ARGS": "/m:4 /p:CL_MPCount=!HALF_PROCESSORS! /nologo" @@ -15,7 +15,7 @@ "PARAMETERS": { "CONFIGURATION":"profile", "OUTPUT_DIRECTORY":"windows_vs2019", - "CMAKE_OPTIONS":"-G \"Visual Studio 16 2019\" -DCMAKE_SYSTEM_VERSION=10.0 -DLY_UNITY_BUILD=TRUE", + "CMAKE_OPTIONS":"-G \"Visual Studio 16 2019\" -DCMAKE_SYSTEM_VERSION=10.0 -DLY_UNITY_BUILD=TRUE -DO3DE_HOME_PATH=\"!WORKSPACE!/home\" -DO3DE_REGISTER_ENGINE_PATH=\"!WORKSPACE!/o3de\" -DO3DE_REGISTER_THIS_ENGINE=TRUE", "CMAKE_LY_PROJECTS":"AtomTest;AtomSampleViewer", "CMAKE_TARGET":"ALL_BUILD", "CMAKE_NATIVE_BUILD_ARGS": "/m /nologo" diff --git a/scripts/build/Platform/Windows/pipeline.json b/scripts/build/Platform/Windows/pipeline.json index 380b8c1a48..5f10ccc7ae 100644 --- a/scripts/build/Platform/Windows/pipeline.json +++ b/scripts/build/Platform/Windows/pipeline.json @@ -12,6 +12,9 @@ }, "packaging": { "CLEAN_WORKSPACE": true + }, + "nightly-clean": { + "CLEAN_WORKSPACE": true } } } \ No newline at end of file diff --git a/scripts/build/Platform/iOS/build_config.json b/scripts/build/Platform/iOS/build_config.json index 921262e267..4566d243ee 100644 --- a/scripts/build/Platform/iOS/build_config.json +++ b/scripts/build/Platform/iOS/build_config.json @@ -19,14 +19,15 @@ }, "debug": { "TAGS": [ - "nightly", + "nightly-incremental", + "nightly-clean", "weekly-build-metrics" ], "COMMAND": "../Mac/build_mac.sh", "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", + "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" @@ -34,7 +35,8 @@ }, "profile": { "TAGS": [ - "nightly", + "nightly-incremental", + "nightly-clean", "daily-pipeline-metrics", "weekly-build-metrics" ], @@ -42,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", + "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" @@ -50,14 +52,15 @@ }, "profile_nounity": { "TAGS": [ - "nightly", + "nightly-incremental", + "nightly-clean", "weekly-build-metrics" ], "COMMAND": "../Mac/build_mac.sh", "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", + "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" @@ -65,7 +68,8 @@ }, "asset_profile": { "TAGS": [ - "nightly", + "nightly-incremental", + "nightly-clean", "weekly-build-metrics" ], "COMMAND": "../Mac/build_asset_mac.sh", @@ -80,28 +84,17 @@ "ASSET_PROCESSOR_PLATFORMS": "ios" } }, - "asset_clean_profile": { - "TAGS": [ - "nightly" - ], - "PIPELINE_ENV": { - "CLEAN_ASSETS": "true" - }, - "steps": [ - "clean", - "asset_profile" - ] - }, "release": { "TAGS": [ - "nightly", + "nightly-incremental", + "nightly-clean", "weekly-build-metrics" ], "COMMAND": "../Mac/build_mac.sh", "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", + "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" diff --git a/scripts/build/Platform/iOS/pipeline.json b/scripts/build/Platform/iOS/pipeline.json index bb94f33d70..58f62b421d 100644 --- a/scripts/build/Platform/iOS/pipeline.json +++ b/scripts/build/Platform/iOS/pipeline.json @@ -12,6 +12,9 @@ }, "packaging": { "CLEAN_WORKSPACE": true + }, + "nightly-clean": { + "CLEAN_WORKSPACE": true } } } \ No newline at end of file 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 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/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 c2edcbe9f2..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 https://jenkins.agscollab.com/view/%7ESandbox/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)) - - 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 diff --git a/scripts/o3de.bat b/scripts/o3de.bat index 9dd0d5b539..0a65b722d7 100644 --- a/scripts/o3de.bat +++ b/scripts/o3de.bat @@ -33,4 +33,6 @@ popd EXIT /b 1 :end popd +EXIT /b %ERRORLEVEL% + diff --git a/scripts/o3de.py b/scripts/o3de.py index 1c528704f4..dbb9c53e4b 100755 --- a/scripts/o3de.py +++ b/scripts/o3de.py @@ -19,15 +19,13 @@ if ROOT_DEV_PATH not in sys.path: sys.path.append(ROOT_DEV_PATH) from cmake.Tools import engine_template -from cmake.Tools import current_project -from cmake.Tools import add_remove_gem +from cmake.Tools import global_project from cmake.Tools import registration def add_args(parser, subparsers) -> None: - current_project.add_args(parser, subparsers) + global_project.add_args(parser, subparsers) engine_template.add_args(parser, subparsers) - add_remove_gem.add_args(parser, subparsers) registration.add_args(parser, subparsers) diff --git a/scripts/o3de.sh b/scripts/o3de.sh index 6b789b494f..dde8808551 100755 --- a/scripts/o3de.sh +++ b/scripts/o3de.sh @@ -15,11 +15,9 @@ #Note this does not actually change the working directory SCRIPT_DIR=$(cd `dirname $0` && pwd) -#The engine root is always the parent of the scripts directory, so $(dirname "$SCRIPT_DIR") should get us engine root -ENGINE_ROOT=$(dirname "$SCRIPT_DIR") - -#The engines python is in the engineroot/python -PYTHON_DIRECTORY="$ENGINE_ROOT/python" +#python should be in the base path +BASE_PATH=$(dirname "$SCRIPT_DIR") +PYTHON_DIRECTORY="$BASE_PATH/python" #If engine python exists use it, if not try the system python if [ ! -d "$PYTHON_DIRECTORY" ]; then @@ -33,4 +31,5 @@ if [ ! -f "$PYTHON_EXECUTABLE" ]; then fi #run the o3de.py pass along the command -$PYTHON_EXECUTABLE "$SCRIPT_DIR/o3de.py" $* \ No newline at end of file +$PYTHON_EXECUTABLE "$SCRIPT_DIR/o3de.py" $* +exit $? \ No newline at end of file diff --git a/scripts/project_manager/projects.py b/scripts/project_manager/projects.py index 5cd506c515..51db7a6440 100755 --- a/scripts/project_manager/projects.py +++ b/scripts/project_manager/projects.py @@ -12,47 +12,45 @@ # PySide project and gem selector GUI import os +import pathlib import sys import argparse import json import logging import subprocess -import threading -import platform from logging.handlers import RotatingFileHandler - from typing import List - -from pathlib import Path from pyside import add_pyside_environment, is_pyside_ready, uninstall_env +engine_path = os.path.realpath(os.path.join(os.path.dirname(__file__), '..', '..')) +sys.path.append(engine_path) +executable_path = '' + logger = logging.getLogger() logger.setLevel(logging.INFO) -log_path = os.path.join(os.path.dirname(__file__), "logs") -if not os.path.isdir(log_path): - os.makedirs(log_path) -log_path = os.path.join(log_path, "project_manager.log") -log_file_handler = RotatingFileHandler(filename=log_path, maxBytes=1024 * 1024, backupCount=1) +from cmake.Tools import engine_template +from cmake.Tools import registration + +o3de_folder = registration.get_o3de_folder() +o3de_logs_folder = registration.get_o3de_logs_folder() +project_manager_log_file_path = o3de_log_folder / "project_manager.log" +log_file_handler = RotatingFileHandler(filename=project_manager_log_file_path, maxBytes=1024 * 1024, backupCount=1) formatter = logging.Formatter('%(asctime)s | %(levelname)s : %(message)s') log_file_handler.setFormatter(formatter) logger.addHandler(log_file_handler) logger.info("Starting Project Manager") -engine_path = os.path.realpath(os.path.join(os.path.dirname(__file__), '..', '..')) -sys.path.append(engine_path) -executable_path = '' - def initialize_pyside_from_parser(): # Parse arguments up top. We need to know the path to our binaries and QT libs in particular to load up # PySide parser = argparse.ArgumentParser() - parser.add_argument('--executable_path', required=True, help='Path to Executable to launch with project') - parser.add_argument('--binaries_path', default=None, help='Path to QT Binaries necessary for PySide. If not' - 'provided executable_path folder is assumed') - parser.add_argument('--parent_pid', default=0, help='Process ID of launching process') + parser.add_argument('--executable-path', required=True, help='Path to Executable to launch with project') + parser.add_argument('--binaries-path', default=None, help='Path to QT Binaries necessary for PySide. If not' + ' provided executable_path folder is assumed') + parser.add_argument('--parent-pid', default=0, help='Process ID of launching process') args = parser.parse_args() @@ -81,21 +79,6 @@ except ImportError as e: logger.error(f"PySide2 imports successful") -from cmake.Tools import engine_template -from cmake.Tools import add_remove_gem - -ui_path = os.path.join(os.path.join(os.path.dirname(__file__), 'ui')) -ui_file = 'projects.ui' -ui_icon_file = 'projects.ico' -manage_gems_file = 'manage_gems.ui' -create_project_file = 'create_project.ui' - -mru_file_name = 'o3de_projects.json' -default_settings_folder = os.path.join(Path.home(), '.o3de') - -# Used to indicate a folder which appears to be a valid o3de project -project_marker_file = 'project.json' - class DialogLoggerSignaller(QObject): send_to_dialog = Signal(str) @@ -132,14 +115,16 @@ class DialogLogger(logging.Handler): self.signaller.send_to_dialog.emit(self.format(record)) - -class ProjectDialog(QObject): +class ProjectManagerDialog(QObject): """ - Main project dialog class responsible for displaying the project selection list + Main project manager dialog is responsible for displaying the project selection list and output pane """ - def __init__(self, parent=None, my_ui_path=ui_path, settings_folder=default_settings_folder): - super(ProjectDialog, self).__init__(parent) + def __init__(self, parent=None): + super(ProjectManagerDialog, self).__init__(parent) + + self.ui_path = (pathlib.Path(__file__).parent / 'ui').resolve() + self.home_folder = registration.get_home_folder() self.log_display = None self.dialog_logger = DialogLogger(self) @@ -147,170 +132,83 @@ class ProjectDialog(QObject): logger.setLevel(logging.INFO) self.dialog_logger.signaller.send_to_dialog.connect(self.handle_log_message) - self.displayed_projects = [] + self.mru_file_path = o3de_folder / 'mru.json' - self.mru_file_path = os.path.join(settings_folder, mru_file_name) + self.create_from_template_ui_file_path = self.ui_path / 'create_from_template.ui' + self.create_gem_ui_file_path = self.ui_path / 'create_gem.ui' + self.create_project_ui_file_path = self.ui_path / 'create_project.ui' + self.manage_project_gem_targets_ui_file_path = self.ui_path / 'manage_gem_targets.ui' + self.project_manager_icon_file_path = self.ui_path / 'project_manager.ico' + self.project_manager_ui_file_path = self.ui_path / 'project_manager.ui' - self.my_ui_file_path = os.path.join(my_ui_path, ui_file) - self.my_ui_icon_path = os.path.join(my_ui_path, ui_icon_file) - self.my_ui_manage_gems_path = os.path.join(my_ui_path, manage_gems_file) - self.my_ui_create_project_path = os.path.join(my_ui_path, create_project_file) - self.ui_dir = my_ui_path - self.ui_file = QFile(self.my_ui_file_path) - self.ui_file.open(QFile.ReadOnly) + self.project_manager_ui_file = QFile(self.project_manager_ui_file_path.as_posix()) + self.project_manager_ui_file.open(QFile.ReadOnly) loader = QUiLoader() - self.dialog = loader.load(self.ui_file) - self.dialog.setWindowIcon(QIcon(self.my_ui_icon_path)) + self.dialog = loader.load(self.project_manager_ui_file) + self.dialog.setWindowIcon(QIcon(self.project_manager_icon_file_path.as_posix())) self.dialog.setFixedSize(self.dialog.size()) - self.browse_projects_button = self.dialog.findChild(QPushButton, 'browseProjectsButton') - self.browse_projects_button.clicked.connect(self.browse_projects_handler) - self.log_display = self.dialog.findChild(QLabel, 'logDisplay') + self.project_list_box = self.dialog.findChild(QComboBox, 'projectListBox') + self.refresh_project_list() + mru = self.get_mru_list() + if len(mru): + last_mru = pathlib.Path(mru[0]).resolve() + for this_slot in range(self.project_list_box.count()): + item_text = self.project_list_box.itemText(this_slot) + if last_mru.as_posix() in item_text: + self.project_list_box.setCurrentIndex(this_slot) + break self.create_project_button = self.dialog.findChild(QPushButton, 'createProjectButton') self.create_project_button.clicked.connect(self.create_project_handler) + self.create_gem_button = self.dialog.findChild(QPushButton, 'createGemButton') + self.create_gem_button.clicked.connect(self.create_gem_handler) + self.create_template_button = self.dialog.findChild(QPushButton, 'createTemplateButton') + self.create_template_button.clicked.connect(self.create_template_handler) + self.create_from_template_button = self.dialog.findChild(QPushButton, 'createFromTemplateButton') + self.create_from_template_button.clicked.connect(self.create_from_template_handler) + + self.add_project_button = self.dialog.findChild(QPushButton, 'addProjectButton') + self.add_project_button.clicked.connect(self.add_project_handler) + self.add_gem_button = self.dialog.findChild(QPushButton, 'addGemButton') + self.add_gem_button.clicked.connect(self.add_gem_handler) + self.add_template_button = self.dialog.findChild(QPushButton, 'addTemplateButton') + self.add_template_button.clicked.connect(self.add_template_handler) + self.add_restricted_button = self.dialog.findChild(QPushButton, 'addRestrictedButton') + self.add_restricted_button.clicked.connect(self.add_restricted_handler) + + self.remove_project_button = self.dialog.findChild(QPushButton, 'removeProjectButton') + self.remove_project_button.clicked.connect(self.remove_project_handler) + self.remove_gem_button = self.dialog.findChild(QPushButton, 'removeGemButton') + self.remove_gem_button.clicked.connect(self.remove_gem_handler) + self.remove_template_button = self.dialog.findChild(QPushButton, 'removeTemplateButton') + self.remove_template_button.clicked.connect(self.remove_template_handler) + self.remove_restricted_button = self.dialog.findChild(QPushButton, 'removeRestrictedButton') + self.remove_restricted_button.clicked.connect(self.remove_restricted_handler) + + self.manage_runtime_project_gem_targets_button = self.dialog.findChild(QPushButton, 'manageRuntimeGemTargetsButton') + self.manage_runtime_project_gem_targets_button.clicked.connect(self.manage_runtime_project_gem_targets_handler) + self.manage_tool_project_gem_targets_button = self.dialog.findChild(QPushButton, 'manageToolGemTargetsButton') + self.manage_tool_project_gem_targets_button.clicked.connect(self.manage_tool_project_gem_targets_handler) + self.manage_server_project_gem_targets_button = self.dialog.findChild(QPushButton, 'manageServerGemTargetsButton') + self.manage_server_project_gem_targets_button.clicked.connect(self.manage_server_project_gem_targets_handler) + + self.log_display = self.dialog.findChild(QLabel, 'logDisplay') self.ok_cancel_button = self.dialog.findChild(QDialogButtonBox, 'okCancel') self.ok_cancel_button.accepted.connect(self.accepted_handler) - self.manage_gems_button = self.dialog.findChild(QPushButton, 'manageGemsButton') - self.manage_gems_button.clicked.connect(self.manage_gems_handler) - - self.project_list_box = self.dialog.findChild(QComboBox, 'projectListBox') - self.add_projects(self.get_mru_list()) - self.project_gem_list = [] - self.dialog.show() - self.load_thread = None - self.gems_list = [] - self.load_gems() - - def update_gems(self) -> None: - """ - Perform a full refresh of active project and available gems. Loads both from - data on disk and refreshes UI - :return: None - """ - project_path = self.path_for_selection() - if not project_path: - self.project_gem_list = set() - else: - self.project_gem_list = add_remove_gem.get_project_gem_list(self.path_for_selection()) - project_gem_model = QStandardItemModel() - for item in sorted(self.project_gem_list): - project_gem_model.appendRow(QStandardItem(item)) - self.project_gems.setModel(project_gem_model) - - add_gem_model = QStandardItemModel() - for item in self.gems_list: - if item.get('Name') in self.project_gem_list: - continue - model_item = QStandardItem(item.get('Name')) - model_item.setData(item.get('Path'), Qt.UserRole) - add_gem_model.appendRow(model_item) - self.add_gems_list.setModel(add_gem_model) - - def get_selected_project_name(self) -> str: - return os.path.basename(self.path_for_selection()) - - def get_launch_project(self) -> str: - return os.path.normpath(self.path_for_selection()) - - def get_executable_launch_params(self) -> list: - """ - Retrieve the necessary launch parameters to make the subprocess launch call with - this is the path - to the executable such as the Editor and the path to the selected project - :return: list of params - """ - launch_params = [executable_path, - f'-regset="/Amazon/AzCore/Bootstrap/project_path={self.get_launch_project()}"'] - return launch_params - - def load_gems(self) -> None: - """ - Starts another thread to discover available gems. This requires file discovery/parsing and would likely - cause a noticeable pause if it were not on another thread - :return: None - """ - self.load_thread = threading.Thread(target=self.load_gems_thread_func) - self.load_thread.start() - - def load_gems_thread_func(self) -> None: - """ - Actual load function for load_gems thread. Blocking call to lower level find method to fill out gems_list - :return: None - """ - self.gems_list = add_remove_gem.find_all_gems([os.path.join(engine_path, 'Gems')]) - - def load_template_list(self) -> None: - """ - Search for available templates to fill out template list - :return: None - """ - self.project_templates = engine_template.find_all_project_templates([os.path.join(engine_path, 'Templates')]) - - def get_gem_info(self, gem_name: str) -> str: - """ - Provided a known gem name provides gem info - :param gem_name: Name of known gem. Names are based on Gem. module names in CMakeLists.txt rather - than folders a Gem lives in. - :return: Dictionary with data about gem if known - """ - for this_gem in self.gems_list: - if this_gem.get('Name') == gem_name: - this_gem - return None - - def get_gem_info_by_path(self, gem_path: str) -> str: - """ - Provided a gem path returns the gem info if known - :param gem_path: Path to gem - :return: Dictionary with data about gem if known - """ - for this_gem in self.gems_list: - if this_gem.get('Path') == gem_path: - return this_gem - return None - - def path_for_gem(self, gem_name: str) -> str: - """ - Provided a known gem name provides the full path on disk - :param gem_name: Name of known gem. Names are based on Gem. module names in CMakeLists.txt rather - than folders a Gem lives in. - :return: Path to CMakeLists.txt containing the Gem modules - """ - for this_gem in self.gems_list: - if this_gem.get('Name') == gem_name: - return this_gem.get('Path') - return '' - - def open_project(self, project_path: str) -> None: - """ - Launch the desired application given the selected project - :param project_path: Path to currently selected project - :return: None - """ - logger.info(f'Attempting to open {project_path}') - self.update_mru_list(project_path) - launch_params = self.get_executable_launch_params() - try: - logger.info(f'Launching with params {launch_params}') - subprocess.Popen(launch_params, env=uninstall_env()) - quit(0) - except subprocess.CalledProcessError as e: - logger.error(f'Failed to start executable with launch params {launch_params} error {e}') - - def path_for_selection(self) -> str: - """ - Retrive the full path to the project the user currently has selected in the drop down - :return: str path to project - """ - if self.project_list_box.currentIndex() == -1: - logger.warning("No project selected") - return "" - return self.project_list_box.itemData(self.project_list_box.currentIndex(), Qt.ToolTipRole) + def refresh_project_list(self) -> None: + projects = registration.get_all_projects() + self.project_list_box.clear() + for this_slot in range(len(projects)): + display_name = f'{os.path.basename(os.path.normpath(projects[this_slot]))} ({projects[this_slot]})' + self.project_list_box.addItem(display_name) + self.project_list_box.setItemData(self.project_list_box.count() - 1, projects[this_slot], + Qt.ToolTipRole) def accepted_handler(self) -> None: """ @@ -324,152 +222,42 @@ class ProjectDialog(QObject): msg_box.setText("Please select a project") msg_box.exec() return - self.open_project(self.path_for_selection()) + self.launch_with_project_path(self.get_selected_project_path()) - def is_project_folder(self, project_path: str) -> bool: - """ - Checks whether the supplied path appears to be a canonical project folder. - Root of a valid project should contain the canonical file - :param project_path: - :return: - """ - return os.path.isfile(os.path.join(project_path, project_marker_file)) + def get_launch_project(self) -> str: + return os.path.normpath(self.get_selected_project_path()) - def add_new_project(self, project_folder, update_mru=True, reset_selected=True, validate=True): + def get_executable_launch_params(self) -> list: """ - Handle request to add a new project to our display and mru lists. Validation checks whether the folder - appears to be a project. Duplicates should never be added with or without validation. - :param project_folder: Absolute path to project folder - :param update_mru: Should the project also be promoted to "most recent" in our mru list - :param reset_selected: Update our drop down to show this as our current selection - :param validate: Verify the folder appears to be a valid project folder - :return: + Retrieve the necessary launch parameters to make the subprocess launch call with - this is the path + to the executable such as the Editor and the path to the selected project + :return: list of params """ - if validate: - if not self.is_project_folder(project_folder): - QMessageBox.warning(self.dialog, "Invalid Project Folder", - f"{project_folder} does not contain a {project_marker_file}" - f" and does not appear to be a valid project") - return - self.add_projects([project_folder]) - if reset_selected: - self.project_list_box.setCurrentIndex(self.project_list_box.count() - 1) - if update_mru: - self.update_mru_list(project_folder) + launch_params = [executable_path, + f'-regset="/Amazon/AzCore/Bootstrap/project_path={self.get_launch_project()}"'] + return launch_params - def browse_projects_handler(self): + def launch_with_project_path(self, project_path: str) -> None: """ - Open a file search dialog looking for a folder which contains a valid project marker. If valid - will update the mru list with the new entry, if invalid will warn the user. + Launch the desired application given the selected project + :param project_path: Path to currently selected project :return: None """ - project_folder = QFileDialog.getExistingDirectory(self.dialog, "Select Project Folder", engine_path) - if project_folder: - self.add_new_project(project_folder) + logger.info(f'Attempting to open {project_path}') + self.update_mru_list(project_path) + launch_params = self.get_executable_launch_params() + logger.info(f'Launching with params {launch_params}') + subprocess.run(launch_params, env=uninstall_env()) - return + def get_selected_project_path(self) -> str: + if self.project_list_box.currentIndex() == -1: + logger.warning("No project selected") + return "" + return self.project_list_box.itemData(self.project_list_box.currentIndex(), Qt.ToolTipRole) - def get_selected_project_gems(self) -> list: - """ - :return: List of (GemName, GemPath) of currently selected gems in the project gems list - """ - selected_items = self.project_gems.selectionModel().selectedRows() - return [self.project_gems.model().data(item) for item in selected_items] - - def remove_gems_handler(self): - """ - Finds the currently selected gems in the active gems list and attempts to remove each and updates the UI. - :return: None - """ - remove_gems = self.get_selected_project_gems() - - for this_gem in remove_gems: - gem_path = self.path_for_gem(this_gem) - add_remove_gem.add_remove_gem(add=False, - dev_root=engine_path, - gem_path=gem_path or os.path.join(engine_path, 'Gems', this_gem), - gem_target=this_gem, - project_path=self.path_for_selection(), - dependencies_file=None, - runtime_dependency=True, - tool_dependency=True, - server_dependency=True) - self.update_gems() - - def manage_gems_handler(self): - """ - Opens the Gem management pane. Waits for the load thread to complete if still running and displays all - active gems for the current project as well as all available gems which aren't currently active. - :return: None - """ - - if not self.path_for_selection(): - msg_box = QMessageBox(parent=self.dialog) - msg_box.setWindowTitle("O3DE") - msg_box.setText("Please select a project") - msg_box.exec() - return - - self.load_thread.join() - loader = QUiLoader() - self.manage_gems_file = QFile(self.my_ui_manage_gems_path) - - if not self.manage_gems_file: - logger.error(f'Failed to load gems UI file at {self.manage_gems_file}') - return - - self.manage_gems_dialog = loader.load(self.manage_gems_file) - - if not self.manage_gems_dialog: - logger.error(f'Failed to load gems dialog file at {self.manage_gems_file}') - return - - self.manage_gems_dialog.setWindowTitle(f"Manage Gems for {self.get_selected_project_name()}") - - self.add_gems_button = self.manage_gems_dialog.findChild(QPushButton, 'addGemsButton') - self.add_gems_button.clicked.connect(self.add_gems_handler) - - self.add_gems_list = self.manage_gems_dialog.findChild(QListView, 'addGemsList') - - self.remove_gems_button = self.manage_gems_dialog.findChild(QPushButton, 'removeGemsButton') - self.remove_gems_button.clicked.connect(self.remove_gems_handler) - - self.project_gems = self.manage_gems_dialog.findChild(QListView, 'projectGems') - self.update_gems() - - self.manage_gems_dialog.exec() - - def get_selected_add_gems(self) -> list: - """ - Find returns a list of currently selected gems in the add listas (GemName, GemPath) - :return: - """ - selected_items = self.add_gems_list.selectionModel().selectedRows() - return [(self.add_gems_list.model().data(item), self.add_gems_list.model().data(item, Qt.UserRole)) for - item in selected_items] - - def add_gems_handler(self) -> None: - """ - Searches the available gems list for selected gems and attempts to add each one to the current project. - Updates UI after completion. - :return: None - """ - add_gems_list = self.get_selected_add_gems() - for this_gem in add_gems_list: - gem_info = self.get_gem_info_by_path(this_gem[1]) - if not gem_info: - logger.error(f'Unknown gem {this_gem}!') - continue - add_remove_gem.add_remove_gem(add=True, - dev_root=engine_path, - gem_path=this_gem[1], - gem_target=gem_info.get('Name'), - project_path=self.path_for_selection(), - dependencies_file=None, - runtime_dependency=gem_info.get('Runtime', False), - tool_dependency=gem_info.get('Tools', False), - server_dependency=gem_info.get('Tools', False)) - self.update_gems() + def get_selected_project_name(self) -> str: + project_data = registration.get_project_data(project_path=self.get_selected_project_path()) + return project_data['project_name'] def create_project_handler(self): """ @@ -477,7 +265,7 @@ class ProjectDialog(QObject): :return: None """ loader = QUiLoader() - self.create_project_file = QFile(self.my_ui_create_project_path) + self.create_project_file = QFile(self.create_project_ui_file_path.as_posix()) if not self.create_project_file: logger.error(f'Failed to create project UI file at {self.create_project_file}') @@ -492,46 +280,25 @@ class ProjectDialog(QObject): self.create_project_ok_button = self.create_project_dialog.findChild(QDialogButtonBox, 'okCancel') self.create_project_ok_button.accepted.connect(self.create_project_accepted_handler) - self.project_template_list = self.create_project_dialog.findChild(QListView, 'projectTemplates') - - self.load_template_list() - - self.load_template_model = QStandardItemModel() - for item in self.project_templates: - model_item = QStandardItem(item[0]) - model_item.setData(item[1], Qt.UserRole) - self.load_template_model.appendRow(model_item) - - self.project_template_list.setModel(self.load_template_model) + self.create_project_template_list = self.create_project_dialog.findChild(QListView, 'projectTemplates') + self.refresh_create_project_template_list() self.create_project_dialog.exec() - def get_selected_project_template(self) -> tuple: - """ - Get the current pair templatename, path to template selecte dby the user - :return: pair - """ - - selected_item = self.project_template_list.selectionModel().currentIndex() - if not selected_item.isValid(): - logger.warning("Select a template to create from") - return None - - create_project_item = (self.project_template_list.model().data(selected_item), - self.project_template_list.model().data(selected_item, Qt.UserRole)) - return create_project_item - def create_project_accepted_handler(self) -> None: """ Searches the available gems list for selected gems and attempts to add each one to the current project. Updates UI after completion. :return: None """ - create_project_item = self.get_selected_project_template() - if not create_project_item: + + selected_item = self.create_project_template_list.selectionModel().currentIndex() + project_template_path = self.create_project_template_list.model().data(selected_item) + if not project_template_path: return - folder_dialog = QFileDialog(self.dialog, "Select a Folder and Enter a New Project Name", engine_path) + folder_dialog = QFileDialog(self.dialog, "Select a Folder and Enter a New Project Name", + registration.get_o3de_projects_folder().as_posix()) folder_dialog.setFileMode(QFileDialog.AnyFile) folder_dialog.setOptions(QFileDialog.ShowDirsOnly) project_count = 0 @@ -544,47 +311,644 @@ class ProjectDialog(QObject): if folder_dialog.exec(): project_folder = folder_dialog.selectedFiles() if project_folder: - if engine_template.create_project(engine_path, project_folder[0], create_project_item[1]) == 0: + if engine_template.create_project(project_path=project_folder[0], + template_path=project_template_path) == 0: # Success - self.add_new_project(project_folder[0], validate=False) + registration.register(project_path=project_folder[0]) + self.refresh_project_list() msg_box = QMessageBox(parent=self.dialog) msg_box.setWindowTitle("O3DE") - msg_box.setText(f"Project {os.path.basename(os.path.normpath(project_folder[0]))} created." - " Build your\nnew project before hitting OK to launch.") + msg_box.setText(f"Project {project_folder[0]} created.") msg_box.exec() return - def get_display_name(self, project_path: str) -> str: + def create_gem_handler(self): """ - Returns the project path in the format to be displayed in the projects MRU list - :param project_path: Path to the project folder - :return: Formatted path - """ - return f'{os.path.basename(os.path.normpath(project_path))} ({project_path})' - - def add_projects(self, new_list: List[str]) -> None: - """ - Attempt to add a list of known projects. Performs validation first that the supplied folder appears valid and - silently drops invalid folders - these can simply be folders which were previously valid and are in the MRU list - but have been moved or deleted. Used both when loading the MRU list or when a user browses or creates a new - project - :param new_list: List of full paths to projects to add + Opens the Create Gem pane. Retrieves a list of available templates for display :return: None """ - new_display_items = [] - new_display_paths = [] - for this_item in new_list: - if self.is_project_folder(this_item) and this_item not in self.displayed_projects: - self.displayed_projects.append(this_item) - new_display_items.append(self.get_display_name(this_item)) - new_display_paths.append(this_item) - # Storing the full path in the tooltip, if this is altered we need to store this elsewhere - # as it's used when selecting a project to open + loader = QUiLoader() + self.create_gem_file = QFile(self.create_gem_ui_file_path.as_posix()) - for this_slot in range(len(new_display_items)): - self.project_list_box.addItem(new_display_items[this_slot]) - self.project_list_box.setItemData(self.project_list_box.count() - 1, new_display_paths[this_slot], - Qt.ToolTipRole) + if not self.create_gem_file: + logger.error(f'Failed to create gem UI file at {self.create_gem_file}') + return + + self.create_gem_dialog = loader.load(self.create_gem_file) + + if not self.create_gem_dialog: + logger.error(f'Failed to load create gem dialog file at {self.create_gem_file}') + return + + self.create_gem_ok_button = self.create_gem_dialog.findChild(QDialogButtonBox, 'okCancel') + self.create_gem_ok_button.accepted.connect(self.create_gem_accepted_handler) + + self.create_gem_template_list = self.create_gem_dialog.findChild(QListView, 'gemTemplates') + self.refresh_create_gem_template_list() + + self.create_gem_dialog.exec() + + def create_gem_accepted_handler(self) -> None: + """ + Searches the available gems list for selected gems and attempts to add each one to the current gem. + Updates UI after completion. + :return: None + """ + selected_item = self.create_gem_template_list.selectionModel().currentIndex() + gem_template_path = self.create_gem_template_list.model().data(selected_item) + if not gem_template_path: + return + + folder_dialog = QFileDialog(self.dialog, "Select a Folder and Enter a New Gem Name", + registration.get_o3de_gems_folder().as_posix()) + folder_dialog.setFileMode(QFileDialog.AnyFile) + folder_dialog.setOptions(QFileDialog.ShowDirsOnly) + gem_count = 0 + gem_name = "MyNewGem" + while os.path.exists(os.path.join(engine_path, gem_name)): + gem_name = f"MyNewGem{gem_count}" + gem_count += 1 + folder_dialog.selectFile(gem_name) + gem_folder = None + if folder_dialog.exec(): + gem_folder = folder_dialog.selectedFiles() + if gem_folder: + if engine_template.create_gem(gem_path=gem_folder[0], + template_path=gem_template_path) == 0: + # Success + registration.register(gem_path=gem_folder[0]) + msg_box = QMessageBox(parent=self.dialog) + msg_box.setWindowTitle("O3DE") + msg_box.setText(f"Gem {gem_folder[0]} created.") + msg_box.exec() + return + + def create_template_handler(self): + """ + Opens a foldr select dialog and lets the user select the source folder they want to make a template + out of, then opens a second folder select dialog to get where they want to put the template and it name + :return: None + """ + + source_folder = QFileDialog.getExistingDirectory(self.dialog, + "Select a Folder to make a template out of.", + registration.get_o3de_folder().as_posix()) + if not source_folder: + return + + destination_template_folder_dialog = QFileDialog(self.dialog, + "Select where the template is to be created and named.", + registration.get_o3de_templates_folder().as_posix()) + destination_template_folder_dialog.setFileMode(QFileDialog.AnyFile) + destination_template_folder_dialog.setOptions(QFileDialog.ShowDirsOnly) + destination_folder = None + if destination_template_folder_dialog.exec(): + destination_folder = destination_template_folder_dialog.selectedFiles() + if not destination_folder: + return + + if engine_template.create_template(source_path=source_folder, + template_path=destination_folder[0]) == 0: + # Success + registration.register(template_path=destination_folder[0]) + msg_box = QMessageBox(parent=self.dialog) + msg_box.setWindowTitle("O3DE") + msg_box.setText(f"Template {destination_folder[0]} created.") + msg_box.exec() + return + + def create_from_template_handler(self): + """ + Opens the Create from_template pane. Retrieves a list of available from_templates for display + :return: None + """ + loader = QUiLoader() + self.create_from_template_file = QFile(self.create_from_template_ui_file_path.as_posix()) + + if not self.create_from_template_file: + logger.error(f'Failed to create from_template UI file at {self.create_from_template_file}') + return + + self.create_from_template_dialog = loader.load(self.create_from_template_file) + + if not self.create_from_template_dialog: + logger.error(f'Failed to load create from_template dialog file at {self.create_from_template_file}') + return + + self.create_from_template_ok_button = self.create_from_template_dialog.findChild(QDialogButtonBox, 'okCancel') + self.create_from_template_ok_button.accepted.connect(self.create_from_template_accepted_handler) + + self.create_from_template_list = self.create_from_template_dialog.findChild(QListView, 'genericTemplates') + self.refresh_create_from_template_list() + + self.create_from_template_dialog.exec() + + def create_from_template_accepted_handler(self) -> None: + """ + Searches the available gems list for selected gems and attempts to add each one to the current gem. + Updates UI after completion. + :return: None + """ + create_gem_item = self.get_selected_gem_template() + if not create_gem_item: + return + + folder_dialog = QFileDialog(self.dialog, "Select a Folder and Enter a New Gem Name", + registration.get_o3de_gems_folder().as_posix()) + folder_dialog.setFileMode(QFileDialog.AnyFile) + folder_dialog.setOptions(QFileDialog.ShowDirsOnly) + gem_count = 0 + gem_name = "MyNewGem" + while os.path.exists(os.path.join(engine_path, gem_name)): + gem_name = f"MyNewGem{gem_count}" + gem_count += 1 + folder_dialog.selectFile(gem_name) + gem_folder = None + if folder_dialog.exec(): + gem_folder = folder_dialog.selectedFiles() + if gem_folder: + if engine_template.create_gem(gem_folder[0], create_gem_item[1]) == 0: + # Success + msg_box = QMessageBox(parent=self.dialog) + msg_box.setWindowTitle("O3DE") + msg_box.setText(f"gem {os.path.basename(os.path.normpath(gem_folder[0]))} created." + " Build your\nnew gem before hitting OK to launch.") + msg_box.exec() + return + + def add_project_handler(self): + """ + Open a file search dialog looking for a folder which contains a valid project. If valid + will update the mru list with the new entry, if invalid will warn the user. + :return: None + """ + project_folder = QFileDialog.getExistingDirectory(self.dialog, "Select Project Folder", + registration.get_o3de_projects_folder().as_posix()) + if project_folder: + if registration.register(project_path=project_folder) == 0: + # Success + self.refresh_project_list() + + msg_box = QMessageBox(parent=self.dialog) + msg_box.setWindowTitle("O3DE") + msg_box.setText(f"Added Project {project_folder}.") + msg_box.exec() + return + + def add_gem_handler(self): + """ + Open a file search dialog looking for a folder which contains a gem. If valid + will update the mru list with the new entry, if invalid will warn the user. + :return: None + """ + gem_folder = QFileDialog.getExistingDirectory(self.dialog, "Select Gem Folder", + registration.get_o3de_gems_folder().as_posix()) + if gem_folder: + if registration.register(gem_path=gem_folder) == 0: + # Success + msg_box = QMessageBox(parent=self.dialog) + msg_box.setWindowTitle("O3DE") + msg_box.setText(f"Added Gem {gem_folder}.") + msg_box.exec() + return + + def add_template_handler(self): + """ + Open a file search dialog looking for a folder which contains a valid template. If valid + will update the mru list with the new entry, if invalid will warn the user. + :return: None + """ + template_folder = QFileDialog.getExistingDirectory(self.dialog, "Select Template Folder", + registration.get_o3de_templates_folder().as_posix()) + if template_folder: + if registration.register(template_path=template_folder) == 0: + # Success + msg_box = QMessageBox(parent=self.dialog) + msg_box.setWindowTitle("O3DE") + msg_box.setText(f"Added Template {template_folder}.") + msg_box.exec() + return + + def add_restricted_handler(self): + """ + Open a file search dialog looking for a folder which contains a valid template. If valid + will update the mru list with the new entry, if invalid will warn the user. + :return: None + """ + restricted_folder = QFileDialog.getExistingDirectory(self.dialog, "Select Restricted Folder", + registration.get_o3de_restricted_folder().as_posix()) + if restricted_folder: + if registration.register(restricted_path=restricted_folder) == 0: + # Success + msg_box = QMessageBox(parent=self.dialog) + msg_box.setWindowTitle("O3DE") + msg_box.setText(f"Added Restricted {restricted_folder}.") + msg_box.exec() + return + + def remove_project_handler(self): + """ + Open a file search dialog looking for a folder which contains a valid project. If valid + will update the mru list with the new entry, if invalid will warn the user. + :return: None + """ + project_folder = QFileDialog.getExistingDirectory(self.dialog, "Select Project Folder", + registration.get_o3de_projects_folder().as_posix()) + if project_folder: + if registration.register(project_path=project_folder, remove=True) == 0: + # Success + self.refresh_project_list() + + msg_box = QMessageBox(parent=self.dialog) + msg_box.setWindowTitle("O3DE") + msg_box.setText(f"Removed Project {project_folder}.") + msg_box.exec() + return + + def remove_gem_handler(self): + """ + Open a file search dialog looking for a folder which contains a gem. If valid + will update the mru list with the new entry, if invalid will warn the user. + :return: None + """ + gem_folder = QFileDialog.getExistingDirectory(self.dialog, "Select Gem Folder", + registration.get_o3de_gems_folder().as_posix()) + if gem_folder: + if registration.register(gem_path=gem_folder, remove=True) == 0: + # Success + msg_box = QMessageBox(parent=self.dialog) + msg_box.setWindowTitle("O3DE") + msg_box.setText(f"Removed Gem {gem_folder}.") + msg_box.exec() + return + + def remove_template_handler(self): + """ + Open a file search dialog looking for a folder which contains a valid template. If valid + will update the mru list with the new entry, if invalid will warn the user. + :return: None + """ + template_folder = QFileDialog.getExistingDirectory(self.dialog, "Select Template Folder", + registration.get_o3de_templates_folder().as_posix()) + if template_folder: + if registration.register(template_path=template_folder, remove=True) == 0: + # Success + msg_box = QMessageBox(parent=self.dialog) + msg_box.setWindowTitle("O3DE") + msg_box.setText(f"Removed Template {template_folder}.") + msg_box.exec() + return + + def remove_restricted_handler(self): + """ + Open a file search dialog looking for a folder which contains a valid template. If valid + will update the mru list with the new entry, if invalid will warn the user. + :return: None + """ + restricted_folder = QFileDialog.getExistingDirectory(self.dialog, "Select Restricted Folder", + registration.get_o3de_restricted_folder().as_posix()) + if restricted_folder: + if registration.register(restricted_path=restricted_folder, remove=True) == 0: + # Success + msg_box = QMessageBox(parent=self.dialog) + msg_box.setWindowTitle("O3DE") + msg_box.setText(f"Removed Restricted {restricted_folder}.") + msg_box.exec() + return + + def manage_runtime_project_gem_targets_handler(self): + """ + Opens the Gem management pane. Waits for the load thread to complete if still running and displays all + active gems for the current project as well as all available gems which aren't currently active. + :return: None + """ + + if not self.get_selected_project_path(): + msg_box = QMessageBox(parent=self.dialog) + msg_box.setWindowTitle("O3DE") + msg_box.setText("Please select a project") + msg_box.exec() + return + + loader = QUiLoader() + self.manage_project_gem_targets_file = QFile(self.manage_project_gem_targets_ui_file_path.as_posix()) + + if not self.manage_project_gem_targets_file: + logger.error(f'Failed to load manage gem targets UI file at {self.manage_project_gem_targets_ui_file_path}') + return + + self.manage_project_gem_targets_dialog = loader.load(self.manage_project_gem_targets_file) + + if not self.manage_project_gem_targets_dialog: + logger.error(f'Failed to load gems dialog file at {self.manage_project_gem_targets_ui_file_path.as_posix()}') + return + + self.manage_project_gem_targets_dialog.setWindowTitle(f"Manage Runtime Gem Targets for Project:" + f" {self.get_selected_project_name()}") + + self.add_gem_button = self.manage_project_gem_targets_dialog.findChild(QPushButton, 'addGemTargetsButton') + self.add_gem_button.clicked.connect(self.add_runtime_project_gem_targets_handler) + + self.available_gem_targets_list = self.manage_project_gem_targets_dialog.findChild(QListView, + 'availableGemTargetsList') + self.refresh_runtime_project_gem_targets_available_list() + + self.remove_project_gem_targets_button = self.manage_project_gem_targets_dialog.findChild(QPushButton, + 'removeGemTargetsButton') + self.remove_project_gem_targets_button.clicked.connect(self.remove_runtime_project_gem_targets_handler) + + self.enabled_gem_targets_list = self.manage_project_gem_targets_dialog.findChild(QListView, + 'enabledGemTargetsList') + self.refresh_runtime_project_gem_targets_enabled_list() + + self.manage_project_gem_targets_dialog.exec() + + def manage_tool_project_gem_targets_handler(self): + """ + Opens the Gem management pane. Waits for the load thread to complete if still running and displays all + active gems for the current project as well as all available gems which aren't currently active. + :return: None + """ + + if not self.get_selected_project_path(): + msg_box = QMessageBox(parent=self.dialog) + msg_box.setWindowTitle("O3DE") + msg_box.setText("Please select a project") + msg_box.exec() + return + + loader = QUiLoader() + self.manage_project_gem_targets_file = QFile(self.manage_project_gem_targets_ui_file_path.as_posix()) + + if not self.manage_project_gem_targets_file: + logger.error(f'Failed to load manage gem targets UI file at {self.manage_project_gem_targets_ui_file_path}') + return + + self.manage_project_gem_targets_dialog = loader.load(self.manage_project_gem_targets_file) + + if not self.manage_project_gem_targets_dialog: + logger.error( + f'Failed to load gems dialog file at {self.manage_project_gem_targets_ui_file_path.as_posix()}') + return + + self.manage_project_gem_targets_dialog.setWindowTitle(f"Manage Tool Gem Targets for Project:" + f" {self.get_selected_project_name()}") + + self.add_gem_button = self.manage_project_gem_targets_dialog.findChild(QPushButton, 'addGemTargetsButton') + self.add_gem_button.clicked.connect(self.add_tool_project_gem_targets_handler) + + self.available_gem_targets_list = self.manage_project_gem_targets_dialog.findChild(QListView, + 'availableGemTargetsList') + self.refresh_tool_project_gem_targets_available_list() + + self.remove_project_gem_targets_button = self.manage_project_gem_targets_dialog.findChild(QPushButton, + 'removeGemTargetsButton') + self.remove_project_gem_targets_button.clicked.connect(self.remove_tool_project_gem_targets_handler) + + self.enabled_gem_targets_list = self.manage_project_gem_targets_dialog.findChild(QListView, + 'enabledGemTargetsList') + self.refresh_tool_project_gem_targets_enabled_list() + + self.manage_project_gem_targets_dialog.exec() + + def manage_server_project_gem_targets_handler(self): + """ + Opens the Gem management pane. Waits for the load thread to complete if still running and displays all + active gems for the current project as well as all available gems which aren't currently active. + :return: None + """ + + if not self.get_selected_project_path(): + msg_box = QMessageBox(parent=self.dialog) + msg_box.setWindowTitle("O3DE") + msg_box.setText("Please select a project") + msg_box.exec() + return + + loader = QUiLoader() + self.manage_project_gem_targets_file = QFile(self.manage_project_gem_targets_ui_file_path.as_posix()) + + if not self.manage_project_gem_targets_file: + logger.error(f'Failed to load manage gem targets UI file at {self.manage_project_gem_targets_ui_file_path}') + return + + self.manage_project_gem_targets_dialog = loader.load(self.manage_project_gem_targets_file) + + if not self.manage_project_gem_targets_dialog: + logger.error( + f'Failed to load gems dialog file at {self.manage_project_gem_targets_ui_file_path.as_posix()}') + return + + self.manage_project_gem_targets_dialog.setWindowTitle(f"Manage Server Gem Targets for Project:" + f" {self.get_selected_project_name()}") + + self.add_gem_button = self.manage_project_gem_targets_dialog.findChild(QPushButton, 'addGemTargetsButton') + self.add_gem_button.clicked.connect(self.add_server_project_gem_targets_handler) + + self.available_gem_targets_list = self.manage_project_gem_targets_dialog.findChild(QListView, + 'availableGemTargetsList') + self.refresh_server_project_gem_targets_available_list() + + self.remove_project_gem_targets_button = self.manage_project_gem_targets_dialog.findChild(QPushButton, + 'removeGemTargetsButton') + self.remove_project_gem_targets_button.clicked.connect(self.remove_server_project_gem_targets_handler) + + self.enabled_gem_targets_list = self.manage_project_gem_targets_dialog.findChild(QListView, + 'enabledGemTargetsList') + self.refresh_server_project_gem_targets_enabled_list() + + self.manage_project_gem_targets_dialog.exec() + + def manage_project_gem_targets_get_selected_available_gems(self) -> list: + selected_items = self.available_gem_targets_list.selectionModel().selectedRows() + return [(self.available_gem_targets_list.model().data(item)) for item in selected_items] + + def manage_project_gem_targets_get_selected_enabled_gems(self) -> list: + selected_items = self.enabled_gem_targets_list.selectionModel().selectedRows() + return [(self.enabled_gem_targets_list.model().data(item)) for item in selected_items] + + def add_runtime_project_gem_targets_handler(self) -> None: + gem_paths = registration.get_all_gems() + for gem_target in self.manage_project_gem_targets_get_selected_available_gems(): + for gem_path in gem_paths: + this_gems_targets = registration.get_gem_targets(gem_path=gem_path) + for this_gem_target in this_gems_targets: + if gem_target == this_gem_target: + registration.add_gem_to_project(gem_path=gem_path, + gem_target=gem_target, + project_path=self.get_selected_project_path(), + runtime_dependency=True) + self.refresh_runtime_project_gem_targets_available_list() + self.refresh_runtime_project_gem_targets_enabled_list() + return + self.refresh_runtime_project_gem_targets_available_list() + self.refresh_runtime_project_gem_targets_enabled_list() + + def remove_runtime_project_gem_targets_handler(self): + gem_paths = registration.get_all_gems() + for gem_target in self.manage_project_gem_targets_get_selected_enabled_gems(): + for gem_path in gem_paths: + this_gems_targets = registration.get_gem_targets(gem_path=gem_path) + for this_gem_target in this_gems_targets: + if gem_target == this_gem_target: + registration.remove_gem_from_project(gem_path=gem_path, + gem_target=gem_target, + project_path=self.get_selected_project_path(), + runtime_dependency=True) + self.refresh_runtime_project_gem_targets_available_list() + self.refresh_runtime_project_gem_targets_enabled_list() + return + self.refresh_runtime_project_gem_targets_available_list() + self.refresh_runtime_project_gem_targets_enabled_list() + + def add_tool_project_gem_targets_handler(self) -> None: + gem_paths = registration.get_all_gems() + for gem_target in self.manage_project_gem_targets_get_selected_available_gems(): + for gem_path in gem_paths: + this_gems_targets = registration.get_gem_targets(gem_path=gem_path) + for this_gem_target in this_gems_targets: + if gem_target == this_gem_target: + registration.add_gem_to_project(gem_path=gem_path, + gem_target=gem_target, + project_path=self.get_selected_project_path(), + tool_dependency=True) + self.refresh_tool_project_gem_targets_available_list() + self.refresh_tool_project_gem_targets_enabled_list() + return + self.refresh_tool_project_gem_targets_available_list() + self.refresh_tool_project_gem_targets_enabled_list() + + def remove_tool_project_gem_targets_handler(self): + gem_paths = registration.get_all_gems() + for gem_target in self.manage_project_gem_targets_get_selected_enabled_gems(): + for gem_path in gem_paths: + this_gems_targets = registration.get_gem_targets(gem_path=gem_path) + for this_gem_target in this_gems_targets: + if gem_target == this_gem_target: + registration.remove_gem_from_project(gem_path=gem_path, + gem_target=gem_target, + project_path=self.get_selected_project_path(), + tool_dependency=True) + self.refresh_tool_project_gem_targets_available_list() + self.refresh_tool_project_gem_targets_enabled_list() + return + self.refresh_tool_project_gem_targets_available_list() + self.refresh_tool_project_gem_targets_enabled_list() + + def add_server_project_gem_targets_handler(self) -> None: + gem_paths = registration.get_all_gems() + for gem_target in self.manage_project_gem_targets_get_selected_available_gems(): + for gem_path in gem_paths: + this_gems_targets = registration.get_gem_targets(gem_path=gem_path) + for this_gem_target in this_gems_targets: + if gem_target == this_gem_target: + registration.add_gem_to_project(gem_path=gem_path, + gem_target=gem_target, + project_path=self.get_selected_project_path(), + server_dependency=True) + self.refresh_server_project_gem_targets_available_list() + self.refresh_server_project_gem_targets_enabled_list() + return + self.refresh_server_project_gem_targets_available_list() + self.refresh_server_project_gem_targets_enabled_list() + + def remove_server_project_gem_targets_handler(self): + gem_paths = registration.get_all_gems() + for gem_target in self.manage_project_gem_targets_get_selected_enabled_gems(): + for gem_path in gem_paths: + this_gems_targets = registration.get_gem_targets(gem_path=gem_path) + for this_gem_target in this_gems_targets: + if gem_target == this_gem_target: + registration.remove_gem_from_project(gem_path=gem_path, + gem_target=gem_target, + project_path=self.get_selected_project_path(), + server_dependency=True) + self.refresh_server_project_gem_targets_available_list() + self.refresh_server_project_gem_targets_enabled_list() + return + self.refresh_server_project_gem_targets_available_list() + self.refresh_server_project_gem_targets_enabled_list() + + def refresh_runtime_project_gem_targets_enabled_list(self) -> None: + enabled_project_gem_targets_model = QStandardItemModel() + enabled_project_gem_targets = registration.get_project_runtime_gem_targets( + project_path=self.get_selected_project_path()) + for gem_target in sorted(enabled_project_gem_targets): + model_item = QStandardItem(gem_target) + enabled_project_gem_targets_model.appendRow(model_item) + self.enabled_gem_targets_list.setModel(enabled_project_gem_targets_model) + + def refresh_runtime_project_gem_targets_available_list(self) -> None: + available_project_gem_targets_model = QStandardItemModel() + enabled_project_gem_targets = registration.get_project_runtime_gem_targets( + project_path=self.get_selected_project_path()) + all_gem_targets = registration.get_all_gem_targets() + for gem_target in sorted(all_gem_targets): + if gem_target not in enabled_project_gem_targets: + model_item = QStandardItem(gem_target) + available_project_gem_targets_model.appendRow(model_item) + self.available_gem_targets_list.setModel(available_project_gem_targets_model) + + def refresh_tool_project_gem_targets_enabled_list(self) -> None: + enabled_project_gem_targets_model = QStandardItemModel() + enabled_project_gem_targets = registration.get_project_tool_gem_targets( + project_path=self.get_selected_project_path()) + for gem_target in sorted(enabled_project_gem_targets): + model_item = QStandardItem(gem_target) + enabled_project_gem_targets_model.appendRow(model_item) + self.enabled_gem_targets_list.setModel(enabled_project_gem_targets_model) + + def refresh_tool_project_gem_targets_available_list(self) -> None: + available_project_gem_targets_model = QStandardItemModel() + enabled_project_gem_targets = registration.get_project_tool_gem_targets( + project_path=self.get_selected_project_path()) + all_gem_targets = registration.get_all_gem_targets() + for gem_target in sorted(all_gem_targets): + if gem_target not in enabled_project_gem_targets: + model_item = QStandardItem(gem_target) + available_project_gem_targets_model.appendRow(model_item) + self.available_gem_targets_list.setModel(available_project_gem_targets_model) + + def refresh_server_project_gem_targets_enabled_list(self) -> None: + enabled_project_gem_targets_model = QStandardItemModel() + enabled_project_gem_targets = registration.get_project_server_gem_targets( + project_path=self.get_selected_project_path()) + for gem_target in sorted(enabled_project_gem_targets): + model_item = QStandardItem(gem_target) + enabled_project_gem_targets_model.appendRow(model_item) + self.enabled_gem_targets_list.setModel(enabled_project_gem_targets_model) + + def refresh_server_project_gem_targets_available_list(self) -> None: + available_project_gem_targets_model = QStandardItemModel() + enabled_project_gem_targets = registration.get_project_server_gem_targets( + project_path=self.get_selected_project_path()) + all_gem_targets = registration.get_all_gem_targets() + for gem_target in sorted(all_gem_targets): + if gem_target not in enabled_project_gem_targets: + model_item = QStandardItem(gem_target) + available_project_gem_targets_model.appendRow(model_item) + self.available_gem_targets_list.setModel(available_project_gem_targets_model) + + def refresh_create_project_template_list(self) -> None: + self.create_project_template_model = QStandardItemModel() + for project_template_path in registration.get_project_templates(): + model_item = QStandardItem(project_template_path) + self.create_project_template_model.appendRow(model_item) + self.create_project_template_list.setModel(self.create_project_template_model) + + def refresh_create_gem_template_list(self) -> None: + self.create_gem_template_model = QStandardItemModel() + for gem_template_path in registration.get_gem_templates(): + model_item = QStandardItem(gem_template_path) + self.create_gem_template_model.appendRow(model_item) + self.create_gem_template_list.setModel(self.create_gem_template_model) + + def refresh_create_from_template_list(self) -> None: + self.create_from_template_model = QStandardItemModel() + for generic_template_path in registration.get_generic_templates(): + model_item = QStandardItem(generic_template_path) + self.create_from_template_model.appendRow(model_item) + self.create_from_template_list.setModel(self.create_from_template_model) def update_mru_list(self, used_project: str) -> None: """ @@ -621,7 +985,7 @@ class ProjectDialog(QObject): def get_mru_list(self) -> List[str]: """ - Retrive the current MRU list. Does not perform validation that the projects still appear valid + Retrieve the current MRU list. Does not perform validation that the projects still appear valid :return: list of full path strings to project folders """ if not os.path.exists(os.path.dirname(self.mru_file_path)): @@ -653,6 +1017,6 @@ class ProjectDialog(QObject): if __name__ == "__main__": dialog_app = QApplication(sys.argv) - my_dialog = ProjectDialog() + my_dialog = ProjectManagerDialog() dialog_app.exec_() sys.exit(0) diff --git a/scripts/project_manager/tests/test_projects.py b/scripts/project_manager/tests/test_projects.py index 69895accfd..d073cf6c7a 100755 --- a/scripts/project_manager/tests/test_projects.py +++ b/scripts/project_manager/tests/test_projects.py @@ -9,54 +9,67 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # + import pytest +''' import os import sys import tempfile import logging +import pathlib from unittest.mock import MagicMock logger = logging.getLogger() # Code lives one folder above -projects_path = os.path.realpath(os.path.join(os.path.dirname(__file__), '..')) -sys.path.append(projects_path) +project_manager_path = os.path.realpath(os.path.join(os.path.dirname(__file__), '..')) +sys.path.append(project_manager_path) from pyside import add_pyside_environment, is_configuration_valid from ly_test_tools import WINDOWS -project_marker_file = "project.json" +sys.path.append(os.path.realpath(os.path.join(os.path.dirname(__file__), '..', '..', '..'))) +executable_path = '' +from cmake.Tools import registration +from cmake.Tools import engine_template + class ProjectHelper: def __init__(self): - self._temp_directory = tempfile.TemporaryDirectory() - self.temp_project_root = self._temp_directory.name - self.temp_file_dir = os.path.join(self.temp_project_root, "o3de") + self._temp_directory = pathlib.Path(tempfile.TemporaryDirectory().name).resolve() + self._temp_directory.mkdir(parents=True, exist_ok=True) + + self.home_path = self._temp_directory + registration.override_home_folder = self.home_path + self.engine_path = registration.get_this_engine_path() + if registration.register(engine_path=self.engine_path): + assert True, f"Failed to register the engine." + + if registration.register_shipped_engine_o3de_objects(): + assert True, f"Failed to register shipped engine objects." + + self.projects_folder = registration.get_o3de_projects_folder() + if not self.projects_folder.is_dir(): + assert True self.application = None self.dialog = None - if not os.path.exists(self.temp_file_dir): - os.makedirs(self.temp_file_dir) - def create_empty_projects(self): - self.project_1_dir = os.path.join(self.temp_project_root, "Project1") - if not os.path.exists(self.project_1_dir): - os.makedirs(self.project_1_dir) - with open(os.path.join(self.project_1_dir,project_marker_file), 'w') as marker_file: - marker_file.write("{}") - self.project_2_dir = os.path.join(self.temp_project_root, "Project2") - if not os.path.exists(self.project_2_dir): - os.makedirs(self.project_2_dir) - with open(os.path.join(self.project_2_dir, project_marker_file), 'w') as marker_file: - marker_file.write("{}") - self.project_3_dir = os.path.join(self.temp_project_root, "Project3") - if not os.path.exists(self.project_3_dir): - os.makedirs(self.project_3_dir) - with open(os.path.join(self.project_3_dir, project_marker_file), 'w') as marker_file: - marker_file.write("{}") - self.invalid_project_dir = os.path.join(self.temp_project_root, "InvalidProject") + self.project_1_dir = self.projects_folder / "Project1" + if engine_template.create_project(project_manager_path=self.project_1_dir): + assert True, f"Failed to create Project1." + self.project_2_dir = self.projects_folder / "Project2" + if engine_template.create_project(project_manager_path=self.project_2_dir): + assert True, f"Failed to create Project2." + + self.project_3_dir = self.projects_folder / "Project3" + if engine_template.create_project(project_manager_path=self.project_3_dir): + assert True, f"Failed to create Project3." + + self.invalid_project_dir = self.projects_folder / "InvalidProject" + self.invalid_project_dir.mkdir(parents=True, exist_ok=True) def setup_dialog_test(self, workspace): add_pyside_environment(workspace.paths.build_directory()) @@ -66,6 +79,7 @@ class ProjectHelper: # need to use the profile version of PySide which works with the profile QT libs which aren't in the debug # folder we've built. return None + from PySide2.QtWidgets import QApplication, QMessageBox if QApplication.instance(): @@ -74,13 +88,13 @@ class ProjectHelper: self.application = QApplication(sys.argv) assert self.application - from projects import ProjectDialog + from projects import ProjectManagerDialog try: - self.dialog = ProjectDialog(settings_folder=self.temp_file_dir) + self.dialog = ProjectManagerDialog(settings_folder=self.home_path) return self.dialog except Exception as e: - logger.error(f'Failed to create ProjectDialog with error {e}') + logger.error(f'Failed to create ProjectManagerDialog with error {e}') return None def create_project_from_template(self, project_name) -> bool: @@ -90,21 +104,24 @@ class ProjectHelper: :return: True for Success, False for failure """ from PySide2.QtWidgets import QWidget, QFileDialog - from projects import ProjectDialog + from projects import ProjectManagerDialog QWidget.exec = MagicMock() self.dialog.create_project_handler() QWidget.exec.assert_called_once() assert len(self.dialog.project_templates), 'Failed to find any project templates' - ProjectDialog.get_selected_project_template = MagicMock(return_value=self.dialog.project_templates[0]) + ProjectManagerDialog.get_selected_project_template = MagicMock(return_value=self.dialog.project_templates[0]) QFileDialog.exec = MagicMock() - create_project_dir = os.path.join(self.temp_project_root, project_name) - QFileDialog.selectedFiles = MagicMock(return_value=[create_project_dir]) + create_project_path = self.projects_folder / project_name + QFileDialog.selectedFiles = MagicMock(return_value=[create_project_path]) self.dialog.create_project_accepted_handler() - assert os.path.isdir(create_project_dir), f"Expected project folder not found at {create_project_dir}" - assert QWidget.exec.call_count == 2, "Message box confirming project creation failed to show" + if create_project_path.is_dir(): + assert True, f"Expected project creation folder not found at {create_project_path}" + + if QWidget.exec.call_count == 2: + assert True, "Message box confirming project creation failed to show" @pytest.fixture @@ -113,7 +130,7 @@ def project_helper(): @pytest.mark.skipif(not WINDOWS, reason="PySide2 only works on windows currently") -@pytest.mark.parametrize('project', ['']) # Workspace wants a project, but this test is not project dependent +@pytest.mark.parametrize('project', ['']) # Workspace wants a project, but this test is not project dependent def test_logger_handler(workspace, project_helper): my_dialog = project_helper.setup_dialog_test(workspace) if not my_dialog: @@ -126,7 +143,7 @@ def test_logger_handler(workspace, project_helper): @pytest.mark.skipif(not WINDOWS, reason="PySide2 only works on windows currently") -@pytest.mark.parametrize('project', ['']) # Workspace wants a project, but this test is not project dependent +@pytest.mark.parametrize('project', ['']) # Workspace wants a project, but this test is not project dependent def test_mru_list(workspace, project_helper): my_dialog = project_helper.setup_dialog_test(workspace) if not my_dialog: @@ -140,16 +157,16 @@ def test_mru_list(workspace, project_helper): assert len(mru_list) == 0, f'MRU list unexpectedly had entries: {mru_list}' QMessageBox.warning = MagicMock() - my_dialog.add_new_project('TestProjectInvalid') + my_dialog.add_project(project_helper.invalid_project_dir) mru_list = my_dialog.get_mru_list() assert len(mru_list) == 0, f'MRU list unexpectedly added an invalid project : {mru_list}' QMessageBox.warning.assert_called_once() - my_dialog.add_new_project(project_helper.project_1_dir) + my_dialog.add_project(project_helper.project_1_dir) mru_list = my_dialog.get_mru_list() assert len(mru_list) == 1, f'MRU list failed to add project at {project_helper.project_1_dir}' - my_dialog.add_new_project(project_helper.project_1_dir) + my_dialog.add_project(project_helper.project_1_dir) mru_list = my_dialog.get_mru_list() assert len(mru_list) == 1, f'MRU list added project at {project_helper.project_1_dir} a second time : {mru_list}' @@ -157,7 +174,7 @@ def test_mru_list(workspace, project_helper): mru_list = my_dialog.get_mru_list() assert len(mru_list) == 1, f'MRU list added project at {project_helper.project_1_dir} a second time : {mru_list}' - my_dialog.add_new_project(project_helper.project_2_dir) + my_dialog.add_project(project_helper.project_2_dir) mru_list = my_dialog.get_mru_list() assert len(mru_list) == 2, f'MRU list failed to add project at {project_helper.project_2_dir}' @@ -170,13 +187,13 @@ def test_mru_list(workspace, project_helper): assert mru_list[0] == project_helper.project_1_dir, f"{project_helper.project_1_dir} wasn't first item" assert mru_list[1] == project_helper.project_2_dir, f"{project_helper.project_2_dir} wasn't second item" - my_dialog.add_new_project(project_helper.invalid_project_dir) + my_dialog.add_project(project_helper.invalid_project_dir) mru_list = my_dialog.get_mru_list() assert len(mru_list) == 2, f'MRU list added invalid item {mru_list}' assert mru_list[0] == project_helper.project_1_dir, f"{project_helper.project_1_dir} wasn't first item" assert mru_list[1] == project_helper.project_2_dir, f"{project_helper.project_2_dir} wasn't second item" - my_dialog.add_new_project(project_helper.project_3_dir) + my_dialog.add_project(project_helper.project_3_dir) mru_list = my_dialog.get_mru_list() assert len(mru_list) == 3, f'MRU list failed to add {project_helper.project_3_dir} : {mru_list}' assert mru_list[0] == project_helper.project_3_dir, f"{project_helper.project_3_dir} wasn't first item" @@ -185,7 +202,7 @@ def test_mru_list(workspace, project_helper): @pytest.mark.skipif(not WINDOWS, reason="PySide2 only works on windows currently") -@pytest.mark.parametrize('project', ['']) # Workspace wants a project, but this test is not project dependent +@pytest.mark.parametrize('project', ['']) # Workspace wants a project, but this test is not project dependent def test_create_project(workspace, project_helper): my_dialog = project_helper.setup_dialog_test(workspace) if not my_dialog: @@ -195,7 +212,7 @@ def test_create_project(workspace, project_helper): @pytest.mark.skipif(not WINDOWS, reason="PySide2 only works on windows currently") -@pytest.mark.parametrize('project', ['']) # Workspace wants a project, but this test is not project dependent +@pytest.mark.parametrize('project', ['']) # Workspace wants a project, but this test is not project dependent def test_add_remove_gems(workspace, project_helper): my_dialog = project_helper.setup_dialog_test(workspace) if not my_dialog: @@ -203,32 +220,36 @@ def test_add_remove_gems(workspace, project_helper): my_project_name = "TestAddRemoveGems" - project_helper.create_project_from_template(my_project_name) - my_project_path = os.path.join(project_helper.temp_project_root, my_project_name) + project_helper.create_project_from_template(project_manager_path=my_project_name) + my_project_path = project_helper.projects_folder / my_project_name from PySide2.QtWidgets import QWidget, QFileDialog - from projects import ProjectDialog + from projects import ProjectManagerDialog - assert my_dialog.path_for_selection() == my_project_path, "Gems project not selected" + assert my_dialog.get_selected_project_path() == my_project_path, "TestAddRemoveGems project not selected" QWidget.exec = MagicMock() my_dialog.manage_gems_handler() - assert my_dialog.manage_gems_dialog, "No gem management dialog created" + assert my_dialog.manage_gem_targets_dialog, "No gem management dialog created" QWidget.exec.assert_called_once() - assert len(my_dialog.gems_list), 'Failed to find any gems' - my_test_gem = my_dialog.gems_list[0] - my_test_gem_name = my_test_gem.get("Name") - my_test_gem_path = my_test_gem.get("Path") - my_test_gem_selection = (my_test_gem_name, my_test_gem_path) - ProjectDialog.get_selected_add_gems = MagicMock(return_value=[my_test_gem_selection]) + if not len(my_dialog.all_gems_list): + assert True, 'Failed to find any gems' + my_test_gem_path = my_dialog.all_gems_list[0] + gem_data = registration.get_gem_data(my_test_gem_path) + my_test_gem_selection = (my_test_gem_name, my_test_gem_path) + ProjectManagerDialog.get_selected_add_gems = MagicMock(return_value=[my_test_gem_selection]) assert my_test_gem_name, "No Name set in test gem" assert my_test_gem_name not in my_dialog.project_gem_list, f'Gem {my_test_gem_name} already in project gem list' + my_dialog.add_gems_handler() assert my_test_gem_name in my_dialog.project_gem_list, f'Gem {my_test_gem_name} failed to add to gem list' - ProjectDialog.get_selected_project_gems = MagicMock(return_value=[my_test_gem_name]) + + ProjectManagerDialog.get_selected_project_gems = MagicMock(return_value=[my_test_gem_name]) my_dialog.remove_gems_handler() assert my_test_gem_name not in my_dialog.project_gem_list, f'Gem {my_test_gem_name} still in project gem list' +''' - +def test_project_place_holder(): + pass \ No newline at end of file diff --git a/scripts/project_manager/ui/create_from_template.ui b/scripts/project_manager/ui/create_from_template.ui new file mode 100644 index 0000000000..b6a8740594 --- /dev/null +++ b/scripts/project_manager/ui/create_from_template.ui @@ -0,0 +1,94 @@ + + + createFromTemplateDialog + + + + 0 + 0 + 467 + 288 + + + + Create From Template + + + + + 50 + 250 + 400 + 32 + + + + Qt::Horizontal + + + QDialogButtonBox::Cancel|QDialogButtonBox::Ok + + + + + + 10 + 20 + 449 + 221 + + + + QAbstractItemView::SingleSelection + + + + + + 10 + 0 + 300 + 16 + + + + Available Templates + + + + + + + okCancel + accepted() + createFromTemplateDialog + accept() + + + 248 + 254 + + + 157 + 274 + + + + + okCancel + rejected() + createFromTemplateDialog + reject() + + + 316 + 260 + + + 286 + 274 + + + + + diff --git a/scripts/project_manager/ui/create_gem.ui b/scripts/project_manager/ui/create_gem.ui new file mode 100644 index 0000000000..5a5fd14a6d --- /dev/null +++ b/scripts/project_manager/ui/create_gem.ui @@ -0,0 +1,94 @@ + + + createGemDialog + + + + 0 + 0 + 467 + 288 + + + + Create Gem + + + + + 50 + 250 + 400 + 32 + + + + Qt::Horizontal + + + QDialogButtonBox::Cancel|QDialogButtonBox::Ok + + + + + + 10 + 20 + 449 + 221 + + + + QAbstractItemView::SingleSelection + + + + + + 10 + 0 + 300 + 16 + + + + Available Templates + + + + + + + okCancel + accepted() + createGemDialog + accept() + + + 248 + 254 + + + 157 + 274 + + + + + okCancel + rejected() + createGemDialog + reject() + + + 316 + 260 + + + 286 + 274 + + + + + diff --git a/scripts/project_manager/ui/create_project.ui b/scripts/project_manager/ui/create_project.ui index b4c8fb5caa..67a13325b0 100644 --- a/scripts/project_manager/ui/create_project.ui +++ b/scripts/project_manager/ui/create_project.ui @@ -6,7 +6,7 @@ 0 0 - 226 + 467 288 @@ -18,7 +18,7 @@ 50 250 - 171 + 400 32 @@ -34,7 +34,7 @@ 10 20 - 211 + 449 221 @@ -47,7 +47,7 @@ 10 0 - 101 + 300 16 diff --git a/scripts/project_manager/ui/manage_gems.ui b/scripts/project_manager/ui/manage_gem_targets.ui similarity index 74% rename from scripts/project_manager/ui/manage_gems.ui rename to scripts/project_manager/ui/manage_gem_targets.ui index 36083bd9df..ea9e607d42 100644 --- a/scripts/project_manager/ui/manage_gems.ui +++ b/scripts/project_manager/ui/manage_gem_targets.ui @@ -1,24 +1,24 @@ - addGemsDialog - + manageGemTargetsDialog + 0 0 - 635 - 327 + 702 + 297 - Manage Gems + Manage Gem Targets - 460 - 290 - 171 + 310 + 260 + 71 32 @@ -29,10 +29,10 @@ QDialogButtonBox::Close - + - 380 + 440 50 250 221 @@ -48,7 +48,7 @@ QAbstractItemView::ExtendedSelection - + 10 @@ -64,14 +64,14 @@ - 380 + 440 30 - 91 + 251 16 - Available Gems + Available Gem Targets @@ -79,38 +79,38 @@ 10 30 - 71 + 251 16 - Enabled Gems + Enabled Gem Targets - + - 267 + 264 130 - 105 + 171 23 - Remove Gems >> + Remove Gem Targets >> - + - 267 + 264 100 - 105 + 171 23 - << Add Gems + << Add Gem Targets @@ -118,12 +118,12 @@ 10 5 - 241 - 16 + 400 + 21 - Adding new Gems may require rebuilding + Adding new Gem Targets may require rebuilding @@ -132,7 +132,7 @@ close accepted() - addGemsDialog + manageGemTargetsDialog accept() @@ -148,7 +148,7 @@ close rejected() - addGemsDialog + manageGemTargetsDialog reject() diff --git a/scripts/project_manager/ui/projects.ico b/scripts/project_manager/ui/project_manager.ico similarity index 100% rename from scripts/project_manager/ui/projects.ico rename to scripts/project_manager/ui/project_manager.ico diff --git a/scripts/project_manager/ui/project_manager.ui b/scripts/project_manager/ui/project_manager.ui new file mode 100644 index 0000000000..6b3b5f758c --- /dev/null +++ b/scripts/project_manager/ui/project_manager.ui @@ -0,0 +1,407 @@ + + + Dialog + + + + 0 + 0 + 712 + 395 + + + + + 1 + 0 + + + + O3DE + + + Select and manage your projects for O3DE + + + + + 540 + 360 + 161 + 31 + + + + Qt::Horizontal + + + QDialogButtonBox::Cancel|QDialogButtonBox::Ok + + + + + + 10 + 30 + 691 + 31 + + + + Current project to launch or manage gems for. + + + + + + 10 + 10 + 47 + 13 + + + + Project + + + + + + 270 + 220 + 431 + 141 + + + + QFrame::Panel + + + QFrame::Sunken + + + + + + true + + + Qt::LinksAccessibleByMouse|Qt::TextSelectableByMouse + + + + + + 10 + 70 + 241 + 151 + + + + Create + + + + + 10 + 110 + 221 + 31 + + + + Create a new O3DE object from a pre configured template. + + + Create From Template + + + + + + 10 + 20 + 221 + 31 + + + + Create a new O3DE object from a pre configured template. + + + Create Project + + + + + + 11 + 50 + 221 + 31 + + + + Create a new O3DE object from a pre configured template. + + + Create Gem + + + + + + 11 + 80 + 221 + 31 + + + + Create a new O3DE object from a pre configured template. + + + Create Template + + + + + + + 260 + 70 + 451 + 141 + + + + Registration + + + + + 10 + 80 + 211 + 31 + + + + Browse for an existing O3DE project. + + + Add Template + + + + + + 10 + 20 + 211 + 31 + + + + Browse for an existing O3DE project. + + + Add Project + + + + + + 10 + 50 + 211 + 31 + + + + Browse for an existing O3DE project. + + + Add Gem + + + + + + 10 + 110 + 211 + 31 + + + + Browse for an existing O3DE project. + + + Add Restricted + + + + + + 230 + 110 + 211 + 31 + + + + Browse for an existing O3DE project. + + + Remove Restricted + + + + + + 230 + 20 + 211 + 31 + + + + Browse for an existing O3DE project. + + + Remove Project + + + + + + 230 + 50 + 211 + 31 + + + + Browse for an existing O3DE project. + + + Remove Gem + + + + + + 230 + 80 + 211 + 31 + + + + Browse for an existing O3DE project. + + + Remove Template + + + + + + + 10 + 230 + 241 + 121 + + + + Manage Project + + + + + 10 + 80 + 221 + 31 + + + + Add or remove gems from your selected project. Gems add and remove additional assets and features to projects. + + + Manage Server Gem Targets + + + + + + 10 + 50 + 221 + 31 + + + + Add or remove gems from your selected project. Gems add and remove additional assets and features to projects. + + + Manage Tool Gem Targets + + + + + + 10 + 20 + 221 + 31 + + + + Add or remove gems from your selected project. Gems add and remove additional assets and features to projects. + + + Manage Runtime Gem Targets + + + + + + + + okCancel + accepted() + Dialog + accept() + + + 248 + 254 + + + 157 + 274 + + + + + okCancel + rejected() + Dialog + reject() + + + 316 + 260 + + + 286 + 274 + + + + + diff --git a/scripts/project_manager/ui/projects.ui b/scripts/project_manager/ui/projects.ui deleted file mode 100644 index 4445029dda..0000000000 --- a/scripts/project_manager/ui/projects.ui +++ /dev/null @@ -1,167 +0,0 @@ - - - Dialog - - - - 0 - 0 - 464 - 136 - - - - - 1 - 0 - - - - O3DE - - - Select and manage your projects for O3DE - - - - - 290 - 100 - 171 - 31 - - - - Qt::Horizontal - - - QDialogButtonBox::Cancel|QDialogButtonBox::Ok - - - - - - 10 - 30 - 451 - 31 - - - - Current project to launch or manage gems for. - - - - - - 10 - 70 - 91 - 23 - - - - Create a new O3DE project from a pre configured template. - - - Create New - - - - - - 10 - 10 - 47 - 13 - - - - Project - - - - - - 110 - 70 - 91 - 23 - - - - Browse for an existing O3DE project. - - - Browse - - - - - - 350 - 70 - 91 - 23 - - - - Add or remove gems from your selected project. Gems add and remove additional assets and features to projects. - - - Manage Gems - - - - - - 5 - 110 - 275 - 16 - - - - - - - Qt::LinksAccessibleByMouse|Qt::TextSelectableByMouse - - - - - - - okCancel - accepted() - Dialog - accept() - - - 248 - 254 - - - 157 - 274 - - - - - okCancel - rejected() - Dialog - reject() - - - 316 - 260 - - - 286 - 274 - - - - -