diff --git a/AutomatedTesting/Gem/PythonTests/AWS/Windows/aws_metrics/aws_metrics_automation_test.py b/AutomatedTesting/Gem/PythonTests/AWS/Windows/aws_metrics/aws_metrics_automation_test.py index 5f6103c46a..34b2217916 100644 --- a/AutomatedTesting/Gem/PythonTests/AWS/Windows/aws_metrics/aws_metrics_automation_test.py +++ b/AutomatedTesting/Gem/PythonTests/AWS/Windows/aws_metrics/aws_metrics_automation_test.py @@ -31,7 +31,7 @@ def setup(launcher: pytest.fixture, Set up the resource mapping configuration and start the log monitor. :param launcher: Client launcher for running the test level. :param asset_processor: asset_processor fixture. - :return log monitor object, metrics file path and the metrics stack name. + :return log monitor object. """ asset_processor.start() asset_processor.wait_for_idle() @@ -73,12 +73,11 @@ def monitor_metrics_submission(log_monitor: pytest.fixture) -> None: f'unexpected_lines values: {unexpected_lines}') -def query_metrics_from_s3(aws_metrics_utils: pytest.fixture, resource_mappings: pytest.fixture, stack_name: str) -> None: +def query_metrics_from_s3(aws_metrics_utils: pytest.fixture, resource_mappings: pytest.fixture) -> None: """ Verify that the metrics events are delivered to the S3 bucket and can be queried. :param aws_metrics_utils: aws_metrics_utils fixture. :param resource_mappings: resource_mappings fixture. - :param stack_name: name of the CloudFormation stack. """ aws_metrics_utils.verify_s3_delivery( resource_mappings.get_resource_name_id('AWSMetrics.AnalyticsBucketName') @@ -89,23 +88,24 @@ def query_metrics_from_s3(aws_metrics_utils: pytest.fixture, resource_mappings: resource_mappings.get_resource_name_id('AWSMetrics.EventsCrawlerName')) # Remove the events_json table if exists so that the sample query can create a table with the same name. - aws_metrics_utils.delete_table(f'{stack_name}-eventsdatabase', 'events_json') - aws_metrics_utils.run_named_queries(f'{stack_name}-AthenaWorkGroup') + aws_metrics_utils.delete_table(resource_mappings.get_resource_name_id('AWSMetrics.EventDatabaseName'), 'events_json') + aws_metrics_utils.run_named_queries(resource_mappings.get_resource_name_id('AWSMetrics.AthenaWorkGroupName')) logger.info('Query metrics from S3 successfully.') -def verify_operational_metrics(aws_metrics_utils: pytest.fixture, stack_name: str, start_time: datetime) -> None: +def verify_operational_metrics(aws_metrics_utils: pytest.fixture, + resource_mappings: pytest.fixture, start_time: datetime) -> None: """ Verify that operational health metrics are delivered to CloudWatch. - aws_metrics_utils: aws_metrics_utils fixture. - stack_name: name of the CloudFormation stack. - start_time: Time when the game launcher starts. + :param aws_metrics_utils: aws_metrics_utils fixture. + :param resource_mappings: resource_mappings fixture. + :param start_time: Time when the game launcher starts. """ aws_metrics_utils.verify_cloud_watch_delivery( 'AWS/Lambda', 'Invocations', [{'Name': 'FunctionName', - 'Value': f'{stack_name}-AnalyticsProcessingLambda'}], + 'Value': resource_mappings.get_resource_name_id('AWSMetrics.AnalyticsProcessingLambdaName')}], start_time) logger.info('AnalyticsProcessingLambda metrics are sent to CloudWatch.') @@ -113,7 +113,7 @@ def verify_operational_metrics(aws_metrics_utils: pytest.fixture, stack_name: st 'AWS/Lambda', 'Invocations', [{'Name': 'FunctionName', - 'Value': f'{stack_name}-EventsProcessingLambda'}], + 'Value': resource_mappings.get_resource_name_id('AWSMetrics.EventProcessingLambdaName')}], start_time) logger.info('EventsProcessingLambda metrics are sent to CloudWatch.') @@ -157,7 +157,6 @@ class TestAWSMetricsWindows(object): workspace: pytest.fixture, aws_utils: pytest.fixture, resource_mappings: pytest.fixture, - stacks: typing.List, aws_metrics_utils: pytest.fixture): """ Verify that the metrics events are sent to CloudWatch and S3 for analytics. @@ -189,10 +188,10 @@ class TestAWSMetricsWindows(object): operational_threads = list() operational_threads.append( AWSMetricsThread(target=query_metrics_from_s3, - args=(aws_metrics_utils, resource_mappings, stacks[0]))) + args=(aws_metrics_utils, resource_mappings))) operational_threads.append( AWSMetricsThread(target=verify_operational_metrics, - args=(aws_metrics_utils, stacks[0], start_time))) + args=(aws_metrics_utils, resource_mappings, start_time))) operational_threads.append( AWSMetricsThread(target=update_kinesis_analytics_application_status, args=(aws_metrics_utils, resource_mappings, False))) diff --git a/AutomatedTesting/Gem/PythonTests/atom_renderer/CMakeLists.txt b/AutomatedTesting/Gem/PythonTests/Atom/CMakeLists.txt similarity index 70% rename from AutomatedTesting/Gem/PythonTests/atom_renderer/CMakeLists.txt rename to AutomatedTesting/Gem/PythonTests/Atom/CMakeLists.txt index 992420904c..02aaa42597 100644 --- a/AutomatedTesting/Gem/PythonTests/atom_renderer/CMakeLists.txt +++ b/AutomatedTesting/Gem/PythonTests/Atom/CMakeLists.txt @@ -13,48 +13,56 @@ if(PAL_TRAIT_BUILD_HOST_TOOLS AND PAL_TRAIT_BUILD_TESTS_SUPPORTED AND AutomatedTesting IN_LIST LY_PROJECTS) ly_add_pytest( - NAME AutomatedTesting::AtomRenderer_HydraTests_Main + NAME AutomatedTesting::Atom_TestSuite_Main TEST_SUITE main - PATH ${CMAKE_CURRENT_LIST_DIR}/test_Atom_MainSuite.py + PATH ${CMAKE_CURRENT_LIST_DIR}/TestSuite_Main.py TEST_SERIAL TIMEOUT 600 RUNTIME_DEPENDENCIES AssetProcessor AutomatedTesting.Assets Editor + COMPONENT + Atom ) ly_add_pytest( - NAME AutomatedTesting::AtomRenderer_HydraTests_Sandbox + NAME AutomatedTesting::Atom_TestSuite_Main_Optimized + TEST_SUITE main + PATH ${CMAKE_CURRENT_LIST_DIR}/TestSuite_Main_Optimized.py + TEST_SERIAL + TIMEOUT 600 + RUNTIME_DEPENDENCIES + AssetProcessor + AutomatedTesting.Assets + Editor + COMPONENT + Atom + ) + ly_add_pytest( + NAME AutomatedTesting::Atom_TestSuite_Sandbox TEST_SUITE sandbox - PATH ${CMAKE_CURRENT_LIST_DIR}/test_Atom_SandboxSuite.py + PATH ${CMAKE_CURRENT_LIST_DIR}/TestSuite_Sandbox.py TEST_SERIAL TIMEOUT 400 RUNTIME_DEPENDENCIES AssetProcessor AutomatedTesting.Assets Editor + COMPONENT + Atom ) ly_add_pytest( - NAME AutomatedTesting::AtomRenderer_HydraTests_GPUTests + NAME AutomatedTesting::Atom_TestSuite_Main_GPU TEST_SUITE main TEST_REQUIRES gpu TEST_SERIAL TIMEOUT 1200 - PATH ${CMAKE_CURRENT_LIST_DIR}/test_Atom_GPUTests.py - RUNTIME_DEPENDENCIES - AssetProcessor - AutomatedTesting.Assets - Editor - ) - ly_add_pytest( - NAME AutomatedTesting::AtomRenderer_HydraTests_ShaderBuildPipeline - TEST_SUITE main - PATH ${CMAKE_CURRENT_LIST_DIR}/test_Atom_ShaderBuildPipelineSuite.py - TEST_SERIAL - TIMEOUT 600 + PATH ${CMAKE_CURRENT_LIST_DIR}/TestSuite_Main_GPU.py RUNTIME_DEPENDENCIES AssetProcessor AutomatedTesting.Assets Editor + COMPONENT + Atom ) endif() diff --git a/AutomatedTesting/Gem/PythonTests/atom_renderer/test_Atom_MainSuite.py b/AutomatedTesting/Gem/PythonTests/Atom/TestSuite_Main.py similarity index 94% rename from AutomatedTesting/Gem/PythonTests/atom_renderer/test_Atom_MainSuite.py rename to AutomatedTesting/Gem/PythonTests/Atom/TestSuite_Main.py index 16e281e494..4c5716d365 100644 --- a/AutomatedTesting/Gem/PythonTests/atom_renderer/test_Atom_MainSuite.py +++ b/AutomatedTesting/Gem/PythonTests/Atom/TestSuite_Main.py @@ -13,10 +13,10 @@ import pytest import ly_test_tools.environment.file_system as file_system import editor_python_test_tools.hydra_test_utils as hydra -from atom_renderer.atom_utils.atom_constants import LIGHT_TYPES +from Atom.atom_utils.atom_constants import LIGHT_TYPES logger = logging.getLogger(__name__) -TEST_DIRECTORY = os.path.join(os.path.dirname(__file__), "atom_hydra_scripts") +TEST_DIRECTORY = os.path.join(os.path.dirname(__file__), "tests") @pytest.mark.parametrize("project", ["AutomatedTesting"]) @@ -38,24 +38,24 @@ class TestAtomEditorComponentsMain(object): 7. Exposure Control 8. Directional Light 9. DepthOfField - 10. Decal (Atom) + 10. Decal """ cfg_args = [level] expected_lines = [ - # Decal (Atom) Component - "Decal (Atom) Entity successfully created", - "Decal (Atom)_test: Component added to the entity: True", - "Decal (Atom)_test: Component removed after UNDO: True", - "Decal (Atom)_test: Component added after REDO: True", - "Decal (Atom)_test: Entered game mode: True", - "Decal (Atom)_test: Exit game mode: True", - "Decal (Atom) Controller|Configuration|Material: SUCCESS", - "Decal (Atom)_test: Entity is hidden: True", - "Decal (Atom)_test: Entity is shown: True", - "Decal (Atom)_test: Entity deleted: True", - "Decal (Atom)_test: UNDO entity deletion works: True", - "Decal (Atom)_test: REDO entity deletion works: True", + # Decal Component + "Decal Entity successfully created", + "Decal_test: Component added to the entity: True", + "Decal_test: Component removed after UNDO: True", + "Decal_test: Component added after REDO: True", + "Decal_test: Entered game mode: True", + "Decal_test: Exit game mode: True", + "Decal Controller|Configuration|Material: SUCCESS", + "Decal_test: Entity is hidden: True", + "Decal_test: Entity is shown: True", + "Decal_test: Entity deleted: True", + "Decal_test: UNDO entity deletion works: True", + "Decal_test: REDO entity deletion works: True", # DepthOfField Component "DepthOfField Entity successfully created", "DepthOfField_test: Component added to the entity: True", diff --git a/AutomatedTesting/Gem/PythonTests/atom_renderer/test_Atom_GPUTests.py b/AutomatedTesting/Gem/PythonTests/Atom/TestSuite_Main_GPU.py similarity index 98% rename from AutomatedTesting/Gem/PythonTests/atom_renderer/test_Atom_GPUTests.py rename to AutomatedTesting/Gem/PythonTests/Atom/TestSuite_Main_GPU.py index e62ab5e5dc..249b9c7096 100644 --- a/AutomatedTesting/Gem/PythonTests/atom_renderer/test_Atom_GPUTests.py +++ b/AutomatedTesting/Gem/PythonTests/Atom/TestSuite_Main_GPU.py @@ -3,8 +3,6 @@ Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT - -Tests that require a GPU in order to run. """ import datetime @@ -22,7 +20,7 @@ import editor_python_test_tools.hydra_test_utils as hydra logger = logging.getLogger(__name__) DEFAULT_SUBFOLDER_PATH = 'user/PythonTests/Automated/Screenshots' -TEST_DIRECTORY = os.path.join(os.path.dirname(__file__), "atom_hydra_scripts") +TEST_DIRECTORY = os.path.join(os.path.dirname(__file__), "tests") def golden_images_directory(): diff --git a/AutomatedTesting/Gem/PythonTests/Atom/TestSuite_Main_Optimized.py b/AutomatedTesting/Gem/PythonTests/Atom/TestSuite_Main_Optimized.py new file mode 100644 index 0000000000..47b2204d56 --- /dev/null +++ b/AutomatedTesting/Gem/PythonTests/Atom/TestSuite_Main_Optimized.py @@ -0,0 +1,46 @@ +""" +Copyright (c) Contributors to the Open 3D Engine Project. +For complete copyright and license terms please see the LICENSE at the root of this distribution. + +SPDX-License-Identifier: Apache-2.0 OR MIT +""" +import pytest + +from ly_test_tools.o3de.editor_test import EditorSharedTest, EditorTestSuite + + +@pytest.mark.xfail(reason="Optimized tests are experimental, we will enable xfail and monitor them temporarily.") +@pytest.mark.parametrize("project", ["AutomatedTesting"]) +@pytest.mark.parametrize("launcher_platform", ['windows_editor']) +class TestAutomation(EditorTestSuite): + + class AtomEditorComponents_DecalAdded(EditorSharedTest): + from Atom.tests import hydra_AtomEditorComponents_DecalAdded as test_module + + class AtomEditorComponents_DepthOfFieldAdded(EditorSharedTest): + from Atom.tests import hydra_AtomEditorComponents_DepthOfFieldAdded as test_module + + class AtomEditorComponents_DirectionalLightAdded(EditorSharedTest): + from Atom.tests import hydra_AtomEditorComponents_DirectionalLightAdded as test_module + + class AtomEditorComponents_ExposureControlAdded(EditorSharedTest): + from Atom.tests import hydra_AtomEditorComponents_ExposureControlAdded as test_module + + class AtomEditorComponents_GlobalSkylightIBLAdded(EditorSharedTest): + from Atom.tests import hydra_AtomEditorComponents_GlobalSkylightIBLAdded as test_module + + class AtomEditorComponents_PhysicalSkyAdded(EditorSharedTest): + from Atom.tests import hydra_AtomEditorComponents_PhysicalSkyAdded as test_module + + class AtomEditorComponents_PostFXRadiusWeightModifierAdded(EditorSharedTest): + from Atom.tests import ( + hydra_AtomEditorComponents_PostFXRadiusWeightModifierAdded as test_module) + + class AtomEditorComponents_LightAdded(EditorSharedTest): + from Atom.tests import hydra_AtomEditorComponents_LightAdded as test_module + + class AtomEditorComponents_DisplayMapperAdded(EditorSharedTest): + from Atom.tests import hydra_AtomEditorComponents_DisplayMapperAdded as test_module + + class ShaderAssetBuilder_RecompilesShaderAsChainOfDependenciesChanges(EditorSharedTest): + from Atom.tests import hydra_ShaderAssetBuilder_RecompilesShaderAsChainOfDependenciesChanges as test_module diff --git a/AutomatedTesting/Gem/PythonTests/atom_renderer/test_Atom_SandboxSuite.py b/AutomatedTesting/Gem/PythonTests/Atom/TestSuite_Sandbox.py similarity index 100% rename from AutomatedTesting/Gem/PythonTests/atom_renderer/test_Atom_SandboxSuite.py rename to AutomatedTesting/Gem/PythonTests/Atom/TestSuite_Sandbox.py diff --git a/AutomatedTesting/Gem/PythonTests/atom_renderer/__init__.py b/AutomatedTesting/Gem/PythonTests/Atom/__init__.py similarity index 100% rename from AutomatedTesting/Gem/PythonTests/atom_renderer/__init__.py rename to AutomatedTesting/Gem/PythonTests/Atom/__init__.py diff --git a/AutomatedTesting/Gem/PythonTests/atom_renderer/atom_utils/__init__.py b/AutomatedTesting/Gem/PythonTests/Atom/atom_utils/__init__.py similarity index 100% rename from AutomatedTesting/Gem/PythonTests/atom_renderer/atom_utils/__init__.py rename to AutomatedTesting/Gem/PythonTests/Atom/atom_utils/__init__.py diff --git a/AutomatedTesting/Gem/PythonTests/atom_renderer/atom_utils/atom_component_helper.py b/AutomatedTesting/Gem/PythonTests/Atom/atom_utils/atom_component_helper.py similarity index 100% rename from AutomatedTesting/Gem/PythonTests/atom_renderer/atom_utils/atom_component_helper.py rename to AutomatedTesting/Gem/PythonTests/Atom/atom_utils/atom_component_helper.py diff --git a/AutomatedTesting/Gem/PythonTests/atom_renderer/atom_utils/atom_constants.py b/AutomatedTesting/Gem/PythonTests/Atom/atom_utils/atom_constants.py similarity index 100% rename from AutomatedTesting/Gem/PythonTests/atom_renderer/atom_utils/atom_constants.py rename to AutomatedTesting/Gem/PythonTests/Atom/atom_utils/atom_constants.py diff --git a/AutomatedTesting/Gem/PythonTests/atom_renderer/atom_utils/benchmark_utils.py b/AutomatedTesting/Gem/PythonTests/Atom/atom_utils/benchmark_utils.py similarity index 100% rename from AutomatedTesting/Gem/PythonTests/atom_renderer/atom_utils/benchmark_utils.py rename to AutomatedTesting/Gem/PythonTests/Atom/atom_utils/benchmark_utils.py diff --git a/AutomatedTesting/Gem/PythonTests/atom_renderer/atom_utils/material_editor_utils.py b/AutomatedTesting/Gem/PythonTests/Atom/atom_utils/material_editor_utils.py similarity index 100% rename from AutomatedTesting/Gem/PythonTests/atom_renderer/atom_utils/material_editor_utils.py rename to AutomatedTesting/Gem/PythonTests/Atom/atom_utils/material_editor_utils.py diff --git a/AutomatedTesting/Gem/PythonTests/atom_renderer/atom_utils/screenshot_utils.py b/AutomatedTesting/Gem/PythonTests/Atom/atom_utils/screenshot_utils.py similarity index 100% rename from AutomatedTesting/Gem/PythonTests/atom_renderer/atom_utils/screenshot_utils.py rename to AutomatedTesting/Gem/PythonTests/Atom/atom_utils/screenshot_utils.py diff --git a/AutomatedTesting/Gem/PythonTests/atom_renderer/golden_images/AreaLight_1.ppm b/AutomatedTesting/Gem/PythonTests/Atom/golden_images/AreaLight_1.ppm similarity index 100% rename from AutomatedTesting/Gem/PythonTests/atom_renderer/golden_images/AreaLight_1.ppm rename to AutomatedTesting/Gem/PythonTests/Atom/golden_images/AreaLight_1.ppm diff --git a/AutomatedTesting/Gem/PythonTests/atom_renderer/golden_images/AreaLight_2.ppm b/AutomatedTesting/Gem/PythonTests/Atom/golden_images/AreaLight_2.ppm similarity index 100% rename from AutomatedTesting/Gem/PythonTests/atom_renderer/golden_images/AreaLight_2.ppm rename to AutomatedTesting/Gem/PythonTests/Atom/golden_images/AreaLight_2.ppm diff --git a/AutomatedTesting/Gem/PythonTests/atom_renderer/golden_images/AreaLight_3.ppm b/AutomatedTesting/Gem/PythonTests/Atom/golden_images/AreaLight_3.ppm similarity index 100% rename from AutomatedTesting/Gem/PythonTests/atom_renderer/golden_images/AreaLight_3.ppm rename to AutomatedTesting/Gem/PythonTests/Atom/golden_images/AreaLight_3.ppm diff --git a/AutomatedTesting/Gem/PythonTests/atom_renderer/golden_images/AreaLight_4.ppm b/AutomatedTesting/Gem/PythonTests/Atom/golden_images/AreaLight_4.ppm similarity index 100% rename from AutomatedTesting/Gem/PythonTests/atom_renderer/golden_images/AreaLight_4.ppm rename to AutomatedTesting/Gem/PythonTests/Atom/golden_images/AreaLight_4.ppm diff --git a/AutomatedTesting/Gem/PythonTests/atom_renderer/golden_images/AreaLight_5.ppm b/AutomatedTesting/Gem/PythonTests/Atom/golden_images/AreaLight_5.ppm similarity index 100% rename from AutomatedTesting/Gem/PythonTests/atom_renderer/golden_images/AreaLight_5.ppm rename to AutomatedTesting/Gem/PythonTests/Atom/golden_images/AreaLight_5.ppm diff --git a/AutomatedTesting/Gem/PythonTests/atom_renderer/golden_images/AtomBasicLevelSetup.ppm b/AutomatedTesting/Gem/PythonTests/Atom/golden_images/AtomBasicLevelSetup.ppm similarity index 100% rename from AutomatedTesting/Gem/PythonTests/atom_renderer/golden_images/AtomBasicLevelSetup.ppm rename to AutomatedTesting/Gem/PythonTests/Atom/golden_images/AtomBasicLevelSetup.ppm diff --git a/AutomatedTesting/Gem/PythonTests/atom_renderer/golden_images/SpotLight_1.ppm b/AutomatedTesting/Gem/PythonTests/Atom/golden_images/SpotLight_1.ppm similarity index 100% rename from AutomatedTesting/Gem/PythonTests/atom_renderer/golden_images/SpotLight_1.ppm rename to AutomatedTesting/Gem/PythonTests/Atom/golden_images/SpotLight_1.ppm diff --git a/AutomatedTesting/Gem/PythonTests/atom_renderer/golden_images/SpotLight_2.ppm b/AutomatedTesting/Gem/PythonTests/Atom/golden_images/SpotLight_2.ppm similarity index 100% rename from AutomatedTesting/Gem/PythonTests/atom_renderer/golden_images/SpotLight_2.ppm rename to AutomatedTesting/Gem/PythonTests/Atom/golden_images/SpotLight_2.ppm diff --git a/AutomatedTesting/Gem/PythonTests/atom_renderer/golden_images/SpotLight_3.ppm b/AutomatedTesting/Gem/PythonTests/Atom/golden_images/SpotLight_3.ppm similarity index 100% rename from AutomatedTesting/Gem/PythonTests/atom_renderer/golden_images/SpotLight_3.ppm rename to AutomatedTesting/Gem/PythonTests/Atom/golden_images/SpotLight_3.ppm diff --git a/AutomatedTesting/Gem/PythonTests/atom_renderer/golden_images/SpotLight_4.ppm b/AutomatedTesting/Gem/PythonTests/Atom/golden_images/SpotLight_4.ppm similarity index 100% rename from AutomatedTesting/Gem/PythonTests/atom_renderer/golden_images/SpotLight_4.ppm rename to AutomatedTesting/Gem/PythonTests/Atom/golden_images/SpotLight_4.ppm diff --git a/AutomatedTesting/Gem/PythonTests/atom_renderer/golden_images/SpotLight_5.ppm b/AutomatedTesting/Gem/PythonTests/Atom/golden_images/SpotLight_5.ppm similarity index 100% rename from AutomatedTesting/Gem/PythonTests/atom_renderer/golden_images/SpotLight_5.ppm rename to AutomatedTesting/Gem/PythonTests/Atom/golden_images/SpotLight_5.ppm diff --git a/AutomatedTesting/Gem/PythonTests/atom_renderer/golden_images/SpotLight_6.ppm b/AutomatedTesting/Gem/PythonTests/Atom/golden_images/SpotLight_6.ppm similarity index 100% rename from AutomatedTesting/Gem/PythonTests/atom_renderer/golden_images/SpotLight_6.ppm rename to AutomatedTesting/Gem/PythonTests/Atom/golden_images/SpotLight_6.ppm diff --git a/AutomatedTesting/Gem/PythonTests/atom_renderer/atom_hydra_scripts/TestAssets/ShaderAssetBuilder/DependencyValidation.azsl.txt b/AutomatedTesting/Gem/PythonTests/Atom/tests/TestAssets/ShaderAssetBuilder/DependencyValidation.azsl.txt similarity index 100% rename from AutomatedTesting/Gem/PythonTests/atom_renderer/atom_hydra_scripts/TestAssets/ShaderAssetBuilder/DependencyValidation.azsl.txt rename to AutomatedTesting/Gem/PythonTests/Atom/tests/TestAssets/ShaderAssetBuilder/DependencyValidation.azsl.txt diff --git a/AutomatedTesting/Gem/PythonTests/atom_renderer/atom_hydra_scripts/TestAssets/ShaderAssetBuilder/DependencyValidation.shader.txt b/AutomatedTesting/Gem/PythonTests/Atom/tests/TestAssets/ShaderAssetBuilder/DependencyValidation.shader.txt similarity index 93% rename from AutomatedTesting/Gem/PythonTests/atom_renderer/atom_hydra_scripts/TestAssets/ShaderAssetBuilder/DependencyValidation.shader.txt rename to AutomatedTesting/Gem/PythonTests/Atom/tests/TestAssets/ShaderAssetBuilder/DependencyValidation.shader.txt index b0eac1783e..4439ec0352 100644 --- a/AutomatedTesting/Gem/PythonTests/atom_renderer/atom_hydra_scripts/TestAssets/ShaderAssetBuilder/DependencyValidation.shader.txt +++ b/AutomatedTesting/Gem/PythonTests/Atom/tests/TestAssets/ShaderAssetBuilder/DependencyValidation.shader.txt @@ -2,7 +2,7 @@ { "Source" : "DependencyValidation.azsl", - "DepthStencilState" : { + "DepthStencilState" : { "Depth" : { "Enable" : false, "CompareFunc" : "GreaterEqual" } }, @@ -22,5 +22,5 @@ } ] } - + } diff --git a/AutomatedTesting/Gem/PythonTests/atom_renderer/atom_hydra_scripts/TestAssets/ShaderAssetBuilder/Test1Color.azsli.txt b/AutomatedTesting/Gem/PythonTests/Atom/tests/TestAssets/ShaderAssetBuilder/Test1Color.azsli.txt similarity index 100% rename from AutomatedTesting/Gem/PythonTests/atom_renderer/atom_hydra_scripts/TestAssets/ShaderAssetBuilder/Test1Color.azsli.txt rename to AutomatedTesting/Gem/PythonTests/Atom/tests/TestAssets/ShaderAssetBuilder/Test1Color.azsli.txt diff --git a/AutomatedTesting/Gem/PythonTests/atom_renderer/atom_hydra_scripts/TestAssets/ShaderAssetBuilder/Test2Color.azsli.txt b/AutomatedTesting/Gem/PythonTests/Atom/tests/TestAssets/ShaderAssetBuilder/Test2Color.azsli.txt similarity index 93% rename from AutomatedTesting/Gem/PythonTests/atom_renderer/atom_hydra_scripts/TestAssets/ShaderAssetBuilder/Test2Color.azsli.txt rename to AutomatedTesting/Gem/PythonTests/Atom/tests/TestAssets/ShaderAssetBuilder/Test2Color.azsli.txt index 2ef946b947..565493a0ab 100644 --- a/AutomatedTesting/Gem/PythonTests/atom_renderer/atom_hydra_scripts/TestAssets/ShaderAssetBuilder/Test2Color.azsli.txt +++ b/AutomatedTesting/Gem/PythonTests/Atom/tests/TestAssets/ShaderAssetBuilder/Test2Color.azsli.txt @@ -12,5 +12,5 @@ float4 GetTest2Color(float4 color) { - return color * 0.5; + return color * 0.5; } diff --git a/AutomatedTesting/Gem/PythonTests/atom_renderer/atom_hydra_scripts/TestAssets/ShaderAssetBuilder/Test3Color.azsli.txt b/AutomatedTesting/Gem/PythonTests/Atom/tests/TestAssets/ShaderAssetBuilder/Test3Color.azsli.txt similarity index 92% rename from AutomatedTesting/Gem/PythonTests/atom_renderer/atom_hydra_scripts/TestAssets/ShaderAssetBuilder/Test3Color.azsli.txt rename to AutomatedTesting/Gem/PythonTests/Atom/tests/TestAssets/ShaderAssetBuilder/Test3Color.azsli.txt index 73b0cca434..7c1ff2be42 100644 --- a/AutomatedTesting/Gem/PythonTests/atom_renderer/atom_hydra_scripts/TestAssets/ShaderAssetBuilder/Test3Color.azsli.txt +++ b/AutomatedTesting/Gem/PythonTests/Atom/tests/TestAssets/ShaderAssetBuilder/Test3Color.azsli.txt @@ -12,5 +12,5 @@ float4 GetTest3Color(float4 color) { - return color * 0.13; + return color * 0.13; } diff --git a/AutomatedTesting/Gem/PythonTests/atom_renderer/atom_hydra_scripts/__init__.py b/AutomatedTesting/Gem/PythonTests/Atom/tests/__init__.py similarity index 100% rename from AutomatedTesting/Gem/PythonTests/atom_renderer/atom_hydra_scripts/__init__.py rename to AutomatedTesting/Gem/PythonTests/Atom/tests/__init__.py diff --git a/AutomatedTesting/Gem/PythonTests/atom_renderer/atom_hydra_scripts/hydra_AtomEditorComponents_AddedToEntity.py b/AutomatedTesting/Gem/PythonTests/Atom/tests/hydra_AtomEditorComponents_AddedToEntity.py similarity index 99% rename from AutomatedTesting/Gem/PythonTests/atom_renderer/atom_hydra_scripts/hydra_AtomEditorComponents_AddedToEntity.py rename to AutomatedTesting/Gem/PythonTests/Atom/tests/hydra_AtomEditorComponents_AddedToEntity.py index a2e950e1dc..602e7564b3 100644 --- a/AutomatedTesting/Gem/PythonTests/atom_renderer/atom_hydra_scripts/hydra_AtomEditorComponents_AddedToEntity.py +++ b/AutomatedTesting/Gem/PythonTests/Atom/tests/hydra_AtomEditorComponents_AddedToEntity.py @@ -184,7 +184,7 @@ def run(): material_asset = asset.AssetCatalogRequestBus( bus.Broadcast, "GetAssetIdByPath", material_asset_path, math.Uuid(), False) ComponentTests( - "Decal (Atom)", lambda entity_obj: verify_set_property( + "Decal", lambda entity_obj: verify_set_property( entity_obj, "Controller|Configuration|Material", material_asset)) # Directional Light Component diff --git a/AutomatedTesting/Gem/PythonTests/Atom/tests/hydra_AtomEditorComponents_DecalAdded.py b/AutomatedTesting/Gem/PythonTests/Atom/tests/hydra_AtomEditorComponents_DecalAdded.py new file mode 100644 index 0000000000..fa02b75fe2 --- /dev/null +++ b/AutomatedTesting/Gem/PythonTests/Atom/tests/hydra_AtomEditorComponents_DecalAdded.py @@ -0,0 +1,151 @@ +""" +Copyright (c) Contributors to the Open 3D Engine Project. +For complete copyright and license terms please see the LICENSE at the root of this distribution. + +SPDX-License-Identifier: Apache-2.0 OR MIT +""" + +# fmt: off +class Tests: + camera_creation = ("Camera Entity successfully created", "Camera Entity failed to be created") + camera_component_added = ("Camera component was added to entity", "Camera component failed to be added to entity") + camera_component_check = ("Entity has a Camera component", "Entity failed to find Camera component") + creation_undo = ("UNDO Entity creation success", "UNDO Entity creation failed") + creation_redo = ("REDO Entity creation success", "REDO Entity creation failed") + decal_creation = ("Decal Entity successfully created", "Decal Entity failed to be created") + decal_component = ("Entity has a Decal component", "Entity failed to find Decal component") + material_property_set = ("Material property set on Decal component", "Couldn't set Material property on Decal component") + enter_game_mode = ("Entered game mode", "Failed to enter game mode") + exit_game_mode = ("Exited game mode", "Couldn't exit game mode") + is_visible = ("Entity is visible", "Entity was not visible") + is_hidden = ("Entity is hidden", "Entity was not hidden") + entity_deleted = ("Entity deleted", "Entity was not deleted") + deletion_undo = ("UNDO deletion success", "UNDO deletion failed") + deletion_redo = ("REDO deletion success", "REDO deletion failed") + no_error_occurred = ("No errors detected", "Errors were detected") +# fmt: on + + +def AtomEditorComponents_Decal_AddedToEntity(): + """ + Summary: + Tests the Decal component can be added to an entity and has the expected functionality. + + Test setup: + - Wait for Editor idle loop. + - Open the "Base" level. + + Expected Behavior: + The component can be added, used in game mode, hidden/shown, deleted, and has accurate required components. + Creation and deletion undo/redo should also work. + + Test Steps: + 1) Create a Decal entity with no components. + 2) Add Decal component to Decal entity. + 3) UNDO the entity creation and component addition. + 4) REDO the entity creation and component addition. + 5) Enter/Exit game mode. + 6) Test IsHidden. + 7) Test IsVisible. + 8) Set Material property on Decal component. + 9) Delete Decal entity. + 10) UNDO deletion. + 11) REDO deletion. + 12) Look for errors. + + :return: None + """ + import os + + import azlmbr.asset as asset + import azlmbr.bus as bus + import azlmbr.legacy.general as general + import azlmbr.math as math + + from editor_python_test_tools.editor_entity_utils import EditorEntity + from editor_python_test_tools.utils import Report, Tracer, TestHelper as helper + + with Tracer() as error_tracer: + # Test setup begins. + # Setup: Wait for Editor idle loop before executing Python hydra scripts then open "Base" level. + helper.init_idle() + helper.open_level("", "Base") + + # Test steps begin. + # 1. Create a Decal entity with no components. + decal_name = "Decal" + decal_entity = EditorEntity.create_editor_entity_at(math.Vector3(512.0, 512.0, 34.0), decal_name) + Report.critical_result(Tests.decal_creation, decal_entity.exists()) + + # 2. Add Decal component to Decal entity. + decal_component = decal_entity.add_component(decal_name) + Report.critical_result(Tests.decal_component, decal_entity.has_component(decal_name)) + + # 3. UNDO the entity creation and component addition. + # -> UNDO component addition. + general.undo() + # -> UNDO naming entity. + general.undo() + # -> UNDO selecting entity. + general.undo() + # -> UNDO entity creation. + general.undo() + general.idle_wait_frames(1) + Report.result(Tests.creation_undo, not decal_entity.exists()) + + # 4. REDO the entity creation and component addition. + # -> REDO entity creation. + general.redo() + # -> REDO selecting entity. + general.redo() + # -> REDO naming entity. + general.redo() + # -> REDO component addition. + general.redo() + general.idle_wait_frames(1) + Report.result(Tests.creation_redo, decal_entity.exists()) + + # 5. Enter/Exit game mode. + helper.enter_game_mode(Tests.enter_game_mode) + general.idle_wait_frames(1) + helper.exit_game_mode(Tests.exit_game_mode) + + # 6. Test IsHidden. + decal_entity.set_visibility_state(False) + Report.result(Tests.is_hidden, decal_entity.is_hidden() is True) + + # 7. Test IsVisible. + decal_entity.set_visibility_state(True) + general.idle_wait_frames(1) + Report.result(Tests.is_visible, decal_entity.is_visible() is True) + + # 8. Set Material property on Decal component. + decal_material_property_path = "Controller|Configuration|Material" + decal_material_asset_path = os.path.join("AutomatedTesting", "Materials", "basic_grey.material") + decal_material_asset = asset.AssetCatalogRequestBus( + bus.Broadcast, "GetAssetIdByPath", decal_material_asset_path, math.Uuid(), False) + decal_component.set_component_property_value(decal_material_property_path, decal_material_asset) + get_material_property = decal_component.get_component_property_value(decal_material_property_path) + Report.result(Tests.material_property_set, get_material_property == decal_material_asset) + + # 9. Delete Decal entity. + decal_entity.delete() + Report.result(Tests.entity_deleted, not decal_entity.exists()) + + # 10. UNDO deletion. + general.undo() + general.idle_wait_frames(1) + Report.result(Tests.deletion_undo, decal_entity.exists()) + + # 11. REDO deletion. + general.redo() + Report.result(Tests.deletion_redo, not decal_entity.exists()) + + # 12. Look for errors. + helper.wait_for_condition(lambda: error_tracer.has_errors, 1.0) + Report.result(Tests.no_error_occurred, not error_tracer.has_errors) + + +if __name__ == "__main__": + from editor_python_test_tools.utils import Report + Report.start_test(AtomEditorComponents_Decal_AddedToEntity) diff --git a/AutomatedTesting/Gem/PythonTests/Atom/tests/hydra_AtomEditorComponents_DepthOfFieldAdded.py b/AutomatedTesting/Gem/PythonTests/Atom/tests/hydra_AtomEditorComponents_DepthOfFieldAdded.py new file mode 100644 index 0000000000..80284902ea --- /dev/null +++ b/AutomatedTesting/Gem/PythonTests/Atom/tests/hydra_AtomEditorComponents_DepthOfFieldAdded.py @@ -0,0 +1,173 @@ +""" +Copyright (c) Contributors to the Open 3D Engine Project. +For complete copyright and license terms please see the LICENSE at the root of this distribution. + +SPDX-License-Identifier: Apache-2.0 OR MIT +""" + +# fmt: off +class Tests: + camera_creation = ("Camera Entity successfully created", "Camera Entity failed to be created") + camera_component_added = ("Camera component was added to Camera entity", "Camera component failed to be added to entity") + camera_component_check = ("Entity has a Camera component", "Entity failed to find Camera component") + camera_property_set = ("DepthOfField Entity set Camera Entity", "DepthOfField Entity could not set Camera Entity") + creation_undo = ("UNDO Entity creation success", "UNDO Entity creation failed") + creation_redo = ("REDO Entity creation success", "REDO Entity creation failed") + depth_of_field_creation = ("DepthOfField Entity successfully created", "DepthOfField Entity failed to be created") + depth_of_field_component = ("Entity has a DepthOfField component", "Entity failed to find DepthOfField component") + depth_of_field_disabled = ("DepthOfField component disabled", "DepthOfField component was not disabled.") + post_fx_component = ("Entity has a Post FX Layer component", "Entity did not have a Post FX Layer component") + depth_of_field_enabled = ("DepthOfField component enabled", "DepthOfField component was not enabled.") + enter_game_mode = ("Entered game mode", "Failed to enter game mode") + exit_game_mode = ("Exited game mode", "Couldn't exit game mode") + is_visible = ("Entity is visible", "Entity was not visible") + is_hidden = ("Entity is hidden", "Entity was not hidden") + entity_deleted = ("Entity deleted", "Entity was not deleted") + deletion_undo = ("UNDO deletion success", "UNDO deletion failed") + deletion_redo = ("REDO deletion success", "REDO deletion failed") + no_error_occurred = ("No errors detected", "Errors were detected") +# fmt: on + + +def AtomEditorComponents_DepthOfField_AddedToEntity(): + """ + Summary: + Tests the DepthOfField component can be added to an entity and has the expected functionality. + + Test setup: + - Wait for Editor idle loop. + - Open the "Base" level. + + Expected Behavior: + The component can be added, used in game mode, hidden/shown, deleted, and has accurate required components. + Creation and deletion undo/redo should also work. + + Test Steps: + 1) Create a DepthOfField entity with no components. + 2) Add a DepthOfField component to DepthOfField entity. + 3) UNDO the entity creation and component addition. + 4) REDO the entity creation and component addition. + 5) Verify DepthOfField component not enabled. + 6) Add Post FX Layer component since it is required by the DepthOfField component. + 7) Verify DepthOfField component is enabled. + 8) Enter/Exit game mode. + 9) Test IsHidden. + 10) Test IsVisible. + 11) Add Camera entity. + 12) Add Camera component to Camera entity. + 13) Set the DepthOfField components's Camera Entity to the newly created Camera entity. + 14) Delete DepthOfField entity. + 15) UNDO deletion. + 16) REDO deletion. + 17) Look for errors. + + :return: None + """ + + import azlmbr.legacy.general as general + import azlmbr.math as math + + from editor_python_test_tools.editor_entity_utils import EditorEntity + from editor_python_test_tools.utils import Report, Tracer, TestHelper as helper + + with Tracer() as error_tracer: + # Test setup begins. + # Setup: Wait for Editor idle loop before executing Python hydra scripts then open "Base" level. + helper.init_idle() + helper.open_level("", "Base") + + # Test steps begin. + # 1. Create a DepthOfField entity with no components. + depth_of_field_name = "DepthOfField" + depth_of_field_entity = EditorEntity.create_editor_entity_at( + math.Vector3(512.0, 512.0, 34.0), depth_of_field_name) + Report.critical_result(Tests.depth_of_field_creation, depth_of_field_entity.exists()) + + # 2. Add a DepthOfField component to DepthOfField entity. + depth_of_field_component = depth_of_field_entity.add_component(depth_of_field_name) + Report.critical_result(Tests.depth_of_field_component, depth_of_field_entity.has_component(depth_of_field_name)) + + # 3. UNDO the entity creation and component addition. + # -> UNDO component addition. + general.undo() + # -> UNDO naming entity. + general.undo() + # -> UNDO selecting entity. + general.undo() + # -> UNDO entity creation. + general.undo() + general.idle_wait_frames(1) + Report.result(Tests.creation_undo, not depth_of_field_entity.exists()) + + # 4. REDO the entity creation and component addition. + # -> REDO entity creation. + general.redo() + # -> REDO selecting entity. + general.redo() + # -> REDO naming entity. + general.redo() + # -> REDO component addition. + general.redo() + general.idle_wait_frames(1) + Report.result(Tests.creation_redo, depth_of_field_entity.exists()) + + # 5. Verify DepthOfField component not enabled. + Report.result(Tests.depth_of_field_disabled, not depth_of_field_component.is_enabled()) + + # 6. Add Post FX Layer component since it is required by the DepthOfField component. + post_fx_layer = "PostFX Layer" + depth_of_field_entity.add_component(post_fx_layer) + Report.result(Tests.post_fx_component, depth_of_field_entity.has_component(post_fx_layer)) + + # 7. Verify DepthOfField component is enabled. + Report.result(Tests.depth_of_field_enabled, depth_of_field_component.is_enabled()) + + # 8. Enter/Exit game mode. + helper.enter_game_mode(Tests.enter_game_mode) + general.idle_wait_frames(1) + helper.exit_game_mode(Tests.exit_game_mode) + + # 9. Test IsHidden. + depth_of_field_entity.set_visibility_state(False) + Report.result(Tests.is_hidden, depth_of_field_entity.is_hidden() is True) + + # 10. Test IsVisible. + depth_of_field_entity.set_visibility_state(True) + general.idle_wait_frames(1) + Report.result(Tests.is_visible, depth_of_field_entity.is_visible() is True) + + # 11. Add Camera entity. + camera_name = "Camera" + camera_entity = EditorEntity.create_editor_entity_at(math.Vector3(512.0, 512.0, 34.0), camera_name) + Report.result(Tests.camera_creation, camera_entity.exists()) + + # 12. Add Camera component to Camera entity. + camera_entity.add_component(camera_name) + Report.result(Tests.camera_component_added, camera_entity.has_component(camera_name)) + + # 13. Set the DepthOfField components's Camera Entity to the newly created Camera entity. + depth_of_field_camera_property_path = "Controller|Configuration|Camera Entity" + depth_of_field_component.set_component_property_value(depth_of_field_camera_property_path, camera_entity.id) + camera_entity_set = depth_of_field_component.get_component_property_value(depth_of_field_camera_property_path) + Report.result(Tests.camera_property_set, camera_entity.id == camera_entity_set) + + # 14. Delete DepthOfField entity. + depth_of_field_entity.delete() + Report.result(Tests.entity_deleted, not depth_of_field_entity.exists()) + + # 15. UNDO deletion. + general.undo() + Report.result(Tests.deletion_undo, depth_of_field_entity.exists()) + + # 16. REDO deletion. + general.redo() + Report.result(Tests.deletion_redo, not depth_of_field_entity.exists()) + + # 17. Look for errors. + helper.wait_for_condition(lambda: error_tracer.has_errors, 1.0) + Report.result(Tests.no_error_occurred, not error_tracer.has_errors) + + +if __name__ == "__main__": + from editor_python_test_tools.utils import Report + Report.start_test(AtomEditorComponents_DepthOfField_AddedToEntity) diff --git a/AutomatedTesting/Gem/PythonTests/Atom/tests/hydra_AtomEditorComponents_DirectionalLightAdded.py b/AutomatedTesting/Gem/PythonTests/Atom/tests/hydra_AtomEditorComponents_DirectionalLightAdded.py new file mode 100644 index 0000000000..048e132df4 --- /dev/null +++ b/AutomatedTesting/Gem/PythonTests/Atom/tests/hydra_AtomEditorComponents_DirectionalLightAdded.py @@ -0,0 +1,157 @@ +""" +Copyright (c) Contributors to the Open 3D Engine Project. +For complete copyright and license terms please see the LICENSE at the root of this distribution. + +SPDX-License-Identifier: Apache-2.0 OR MIT +""" + +# fmt: off +class Tests: + camera_creation = ("Camera Entity successfully created", "Camera Entity failed to be created") + camera_component_added = ("Camera component was added to entity", "Camera component failed to be added to entity") + camera_component_check = ("Entity has a Camera component", "Entity failed to find Camera component") + creation_undo = ("UNDO Entity creation success", "UNDO Entity creation failed") + creation_redo = ("REDO Entity creation success", "REDO Entity creation failed") + directional_light_creation = ("Directional Light Entity successfully created", "Directional Light Entity failed to be created") + directional_light_component = ("Entity has a Directional Light component", "Entity failed to find Directional Light component") + shadow_camera_check = ("Directional Light component Shadow camera set", "Directional Light component Shadow camera was not set") + enter_game_mode = ("Entered game mode", "Failed to enter game mode") + exit_game_mode = ("Exited game mode", "Couldn't exit game mode") + is_visible = ("Entity is visible", "Entity was not visible") + is_hidden = ("Entity is hidden", "Entity was not hidden") + entity_deleted = ("Entity deleted", "Entity was not deleted") + deletion_undo = ("UNDO deletion success", "UNDO deletion failed") + deletion_redo = ("REDO deletion success", "REDO deletion failed") + no_error_occurred = ("No errors detected", "Errors were detected") +# fmt: on + + +def AtomEditorComponents_DirectionalLight_AddedToEntity(): + """ + Summary: + Tests the Directional Light component can be added to an entity and has the expected functionality. + + Test setup: + - Wait for Editor idle loop. + - Open the "Base" level. + + Expected Behavior: + The component can be added, used in game mode, hidden/shown, deleted, and has accurate required components. + Creation and deletion undo/redo should also work. + + Test Steps: + 1) Create a Directional Light entity with no components. + 2) Add Directional Light component to Directional Light entity. + 3) UNDO the entity creation and component addition. + 4) REDO the entity creation and component addition. + 5) Enter/Exit game mode. + 6) Test IsHidden. + 7) Test IsVisible. + 8) Add Camera entity. + 9) Add Camera component to Camera entity + 10) Set the Directional Light component property Shadow|Camera to the Camera entity. + 11) Delete Directional Light entity. + 12) UNDO deletion. + 13) REDO deletion. + 14) Look for errors. + + :return: None + """ + + import azlmbr.legacy.general as general + import azlmbr.math as math + + from editor_python_test_tools.editor_entity_utils import EditorEntity + from editor_python_test_tools.utils import Report, Tracer, TestHelper as helper + + with Tracer() as error_tracer: + # Test setup begins. + # Setup: Wait for Editor idle loop before executing Python hydra scripts then open "Base" level. + helper.init_idle() + helper.open_level("", "Base") + + # Test steps begin. + # 1. Create a Directional Light entity with no components. + directional_light_name = "Directional Light" + directional_light_entity = EditorEntity.create_editor_entity_at( + math.Vector3(512.0, 512.0, 34.0), directional_light_name) + Report.critical_result(Tests.directional_light_creation, directional_light_entity.exists()) + + # 2. Add Directional Light component to Directional Light entity. + directional_light_component = directional_light_entity.add_component(directional_light_name) + Report.critical_result( + Tests.directional_light_component, directional_light_entity.has_component(directional_light_name)) + + # 3. UNDO the entity creation and component addition. + # -> UNDO component addition. + general.undo() + # -> UNDO naming entity. + general.undo() + # -> UNDO selecting entity. + general.undo() + # -> UNDO entity creation. + general.undo() + general.idle_wait_frames(1) + Report.result(Tests.creation_undo, not directional_light_entity.exists()) + + # 4. REDO the entity creation and component addition. + # -> REDO entity creation. + general.redo() + # -> REDO selecting entity. + general.redo() + # -> REDO naming entity. + general.redo() + # -> REDO component addition. + general.redo() + general.idle_wait_frames(1) + Report.result(Tests.creation_redo, directional_light_entity.exists()) + + # 5. Enter/Exit game mode. + helper.enter_game_mode(Tests.enter_game_mode) + general.idle_wait_frames(1) + helper.exit_game_mode(Tests.exit_game_mode) + + # 6. Test IsHidden. + directional_light_entity.set_visibility_state(False) + Report.result(Tests.is_hidden, directional_light_entity.is_hidden() is True) + + # 7. Test IsVisible. + directional_light_entity.set_visibility_state(True) + general.idle_wait_frames(1) + Report.result(Tests.is_visible, directional_light_entity.is_visible() is True) + + # 8. Add Camera entity. + camera_name = "Camera" + camera_entity = EditorEntity.create_editor_entity_at(math.Vector3(512.0, 512.0, 34.0), camera_name) + Report.result(Tests.camera_creation, camera_entity.exists()) + + # 9. Add Camera component to Camera entity. + camera_entity.add_component(camera_name) + Report.result(Tests.camera_component_added, camera_entity.has_component(camera_name)) + + # 10. Set the Directional Light component property Shadow|Camera to the Camera entity. + shadow_camera_property_path = "Controller|Configuration|Shadow|Camera" + directional_light_component.set_component_property_value(shadow_camera_property_path, camera_entity.id) + shadow_camera_set = directional_light_component.get_component_property_value(shadow_camera_property_path) + Report.result(Tests.shadow_camera_check, camera_entity.id == shadow_camera_set) + + # 11. Delete DirectionalLight entity. + directional_light_entity.delete() + Report.result(Tests.entity_deleted, not directional_light_entity.exists()) + + # 12. UNDO deletion. + general.undo() + Report.result(Tests.deletion_undo, directional_light_entity.exists()) + + # 13. REDO deletion. + general.redo() + Report.result(Tests.deletion_redo, not directional_light_entity.exists()) + + # 14. Look for errors. + helper.wait_for_condition(lambda: error_tracer.has_errors, 1.0) + Report.result(Tests.no_error_occurred, not error_tracer.has_errors) + + +if __name__ == "__main__": + from editor_python_test_tools.utils import Report + Report.start_test(AtomEditorComponents_DirectionalLight_AddedToEntity) diff --git a/AutomatedTesting/Gem/PythonTests/Atom/tests/hydra_AtomEditorComponents_DisplayMapperAdded.py b/AutomatedTesting/Gem/PythonTests/Atom/tests/hydra_AtomEditorComponents_DisplayMapperAdded.py new file mode 100644 index 0000000000..39d7acf4f4 --- /dev/null +++ b/AutomatedTesting/Gem/PythonTests/Atom/tests/hydra_AtomEditorComponents_DisplayMapperAdded.py @@ -0,0 +1,137 @@ +""" +Copyright (c) Contributors to the Open 3D Engine Project. +For complete copyright and license terms please see the LICENSE at the root of this distribution. + +SPDX-License-Identifier: Apache-2.0 OR MIT +""" + +# fmt: off +class Tests: + camera_creation = ("Camera Entity successfully created", "Camera Entity failed to be created") + camera_component_added = ("Camera component was added to entity", "Camera component failed to be added to entity") + camera_component_check = ("Entity has a Camera component", "Entity failed to find Camera component") + creation_undo = ("UNDO Entity creation success", "UNDO Entity creation failed") + creation_redo = ("REDO Entity creation success", "REDO Entity creation failed") + display_mapper_creation = ("Display Mapper Entity successfully created", "Display Mapper Entity failed to be created") + display_mapper_component = ("Entity has a Display Mapper component", "Entity failed to find Display Mapper component") + enter_game_mode = ("Entered game mode", "Failed to enter game mode") + exit_game_mode = ("Exited game mode", "Couldn't exit game mode") + is_visible = ("Entity is visible", "Entity was not visible") + is_hidden = ("Entity is hidden", "Entity was not hidden") + entity_deleted = ("Entity deleted", "Entity was not deleted") + deletion_undo = ("UNDO deletion success", "UNDO deletion failed") + deletion_redo = ("REDO deletion success", "REDO deletion failed") + no_error_occurred = ("No errors detected", "Errors were detected") +# fmt: on + + +def AtomEditorComponents_DisplayMapper_AddedToEntity(): + """ + Summary: + Tests the Display Mapper component can be added to an entity and has the expected functionality. + + Test setup: + - Wait for Editor idle loop. + - Open the "Base" level. + + Expected Behavior: + The component can be added, used in game mode, hidden/shown, deleted, and has accurate required components. + Creation and deletion undo/redo should also work. + + Test Steps: + 1) Create a Display Mapper entity with no components. + 2) Add Display Mapper component to Display Mapper entity. + 3) UNDO the entity creation and component addition. + 4) REDO the entity creation and component addition. + 5) Enter/Exit game mode. + 6) Test IsHidden. + 7) Test IsVisible. + 8) Delete Display Mapper entity. + 9) UNDO deletion. + 10) REDO deletion. + 11) Look for errors. + + :return: None + """ + + import azlmbr.legacy.general as general + import azlmbr.math as math + + from editor_python_test_tools.editor_entity_utils import EditorEntity + from editor_python_test_tools.utils import Report, Tracer, TestHelper as helper + + with Tracer() as error_tracer: + # Test setup begins. + # Setup: Wait for Editor idle loop before executing Python hydra scripts then open "Base" level. + helper.init_idle() + helper.open_level("", "Base") + + # Test steps begin. + # 1. Create a Display Mapper entity with no components. + display_mapper = "Display Mapper" + display_mapper_entity = EditorEntity.create_editor_entity_at( + math.Vector3(512.0, 512.0, 34.0), f"{display_mapper}") + Report.critical_result(Tests.display_mapper_creation, display_mapper_entity.exists()) + + # 2. Add Display Mapper component to Display Mapper entity. + display_mapper_entity.add_component(display_mapper) + Report.critical_result(Tests.display_mapper_component, display_mapper_entity.has_component(display_mapper)) + + # 3. UNDO the entity creation and component addition. + # -> UNDO component addition. + general.undo() + # -> UNDO naming entity. + general.undo() + # -> UNDO selecting entity. + general.undo() + # -> UNDO entity creation. + general.undo() + general.idle_wait_frames(1) + Report.result(Tests.creation_undo, not display_mapper_entity.exists()) + + # 4. REDO the entity creation and component addition. + # -> REDO entity creation. + general.redo() + # -> REDO selecting entity. + general.redo() + # -> REDO naming entity. + general.redo() + # -> REDO component addition. + general.redo() + general.idle_wait_frames(1) + Report.result(Tests.creation_redo, display_mapper_entity.exists()) + + # 5. Enter/Exit game mode. + helper.enter_game_mode(Tests.enter_game_mode) + general.idle_wait_frames(1) + helper.exit_game_mode(Tests.exit_game_mode) + + # 6. Test IsHidden. + display_mapper_entity.set_visibility_state(False) + Report.result(Tests.is_hidden, display_mapper_entity.is_hidden() is True) + + # 7. Test IsVisible. + display_mapper_entity.set_visibility_state(True) + general.idle_wait_frames(1) + Report.result(Tests.is_visible, display_mapper_entity.is_visible() is True) + + # 8. Delete Display Mapper entity. + display_mapper_entity.delete() + Report.result(Tests.entity_deleted, not display_mapper_entity.exists()) + + # 9. UNDO deletion. + general.undo() + Report.result(Tests.deletion_undo, display_mapper_entity.exists()) + + # 10. REDO deletion. + general.redo() + Report.result(Tests.deletion_redo, not display_mapper_entity.exists()) + + # 11. Look for errors. + helper.wait_for_condition(lambda: error_tracer.has_errors, 1.0) + Report.result(Tests.no_error_occurred, not error_tracer.has_errors) + + +if __name__ == "__main__": + from editor_python_test_tools.utils import Report + Report.start_test(AtomEditorComponents_DisplayMapper_AddedToEntity) diff --git a/AutomatedTesting/Gem/PythonTests/Atom/tests/hydra_AtomEditorComponents_ExposureControlAdded.py b/AutomatedTesting/Gem/PythonTests/Atom/tests/hydra_AtomEditorComponents_ExposureControlAdded.py new file mode 100644 index 0000000000..23a84435f7 --- /dev/null +++ b/AutomatedTesting/Gem/PythonTests/Atom/tests/hydra_AtomEditorComponents_ExposureControlAdded.py @@ -0,0 +1,145 @@ +""" +Copyright (c) Contributors to the Open 3D Engine Project. +For complete copyright and license terms please see the LICENSE at the root of this distribution. + +SPDX-License-Identifier: Apache-2.0 OR MIT +""" + +# fmt: off +class Tests: + camera_creation = ("Camera Entity successfully created", "Camera Entity failed to be created") + camera_component_added = ("Camera component was added to entity", "Camera component failed to be added to entity") + camera_component_check = ("Entity has a Camera component", "Entity failed to find Camera component") + creation_undo = ("UNDO Entity creation success", "UNDO Entity creation failed") + creation_redo = ("REDO Entity creation success", "REDO Entity creation failed") + exposure_control_creation = ("ExposureControl Entity successfully created", "ExposureControl Entity failed to be created") + exposure_control_component = ("Entity has a Exposure Control component", "Entity failed to find Exposure Control component") + post_fx_component = ("Entity has a Post FX Layer component", "Entity did not have a Post FX Layer component") + enter_game_mode = ("Entered game mode", "Failed to enter game mode") + exit_game_mode = ("Exited game mode", "Couldn't exit game mode") + is_visible = ("Entity is visible", "Entity was not visible") + is_hidden = ("Entity is hidden", "Entity was not hidden") + entity_deleted = ("Entity deleted", "Entity was not deleted") + deletion_undo = ("UNDO deletion success", "UNDO deletion failed") + deletion_redo = ("REDO deletion success", "REDO deletion failed") + no_error_occurred = ("No errors detected", "Errors were detected") +# fmt: on + + +def AtomEditorComponents_ExposureControl_AddedToEntity(): + """ + Summary: + Tests the Exposure Control component can be added to an entity and has the expected functionality. + + Test setup: + - Wait for Editor idle loop. + - Open the "Base" level. + + Expected Behavior: + The component can be added, used in game mode, hidden/shown, deleted, and has accurate required components. + Creation and deletion undo/redo should also work. + + Test Steps: + 1) Create an Exposure Control entity with no components. + 2) Add Exposure Control component to Exposure Control entity. + 3) UNDO the entity creation and component addition. + 4) REDO the entity creation and component addition. + 5) Enter/Exit game mode. + 6) Test IsHidden. + 7) Test IsVisible. + 8) Add Post FX Layer component. + 9) Delete Exposure Control entity. + 10) UNDO deletion. + 11) REDO deletion. + 12) Look for errors. + + :return: None + """ + + import azlmbr.legacy.general as general + import azlmbr.math as math + + from editor_python_test_tools.editor_entity_utils import EditorEntity + from editor_python_test_tools.utils import Report, Tracer, TestHelper as helper + + with Tracer() as error_tracer: + # Test setup begins. + # Setup: Wait for Editor idle loop before executing Python hydra scripts then open "Base" level. + helper.init_idle() + helper.open_level("", "Base") + + # Test steps begin. + # 1. Creation of Exposure Control entity with no components. + exposure_control_name = "Exposure Control" + exposure_control_entity = EditorEntity.create_editor_entity_at( + math.Vector3(512.0, 512.0, 34.0), f"{exposure_control_name}") + Report.critical_result(Tests.exposure_control_creation, exposure_control_entity.exists()) + + # 2. Add Exposure Control component to Exposure Control entity. + exposure_control_entity.add_component(exposure_control_name) + Report.critical_result( + Tests.exposure_control_component, exposure_control_entity.has_component(exposure_control_name)) + + # 3. UNDO the entity creation and component addition. + # -> UNDO component addition. + general.undo() + # -> UNDO naming entity. + general.undo() + # -> UNDO selecting entity. + general.undo() + # -> UNDO entity creation. + general.undo() + general.idle_wait_frames(1) + Report.result(Tests.creation_undo, not exposure_control_entity.exists()) + + # 4. REDO the entity creation and component addition. + # -> REDO entity creation. + general.redo() + # -> REDO selecting entity. + general.redo() + # -> REDO naming entity. + general.redo() + # -> REDO component addition. + general.redo() + general.idle_wait_frames(1) + Report.result(Tests.creation_redo, exposure_control_entity.exists()) + + # 5. Enter/Exit game mode. + helper.enter_game_mode(Tests.enter_game_mode) + general.idle_wait_frames(1) + helper.exit_game_mode(Tests.exit_game_mode) + + # 6. Test IsHidden. + exposure_control_entity.set_visibility_state(False) + Report.result(Tests.is_hidden, exposure_control_entity.is_hidden() is True) + + # 7. Test IsVisible. + exposure_control_entity.set_visibility_state(True) + general.idle_wait_frames(1) + Report.result(Tests.is_visible, exposure_control_entity.is_visible() is True) + + # 8. Add Post FX Layer component. + post_fx_layer_name = "PostFX Layer" + exposure_control_entity.add_component(post_fx_layer_name) + Report.result(Tests.post_fx_component, exposure_control_entity.has_component(post_fx_layer_name)) + + # 9. Delete ExposureControl entity. + exposure_control_entity.delete() + Report.result(Tests.entity_deleted, not exposure_control_entity.exists()) + + # 10. UNDO deletion. + general.undo() + Report.result(Tests.deletion_undo, exposure_control_entity.exists()) + + # 11. REDO deletion. + general.redo() + Report.result(Tests.deletion_redo, not exposure_control_entity.exists()) + + # 12. Look for errors. + helper.wait_for_condition(lambda: error_tracer.has_errors, 1.0) + Report.result(Tests.no_error_occurred, not error_tracer.has_errors) + + +if __name__ == "__main__": + from editor_python_test_tools.utils import Report + Report.start_test(AtomEditorComponents_ExposureControl_AddedToEntity) diff --git a/AutomatedTesting/Gem/PythonTests/Atom/tests/hydra_AtomEditorComponents_GlobalSkylightIBLAdded.py b/AutomatedTesting/Gem/PythonTests/Atom/tests/hydra_AtomEditorComponents_GlobalSkylightIBLAdded.py new file mode 100644 index 0000000000..cc891f5929 --- /dev/null +++ b/AutomatedTesting/Gem/PythonTests/Atom/tests/hydra_AtomEditorComponents_GlobalSkylightIBLAdded.py @@ -0,0 +1,164 @@ +""" +Copyright (c) Contributors to the Open 3D Engine Project. +For complete copyright and license terms please see the LICENSE at the root of this distribution. + +SPDX-License-Identifier: Apache-2.0 OR MIT +""" + +# fmt: off +class Tests: + camera_creation = ("Camera Entity successfully created", "Camera Entity failed to be created") + camera_component_added = ("Camera component was added to entity", "Camera component failed to be added to entity") + camera_component_check = ("Entity has a Camera component", "Entity failed to find Camera component") + creation_undo = ("UNDO Entity creation success", "UNDO Entity creation failed") + creation_redo = ("REDO Entity creation success", "REDO Entity creation failed") + global_skylight_creation = ("Global Skylight (IBL) Entity successfully created", "Global Skylight (IBL) Entity failed to be created") + global_skylight_component = ("Entity has a Global Skylight (IBL) component", "Entity failed to find Global Skylight (IBL) component") + diffuse_image_set = ("Entity has the Diffuse Image set", "Entity did not the Diffuse Image set") + specular_image_set = ("Entity has the Specular Image set", "Entity did not the Specular Image set") + enter_game_mode = ("Entered game mode", "Failed to enter game mode") + exit_game_mode = ("Exited game mode", "Couldn't exit game mode") + is_visible = ("Entity is visible", "Entity was not visible") + is_hidden = ("Entity is hidden", "Entity was not hidden") + entity_deleted = ("Entity deleted", "Entity was not deleted") + deletion_undo = ("UNDO deletion success", "UNDO deletion failed") + deletion_redo = ("REDO deletion success", "REDO deletion failed") + no_error_occurred = ("No errors detected", "Errors were detected") +# fmt: on + + +def AtomEditorComponents_GlobalSkylightIBL_AddedToEntity(): + """ + Summary: + Tests the Global Skylight (IBL) component can be added to an entity and has the expected functionality. + + Test setup: + - Wait for Editor idle loop. + - Open the "Base" level. + + Expected Behavior: + The component can be added, used in game mode, hidden/shown, deleted, and has accurate required components. + Creation and deletion undo/redo should also work. + + Test Steps: + 1) Create a Global Skylight (IBL) entity with no components. + 2) Add Global Skylight (IBL) component to Global Skylight (IBL) entity. + 3) UNDO the entity creation and component addition. + 4) REDO the entity creation and component addition. + 5) Enter/Exit game mode. + 6) Test IsHidden. + 7) Test IsVisible. + 8) Add Post FX Layer component. + 9) Add Camera component + 10) Delete Global Skylight (IBL) entity. + 11) UNDO deletion. + 12) REDO deletion. + 13) Look for errors. + + :return: None + """ + import os + + import azlmbr.legacy.general as general + import azlmbr.math as math + + from editor_python_test_tools.asset_utils import Asset + from editor_python_test_tools.editor_entity_utils import EditorEntity + from editor_python_test_tools.utils import Report, Tracer, TestHelper as helper + + with Tracer() as error_tracer: + # Test setup begins. + # Setup: Wait for Editor idle loop before executing Python hydra scripts then open "Base" level. + helper.init_idle() + helper.open_level("", "Base") + + # Test steps begin. + # 1. Create a Global Skylight (IBL) entity with no components. + global_skylight_name = "Global Skylight (IBL)" + global_skylight_entity = EditorEntity.create_editor_entity_at( + math.Vector3(512.0, 512.0, 34.0), global_skylight_name) + Report.critical_result(Tests.global_skylight_creation, global_skylight_entity.exists()) + + # 2. Add Global Skylight (IBL) component to Global Skylight (IBL) entity. + global_skylight_component = global_skylight_entity.add_component(global_skylight_name) + Report.critical_result( + Tests.global_skylight_component, global_skylight_entity.has_component(global_skylight_name)) + + # 3. UNDO the entity creation and component addition. + # -> UNDO component addition. + general.undo() + # -> UNDO naming entity. + general.undo() + # -> UNDO selecting entity. + general.undo() + # -> UNDO entity creation. + general.undo() + general.idle_wait_frames(1) + Report.result(Tests.creation_undo, not global_skylight_entity.exists()) + + # 4. REDO the entity creation and component addition. + # -> REDO entity creation. + general.redo() + # -> REDO selecting entity. + general.redo() + # -> REDO naming entity. + general.redo() + # -> REDO component addition. + general.redo() + general.idle_wait_frames(1) + Report.result(Tests.creation_redo, global_skylight_entity.exists()) + + # 5. Enter/Exit game mode. + helper.enter_game_mode(Tests.enter_game_mode) + general.idle_wait_frames(1) + helper.exit_game_mode(Tests.exit_game_mode) + + # 6. Test IsHidden. + global_skylight_entity.set_visibility_state(False) + Report.result(Tests.is_hidden, global_skylight_entity.is_hidden() is True) + + # 7. Test IsVisible. + global_skylight_entity.set_visibility_state(True) + general.idle_wait_frames(1) + Report.result(Tests.is_visible, global_skylight_entity.is_visible() is True) + + # 8. Set the Diffuse Image asset on the Global Skylight (IBL) entity. + global_skylight_diffuse_image_property = "Controller|Configuration|Diffuse Image" + diffuse_image_path = os.path.join("LightingPresets", "greenwich_park_02_4k_iblskyboxcm.exr.streamingimage") + diffuse_image_asset = Asset.find_asset_by_path(diffuse_image_path, False) + global_skylight_component.set_component_property_value( + global_skylight_diffuse_image_property, diffuse_image_asset.id) + diffuse_image_set = global_skylight_component.get_component_property_value( + global_skylight_diffuse_image_property) + Report.result(Tests.diffuse_image_set, diffuse_image_set == diffuse_image_asset.id) + + # 9. Set the Specular Image asset on the Global Light (IBL) entity. + global_skylight_specular_image_property = "Controller|Configuration|Specular Image" + specular_image_path = os.path.join("LightingPresets", "greenwich_park_02_4k_iblskyboxcm.exr.streamingimage") + specular_image_asset = Asset.find_asset_by_path(specular_image_path, False) + global_skylight_component.set_component_property_value( + global_skylight_specular_image_property, specular_image_asset.id) + specular_image_added = global_skylight_component.get_component_property_value( + global_skylight_specular_image_property) + Report.result(Tests.specular_image_set, specular_image_added == specular_image_asset.id) + + # 10. Delete Global Skylight (IBL) entity. + global_skylight_entity.delete() + Report.result(Tests.entity_deleted, not global_skylight_entity.exists()) + + # 11. UNDO deletion. + general.undo() + Report.result(Tests.deletion_undo, global_skylight_entity.exists()) + + # 12. REDO deletion. + general.redo() + Report.result(Tests.deletion_redo, not global_skylight_entity.exists()) + + # 13. Look for errors. + helper.wait_for_condition(lambda: error_tracer.has_errors, 1.0) + Report.result(Tests.no_error_occurred, not error_tracer.has_errors) + + +if __name__ == "__main__": + from editor_python_test_tools.utils import Report + Report.start_test(AtomEditorComponents_GlobalSkylightIBL_AddedToEntity) diff --git a/AutomatedTesting/Gem/PythonTests/Atom/tests/hydra_AtomEditorComponents_LightAdded.py b/AutomatedTesting/Gem/PythonTests/Atom/tests/hydra_AtomEditorComponents_LightAdded.py new file mode 100644 index 0000000000..8b1432f1f7 --- /dev/null +++ b/AutomatedTesting/Gem/PythonTests/Atom/tests/hydra_AtomEditorComponents_LightAdded.py @@ -0,0 +1,136 @@ +""" +Copyright (c) Contributors to the Open 3D Engine Project. +For complete copyright and license terms please see the LICENSE at the root of this distribution. + +SPDX-License-Identifier: Apache-2.0 OR MIT +""" + +# fmt: off +class Tests: + camera_creation = ("Camera Entity successfully created", "Camera Entity failed to be created") + camera_component_added = ("Camera component was added to entity", "Camera component failed to be added to entity") + camera_component_check = ("Entity has a Camera component", "Entity failed to find Camera component") + creation_undo = ("UNDO Entity creation success", "UNDO Entity creation failed") + creation_redo = ("REDO Entity creation success", "REDO Entity creation failed") + light_creation = ("Light Entity successfully created", "Light Entity failed to be created") + light_component = ("Entity has a Light component", "Entity failed to find Light component") + enter_game_mode = ("Entered game mode", "Failed to enter game mode") + exit_game_mode = ("Exited game mode", "Couldn't exit game mode") + is_visible = ("Entity is visible", "Entity was not visible") + is_hidden = ("Entity is hidden", "Entity was not hidden") + entity_deleted = ("Entity deleted", "Entity was not deleted") + deletion_undo = ("UNDO deletion success", "UNDO deletion failed") + deletion_redo = ("REDO deletion success", "REDO deletion failed") + no_error_occurred = ("No errors detected", "Errors were detected") +# fmt: on + + +def AtomEditorComponents_Light_AddedToEntity(): + """ + Summary: + Tests the Light component can be added to an entity and has the expected functionality. + + Test setup: + - Wait for Editor idle loop. + - Open the "Base" level. + + Expected Behavior: + The component can be added, used in game mode, hidden/shown, deleted, and has accurate required components. + Creation and deletion undo/redo should also work. + + Test Steps: + 1) Create a Light entity with no components. + 2) Add Light component to the Light entity. + 3) UNDO the entity creation and component addition. + 4) REDO the entity creation and component addition. + 5) Enter/Exit game mode. + 6) Test IsHidden. + 7) Test IsVisible. + 8) Delete Light entity. + 9) UNDO deletion. + 10) REDO deletion. + 11) Look for errors. + + :return: None + """ + + import azlmbr.legacy.general as general + import azlmbr.math as math + + from editor_python_test_tools.editor_entity_utils import EditorEntity + from editor_python_test_tools.utils import Report, Tracer, TestHelper as helper + + with Tracer() as error_tracer: + # Test setup begins. + # Setup: Wait for Editor idle loop before executing Python hydra scripts then open "Base" level. + helper.init_idle() + helper.open_level("", "Base") + + # Test steps begin. + # 1. Create a Light entity with no components. + light_name = "Light" + light_entity = EditorEntity.create_editor_entity_at(math.Vector3(512.0, 512.0, 34.0), light_name) + Report.critical_result(Tests.light_creation, light_entity.exists()) + + # 2. Add Light component to the Light entity. + light_entity.add_component(light_name) + Report.critical_result(Tests.light_component, light_entity.has_component(light_name)) + + # 3. UNDO the entity creation and component addition. + # -> UNDO component addition. + general.undo() + # -> UNDO naming entity. + general.undo() + # -> UNDO selecting entity. + general.undo() + # -> UNDO entity creation. + general.undo() + general.idle_wait_frames(1) + Report.result(Tests.creation_undo, not light_entity.exists()) + + # 4. REDO the entity creation and component addition. + # -> REDO entity creation. + general.redo() + # -> REDO selecting entity. + general.redo() + # -> REDO naming entity. + general.redo() + # -> REDO component addition. + general.redo() + general.idle_wait_frames(1) + Report.result(Tests.creation_redo, light_entity.exists()) + + # 5. Enter/Exit game mode. + helper.enter_game_mode(Tests.enter_game_mode) + general.idle_wait_frames(1) + helper.exit_game_mode(Tests.exit_game_mode) + + # 6. Test IsHidden. + light_entity.set_visibility_state(False) + Report.result(Tests.is_hidden, light_entity.is_hidden() is True) + + # 7. Test IsVisible. + light_entity.set_visibility_state(True) + general.idle_wait_frames(1) + Report.result(Tests.is_visible, light_entity.is_visible() is True) + + # 8. Delete Light entity. + light_entity.delete() + Report.result(Tests.entity_deleted, not light_entity.exists()) + + # 9. UNDO deletion. + general.undo() + Report.result(Tests.deletion_undo, light_entity.exists()) + + # 10. REDO deletion. + general.redo() + Report.result(Tests.deletion_redo, not light_entity.exists()) + + # 11. Look for errors. + helper.wait_for_condition(lambda: error_tracer.has_errors, 1.0) + Report.result(Tests.no_error_occurred, not error_tracer.has_errors) + + +if __name__ == "__main__": + from editor_python_test_tools.utils import Report + Report.start_test(AtomEditorComponents_Light_AddedToEntity) diff --git a/AutomatedTesting/Gem/PythonTests/atom_renderer/atom_hydra_scripts/hydra_AtomEditorComponents_LightComponent.py b/AutomatedTesting/Gem/PythonTests/Atom/tests/hydra_AtomEditorComponents_LightComponent.py similarity index 95% rename from AutomatedTesting/Gem/PythonTests/atom_renderer/atom_hydra_scripts/hydra_AtomEditorComponents_LightComponent.py rename to AutomatedTesting/Gem/PythonTests/Atom/tests/hydra_AtomEditorComponents_LightComponent.py index 8d138e67b8..751f425916 100644 --- a/AutomatedTesting/Gem/PythonTests/atom_renderer/atom_hydra_scripts/hydra_AtomEditorComponents_LightComponent.py +++ b/AutomatedTesting/Gem/PythonTests/Atom/tests/hydra_AtomEditorComponents_LightComponent.py @@ -1,10 +1,8 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. +Copyright (c) Contributors to the Open 3D Engine Project. +For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT - -Hydra script that creates an entity, attaches the Light component to it for test verifications. -The test verifies that each light type option is available and can be selected without errors. """ import os @@ -19,7 +17,7 @@ import azlmbr.legacy.general as general sys.path.append(os.path.join(azlmbr.paths.devassets, "Gem", "PythonTests")) import editor_python_test_tools.hydra_editor_utils as hydra -from atom_renderer.atom_utils.atom_constants import LIGHT_TYPES +from Atom.atom_utils.atom_constants import LIGHT_TYPES LIGHT_TYPE_PROPERTY = 'Controller|Configuration|Light type' SPHERE_AND_SPOT_DISK_LIGHT_PROPERTIES = [ diff --git a/AutomatedTesting/Gem/PythonTests/Atom/tests/hydra_AtomEditorComponents_PhysicalSkyAdded.py b/AutomatedTesting/Gem/PythonTests/Atom/tests/hydra_AtomEditorComponents_PhysicalSkyAdded.py new file mode 100644 index 0000000000..04441d5b2c --- /dev/null +++ b/AutomatedTesting/Gem/PythonTests/Atom/tests/hydra_AtomEditorComponents_PhysicalSkyAdded.py @@ -0,0 +1,136 @@ +""" +Copyright (c) Contributors to the Open 3D Engine Project. +For complete copyright and license terms please see the LICENSE at the root of this distribution. + +SPDX-License-Identifier: Apache-2.0 OR MIT +""" + +# fmt: off +class Tests: + camera_creation = ("Camera Entity successfully created", "Camera Entity failed to be created") + camera_component_added = ("Camera component was added to entity", "Camera component failed to be added to entity") + camera_component_check = ("Entity has a Camera component", "Entity failed to find Camera component") + creation_undo = ("UNDO Entity creation success", "UNDO Entity creation failed") + creation_redo = ("REDO Entity creation success", "REDO Entity creation failed") + physical_sky_creation = ("Physical Sky Entity successfully created", "Physical Sky Entity failed to be created") + physical_sky_component = ("Entity has a Physical Sky component", "Entity failed to find Physical Sky component") + enter_game_mode = ("Entered game mode", "Failed to enter game mode") + exit_game_mode = ("Exited game mode", "Couldn't exit game mode") + is_visible = ("Entity is visible", "Entity was not visible") + is_hidden = ("Entity is hidden", "Entity was not hidden") + entity_deleted = ("Entity deleted", "Entity was not deleted") + deletion_undo = ("UNDO deletion success", "UNDO deletion failed") + deletion_redo = ("REDO deletion success", "REDO deletion failed") + no_error_occurred = ("No errors detected", "Errors were detected") +# fmt: on + + +def AtomEditorComponents_PhysicalSky_AddedToEntity(): + """ + Summary: + Tests the Physical Sky component can be added to an entity and has the expected functionality. + + Test setup: + - Wait for Editor idle loop. + - Open the "Base" level. + + Expected Behavior: + The component can be added, used in game mode, hidden/shown, deleted, and has accurate required components. + Creation and deletion undo/redo should also work. + + Test Steps: + 1) Create a Physical Sky entity with no components. + 2) Add Physical Sky component to Physical Sky entity. + 3) UNDO the entity creation and component addition. + 4) REDO the entity creation and component addition. + 5) Enter/Exit game mode. + 6) Test IsHidden. + 7) Test IsVisible. + 8) Delete Physical Sky entity. + 9) UNDO deletion. + 10) REDO deletion. + 11) Look for errors. + + :return: None + """ + + import azlmbr.legacy.general as general + import azlmbr.math as math + + from editor_python_test_tools.editor_entity_utils import EditorEntity + from editor_python_test_tools.utils import Report, Tracer, TestHelper as helper + + with Tracer() as error_tracer: + # Test setup begins. + # Setup: Wait for Editor idle loop before executing Python hydra scripts then open "Base" level. + helper.init_idle() + helper.open_level("", "Base") + + # Test steps begin. + # 1. Create a Physical Sky entity with no components. + physical_sky_name = "Physical Sky" + physical_sky_entity = EditorEntity.create_editor_entity_at(math.Vector3(512.0, 512.0, 34.0), physical_sky_name) + Report.critical_result(Tests.physical_sky_creation, physical_sky_entity.exists()) + + # 2. Add Physical Sky component to Physical Sky entity. + physical_sky_entity.add_component(physical_sky_name) + Report.critical_result(Tests.physical_sky_component, physical_sky_entity.has_component(physical_sky_name)) + + # 3. UNDO the entity creation and component addition. + # -> UNDO component addition. + general.undo() + # -> UNDO naming entity. + general.undo() + # -> UNDO selecting entity. + general.undo() + # -> UNDO entity creation. + general.undo() + general.idle_wait_frames(1) + Report.result(Tests.creation_undo, not physical_sky_entity.exists()) + + # 4. REDO the entity creation and component addition. + # -> REDO entity creation. + general.redo() + # -> REDO selecting entity. + general.redo() + # -> REDO naming entity. + general.redo() + # -> REDO component addition. + general.redo() + general.idle_wait_frames(1) + Report.result(Tests.creation_redo, physical_sky_entity.exists()) + + # 5. Enter/Exit game mode. + helper.enter_game_mode(Tests.enter_game_mode) + general.idle_wait_frames(1) + helper.exit_game_mode(Tests.exit_game_mode) + + # 6. Test IsHidden. + physical_sky_entity.set_visibility_state(False) + Report.result(Tests.is_hidden, physical_sky_entity.is_hidden() is True) + + # 7. Test IsVisible. + physical_sky_entity.set_visibility_state(True) + general.idle_wait_frames(1) + Report.result(Tests.is_visible, physical_sky_entity.is_visible() is True) + + # 8. Delete Physical Sky entity. + physical_sky_entity.delete() + Report.result(Tests.entity_deleted, not physical_sky_entity.exists()) + + # 9. UNDO deletion. + general.undo() + Report.result(Tests.deletion_undo, physical_sky_entity.exists()) + + # 10. REDO deletion. + general.redo() + Report.result(Tests.deletion_redo, not physical_sky_entity.exists()) + + # 11. Look for errors. + helper.wait_for_condition(lambda: error_tracer.has_errors, 1.0) + Report.result(Tests.no_error_occurred, not error_tracer.has_errors) + + +if __name__ == "__main__": + from editor_python_test_tools.utils import Report + Report.start_test(AtomEditorComponents_PhysicalSky_AddedToEntity) diff --git a/AutomatedTesting/Gem/PythonTests/Atom/tests/hydra_AtomEditorComponents_PostFXRadiusWeightModifierAdded.py b/AutomatedTesting/Gem/PythonTests/Atom/tests/hydra_AtomEditorComponents_PostFXRadiusWeightModifierAdded.py new file mode 100644 index 0000000000..8914ab9e7e --- /dev/null +++ b/AutomatedTesting/Gem/PythonTests/Atom/tests/hydra_AtomEditorComponents_PostFXRadiusWeightModifierAdded.py @@ -0,0 +1,138 @@ +""" +Copyright (c) Contributors to the Open 3D Engine Project. +For complete copyright and license terms please see the LICENSE at the root of this distribution. + +SPDX-License-Identifier: Apache-2.0 OR MIT +""" + +# fmt: off +class Tests: + camera_creation = ("Camera Entity successfully created", "Camera Entity failed to be created") + camera_component_added = ("Camera component was added to entity", "Camera component failed to be added to entity") + camera_component_check = ("Entity has a Camera component", "Entity failed to find Camera component") + creation_undo = ("UNDO Entity creation success", "UNDO Entity creation failed") + creation_redo = ("REDO Entity creation success", "REDO Entity creation failed") + postfx_radius_weight_creation = ("PostFX Radius Weight Modifier Entity successfully created", "PostFX Radius Weight Modifier Entity failed to be created") + postfx_radius_weight_component = ("Entity has a PostFX Radius Weight Modifier component", "Entity failed to find PostFX Radius Weight Modifier component") + enter_game_mode = ("Entered game mode", "Failed to enter game mode") + exit_game_mode = ("Exited game mode", "Couldn't exit game mode") + is_visible = ("Entity is visible", "Entity was not visible") + is_hidden = ("Entity is hidden", "Entity was not hidden") + entity_deleted = ("Entity deleted", "Entity was not deleted") + deletion_undo = ("UNDO deletion success", "UNDO deletion failed") + deletion_redo = ("REDO deletion success", "REDO deletion failed") + no_error_occurred = ("No errors detected", "Errors were detected") +# fmt: on + + +def AtomEditorComponents_PostFXRadiusWeightModifier_AddedToEntity(): + """ + Summary: + Tests the PostFX Radius Weight Modifier component can be added to an entity and has the expected functionality. + + Test setup: + - Wait for Editor idle loop. + - Open the "Base" level. + + Expected Behavior: + The component can be added, used in game mode, hidden/shown, deleted, and has accurate required components. + Creation and deletion undo/redo should also work. + + Test Steps: + 1) Create a Post FX Radius Weight Modifier entity with no components. + 2) Add Post FX Radius Weight Modifier component to Post FX Radius Weight Modifier entity. + 3) UNDO the entity creation and component addition. + 4) REDO the entity creation and component addition. + 5) Enter/Exit game mode. + 6) Test IsHidden. + 7) Test IsVisible. + 8) Delete PostFX Radius Weight Modifier entity. + 9) UNDO deletion. + 10) REDO deletion. + 11) Look for errors. + + :return: None + """ + + import azlmbr.legacy.general as general + import azlmbr.math as math + + from editor_python_test_tools.editor_entity_utils import EditorEntity + from editor_python_test_tools.utils import Report, Tracer, TestHelper as helper + + with Tracer() as error_tracer: + # Test setup begins. + # Setup: Wait for Editor idle loop before executing Python hydra scripts then open "Base" level. + helper.init_idle() + helper.open_level("", "Base") + + # Test steps begin. + # 1. Create a Post FX Radius Weight Modifier entity with no components. + postfx_radius_weight_name = "PostFX Radius Weight Modifier" + postfx_radius_weight_entity = EditorEntity.create_editor_entity_at( + math.Vector3(512.0, 512.0, 34.0), postfx_radius_weight_name) + Report.critical_result(Tests.postfx_radius_weight_creation, postfx_radius_weight_entity.exists()) + + # 2. Add Post FX Radius Weight Modifier component to Post FX Radius Weight Modifier entity. + postfx_radius_weight_entity.add_component(postfx_radius_weight_name) + Report.critical_result( + Tests.postfx_radius_weight_component, postfx_radius_weight_entity.has_component(postfx_radius_weight_name)) + + # 3. UNDO the entity creation and component addition. + # -> UNDO component addition. + general.undo() + # -> UNDO naming entity. + general.undo() + # -> UNDO selecting entity. + general.undo() + # -> UNDO entity creation. + general.undo() + general.idle_wait_frames(1) + Report.result(Tests.creation_undo, not postfx_radius_weight_entity.exists()) + + # 4. REDO the entity creation and component addition. + # -> REDO entity creation. + general.redo() + # -> REDO selecting entity. + general.redo() + # -> REDO naming entity. + general.redo() + # -> REDO component addition. + general.redo() + general.idle_wait_frames(1) + Report.result(Tests.creation_redo, postfx_radius_weight_entity.exists()) + + # 5. Enter/Exit game mode. + helper.enter_game_mode(Tests.enter_game_mode) + general.idle_wait_frames(1) + helper.exit_game_mode(Tests.exit_game_mode) + + # 6. Test IsHidden. + postfx_radius_weight_entity.set_visibility_state(False) + Report.result(Tests.is_hidden, postfx_radius_weight_entity.is_hidden() is True) + + # 7. Test IsVisible. + postfx_radius_weight_entity.set_visibility_state(True) + general.idle_wait_frames(1) + Report.result(Tests.is_visible, postfx_radius_weight_entity.is_visible() is True) + + # 8. Delete PostFX Radius Weight Modifier entity. + postfx_radius_weight_entity.delete() + Report.result(Tests.entity_deleted, not postfx_radius_weight_entity.exists()) + + # 9. UNDO deletion. + general.undo() + Report.result(Tests.deletion_undo, postfx_radius_weight_entity.exists()) + + # 10. REDO deletion. + general.redo() + Report.result(Tests.deletion_redo, not postfx_radius_weight_entity.exists()) + + # 11. Look for errors. + helper.wait_for_condition(lambda: error_tracer.has_errors, 1.0) + Report.result(Tests.no_error_occurred, not error_tracer.has_errors) + + +if __name__ == "__main__": + from editor_python_test_tools.utils import Report + Report.start_test(AtomEditorComponents_PostFXRadiusWeightModifier_AddedToEntity) diff --git a/AutomatedTesting/Gem/PythonTests/atom_renderer/atom_hydra_scripts/hydra_AtomMaterialEditor_BasicTests.py b/AutomatedTesting/Gem/PythonTests/Atom/tests/hydra_AtomMaterialEditor_BasicTests.py similarity index 95% rename from AutomatedTesting/Gem/PythonTests/atom_renderer/atom_hydra_scripts/hydra_AtomMaterialEditor_BasicTests.py rename to AutomatedTesting/Gem/PythonTests/Atom/tests/hydra_AtomMaterialEditor_BasicTests.py index 9047b4c871..88a1ef4c7b 100644 --- a/AutomatedTesting/Gem/PythonTests/atom_renderer/atom_hydra_scripts/hydra_AtomMaterialEditor_BasicTests.py +++ b/AutomatedTesting/Gem/PythonTests/Atom/tests/hydra_AtomMaterialEditor_BasicTests.py @@ -3,12 +3,12 @@ Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT - -import azlmbr.materialeditor will fail with a ModuleNotFound error when using this script with Editor.exe -This is because azlmbr.materialeditor only binds to MaterialEditor.exe and not Editor.exe -You need to launch this script with MaterialEditor.exe in order for azlmbr.materialeditor to appear. """ +# import azlmbr.materialeditor will fail with a ModuleNotFound error when using this script with Editor.exe +# This is because azlmbr.materialeditor only binds to MaterialEditor.exe and not Editor.exe +# You need to launch this script with MaterialEditor.exe in order for azlmbr.materialeditor to appear. + import os import sys import time @@ -18,7 +18,7 @@ import azlmbr.paths sys.path.append(os.path.join(azlmbr.paths.devassets, "Gem", "PythonTests")) -import atom_renderer.atom_utils.material_editor_utils as material_editor +import Atom.atom_utils.material_editor_utils as material_editor NEW_MATERIAL = "test_material.material" NEW_MATERIAL_1 = "test_material_1.material" diff --git a/AutomatedTesting/Gem/PythonTests/atom_renderer/atom_hydra_scripts/hydra_GPUTest_AtomFeatureIntegrationBenchmark.py b/AutomatedTesting/Gem/PythonTests/Atom/tests/hydra_GPUTest_AtomFeatureIntegrationBenchmark.py similarity index 92% rename from AutomatedTesting/Gem/PythonTests/atom_renderer/atom_hydra_scripts/hydra_GPUTest_AtomFeatureIntegrationBenchmark.py rename to AutomatedTesting/Gem/PythonTests/Atom/tests/hydra_GPUTest_AtomFeatureIntegrationBenchmark.py index 3aa9fe660c..4f7edeba75 100644 --- a/AutomatedTesting/Gem/PythonTests/atom_renderer/atom_hydra_scripts/hydra_GPUTest_AtomFeatureIntegrationBenchmark.py +++ b/AutomatedTesting/Gem/PythonTests/Atom/tests/hydra_GPUTest_AtomFeatureIntegrationBenchmark.py @@ -3,11 +3,6 @@ Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT - -Hydra script that is used to create a new level with a default rendering setup. -After the level is setup, screenshots are diffed against golden images are used to verify pass/fail results of the test. - -See the run() function for more in-depth test info. """ import os @@ -19,7 +14,7 @@ sys.path.append(os.path.join(azlmbr.paths.devroot, "AutomatedTesting", "Gem", "P import editor_python_test_tools.hydra_editor_utils as hydra from editor_python_test_tools.editor_test_helper import EditorTestHelper -from atom_renderer.atom_utils.benchmark_utils import BenchmarkHelper +from Atom.atom_utils.benchmark_utils import BenchmarkHelper SCREEN_WIDTH = 1280 SCREEN_HEIGHT = 720 diff --git a/AutomatedTesting/Gem/PythonTests/atom_renderer/atom_hydra_scripts/hydra_GPUTest_BasicLevelSetup.py b/AutomatedTesting/Gem/PythonTests/Atom/tests/hydra_GPUTest_BasicLevelSetup.py similarity index 97% rename from AutomatedTesting/Gem/PythonTests/atom_renderer/atom_hydra_scripts/hydra_GPUTest_BasicLevelSetup.py rename to AutomatedTesting/Gem/PythonTests/Atom/tests/hydra_GPUTest_BasicLevelSetup.py index 920c044be0..62a122a723 100644 --- a/AutomatedTesting/Gem/PythonTests/atom_renderer/atom_hydra_scripts/hydra_GPUTest_BasicLevelSetup.py +++ b/AutomatedTesting/Gem/PythonTests/Atom/tests/hydra_GPUTest_BasicLevelSetup.py @@ -3,11 +3,6 @@ Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT - -Hydra script that is used to create a new level with a default rendering setup. -After the level is setup, screenshots are diffed against golden images are used to verify pass/fail results of the test. - -See the run() function for more in-depth test info. """ import os @@ -26,7 +21,7 @@ sys.path.append(os.path.join(azlmbr.paths.devroot, "AutomatedTesting", "Gem", "P import editor_python_test_tools.hydra_editor_utils as hydra from editor_python_test_tools.editor_test_helper import EditorTestHelper -from atom_renderer.atom_utils.screenshot_utils import ScreenshotHelper +from Atom.atom_utils.screenshot_utils import ScreenshotHelper SCREEN_WIDTH = 1280 SCREEN_HEIGHT = 720 diff --git a/AutomatedTesting/Gem/PythonTests/atom_renderer/atom_hydra_scripts/hydra_GPUTest_LightComponent.py b/AutomatedTesting/Gem/PythonTests/Atom/tests/hydra_GPUTest_LightComponent.py similarity index 97% rename from AutomatedTesting/Gem/PythonTests/atom_renderer/atom_hydra_scripts/hydra_GPUTest_LightComponent.py rename to AutomatedTesting/Gem/PythonTests/Atom/tests/hydra_GPUTest_LightComponent.py index 8063445608..4a3ae8c85d 100644 --- a/AutomatedTesting/Gem/PythonTests/atom_renderer/atom_hydra_scripts/hydra_GPUTest_LightComponent.py +++ b/AutomatedTesting/Gem/PythonTests/Atom/tests/hydra_GPUTest_LightComponent.py @@ -3,12 +3,6 @@ Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT - -Hydra script that is used to create an entity with a Light component attached. -It then updates the property values of the Light component and takes a screenshot. -The screenshot is compared against an expected golden image for test verification. - -See the run() function for more in-depth test info. """ import os import sys @@ -23,7 +17,7 @@ import azlmbr.legacy.general as general sys.path.append(os.path.join(azlmbr.paths.devroot, "AutomatedTesting", "Gem", "PythonTests")) import editor_python_test_tools.hydra_editor_utils as hydra -from atom_renderer.atom_utils import atom_component_helper, atom_constants, screenshot_utils +from Atom.atom_utils import atom_component_helper, atom_constants, screenshot_utils from editor_python_test_tools.editor_test_helper import EditorTestHelper helper = EditorTestHelper(log_prefix="Atom_EditorTestHelper") diff --git a/AutomatedTesting/Gem/PythonTests/atom_renderer/atom_hydra_scripts/hydra_ShaderAssetBuilder_RecompilesShaderAsChainOfDependenciesChanges.py b/AutomatedTesting/Gem/PythonTests/Atom/tests/hydra_ShaderAssetBuilder_RecompilesShaderAsChainOfDependenciesChanges.py similarity index 60% rename from AutomatedTesting/Gem/PythonTests/atom_renderer/atom_hydra_scripts/hydra_ShaderAssetBuilder_RecompilesShaderAsChainOfDependenciesChanges.py rename to AutomatedTesting/Gem/PythonTests/Atom/tests/hydra_ShaderAssetBuilder_RecompilesShaderAsChainOfDependenciesChanges.py index a05420d960..f13227aa9d 100644 --- a/AutomatedTesting/Gem/PythonTests/atom_renderer/atom_hydra_scripts/hydra_ShaderAssetBuilder_RecompilesShaderAsChainOfDependenciesChanges.py +++ b/AutomatedTesting/Gem/PythonTests/Atom/tests/hydra_ShaderAssetBuilder_RecompilesShaderAsChainOfDependenciesChanges.py @@ -3,78 +3,19 @@ Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT - """ -import os -import shutil - -def _copy_file(src_file, src_path, target_file, target_path): - # type: (str, str, str, str) -> None - """ - Copies the [src_file] located in [src_path] to the [target_file] located at [target_path]. - Leaves the [target_file] unlocked for reading and writing privileges - :param src_file: The source file to copy (file name) - :param src_path: The source file's path - :param target_file: The target file to copy into (file name) - :param target_path: The target file's path - :return: None - """ - target_file_path = os.path.join(target_path, target_file) - src_file_path = os.path.join(src_path, src_file) - if os.path.exists(target_file_path): - fs.unlock_file(target_file_path) - shutil.copyfile(src_file_path, target_file_path) - -def _copy_tmp_files_in_order(src_directory, file_list, dst_directory, wait_time_in_between = 0.0): - # type: (str, list, str, float) -> None - """ - This function assumes that for each file name listed in @file_list - there's file named "@filename.txt" which the original source file - but they will be copied with just the @filename (.txt removed). - """ - for filename in file_list: - src_name = f"{filename}.txt" - _copy_file(src_name, src_directory, filename, dst_directory) - if wait_time_in_between > 0.0: - print(f"Created {filename} in {dst_directory}") - general.idle_wait(wait_time_in_between) - - -def _remove_file(src_file, src_path): - # type: (str, str) -> None - """ - Removes the [src_file] located in [src_path]. - :param src_file: The source file to copy (file name) - :param src_path: The source file's path - :return: None - """ - src_file_path = os.path.join(src_path, src_file) - if os.path.exists(src_file_path): - fs.unlock_file(src_file_path) - os.remove(src_file_path) - - -def _remove_files(directory, file_list): - for filename in file_list: - _remove_file(filename, directory) - - -def _asset_exists(cache_relative_path): - asset_id = azasset.AssetCatalogRequestBus(azbus.Broadcast, "GetAssetIdByPath", cache_relative_path, azmath.Uuid(), False) - return asset_id.is_valid() - -# List of results that we want to check, this is not 100% necessary but it's a good -# practice to make it easier to debug tests. -# Here we define a tuple of tests -class Results(): - azshader_was_removed = ("azshader was removed", "Failed to remove azshader") - azshader_was_compiled = ("azshader was compiled", "Failed to compile azshader") +# fmt: off +class Tests(): + azshader_was_removed = ("azshader was removed", "Failed to remove azshader") + azshader_was_compiled = ("azshader was compiled", "Failed to compile azshader") + no_error_occurred = ("No errors detected", "Errors were detected") +# fmt: on def ShaderAssetBuilder_RecompilesShaderAsChainOfDependenciesChanges(): """ - This test validates [ATOM-5441] Shader Builders May Fail When Multiple New Files Are Added + This test validates: "Shader Builders May Fail When Multiple New Files Are Added" It creates source assets to compile a particular shader. 1- The first phase generates the source assets out of order and slowly. The AP should wakeup each time one of the source dependencies appears but will fail each time. Only when the @@ -82,6 +23,71 @@ def ShaderAssetBuilder_RecompilesShaderAsChainOfDependenciesChanges(): 2- The second phase is similar as above, except that all source assets will be created at once and We also expect that in the end the shader is built successfully. """ + import os + import shutil + + import azlmbr.asset as azasset + import azlmbr.bus as azbus + import azlmbr.legacy.general as general + import azlmbr.math as azmath + + from editor_python_test_tools.utils import TestHelper as helper + from editor_python_test_tools.utils import Tracer + import ly_test_tools.environment.file_system as fs + + def _copy_file(src_file, src_path, target_file, target_path): + # type: (str, str, str, str) -> None + """ + Copies the [src_file] located in [src_path] to the [target_file] located at [target_path]. + Leaves the [target_file] unlocked for reading and writing privileges + :param src_file: The source file to copy (file name) + :param src_path: The source file's path + :param target_file: The target file to copy into (file name) + :param target_path: The target file's path + :return: None + """ + target_file_path = os.path.join(target_path, target_file) + src_file_path = os.path.join(src_path, src_file) + if os.path.exists(target_file_path): + fs.unlock_file(target_file_path) + shutil.copyfile(src_file_path, target_file_path) + + def _copy_tmp_files_in_order(src_directory, file_list, dst_directory, wait_time_in_between=0.0): + # type: (str, list, str, float) -> None + """ + This function assumes that for each file name listed in @file_list + there's file named "@filename.txt" which the original source file + but they will be copied with just the @filename (.txt removed). + """ + for filename in file_list: + src_name = f"{filename}.txt" + _copy_file(src_name, src_directory, filename, dst_directory) + if wait_time_in_between > 0.0: + print(f"Created {filename} in {dst_directory}") + general.idle_wait(wait_time_in_between) + + def _remove_file(src_file, src_path): + # type: (str, str) -> None + """ + Removes the [src_file] located in [src_path]. + :param src_file: The source file to copy (file name) + :param src_path: The source file's path + :return: None + """ + src_file_path = os.path.join(src_path, src_file) + if os.path.exists(src_file_path): + fs.unlock_file(src_file_path) + os.remove(src_file_path) + + def _remove_files(directory, file_list): + for filename in file_list: + _remove_file(filename, directory) + + def _asset_exists(cache_relative_path): + asset_id = azasset.AssetCatalogRequestBus(azbus.Broadcast, "GetAssetIdByPath", cache_relative_path, + azmath.Uuid(), False) + return asset_id.is_valid() + # Required for automated tests helper.init_idle() @@ -115,14 +121,14 @@ def ShaderAssetBuilder_RecompilesShaderAsChainOfDependenciesChanges(): azshader_name = "assets/dependencyvalidation.azshader" helper.wait_for_condition(lambda: not _asset_exists(azshader_name), 5.0) - Report.critical_result(Results.azshader_was_removed, not _asset_exists(azshader_name)) + Report.critical_result(Tests.azshader_was_removed, not _asset_exists(azshader_name)) _copy_tmp_files_in_order(src_assets_subdir, file_list, game_asset_path, 1.0) # Give enough time to AP to compile the shader helper.wait_for_condition(lambda: _asset_exists(azshader_name), 60.0) - Report.critical_result(Results.azshader_was_compiled, _asset_exists(azshader_name)) + Report.critical_result(Tests.azshader_was_compiled, _asset_exists(azshader_name)) # The first part was about compiling the shader under normal conditions. # Let's remove the files from the previous phase and will proceed @@ -130,7 +136,7 @@ def ShaderAssetBuilder_RecompilesShaderAsChainOfDependenciesChanges(): # ShaderAssetBuilder will only succeed when the last file becomes visible. _remove_files(game_asset_path, reverse_file_list) helper.wait_for_condition(lambda: not _asset_exists(azshader_name), 5.0) - Report.critical_result(Results.azshader_was_removed, not _asset_exists(azshader_name)) + Report.critical_result(Tests.azshader_was_removed, not _asset_exists(azshader_name)) # Remark, if you are running this test manually from the Editor with "pyRunFile", # You'll notice how the AP issues notifications that it fails to compile the shader @@ -148,7 +154,7 @@ def ShaderAssetBuilder_RecompilesShaderAsChainOfDependenciesChanges(): # Give enough time to AP to compile the shader helper.wait_for_condition(lambda: _asset_exists(azshader_name), 60.0) - Report.critical_result(Results.azshader_was_compiled, _asset_exists(azshader_name)) + Report.critical_result(Tests.azshader_was_compiled, _asset_exists(azshader_name)) # The last phase of the test puts stress on potential race conditions # when all required files appear as soon as possible. @@ -157,7 +163,7 @@ def ShaderAssetBuilder_RecompilesShaderAsChainOfDependenciesChanges(): # Remove left over files. _remove_files(game_asset_path, reverse_file_list) helper.wait_for_condition(lambda: not _asset_exists(azshader_name), 5.0) - Report.critical_result(Results.azshader_was_removed, not _asset_exists(azshader_name)) + Report.critical_result(Tests.azshader_was_removed, not _asset_exists(azshader_name)) # Now let's copy all the source files to the "Assets" folder as fast as possible. _copy_tmp_files_in_order(src_assets_subdir, reverse_file_list, game_asset_path) @@ -165,24 +171,17 @@ def ShaderAssetBuilder_RecompilesShaderAsChainOfDependenciesChanges(): # Give enough time to AP to compile the shader helper.wait_for_condition(lambda: _asset_exists(azshader_name), 60.0) - Report.critical_result(Results.azshader_was_compiled, _asset_exists(azshader_name)) + Report.critical_result(Tests.azshader_was_compiled, _asset_exists(azshader_name)) # All good, let's cleanup leftover files before closing the test. _remove_files(game_asset_path, reverse_file_list) helper.wait_for_condition(lambda: not _asset_exists(azshader_name), 5.0) + # Look for errors to raise. + helper.wait_for_condition(lambda: error_tracer.has_errors, 1.0) + Report.result(Tests.no_error_occurred, not error_tracer.has_errors) + if __name__ == "__main__": - # All exposed python bindings are in azlmbr - import azlmbr.legacy.general as general - import azlmbr.bus as azbus - import azlmbr.asset as azasset - import azlmbr.math as azmath - - # Import report and test helper utilities from editor_python_test_tools.utils import Report - from editor_python_test_tools.utils import TestHelper as helper - from editor_python_test_tools.utils import Tracer - import ly_test_tools.environment.file_system as fs - - Report.start_test(ShaderAssetBuilder_RecompilesShaderAsChainOfDependenciesChanges) \ No newline at end of file + Report.start_test(ShaderAssetBuilder_RecompilesShaderAsChainOfDependenciesChanges) diff --git a/AutomatedTesting/Gem/PythonTests/CMakeLists.txt b/AutomatedTesting/Gem/PythonTests/CMakeLists.txt index 7fd3b3a241..466a4b1679 100644 --- a/AutomatedTesting/Gem/PythonTests/CMakeLists.txt +++ b/AutomatedTesting/Gem/PythonTests/CMakeLists.txt @@ -18,7 +18,7 @@ include(${pal_dir}/PAL_traits_${PAL_PLATFORM_NAME_LOWERCASE}.cmake) add_subdirectory(assetpipeline) ## Atom Renderer ## -add_subdirectory(atom_renderer) +add_subdirectory(Atom) ## Physics ## add_subdirectory(Physics) diff --git a/AutomatedTesting/Gem/PythonTests/EditorPythonTestTools/editor_python_test_tools/editor_entity_utils.py b/AutomatedTesting/Gem/PythonTests/EditorPythonTestTools/editor_python_test_tools/editor_entity_utils.py index fec9d9880b..154b5730d7 100644 --- a/AutomatedTesting/Gem/PythonTests/EditorPythonTestTools/editor_python_test_tools/editor_entity_utils.py +++ b/AutomatedTesting/Gem/PythonTests/EditorPythonTestTools/editor_python_test_tools/editor_entity_utils.py @@ -20,6 +20,7 @@ import azlmbr.legacy.general as general # Helper file Imports from editor_python_test_tools.utils import Report + class EditorComponent: """ EditorComponent class used to set and get the component property value using path @@ -28,7 +29,6 @@ class EditorComponent: which also assigns self.id and self.type_id to the EditorComponent object. """ - # Methods def get_component_name(self) -> str: """ Used to get name of component @@ -87,6 +87,13 @@ class EditorComponent: outcome.IsSuccess() ), f"Failure: Could not set value to '{self.get_component_name()}' : '{component_property_path}'" + def is_enabled(self): + """ + Used to verify if the component is enabled. + :return: True if enabled, otherwise False. + """ + return editor.EditorComponentAPIBus(bus.Broadcast, "IsComponentEnabled", self.id) + @staticmethod def get_type_ids(component_names: list) -> list: """ @@ -254,7 +261,7 @@ class EditorEntity: def get_components_of_type(self, component_names: list) -> List[EditorComponent]: """ Used to get components of type component_name that already exists on Entity - :param component_name: Name to component to check + :param component_names: List of names of components to check :return: List of Entity Component objects of given component name """ component_list = [] @@ -318,3 +325,39 @@ class EditorEntity: editor.EditorEntityAPIBus(bus.Event, "SetStartStatus", self.id, status_to_set) set_status = self.get_start_status() assert set_status == status_to_set, f"Failed to set start status of {desired_start_status} to {self.get_name}" + + def delete(self) -> None: + """ + Used to delete the Entity. + :return: None + """ + editor.ToolsApplicationRequestBus(bus.Broadcast, "DeleteEntityById", self.id) + + def set_visibility_state(self, is_visible: bool) -> None: + """ + Sets the visibility state on the object to visible or not visible. + :param is_visible: True for making visible, False to make not visible. + :return: None + """ + editor.EditorEntityAPIBus(bus.Event, "SetVisibilityState", self.id, is_visible) + + def exists(self) -> bool: + """ + Used to verify if the Entity exists. + :return: True if the Entity exists, False otherwise. + """ + return editor.ToolsApplicationRequestBus(bus.Broadcast, "EntityExists", self.id) + + def is_hidden(self) -> bool: + """ + Gets the "isHidden" value from the Entity. + :return: True if "isHidden" is enabled, False otherwise. + """ + return editor.EditorEntityInfoRequestBus(bus.Event, "IsHidden", self.id) + + def is_visible(self) -> bool: + """ + Gets the "isVisible" value from the Entity. + :return: True if "isVisible" is enabled, False otherwise. + """ + return editor.EditorEntityInfoRequestBus(bus.Event, "IsVisible", self.id) diff --git a/AutomatedTesting/Gem/PythonTests/EditorPythonTestTools/editor_python_test_tools/hydra_test_utils.py b/AutomatedTesting/Gem/PythonTests/EditorPythonTestTools/editor_python_test_tools/hydra_test_utils.py index 3d4d9ea419..54bc118f48 100644 --- a/AutomatedTesting/Gem/PythonTests/EditorPythonTestTools/editor_python_test_tools/hydra_test_utils.py +++ b/AutomatedTesting/Gem/PythonTests/EditorPythonTestTools/editor_python_test_tools/hydra_test_utils.py @@ -81,7 +81,8 @@ def launch_and_validate_results(request, test_directory, editor, editor_script, def launch_and_validate_results_launcher(launcher, level, remote_console_instance, expected_lines, null_renderer=True, - port_listener_timeout=120, log_monitor_timeout=300, remote_console_port=4600): + port_listener_timeout=120, log_monitor_timeout=300, remote_console_port=4600, + launch_ap=True): """ Runs the launcher with the specified level, and monitors Game.log for expected lines. :param launcher: Configured launcher object to run test against. @@ -92,6 +93,7 @@ def launch_and_validate_results_launcher(launcher, level, remote_console_instanc :param port_listener_timeout: Timeout for verifying successful connection to Remote Console. :param log_monitor_timeout: Timeout for monitoring for lines in Game.log :param remote_console_port: The port used to communicate with the Remote Console. + :param launch_ap: Whether or not to launch AP. Defaults to True. """ def _check_for_listening_port(port): @@ -110,7 +112,7 @@ def launch_and_validate_results_launcher(launcher, level, remote_console_instanc launcher.args.extend(["-rhi=Null"]) # Start the Launcher - with launcher.start(): + with launcher.start(launch_ap=launch_ap): # Ensure Remote Console can be reached waiter.wait_for( diff --git a/AutomatedTesting/Gem/PythonTests/atom_renderer/test_Atom_ShaderBuildPipelineSuite.py b/AutomatedTesting/Gem/PythonTests/atom_renderer/test_Atom_ShaderBuildPipelineSuite.py deleted file mode 100644 index 9ef93ea238..0000000000 --- a/AutomatedTesting/Gem/PythonTests/atom_renderer/test_Atom_ShaderBuildPipelineSuite.py +++ /dev/null @@ -1,19 +0,0 @@ -""" -Copyright (c) Contributors to the Open 3D Engine Project. -For complete copyright and license terms please see the LICENSE at the root of this distribution. - -SPDX-License-Identifier: Apache-2.0 OR MIT - -Main suite tests for the Shader Build Pipeline. -""" -import pytest -from ly_test_tools import LAUNCHERS -from ly_test_tools.o3de.editor_test import EditorTestSuite, EditorSingleTest - -@pytest.mark.parametrize("project", ["AutomatedTesting"]) -@pytest.mark.parametrize("launcher_platform", ['windows_editor']) -class TestShaderBuildPipelineMain(EditorTestSuite): - """Holds tests for Shader Build Pipeline validation""" - - class ShaderAssetBuilder_RecompilesShaderAsChainOfDependenciesChanges(EditorSingleTest): - from .atom_hydra_scripts import hydra_ShaderAssetBuilder_RecompilesShaderAsChainOfDependenciesChanges as test_module \ No newline at end of file diff --git a/AutomatedTesting/Gem/PythonTests/largeworlds/CMakeLists.txt b/AutomatedTesting/Gem/PythonTests/largeworlds/CMakeLists.txt index b3030e84ac..f1299ddc2d 100644 --- a/AutomatedTesting/Gem/PythonTests/largeworlds/CMakeLists.txt +++ b/AutomatedTesting/Gem/PythonTests/largeworlds/CMakeLists.txt @@ -14,8 +14,7 @@ if(PAL_TRAIT_BUILD_TESTS_SUPPORTED AND PAL_TRAIT_BUILD_HOST_TOOLS AND PAL_TRAIT_ NAME AutomatedTesting::DynamicVegetationTests_Main TEST_SERIAL TEST_SUITE main - PATH ${CMAKE_CURRENT_LIST_DIR}/dyn_veg - PYTEST_MARKS "not SUITE_sandbox and not SUITE_periodic and not SUITE_benchmark" + PATH ${CMAKE_CURRENT_LIST_DIR}/dyn_veg/TestSuite_Main.py RUNTIME_DEPENDENCIES AZ::AssetProcessor Legacy::Editor @@ -27,104 +26,33 @@ if(PAL_TRAIT_BUILD_TESTS_SUPPORTED AND PAL_TRAIT_BUILD_HOST_TOOLS AND PAL_TRAIT_ ly_add_pytest( - NAME AutomatedTesting::DynamicVegetationTests_Sandbox + NAME AutomatedTesting::DynamicVegetationTests_Periodic TEST_SERIAL - TEST_SUITE sandbox - PATH ${CMAKE_CURRENT_LIST_DIR}/dyn_veg - PYTEST_MARKS "SUITE_sandbox" + TEST_SUITE periodic + PATH ${CMAKE_CURRENT_LIST_DIR}/dyn_veg/TestSuite_Periodic.py RUNTIME_DEPENDENCIES AZ::AssetProcessor Legacy::Editor + AutomatedTesting.Assets AutomatedTesting.GameLauncher - AutomatedTesting.Assets COMPONENT LargeWorlds ) ly_add_pytest( - NAME AutomatedTesting::DynamicVegetationFilterTests_Periodic + NAME AutomatedTesting::DynamicVegetationTests_Main_Optimized TEST_SERIAL - TEST_SUITE periodic - PATH ${CMAKE_CURRENT_LIST_DIR}/dyn_veg - PYTEST_MARKS "SUITE_periodic and dynveg_filter" + TEST_SUITE main + PATH ${CMAKE_CURRENT_LIST_DIR}/dyn_veg/TestSuite_Main_Optimized.py RUNTIME_DEPENDENCIES - AZ::AssetProcessor - Legacy::Editor - AutomatedTesting.Assets + AZ::AssetProcessor + Legacy::Editor + AutomatedTesting.Assets + AutomatedTesting.GameLauncher COMPONENT LargeWorlds ) - ly_add_pytest( - NAME AutomatedTesting::DynamicVegetationModifierTests_Periodic - TEST_SERIAL - TEST_SUITE periodic - PATH ${CMAKE_CURRENT_LIST_DIR}/dyn_veg - PYTEST_MARKS "SUITE_periodic and dynveg_modifier" - RUNTIME_DEPENDENCIES - AZ::AssetProcessor - Legacy::Editor - AutomatedTesting.Assets - COMPONENT - LargeWorlds - ) - - ly_add_pytest( - NAME AutomatedTesting::DynamicVegetationRegressionTests_Periodic - TEST_SERIAL - TEST_SUITE periodic - PATH ${CMAKE_CURRENT_LIST_DIR}/dyn_veg - PYTEST_MARKS "SUITE_periodic and dynveg_regression" - RUNTIME_DEPENDENCIES - AZ::AssetProcessor - Legacy::Editor - AutomatedTesting.Assets - COMPONENT - LargeWorlds - ) - - ly_add_pytest( - NAME AutomatedTesting::DynamicVegetationAreaTests_Periodic - TEST_SERIAL - TEST_SUITE periodic - PATH ${CMAKE_CURRENT_LIST_DIR}/dyn_veg - PYTEST_MARKS "SUITE_periodic and dynveg_area" - RUNTIME_DEPENDENCIES - AZ::AssetProcessor - Legacy::Editor - AutomatedTesting.Assets - COMPONENT - LargeWorlds - ) - - ly_add_pytest( - NAME AutomatedTesting::DynamicVegetationMiscTests_Periodic - TEST_SERIAL - TEST_SUITE periodic - PATH ${CMAKE_CURRENT_LIST_DIR}/dyn_veg - PYTEST_MARKS "SUITE_periodic and dynveg_misc" - RUNTIME_DEPENDENCIES - AZ::AssetProcessor - Legacy::Editor - AutomatedTesting.Assets - COMPONENT - LargeWorlds - ) - - ly_add_pytest( - NAME AutomatedTesting::DynamicVegetationSurfaceTagTests_Periodic - TEST_SERIAL - TEST_SUITE periodic - PATH ${CMAKE_CURRENT_LIST_DIR}/dyn_veg - PYTEST_MARKS "SUITE_periodic and dynveg_surfacetagemitter" - RUNTIME_DEPENDENCIES - AZ::AssetProcessor - Legacy::Editor - AutomatedTesting.Assets - COMPONENT - LargeWorlds - ) - ## LandscapeCanvas ## ly_add_pytest( diff --git a/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/AltitudeFilter_ComponentAndOverrides_InstancesPlantAtSpecifiedAltitude.py b/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/AltitudeFilter_ComponentAndOverrides_InstancesPlantAtSpecifiedAltitude.py index 928d38ac5a..e404624c93 100755 --- a/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/AltitudeFilter_ComponentAndOverrides_InstancesPlantAtSpecifiedAltitude.py +++ b/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/AltitudeFilter_ComponentAndOverrides_InstancesPlantAtSpecifiedAltitude.py @@ -5,119 +5,119 @@ For complete copyright and license terms please see the LICENSE at the root of t SPDX-License-Identifier: Apache-2.0 OR MIT """ -""" -C4814463 - Altitude Filter overrides function as expected -C4847477 - Altitude Min/Max can be manually set -""" -import os -import sys - -sys.path.append(os.path.dirname(os.path.abspath(__file__))) -import azlmbr.editor as editor -import azlmbr.legacy.general as general -import azlmbr.bus as bus -import azlmbr.math as math -import azlmbr.paths - -sys.path.append(os.path.join(azlmbr.paths.devroot, 'AutomatedTesting', 'Gem', 'PythonTests')) -import editor_python_test_tools.hydra_editor_utils as hydra -from editor_python_test_tools.editor_test_helper import EditorTestHelper -from largeworlds.large_worlds_utils import editor_dynveg_test_helper as dynveg +class Tests: + prefilter_instance_count = ( + "Pre-filter instance counts are accurate", + "Unexpected number of pre-filter instances found" + ) + postfilter_instance_count = ( + "Post-filter instance counts are accurate", + "Unexpected number of post-filter instances found" + ) + postfilter_overrides_instance_count = ( + "Override instance counts are accurate", + "Unexpected number of override instances found" + ) -class TestAltitudeFilterComponentAndOverrides(EditorTestHelper): - def __init__(self): - EditorTestHelper.__init__(self, log_prefix="AltitudeFilterComponentAndOverrides", args=["level"]) +def AltitudeFilter_ComponentAndOverrides_InstancesPlantAtSpecifiedAltitude(): + """ + Summary: + A new level is created. A spawner entity is added, along with a planting surface at 32 on Z, and another at 36 + on Z. An Altitude Filter is added to the spawner entity, and Altitude Min/Max values are set. Instance counts + are validated. The same test is then performed for Altitude Filter overrides. - def run_test(self): - """ - Summary: - A new level is created. A spawner entity is added, along with a planting surface at 32 on Z, and another at 36 - on Z. An Altitude Filter is added to the spawner entity, and Altitude Min/Max values are set. Instance counts - are validated. The same test is then performed for Altitude Filter overrides. + Expected Behavior: + Instances are only spawned within the specified altitude ranges. - Expected Behavior: - Instances are only spawned within the specified altitude ranges. + Test Steps: + 1) Open a simple level + 2) Create an instance spawner entity + 3) Create surfaces to plant on, one at 32 on Z and another at 36 on Z. + 4) Initial instance counts pre-filter are verified. + 5) Altitude Min/Max is set on the Vegetation Altitude Filter component. + 6) Instance counts post-filter are verified. + 7) Altitude Min/Max is set on descriptor overrides. + 8) Instance counts post-filter are verified. - Test Steps: - 1) Create a new level - 2) Create an instance spawner entity - 3) Create surfaces to plant on, one at 32 on Z and another at 36 on Z. - 4) Initial instance counts pre-filter are verified. - 5) Altitude Min/Max is set on the Vegetation Altitude Filter component. - 6) Instance counts post-filter are verified. - 7) Altitude Min/Max is set on descriptor overrides. - 8) Instance counts post-filter are verified. + 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. - 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 + """ - :return: None - """ + import os - # 1) Create a new, temporary level - self.test_success = self.create_level( - self.args["level"], - heightmap_resolution=1024, - heightmap_meters_per_pixel=1, - terrain_texture_resolution=4096, - use_terrain=False, - ) + import azlmbr.editor as editor + import azlmbr.legacy.general as general + import azlmbr.bus as bus + import azlmbr.math as math - # Set view of planting area for visual debugging - general.set_current_view_position(512.0, 500.0, 38.0) - general.set_current_view_rotation(-20.0, 0.0, 0.0) + import editor_python_test_tools.hydra_editor_utils as hydra + from largeworlds.large_worlds_utils import editor_dynveg_test_helper as dynveg + from editor_python_test_tools.utils import Report + from editor_python_test_tools.utils import TestHelper as helper - # 2) Create a new entity with required vegetation area components - center_point = math.Vector3(512.0, 512.0, 32.0) - asset_path = os.path.join("Slices", "PinkFlower.dynamicslice") - spawner_entity = dynveg.create_vegetation_area("Instance Spawner", center_point, 32.0, 32.0, 32.0, asset_path) + # 1) Open an existing simple level + helper.init_idle() + helper.open_level("Physics", "Base") - # Add a Vegetation Altitude Filter - spawner_entity.add_component("Vegetation Altitude Filter") + # Set view of planting area for visual debugging + general.set_current_view_position(512.0, 500.0, 38.0) + general.set_current_view_rotation(-20.0, 0.0, 0.0) - # 3) Add surfaces to plant on - dynveg.create_surface_entity("Planting Surface", center_point, 32.0, 32.0, 1.0) - elevated_surface_center_point = math.Vector3(512.0, 512.0, 36.0) - dynveg.create_surface_entity("Planting Surface Elevated", elevated_surface_center_point, 32.0, 32.0, 1.0) + # 2) Create a new entity with required vegetation area components + center_point = math.Vector3(512.0, 512.0, 32.0) + asset_path = os.path.join("Slices", "PinkFlower.dynamicslice") + spawner_entity = dynveg.create_vegetation_area("Instance Spawner", center_point, 32.0, 32.0, 32.0, asset_path) - # Set instances to spawn on a center snap point to avoid unexpected instances around the edges of the box shape - veg_system_settings_component = hydra.add_level_component("Vegetation System Settings") - editor.EditorComponentAPIBus(bus.Broadcast, "SetComponentProperty", veg_system_settings_component, - 'Configuration|Area System Settings|Sector Point Snap Mode', 1) + # Add a Vegetation Altitude Filter + spawner_entity.add_component("Vegetation Altitude Filter") - # 4) Verify initial instance counts pre-filter - num_expected = (40 * 40) * 2 # 20 instances per 16m per side x 2 surfaces - spawner_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 spawner_success + # 3) Add surfaces to plant on + dynveg.create_surface_entity("Planting Surface", center_point, 32.0, 32.0, 1.0) + elevated_surface_center_point = math.Vector3(512.0, 512.0, 36.0) + dynveg.create_surface_entity("Planting Surface Elevated", elevated_surface_center_point, 32.0, 32.0, 1.0) - # 5) Set min/max vegetation altitude, instances should now only appear between 35-37m on the Z-axis - spawner_entity.get_set_test(3, "Configuration|Altitude Min", 35) - spawner_entity.get_set_test(3, "Configuration|Altitude Max", 37) + # Set instances to spawn on a center snap point to avoid unexpected instances around the edges of the box shape + veg_system_settings_component = hydra.add_level_component("Vegetation System Settings") + editor.EditorComponentAPIBus(bus.Broadcast, "SetComponentProperty", veg_system_settings_component, + 'Configuration|Area System Settings|Sector Point Snap Mode', 1) - # 6) Validate expected instance counts - num_expected = 40 * 40 # Instances should now only plant on the elevated surface - altitude_min_max_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 altitude_min_max_success + # 4) Verify initial instance counts pre-filter + num_expected = (40 * 40) * 2 # 20 instances per 16m per side x 2 surfaces + spawner_success = helper.wait_for_condition(lambda: dynveg.validate_instance_count_in_entity_shape(spawner_entity.id, num_expected), 5.0) + Report.result(Tests.prefilter_instance_count, spawner_success) - # Resize Spawner Entity's Box Shape component to allow monitoring for a different instance count - box_size = math.Vector3(16.0, 16.0, 16.0) - spawner_entity.get_set_test(1, "Box Shape|Box Configuration|Dimensions", box_size) + # 5) Set min/max vegetation altitude, instances should now only appear between 35-37m on the Z-axis + spawner_entity.get_set_test(3, "Configuration|Altitude Min", 35) + spawner_entity.get_set_test(3, "Configuration|Altitude Max", 37) - # 7) Allow overrides on Altitude Filter and set Altitude Filter Min/Max overrides on descriptor - spawner_entity.get_set_test(3, "Configuration|Allow Per-Item Overrides", True) - spawner_entity.get_set_test(2, "Configuration|Embedded Assets|[0]|Altitude Filter|Override Enabled", True) - spawner_entity.get_set_test(2, "Configuration|Embedded Assets|[0]|Altitude Filter|Min", 35) - spawner_entity.get_set_test(2, "Configuration|Embedded Assets|[0]|Altitude Filter|Max", 37) + # 6) Validate expected instance counts + num_expected = 40 * 40 # Instances should now only plant on the elevated surface + altitude_min_max_success = helper.wait_for_condition(lambda: dynveg.validate_instance_count_in_entity_shape(spawner_entity.id, num_expected), 5.0) + Report.result(Tests.postfilter_instance_count, altitude_min_max_success) - # 8) Validate expected instances at specified elevations - num_expected = 20 * 20 # 20 instances per 16m per side - overrides_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 overrides_success + # Resize Spawner Entity's Box Shape component to allow monitoring for a different instance count + box_size = math.Vector3(16.0, 16.0, 16.0) + spawner_entity.get_set_test(1, "Box Shape|Box Configuration|Dimensions", box_size) + + # 7) Allow overrides on Altitude Filter and set Altitude Filter Min/Max overrides on descriptor + spawner_entity.get_set_test(3, "Configuration|Allow Per-Item Overrides", True) + spawner_entity.get_set_test(2, "Configuration|Embedded Assets|[0]|Altitude Filter|Override Enabled", True) + spawner_entity.get_set_test(2, "Configuration|Embedded Assets|[0]|Altitude Filter|Min", 35) + spawner_entity.get_set_test(2, "Configuration|Embedded Assets|[0]|Altitude Filter|Max", 37) + + # 8) Validate expected instances at specified elevations + num_expected = 20 * 20 # 20 instances per 16m per side + overrides_success = helper.wait_for_condition(lambda: dynveg.validate_instance_count_in_entity_shape(spawner_entity.id, num_expected), 5.0) + Report.result(Tests.postfilter_overrides_instance_count, overrides_success) -test = TestAltitudeFilterComponentAndOverrides() -test.run() +if __name__ == "__main__": + + from editor_python_test_tools.utils import Report + Report.start_test(AltitudeFilter_ComponentAndOverrides_InstancesPlantAtSpecifiedAltitude) diff --git a/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/AltitudeFilter_FilterStageToggle.py b/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/AltitudeFilter_FilterStageToggle.py index 2ef72f72eb..3fc6a0afde 100755 --- a/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/AltitudeFilter_FilterStageToggle.py +++ b/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/AltitudeFilter_FilterStageToggle.py @@ -5,90 +5,88 @@ For complete copyright and license terms please see the LICENSE at the root of t SPDX-License-Identifier: Apache-2.0 OR MIT """ -import os -import sys -import azlmbr.bus as bus -import azlmbr.components as components -import azlmbr.editor as editor -import azlmbr.legacy.general as general -import azlmbr.math as math -import azlmbr.paths - -sys.path.append(os.path.join(azlmbr.paths.devroot, "AutomatedTesting", "Gem", "PythonTests")) -import editor_python_test_tools.hydra_editor_utils as hydra -from editor_python_test_tools.editor_test_helper import EditorTestHelper -from largeworlds.large_worlds_utils import editor_dynveg_test_helper as dynveg +class Tests: + preprocess_instance_count = ( + "Pre-process instance counts are accurate", + "Unexpected number of pre-process instances found" + ) + postprocess_instance_count = ( + "Post-process instance counts are accurate", + "Unexpected number of post-process instances found" + ) -class TestAltitudeFilterFilterStageToggle(EditorTestHelper): - def __init__(self): - EditorTestHelper.__init__(self, log_prefix="AltitudeFilter_FilterStageToggle", args=["level"]) +def AltitudeFilter_FilterStageToggle(): + """ + Summary: + Filter Stage toggle affects final vegetation position - def run_test(self): - """ - Summary: - Filter Stage toggle affects final vegetation position + Expected Result: + Vegetation instances plant differently depending on the Filter Stage setting. + PostProcess should cause some number of plants that appear above and below the desired altitude range to disappear. - Expected Result: - Vegetation instances plant differently depending on the Filter Stage setting. - PostProcess should cause some number of plants that appear above and below the desired altitude range to disappear. + :return: None + """ - :return: None - """ + import os - PREPROCESS_INSTANCE_COUNT = 44 - POSTPROCESS_INSTANCE_COUNT = 34 + import azlmbr.legacy.general as general + import azlmbr.math as math - # Create empty level - self.test_success = self.create_level( - self.args["level"], - heightmap_resolution=1024, - heightmap_meters_per_pixel=1, - terrain_texture_resolution=4096, - use_terrain=False, - ) + import editor_python_test_tools.hydra_editor_utils as hydra + from largeworlds.large_worlds_utils import editor_dynveg_test_helper as dynveg + from editor_python_test_tools.utils import Report + from editor_python_test_tools.utils import TestHelper as helper - general.set_current_view_position(512.0, 480.0, 38.0) + PREPROCESS_INSTANCE_COUNT = 44 + POSTPROCESS_INSTANCE_COUNT = 34 - # Create basic vegetation entity - position = math.Vector3(512.0, 512.0, 32.0) - asset_path = os.path.join("Slices", "PinkFlower.dynamicslice") - vegetation = dynveg.create_vegetation_area("vegetation", position, 16.0, 16.0, 16.0, asset_path) + # Open an existing simple level + helper.init_idle() + helper.open_level("Physics", "Base") + general.set_current_view_position(512.0, 480.0, 38.0) - # Add a Vegetation Altitude Filter to the vegetation area entity - vegetation.add_component("Vegetation Altitude Filter") + # Create basic vegetation entity + position = math.Vector3(512.0, 512.0, 32.0) + asset_path = os.path.join("Slices", "PinkFlower.dynamicslice") + vegetation = dynveg.create_vegetation_area("vegetation", position, 16.0, 16.0, 16.0, asset_path) - # Create Surface for instances to plant on - dynveg.create_surface_entity("Surface_Entity_Parent", position, 16.0, 16.0, 1.0) + # Add a Vegetation Altitude Filter to the vegetation area entity + vegetation.add_component("Vegetation Altitude Filter") - # Add entity with Mesh to replicate creation of hills - hill_entity = dynveg.create_mesh_surface_entity_with_slopes("hill", position, 10.0) + # Create Surface for instances to plant on + dynveg.create_surface_entity("Surface_Entity_Parent", position, 16.0, 16.0, 1.0) - # Set a Min Altitude of 38 and Max of 40 in Vegetation Altitude Filter - vegetation.get_set_test(3, "Configuration|Altitude Min", 38.0) - vegetation.get_set_test(3, "Configuration|Altitude Max", 40.0) + # Add entity with Mesh to replicate creation of hills + hill_entity = dynveg.create_mesh_surface_entity_with_slopes("hill", position, 10.0) - # Create a new entity as a child of the vegetation area entity with Random Noise Gradient Generator, Gradient - # Transform Modifier, and Box Shape component - random_noise = hydra.Entity("random_noise") - random_noise.create_entity(position, ["Random Noise Gradient", "Gradient Transform Modifier", "Box Shape"]) - random_noise.set_test_parent_entity(vegetation) + # Set a Min Altitude of 38 and Max of 40 in Vegetation Altitude Filter + vegetation.get_set_test(3, "Configuration|Altitude Min", 38.0) + vegetation.get_set_test(3, "Configuration|Altitude Max", 40.0) - # Add a Vegetation Position Modifier to the vegetation area entity. - vegetation.add_component("Vegetation Position Modifier") + # Create a new entity as a child of the vegetation area entity with Random Noise Gradient Generator, Gradient + # Transform Modifier, and Box Shape component + random_noise = hydra.Entity("random_noise") + random_noise.create_entity(position, ["Random Noise Gradient", "Gradient Transform Modifier", "Box Shape"]) + random_noise.set_test_parent_entity(vegetation) - # Pin the Random Noise entity to the Gradient Entity Id field of the Position Modifier's Gradient X - vegetation.get_set_test(4, "Configuration|Position X|Gradient|Gradient Entity Id", random_noise.id) + # Add a Vegetation Position Modifier to the vegetation area entity. + vegetation.add_component("Vegetation Position Modifier") - # Toggle between PreProcess and PostProcess in Vegetation Altitude Filter - vegetation.get_set_test(3, "Configuration|Filter Stage", 1) - result = self.wait_for_condition(lambda: dynveg.validate_instance_count(position, 30.0, PREPROCESS_INSTANCE_COUNT), 2.0) - self.log(f"Vegetation instances count equal to expected value for PREPROCESS filter stage: {result}") - vegetation.get_set_test(3, "Configuration|Filter Stage", 2) - result = self.wait_for_condition(lambda: dynveg.validate_instance_count(position, 30.0, POSTPROCESS_INSTANCE_COUNT), 2.0) - self.log(f"Vegetation instances count equal to expected value for POSTPROCESS filter stage: {result}") + # Pin the Random Noise entity to the Gradient Entity Id field of the Position Modifier's Gradient X + vegetation.get_set_test(4, "Configuration|Position X|Gradient|Gradient Entity Id", random_noise.id) + + # Toggle between PreProcess and PostProcess in Vegetation Altitude Filter + vegetation.get_set_test(3, "Configuration|Filter Stage", 1) + result = helper.wait_for_condition(lambda: dynveg.validate_instance_count(position, 30.0, PREPROCESS_INSTANCE_COUNT), 2.0) + Report.result(Tests.preprocess_instance_count, result) + vegetation.get_set_test(3, "Configuration|Filter Stage", 2) + result = helper.wait_for_condition(lambda: dynveg.validate_instance_count(position, 30.0, POSTPROCESS_INSTANCE_COUNT), 2.0) + Report.result(Tests.postprocess_instance_count, result) -test = TestAltitudeFilterFilterStageToggle() -test.run() +if __name__ == "__main__": + + from editor_python_test_tools.utils import Report + Report.start_test(AltitudeFilter_FilterStageToggle) diff --git a/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/AltitudeFilter_ShapeSample_InstancesPlantAtSpecifiedAltitude.py b/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/AltitudeFilter_ShapeSample_InstancesPlantAtSpecifiedAltitude.py index 8139ec5cac..bcd42b7fbb 100755 --- a/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/AltitudeFilter_ShapeSample_InstancesPlantAtSpecifiedAltitude.py +++ b/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/AltitudeFilter_ShapeSample_InstancesPlantAtSpecifiedAltitude.py @@ -5,104 +5,105 @@ For complete copyright and license terms please see the LICENSE at the root of t SPDX-License-Identifier: Apache-2.0 OR MIT """ -import os -import sys -sys.path.append(os.path.dirname(os.path.abspath(__file__))) -import azlmbr.editor as editor -import azlmbr.legacy.general as general -import azlmbr.bus as bus -import azlmbr.math as math -import azlmbr.paths - -sys.path.append(os.path.join(azlmbr.paths.devroot, 'AutomatedTesting', 'Gem', 'PythonTests')) -import editor_python_test_tools.hydra_editor_utils as hydra -from editor_python_test_tools.editor_test_helper import EditorTestHelper -from largeworlds.large_worlds_utils import editor_dynveg_test_helper as dynveg +class Tests: + prefilter_instance_count = ( + "Pre-filter instance counts are accurate", + "Unexpected number of pre-filter instances found" + ) + postfilter_instance_count = ( + "Post-filter instance counts are accurate", + "Unexpected number of post-filter instances found" + ) -class TestAltitudeFilterShapeSample(EditorTestHelper): - def __init__(self): - EditorTestHelper.__init__(self, log_prefix="AltitudeFilterShapeSample", args=["level"]) +def AltitudeFilter_ShapeSample_InstancesPlantAtSpecifiedAltitude(): + """ + Summary: + A new level is created. A spawner entity is added, along with a planting surface at 32 on Z, and another at 36 + on Z. An Altitude Filter is added to the spawner entity, and set to sample a shape entity. Instance counts are + validated. - def run_test(self): - """ - Summary: - A new level is created. A spawner entity is added, along with a planting surface at 32 on Z, and another at 36 - on Z. An Altitude Filter is added to the spawner entity, and set to sample a shape entity. Instance counts are - validated. + Expected Behavior: + Instances are only spawned within the altitude range specified by the sampled shape. - Expected Behavior: - Instances are only spawned within the altitude range specified by the sampled shape. + Test Steps: + 1) Open a simple level + 2) Create an instance spawner entity + 3) Create surfaces to plant on, one at 32 on Z and another at 36 on Z. + 4) Initial instance counts pre-filter are verified. + 5) A new entity with shape is created, an sampled on the Vegetation Altitude Filter. + 6) Instance counts post-filter are verified. - Test Steps: - 1) Create a new level - 2) Create an instance spawner entity - 3) Create surfaces to plant on, one at 32 on Z and another at 36 on Z. - 4) Initial instance counts pre-filter are verified. - 5) A new entity with shape is created, an sampled on the Vegetation Altitude Filter. - 6) Instance counts post-filter are verified. + 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. - 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 + """ - :return: None - """ + import os - # 1) Create a new, temporary level - self.test_success = self.create_level( - self.args["level"], - heightmap_resolution=1024, - heightmap_meters_per_pixel=1, - terrain_texture_resolution=4096, - use_terrain=False, - ) + import azlmbr.editor as editor + import azlmbr.legacy.general as general + import azlmbr.bus as bus + import azlmbr.math as math - # Set view of planting area for visual debugging - general.set_current_view_position(512.0, 500.0, 38.0) - general.set_current_view_rotation(-20.0, 0.0, 0.0) + import editor_python_test_tools.hydra_editor_utils as hydra + from largeworlds.large_worlds_utils import editor_dynveg_test_helper as dynveg + from editor_python_test_tools.utils import Report + from editor_python_test_tools.utils import TestHelper as helper - # 2) Create a new entity with required vegetation area components - center_point = math.Vector3(512.0, 512.0, 32.0) - asset_path = os.path.join("Slices", "PinkFlower.dynamicslice") - spawner_entity = dynveg.create_vegetation_area("Instance Spawner", center_point, 16.0, 16.0, 16.0, asset_path) + # 1) Open an existing simple level + helper.init_idle() + helper.open_level("Physics", "Base") - # Add a Vegetation Altitude Filter - spawner_entity.add_component("Vegetation Altitude Filter") + # Set view of planting area for visual debugging + general.set_current_view_position(512.0, 500.0, 38.0) + general.set_current_view_rotation(-20.0, 0.0, 0.0) - # 3) Add surfaces to plant on - dynveg.create_surface_entity("Planting Surface", center_point, 32.0, 32.0, 1.0) - elevated_surface_center_point = math.Vector3(512.0, 512.0, 36.0) - dynveg.create_surface_entity("Planting Surface Elevated", elevated_surface_center_point, 32.0, 32.0, 1.0) + # 2) Create a new entity with required vegetation area components + center_point = math.Vector3(512.0, 512.0, 32.0) + asset_path = os.path.join("Slices", "PinkFlower.dynamicslice") + spawner_entity = dynveg.create_vegetation_area("Instance Spawner", center_point, 16.0, 16.0, 16.0, asset_path) - # Set instances to spawn on a center snap point to avoid unexpected instances around the edges of the box shape - veg_system_settings_component = hydra.add_level_component("Vegetation System Settings") - editor.EditorComponentAPIBus(bus.Broadcast, "SetComponentProperty", veg_system_settings_component, - 'Configuration|Area System Settings|Sector Point Snap Mode', 1) + # Add a Vegetation Altitude Filter + spawner_entity.add_component("Vegetation Altitude Filter") - # 4) Verify initial instance counts pre-filter - num_expected = (20 * 20) * 2 # 20 instances per 16m per side x 2 surfaces - spawner_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 spawner_success + # 3) Add surfaces to plant on + dynveg.create_surface_entity("Planting Surface", center_point, 32.0, 32.0, 1.0) + elevated_surface_center_point = math.Vector3(512.0, 512.0, 36.0) + dynveg.create_surface_entity("Planting Surface Elevated", elevated_surface_center_point, 32.0, 32.0, 1.0) - # 5) Create a new entity with a shape at 36 on the Z-axis, and pin the entity to the Vegetation Altitude Filter - shape_sampler_center_point = math.Vector3(512.0, 512.0, 36.0) - shape_sampler = hydra.Entity("Shape Sampler") - shape_sampler.create_entity( - shape_sampler_center_point, - ["Box Shape"] - ) - if shape_sampler.id.IsValid(): - print(f"'{shape_sampler.name}' created") - spawner_entity.get_set_test(3, 'Configuration|Pin To Shape Entity Id', shape_sampler.id) + # Set instances to spawn on a center snap point to avoid unexpected instances around the edges of the box shape + veg_system_settings_component = hydra.add_level_component("Vegetation System Settings") + editor.EditorComponentAPIBus(bus.Broadcast, "SetComponentProperty", veg_system_settings_component, + 'Configuration|Area System Settings|Sector Point Snap Mode', 1) - # 6) Validate expected instance counts - num_expected = 20 * 20 # Instances should now only plant on the elevated surface - sampler_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 sampler_success + # 4) Verify initial instance counts pre-filter + num_expected = (20 * 20) * 2 # 20 instances per 16m per side x 2 surfaces + spawner_success = helper.wait_for_condition(lambda: dynveg.validate_instance_count_in_entity_shape(spawner_entity.id, num_expected), 5.0) + Report.result(Tests.prefilter_instance_count, spawner_success) + + # 5) Create a new entity with a shape at 36 on the Z-axis, and pin the entity to the Vegetation Altitude Filter + shape_sampler_center_point = math.Vector3(512.0, 512.0, 36.0) + shape_sampler = hydra.Entity("Shape Sampler") + shape_sampler.create_entity( + shape_sampler_center_point, + ["Box Shape"] + ) + if shape_sampler.id.IsValid(): + print(f"'{shape_sampler.name}' created") + spawner_entity.get_set_test(3, 'Configuration|Pin To Shape Entity Id', shape_sampler.id) + + # 6) Validate expected instance counts + num_expected = 20 * 20 # Instances should now only plant on the elevated surface + sampler_success = helper.wait_for_condition(lambda: dynveg.validate_instance_count_in_entity_shape(spawner_entity.id, num_expected), 5.0) + Report.result(Tests.postfilter_instance_count, sampler_success) -test = TestAltitudeFilterShapeSample() -test.run() +if __name__ == "__main__": + + from editor_python_test_tools.utils import Report + Report.start_test(AltitudeFilter_ShapeSample_InstancesPlantAtSpecifiedAltitude) diff --git a/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/AreaComponentSlices_SliceCreationAndVisibilityToggle.py b/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/AreaComponentSlices_SliceCreationAndVisibilityToggle.py deleted file mode 100755 index 095024cca1..0000000000 --- a/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/AreaComponentSlices_SliceCreationAndVisibilityToggle.py +++ /dev/null @@ -1,125 +0,0 @@ -""" -Copyright (c) Contributors to the Open 3D Engine Project. -For complete copyright and license terms please see the LICENSE at the root of this distribution. - -SPDX-License-Identifier: Apache-2.0 OR MIT -""" - -import os -import sys - -import azlmbr.math as math -import azlmbr.legacy.general as general -import azlmbr.slice as slice -import azlmbr.bus as bus -import azlmbr.editor as editor -import azlmbr.asset as asset -import azlmbr.paths - -sys.path.append(os.path.join(azlmbr.paths.devroot, "AutomatedTesting", "Gem", "PythonTests")) -import editor_python_test_tools.hydra_editor_utils as hydra -from editor_python_test_tools.editor_test_helper import EditorTestHelper -from largeworlds.large_worlds_utils import editor_dynveg_test_helper as dynveg - - -class TestAreaComponentsSliceCreationAndVisibilityToggle(EditorTestHelper): - def __init__(self): - EditorTestHelper.__init__( - self, log_prefix="AreaComponentSlices_SliceCreationAndVisibilityToggle", args=["level"] - ) - - def run_test(self): - """ - Summary: - C2627900 Verifies if a slice containing the component can be created. - C2627905 A slice containing the Vegetation Layer Blender component can be created. - C2627904: Hiding a slice containing the component clears any visuals from the Viewport. - - Expected Result: - C2627900, C2627905: Slice is created, and is properly processed in the Asset Processor. - C2627904: Vegetation area visuals are hidden from the Viewport. - - :return: None - """ - - def path_is_valid_asset(asset_path): - asset_id = asset.AssetCatalogRequestBus(bus.Broadcast, "GetAssetIdByPath", asset_path, math.Uuid(), False) - return asset_id.invoke("IsValid") - - # 1) Create empty level - self.test_success = self.create_level( - self.args["level"], - heightmap_resolution=1024, - heightmap_meters_per_pixel=1, - terrain_texture_resolution=4096, - use_terrain=False, - ) - - general.set_current_view_position(512.0, 480.0, 38.0) - - # 2) C2627900 Verifies if a slice containing the Vegetation Layer Spawner component can be created. - # 2.1) Create basic vegetation entity - position = math.Vector3(512.0, 512.0, 32.0) - asset_path = os.path.join("Slices", "PinkFlower.dynamicslice") - veg_1 = dynveg.create_vegetation_area("vegetation_1", position, 16.0, 16.0, 16.0, asset_path) - - # 2.2) Create slice from the entity - slice_path = os.path.join("slices", "TestSlice_1.slice") - slice.SliceRequestBus(bus.Broadcast, "CreateNewSlice", veg_1.id, slice_path) - - # 2.3) Verify if the slice has been created successfully - self.wait_for_condition(lambda: path_is_valid_asset(slice_path), 5.0) - self.log( - f"Slice has been created successfully (entity with spawner component): {path_is_valid_asset(slice_path)}" - ) - - # 3) C2627904: Hiding a slice containing the component clears any visuals from the Viewport - # 3.1) Create Surface for instances to plant on - dynveg.create_surface_entity("Surface_Entity", position, 16.0, 16.0, 1.0) - - # 3.2) Initially verify instance count before hiding slice - self.wait_for_condition(lambda: dynveg.validate_instance_count(position, 16.0, 400)) - self.log( - f"Vegetation plants initially when slice is shown: {dynveg.validate_instance_count(position, 16.0, 400)}" - ) - - # 3.3) Hide the slice and verify instance count - editor.EditorEntityAPIBus(bus.Event, "SetVisibilityState", veg_1.id, False) - self.wait_for_condition(lambda: dynveg.validate_instance_count(position, 16.0, 0)) - self.log(f"Vegetation is cleared when slice is hidden: {dynveg.validate_instance_count(position, 16.0, 0)}") - - # 3.4) Unhide the slice - editor.EditorEntityAPIBus(bus.Event, "SetVisibilityState", veg_1.id, True) - - # 4) C2627905 A slice containing the Vegetation Layer Blender component can be created. - # 4.1) Create another vegetation entity to add to blender component - veg_2 = dynveg.create_vegetation_area("vegetation_2", position, 1.0, 1.0, 1.0, "") - - # 4.2) Create entity with Vegetation Layer Blender - components_to_add = ["Box Shape", "Vegetation Layer Blender"] - blender_entity = hydra.Entity("blender_entity") - blender_entity.create_entity(position, components_to_add) - - # 4.3) Pin both the vegetation areas to the blender entity - pte = hydra.get_property_tree(blender_entity.components[1]) - path = "Configuration|Vegetation Areas" - pte.update_container_item(path, 0, veg_1.id) - pte.add_container_item(path, 1, veg_2.id) - - # 4.4) Drag the simple vegetation areas under the Vegetation Layer Blender entity to create an entity hierarchy. - veg_1.set_test_parent_entity(blender_entity) - veg_2.set_test_parent_entity(blender_entity) - - # 4.5) Create slice from blender entity - slice_path = os.path.join("slices", "TestSlice_2.slice") - slice.SliceRequestBus(bus.Broadcast, "CreateNewSlice", blender_entity.id, slice_path) - - # 4.6) Verify if the slice has been created successfully - self.wait_for_condition(lambda: path_is_valid_asset(slice_path), 5.0) - self.log( - f"Slice has been created successfully (entity with blender component): {path_is_valid_asset(slice_path)}" - ) - - -test = TestAreaComponentsSliceCreationAndVisibilityToggle() -test.run() diff --git a/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/AssetListCombiner_CombinedDescriptorsExpressInConfiguredArea.py b/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/AssetListCombiner_CombinedDescriptorsExpressInConfiguredArea.py index 5242160b35..7f6ce87110 100755 --- a/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/AssetListCombiner_CombinedDescriptorsExpressInConfiguredArea.py +++ b/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/AssetListCombiner_CombinedDescriptorsExpressInConfiguredArea.py @@ -5,162 +5,167 @@ For complete copyright and license terms please see the LICENSE at the root of t SPDX-License-Identifier: Apache-2.0 OR MIT """ -import os -import sys -sys.path.append(os.path.dirname(os.path.abspath(__file__))) -import azlmbr.bus as bus -import azlmbr.editor as editor -import azlmbr.legacy.general as general -import azlmbr.math as math -import azlmbr.paths -import azlmbr.vegetation as vegetation - -sys.path.append(os.path.join(azlmbr.paths.devroot, 'AutomatedTesting', 'Gem', 'PythonTests')) -import editor_python_test_tools.hydra_editor_utils as hydra -from editor_python_test_tools.editor_test_helper import EditorTestHelper -from largeworlds.large_worlds_utils import editor_dynveg_test_helper as dynveg +class Tests: + combined_instance_count_validation = ( + "Combined instance counts are as expected", + "Found an unexpected number of instances" + ) + replaced_asset_list_combined_instance_count_validation = ( + "Combined instance counts are as expected after replacing an Asset List reference", + "Found an unexpected number of instances after replacing an Asset List reference" + ) + removed_asset_lists_combined_instance_count_validation = ( + "Instance counts are as expected after removing the referenced Asset Lists", + "Found an unexpected number of instances after removing the referenced Asset Lists" + ) -class TestAssetListCombiner(EditorTestHelper): - def __init__(self): - EditorTestHelper.__init__(self, log_prefix="AssetListCombiner_CombinedDescriptors", args=["level"]) +def AssetListCombiner_CombinedDescriptorsExpressInConfiguredArea(): + """ + Summary: + Combined descriptors appear as expected in a vegetation area. Also verifies remove/replace of assigned Asset + Lists. - def run_test(self): - """ - Summary: - Combined descriptors appear as expected in a vegetation area. Also verifies remove/replace of assigned Asset - Lists. + Expected Behavior: + Vegetation fills in the area using the assets assigned to both Vegetation Asset Lists. - Expected Behavior: - Vegetation fills in the area using the assets assigned to both Vegetation Asset Lists. + Test Steps: + 1) Open a simple level + 2) Create 3 entities with Vegetation Asset List components set to spawn different descriptors + 3) Create a planting surface and add a Vegetation System Settings level component with instances set to spawn + on center instead of corner + 4) Create a spawner using a Vegetation Asset List Combiner component and a Weight Selector, and disallow + spawning empty assets + 5) Add 2 of the Asset List entities to the Vegetation Asset List Combiner component (PinkFlower and Empty) + 6) Create a Constant Gradient entity as a child of the spawner entity, and a Dither Gradient Modifier entity + as a child of the Constant Gradient entity, and configure for a checkerboard pattern + 7) Pin the Dither Gradient Entity to the Asset Weight Selector of the spawner entity + 8) Validate instance count with configured Asset List Combiner + 9) Replace the reference to the 2nd asset list on the Vegetation Asset List Combiner component and validate + instance count + 10) Remove the referenced Asset Lists on the Asset List Combiner, Disable/Re-enable the Asset List + Combiner component to force a refresh, and validate instance count - Test Steps: - 1) Create a new, temporary level - 2) Create 3 entities with Vegetation Asset List components set to spawn different descriptors - 3) Create a planting surface and add a Vegetation System Settings level component with instances set to spawn - on center instead of corner - 4) Create a spawner using a Vegetation Asset List Combiner component and a Weight Selector, and disallow - spawning empty assets - 5) Add 2 of the Asset List entities to the Vegetation Asset List Combiner component (PinkFlower and Empty) - 6) Create a Constant Gradient entity as a child of the spawner entity, and a Dither Gradient Modifier entity - as a child of the Constant Gradient entity, and configure for a checkerboard pattern - 7) Pin the Dither Gradient Entity to the Asset Weight Selector of the spawner entity - 8) Validate instance count with configured Asset List Combiner - 9) Replace the reference to the 2nd asset list on the Vegetation Asset List Combiner component and validate - instance count - 10) Remove the referenced Asset Lists on the Asset List Combiner, Disable/Re-enable the Asset List - Combiner component to force a refresh, and validate instance count + 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. - 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 + """ - :return: None - """ + import os - def create_asset_list_entity(name, center, dynamic_slice_asset_path): - asset_list_entity = hydra.Entity(name) - asset_list_entity.create_entity( - center, - ["Vegetation Asset List"] - ) - if asset_list_entity.id.IsValid(): - print(f"'{asset_list_entity.name}' created") + import azlmbr.bus as bus + import azlmbr.editor as editor + import azlmbr.legacy.general as general + import azlmbr.math as math + import azlmbr.vegetation as vegetation - # Set the Asset List to a Dynamic Slice spawner with a specific slice asset selected - dynamic_slice_spawner = vegetation.DynamicSliceInstanceSpawner() - dynamic_slice_spawner.SetSliceAssetPath(dynamic_slice_asset_path) - descriptor = hydra.get_component_property_value(asset_list_entity.components[0], - "Configuration|Embedded Assets|[0]") - descriptor.spawner = dynamic_slice_spawner - asset_list_entity.get_set_test(0, "Configuration|Embedded Assets|[0]", descriptor) - return asset_list_entity + import editor_python_test_tools.hydra_editor_utils as hydra + from largeworlds.large_worlds_utils import editor_dynveg_test_helper as dynveg + from editor_python_test_tools.utils import Report + from editor_python_test_tools.utils import TestHelper as helper - # 1) Create a new, temporary level - self.test_success = self.create_level( - self.args["level"], - heightmap_resolution=1024, - heightmap_meters_per_pixel=1, - terrain_texture_resolution=4096, - use_terrain=False, + def create_asset_list_entity(name, center, dynamic_slice_asset_path): + asset_list_entity = hydra.Entity(name) + asset_list_entity.create_entity( + center, + ["Vegetation Asset List"] ) + if asset_list_entity.id.IsValid(): + print(f"'{asset_list_entity.name}' created") - # Set view of planting area for visual debugging - general.set_current_view_position(512.0, 500.0, 38.0) - general.set_current_view_rotation(-20.0, 0.0, 0.0) + # Set the Asset List to a Dynamic Slice spawner with a specific slice asset selected + dynamic_slice_spawner = vegetation.DynamicSliceInstanceSpawner() + dynamic_slice_spawner.SetSliceAssetPath(dynamic_slice_asset_path) + descriptor = hydra.get_component_property_value(asset_list_entity.components[0], + "Configuration|Embedded Assets|[0]") + descriptor.spawner = dynamic_slice_spawner + asset_list_entity.get_set_test(0, "Configuration|Embedded Assets|[0]", descriptor) + return asset_list_entity - # 2) Create 3 entities with Vegetation Asset List components set to spawn different descriptors - center_point = math.Vector3(512.0, 512.0, 32.0) - asset_path = os.path.join("Slices", "PinkFlower.dynamicslice") - asset_path2 = os.path.join("Slices", "PurpleFlower.dynamicslice") - asset_list_entity = create_asset_list_entity("Asset List 1", center_point, asset_path) - asset_list_entity2 = create_asset_list_entity("Asset List 2", center_point, None) - asset_list_entity3 = create_asset_list_entity("Asset List 3", center_point, asset_path2) + # 1) Open an existing simple level + helper.init_idle() + helper.open_level("Physics", "Base") - # 3) Create a planting surface and add a Vegetation System Settings level component with instances set to spawn - # on center instead of corner - dynveg.create_surface_entity("Surface Entity", center_point, 32.0, 32.0, 1.0) - veg_system_settings_component = hydra.add_level_component("Vegetation System Settings") - editor.EditorComponentAPIBus(bus.Broadcast, "SetComponentProperty", veg_system_settings_component, - 'Configuration|Area System Settings|Sector Point Snap Mode', 1) + # Set view of planting area for visual debugging + general.set_current_view_position(512.0, 500.0, 38.0) + general.set_current_view_rotation(-20.0, 0.0, 0.0) - # 4) Create a spawner using a Vegetation Asset List Combiner component and a Weight Selector, and disallow - # spawning empty assets - spawner_entity = dynveg.create_vegetation_area("Spawner Entity", center_point, 16.0, 16.0, 16.0, None) - spawner_entity.remove_component("Vegetation Asset List") - spawner_entity.add_component("Vegetation Asset List Combiner") - spawner_entity.add_component("Vegetation Asset Weight Selector") - spawner_entity.get_set_test(0, "Configuration|Allow Empty Assets", False) + # 2) Create 3 entities with Vegetation Asset List components set to spawn different descriptors + center_point = math.Vector3(512.0, 512.0, 32.0) + asset_path = os.path.join("Slices", "PinkFlower.dynamicslice") + asset_path2 = os.path.join("Slices", "PurpleFlower.dynamicslice") + asset_list_entity = create_asset_list_entity("Asset List 1", center_point, asset_path) + asset_list_entity2 = create_asset_list_entity("Asset List 2", center_point, None) + asset_list_entity3 = create_asset_list_entity("Asset List 3", center_point, asset_path2) - # 5) Add the Asset List entities to the Vegetation Asset List Combiner component - asset_list_entities = [asset_list_entity.id, asset_list_entity2.id] - spawner_entity.get_set_test(2, "Configuration|Descriptor Providers", asset_list_entities) + # 3) Create a planting surface and add a Vegetation System Settings level component with instances set to spawn + # on center instead of corner + dynveg.create_surface_entity("Surface Entity", center_point, 32.0, 32.0, 1.0) + veg_system_settings_component = hydra.add_level_component("Vegetation System Settings") + editor.EditorComponentAPIBus(bus.Broadcast, "SetComponentProperty", veg_system_settings_component, + 'Configuration|Area System Settings|Sector Point Snap Mode', 1) - # 6) Create a Constant Gradient entity as a child of the spawner entity, and a Dither Gradient Modifier entity - # as a child of the Constant Gradient entity, and configure for a checkerboard pattern - components_to_add = ["Constant Gradient"] - constant_gradient_entity = hydra.Entity("Constant Gradient Entity") - constant_gradient_entity.create_entity(center_point, components_to_add, parent_id=spawner_entity.id) - constant_gradient_entity.get_set_test(0, "Configuration|Value", 0.5) + # 4) Create a spawner using a Vegetation Asset List Combiner component and a Weight Selector, and disallow + # spawning empty assets + spawner_entity = dynveg.create_vegetation_area("Spawner Entity", center_point, 16.0, 16.0, 16.0, None) + spawner_entity.remove_component("Vegetation Asset List") + spawner_entity.add_component("Vegetation Asset List Combiner") + spawner_entity.add_component("Vegetation Asset Weight Selector") + spawner_entity.get_set_test(0, "Configuration|Allow Empty Assets", False) - components_to_add = ["Dither Gradient Modifier"] - dither_gradient_entity = hydra.Entity("Dither Gradient Entity") - dither_gradient_entity.create_entity(center_point, components_to_add, parent_id=constant_gradient_entity.id) - dither_gradient_entity.get_set_test(0, "Configuration|Gradient|Gradient Entity Id", constant_gradient_entity.id) + # 5) Add the Asset List entities to the Vegetation Asset List Combiner component + asset_list_entities = [asset_list_entity.id, asset_list_entity2.id] + spawner_entity.get_set_test(2, "Configuration|Descriptor Providers", asset_list_entities) - # 7) Pin the Dither Gradient Entity to the Asset Weight Selector of the spawner entity - spawner_entity.get_set_test(3, "Configuration|Gradient|Gradient Entity Id", dither_gradient_entity.id) + # 6) Create a Constant Gradient entity as a child of the spawner entity, and a Dither Gradient Modifier entity + # as a child of the Constant Gradient entity, and configure for a checkerboard pattern + components_to_add = ["Constant Gradient"] + constant_gradient_entity = hydra.Entity("Constant Gradient Entity") + constant_gradient_entity.create_entity(center_point, components_to_add, parent_id=spawner_entity.id) + constant_gradient_entity.get_set_test(0, "Configuration|Value", 0.5) - # 8) Validate instance count. We should now have 200 instances in the spawner area as every other instance - # should be an empty asset which the spawner is set to disallow - num_expected = 20 * 20 / 2 - success = self.wait_for_condition(lambda: dynveg.validate_instance_count_in_entity_shape(spawner_entity.id, - num_expected), 5.0) - self.test_success = success and self.test_success + components_to_add = ["Dither Gradient Modifier"] + dither_gradient_entity = hydra.Entity("Dither Gradient Entity") + dither_gradient_entity.create_entity(center_point, components_to_add, parent_id=constant_gradient_entity.id) + dither_gradient_entity.get_set_test(0, "Configuration|Gradient|Gradient Entity Id", constant_gradient_entity.id) - # 9) Replace the reference to the 2nd asset list on the Vegetation Asset List Combiner component and validate - # instance count. Should now be 400 instances as the empty spaces can now be claimed by the new descriptor - spawner_entity.get_set_test(2, "Configuration|Descriptor Providers|[1]", asset_list_entity3.id) - num_expected = 20 * 20 - success = self.wait_for_condition(lambda: dynveg.validate_instance_count_in_entity_shape(spawner_entity.id, - num_expected), 5.0) - self.test_success = success and self.test_success + # 7) Pin the Dither Gradient Entity to the Asset Weight Selector of the spawner entity + spawner_entity.get_set_test(3, "Configuration|Gradient|Gradient Entity Id", dither_gradient_entity.id) - # 10) Remove the referenced Asset Lists on the Asset List Combiner, Disable/Re-enable the Asset List - # Combiner component to force a refresh, and validate instance count. We should now have 0 instances. - pte = hydra.get_property_tree(spawner_entity.components[2]) - path = "Configuration|Descriptor Providers" - pte.reset_container(path) - # Component refresh is currently necessary due to container operations not causing a refresh (LY-120947) - editor.EditorComponentAPIBus(bus.Broadcast, "DisableComponents", [spawner_entity.components[2]]) - editor.EditorComponentAPIBus(bus.Broadcast, "EnableComponents", [spawner_entity.components[2]]) - num_expected = 0 - success = self.wait_for_condition(lambda: dynveg.validate_instance_count_in_entity_shape(spawner_entity.id, - num_expected), 5.0) - self.test_success = success and self.test_success + # 8) Validate instance count. We should now have 200 instances in the spawner area as every other instance + # should be an empty asset which the spawner is set to disallow + num_expected = 20 * 20 / 2 + success = helper.wait_for_condition(lambda: dynveg.validate_instance_count_in_entity_shape(spawner_entity.id, + num_expected), 5.0) + Report.result(Tests.combined_instance_count_validation, success) + + # 9) Replace the reference to the 2nd asset list on the Vegetation Asset List Combiner component and validate + # instance count. Should now be 400 instances as the empty spaces can now be claimed by the new descriptor + spawner_entity.get_set_test(2, "Configuration|Descriptor Providers|[1]", asset_list_entity3.id) + num_expected = 20 * 20 + success = helper.wait_for_condition(lambda: dynveg.validate_instance_count_in_entity_shape(spawner_entity.id, + num_expected), 5.0) + Report.result(Tests.replaced_asset_list_combined_instance_count_validation, success) + + # 10) Remove the referenced Asset Lists on the Asset List Combiner, Disable/Re-enable the Asset List + # Combiner component to force a refresh, and validate instance count. We should now have 0 instances. + pte = hydra.get_property_tree(spawner_entity.components[2]) + path = "Configuration|Descriptor Providers" + pte.reset_container(path) + # Component refresh is currently necessary due to container operations not causing a refresh (LY-120947) + editor.EditorComponentAPIBus(bus.Broadcast, "DisableComponents", [spawner_entity.components[2]]) + editor.EditorComponentAPIBus(bus.Broadcast, "EnableComponents", [spawner_entity.components[2]]) + num_expected = 0 + success = helper.wait_for_condition(lambda: dynveg.validate_instance_count_in_entity_shape(spawner_entity.id, + num_expected), 5.0) + Report.result(Tests.removed_asset_lists_combined_instance_count_validation, success) -test = TestAssetListCombiner() -test.run() +if __name__ == "__main__": + + from editor_python_test_tools.utils import Report + Report.start_test(AssetListCombiner_CombinedDescriptorsExpressInConfiguredArea) diff --git a/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/AssetWeightSelector_InstancesExpressBasedOnWeight.py b/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/AssetWeightSelector_InstancesExpressBasedOnWeight.py index 113bbc8ea8..53b45e8470 100755 --- a/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/AssetWeightSelector_InstancesExpressBasedOnWeight.py +++ b/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/AssetWeightSelector_InstancesExpressBasedOnWeight.py @@ -5,112 +5,110 @@ For complete copyright and license terms please see the LICENSE at the root of t SPDX-License-Identifier: Apache-2.0 OR MIT """ -""" -C6269654: Vegetation areas using weight selectors properly distribute instances according to Sort By Weight setting -""" -import os -import sys - -sys.path.append(os.path.dirname(os.path.abspath(__file__))) -import azlmbr.legacy.general as general -import azlmbr.math as math -import azlmbr.paths - -sys.path.append(os.path.join(azlmbr.paths.devroot, 'AutomatedTesting', 'Gem', 'PythonTests')) -import editor_python_test_tools.hydra_editor_utils as hydra -from editor_python_test_tools.editor_test_helper import EditorTestHelper -from largeworlds.large_worlds_utils import editor_dynveg_test_helper as dynveg +class Tests: + highest_weight_instance_count = ( + "Found the expected number of instances when sorting by highest weight", + "Found an unexpected number of instances when sorting by highest weight" + ) + lowest_weight_instance_count = ( + "Found the expected number of instances when sorting by lowest weight", + "Found an unexpected number of instances when sorting by lowest weight" + ) -class TestAssetWeightSelectorSortByWeight(EditorTestHelper): - def __init__(self): - EditorTestHelper.__init__(self, log_prefix="AssetWeightSelector_SortByWeight", args=["level"]) +def AssetWeightSelector_InstancesExpressBasedOnWeight(): + """ + Summary: + Vegetation areas using weight selectors properly distribute instances according to Sort By Weight setting - def run_test(self): - """ - Summary: - Vegetation areas using weight selectors properly distribute instances according to Sort By Weight setting + Expected Behavior: + Vegetation is planted in the area according to the generated gradient pattern. + Higher weight assets are more likely to express when "Descending (highest first)" is selected. + Lower weight assets are more likely to express when "Ascending (lowest first)" is selected. - Expected Behavior: - Vegetation is planted in the area according to the generated gradient pattern. - Higher weight assets are more likely to express when "Descending (highest first)" is selected. - Lower weight assets are more likely to express when "Ascending (lowest first)" is selected. + Test Steps: + 1) Open a simple level + 2) Create instance spawner with 2 descriptors, one with an Empty Asset + 3) Create a planting surface + 4) Create a child entity of the instance spawner with a Constant Gradient component with default values (1.0) + 5) Pin the child entity to Vegetation Asset Weight Selector of the instance spawner entity + 6) Set first descriptor to a higher weight, and toggle off Allow Empty Assets + 7) Validate instance count with initial setup/sort values + 8) Change sort values and validate instance count - Test Steps: - 1) Create new level - 2) Create instance spawner with 2 descriptors, one with an Empty Asset - 3) Create a planting surface - 4) Create a child entity of the instance spawner with a Constant Gradient component with default values (1.0) - 5) Pin the child entity to Vegetation Asset Weight Selector of the instance spawner entity - 6) Set first descriptor to a higher weight, and toggle off Allow Empty Assets - 7) Validate instance count with initial setup/sort values - 8) Change sort values and validate instance count + 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. - 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 + """ - :return: None - """ - # 1) Create a new, temporary level - self.test_success = self.create_level( - self.args["level"], - heightmap_resolution=1024, - heightmap_meters_per_pixel=1, - terrain_texture_resolution=4096, - use_terrain=False, - ) + import os - # Set view of planting area for visual debugging - general.set_current_view_position(512.0, 500.0, 38.0) - general.set_current_view_rotation(-20.0, 0.0, 0.0) + import azlmbr.legacy.general as general + import azlmbr.math as math - # 2) Create a new instance spawner entity with multiple Dynamic Slice Instance Spawner descriptors, one set to a - # valid slice entity, and one set to None - spawner_center_point = math.Vector3(512.0, 512.0, 32.0) - asset_path = os.path.join("Slices", "PinkFlower.dynamicslice") - spawner_entity = dynveg.create_vegetation_area("Instance Spawner", spawner_center_point, 16.0, 16.0, 16.0, - asset_path) - desc_asset = hydra.get_component_property_value(spawner_entity.components[2], - "Configuration|Embedded Assets")[0] - desc_list = [desc_asset, desc_asset] - spawner_entity.get_set_test(2, "Configuration|Embedded Assets", desc_list) - spawner_entity.get_set_test(2, "Configuration|Embedded Assets|[1]|Instance|Slice Asset", None) + import editor_python_test_tools.hydra_editor_utils as hydra + from largeworlds.large_worlds_utils import editor_dynveg_test_helper as dynveg + from editor_python_test_tools.utils import Report + from editor_python_test_tools.utils import TestHelper as helper - # Add an Asset Weight Selector component to the spawner entity - spawner_entity.add_component("Vegetation Asset Weight Selector") + # 1) Open an existing simple level + helper.init_idle() + helper.open_level("Physics", "Base") - # 3) Create a planting surface - dynveg.create_surface_entity("Planting Surface", spawner_center_point, 32.0, 32.0, 1.0) + # Set view of planting area for visual debugging + general.set_current_view_position(512.0, 500.0, 38.0) + general.set_current_view_rotation(-20.0, 0.0, 0.0) - # 4) Create a child entity of the spawner entity with a Constant Gradient component - components_to_add = ["Constant Gradient"] - gradient_entity = hydra.Entity("Gradient Entity") - gradient_entity.create_entity(spawner_center_point, components_to_add, parent_id=spawner_entity.id) + # 2) Create a new instance spawner entity with multiple Dynamic Slice Instance Spawner descriptors, one set to a + # valid slice entity, and one set to None + spawner_center_point = math.Vector3(512.0, 512.0, 32.0) + asset_path = os.path.join("Slices", "PinkFlower.dynamicslice") + spawner_entity = dynveg.create_vegetation_area("Instance Spawner", spawner_center_point, 16.0, 16.0, 16.0, + asset_path) + desc_asset = hydra.get_component_property_value(spawner_entity.components[2], + "Configuration|Embedded Assets")[0] + desc_list = [desc_asset, desc_asset] + spawner_entity.get_set_test(2, "Configuration|Embedded Assets", desc_list) + spawner_entity.get_set_test(2, "Configuration|Embedded Assets|[1]|Instance|Slice Asset", None) - # 5) Pin the Constant Gradient to the Vegetation Asset Weight Selector - spawner_entity.get_set_test(3, 'Configuration|Gradient|Gradient Entity Id', gradient_entity.id) + # Add an Asset Weight Selector component to the spawner entity + spawner_entity.add_component("Vegetation Asset Weight Selector") - # 6) Set the first descriptor weight to a higher value and toggle off Allow Empty Assets on the Layer Spawner - # component - spawner_entity.get_set_test(2, 'Configuration|Embedded Assets|[0]|Weight', 50) - spawner_entity.get_set_test(0, 'Configuration|Allow Empty Assets', False) + # 3) Create a planting surface + dynveg.create_surface_entity("Planting Surface", spawner_center_point, 32.0, 32.0, 1.0) - # 7) Query for expected instances with default settings. We should have 0 instances with default Constant - # Gradient setup sorting by higher weight first - num_expected = 0 - initial_success = self.wait_for_condition(lambda: dynveg.validate_instance_count_in_entity_shape(spawner_entity.id, num_expected), 5.0) - self.test_success = initial_success and self.test_success + # 4) Create a child entity of the spawner entity with a Constant Gradient component + components_to_add = ["Constant Gradient"] + gradient_entity = hydra.Entity("Gradient Entity") + gradient_entity.create_entity(spawner_center_point, components_to_add, parent_id=spawner_entity.id) - # 8) Sort by lowest weight first, and verify instance counts. We should now have 400 instances as the highest - # priority instance won't be allowed to claim space due to "Allow Empty Assets" being False - spawner_entity.get_set_test(3, 'Configuration|Sort By Weight', 1) - num_expected = 20 * 20 - final_success = self.wait_for_condition(lambda: dynveg.validate_instance_count_in_entity_shape(spawner_entity.id, num_expected), 5.0) - self.test_success = final_success and self.test_success + # 5) Pin the Constant Gradient to the Vegetation Asset Weight Selector + spawner_entity.get_set_test(3, 'Configuration|Gradient|Gradient Entity Id', gradient_entity.id) + + # 6) Set the first descriptor weight to a higher value and toggle off Allow Empty Assets on the Layer Spawner + # component + spawner_entity.get_set_test(2, 'Configuration|Embedded Assets|[0]|Weight', 50) + spawner_entity.get_set_test(0, 'Configuration|Allow Empty Assets', False) + + # 7) Query for expected instances with default settings. We should have 0 instances with default Constant + # Gradient setup sorting by higher weight first + num_expected = 0 + initial_success = helper.wait_for_condition(lambda: dynveg.validate_instance_count_in_entity_shape(spawner_entity.id, num_expected), 5.0) + Report.result(Tests.highest_weight_instance_count, initial_success) + + # 8) Sort by lowest weight first, and verify instance counts. We should now have 400 instances as the highest + # priority instance won't be allowed to claim space due to "Allow Empty Assets" being False + spawner_entity.get_set_test(3, 'Configuration|Sort By Weight', 1) + num_expected = 20 * 20 + final_success = helper.wait_for_condition(lambda: dynveg.validate_instance_count_in_entity_shape(spawner_entity.id, num_expected), 5.0) + Report.result(Tests.lowest_weight_instance_count, final_success) -test = TestAssetWeightSelectorSortByWeight() -test.run() +if __name__ == "__main__": + + from editor_python_test_tools.utils import Report + Report.start_test(AssetWeightSelector_InstancesExpressBasedOnWeight) 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 12fb6d8eff..c2adffc6ca 100755 --- a/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/DistanceBetweenFilterOverrides_InstancesPlantAtSpecifiedRadius.py +++ b/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/DistanceBetweenFilterOverrides_InstancesPlantAtSpecifiedRadius.py @@ -5,108 +5,118 @@ For complete copyright and license terms please see the LICENSE at the root of t SPDX-License-Identifier: Apache-2.0 OR MIT """ -import os -import sys -sys.path.append(os.path.dirname(os.path.abspath(__file__))) -import azlmbr.editor as editor -import azlmbr.legacy.general as general -import azlmbr.bus as bus -import azlmbr.math as math -import azlmbr.paths - -sys.path.append(os.path.join(azlmbr.paths.devroot, 'AutomatedTesting', 'Gem', 'PythonTests')) -import editor_python_test_tools.hydra_editor_utils as hydra -from editor_python_test_tools.editor_test_helper import EditorTestHelper -from largeworlds.large_worlds_utils import editor_dynveg_test_helper as dynveg +class Tests: + initial_instance_counts = ( + "Initial instance counts are as expected", + "Unexpected number of initial instances found" + ) + instance_counts_1m = ( + "Instance counts with 1 meters between instances are as expected", + "Unexpected number of instances found with 1 meters between instances" + ) + instance_counts_2m = ( + "Instance counts with 2 meters between instances are as expected", + "Unexpected number of instances found with 2 meters between instances" + ) + instance_counts_16m = ( + "Instance counts with 16 meters between instances are as expected", + "Unexpected number of instances found with 16 meters between instances" + ) -class TestDistanceBetweenFilterComponentOverrides(EditorTestHelper): - def __init__(self): - EditorTestHelper.__init__(self, log_prefix="DistanceBetweenFilterComponentOverrides", args=["level"]) +def DistanceBetweenFilterOverrides_InstancesPlantAtSpecifiedRadius(): + """ + Summary: Creates a level with a simple vegetation area. A Vegetation Distance Between Filter is + added and the min radius is changed as an override on the descriptor. Instance counts at specific points are + validated. - def run_test(self): - """ - Summary: Creates a level with a simple vegetation area. A Vegetation Distance Between Filter is - added and the min radius is changed as an override on the descriptor. Instance counts at specific points are - validated. + Test Steps: + 1) Open a simple level + 2) Create a vegetation area + 3) Create a surface for planting + 4) Add the Vegetation System Settings component and setup for the test + 5-8) Add the Distance Between Filter, setup overrides on both the component and descriptor, and validate + expected instance counts with a few different Radius values - Test Steps: - 1) Create a new level - 2) Create a vegetation area - 3) Create a surface for planting - 4) Add the Vegetation System Settings component and setup for the test - 5-8) Add the Distance Between Filter, setup overrides on both the component and descriptor, and validate - expected instance counts with a few different Radius values + 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. - 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 + """ - :return: None - """ - instance_query_point_a = math.Vector3(512.5, 512.5, 32.0) - instance_query_point_b = math.Vector3(514.0, 512.5, 32.0) - instance_query_point_c = math.Vector3(515.0, 512.5, 32.0) + import os - # 1) Create a new, temporary level - self.test_success = self.create_level( - self.args["level"], - heightmap_resolution=1024, - heightmap_meters_per_pixel=1, - terrain_texture_resolution=4096, - use_terrain=False, - ) + import azlmbr.editor as editor + import azlmbr.legacy.general as general + import azlmbr.bus as bus + import azlmbr.math as math - general.set_current_view_position(512.0, 480.0, 38.0) + import editor_python_test_tools.hydra_editor_utils as hydra + from largeworlds.large_worlds_utils import editor_dynveg_test_helper as dynveg + from editor_python_test_tools.utils import Report + from editor_python_test_tools.utils import TestHelper as helper - # 2) Create a new entity with required vegetation area components - spawner_center_point = math.Vector3(520.0, 520.0, 32.0) - asset_path = os.path.join("Slices", "1m_cube.dynamicslice") - spawner_entity = dynveg.create_vegetation_area("Instance Spawner", spawner_center_point, 16.0, 16.0, 16.0, - asset_path) + instance_query_point_a = math.Vector3(512.5, 512.5, 32.0) + instance_query_point_b = math.Vector3(514.0, 512.5, 32.0) + instance_query_point_c = math.Vector3(515.0, 512.5, 32.0) - # 3) Create a surface to plant on - surface_center_point = math.Vector3(512.0, 512.0, 32.0) - dynveg.create_surface_entity("Planting Surface", surface_center_point, 128.0, 128.0, 1.0) + # 1) Open an existing simple level + helper.init_idle() + helper.open_level("Physics", "Base") - # 4) Add a Vegetation System Settings Level component and set Sector Point Snap Mode to Center - veg_system_settings_component = hydra.add_level_component("Vegetation System Settings") - editor.EditorComponentAPIBus(bus.Broadcast, "SetComponentProperty", veg_system_settings_component, - 'Configuration|Area System Settings|Sector Point Snap Mode', 1) - editor.EditorComponentAPIBus(bus.Broadcast, "SetComponentProperty", veg_system_settings_component, - 'Configuration|Area System Settings|Sector Point Density', 16) + general.set_current_view_position(512.0, 480.0, 38.0) - # 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) - 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 + # 2) Create a new entity with required vegetation area components + spawner_center_point = math.Vector3(520.0, 520.0, 32.0) + asset_path = os.path.join("Slices", "1m_cube.dynamicslice") + spawner_entity = dynveg.create_vegetation_area("Instance Spawner", spawner_center_point, 16.0, 16.0, 16.0, + asset_path) - # 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) - 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 + # 3) Create a surface to plant on + surface_center_point = math.Vector3(512.0, 512.0, 32.0) + dynveg.create_surface_entity("Planting Surface", surface_center_point, 128.0, 128.0, 1.0) - # 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) - 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 + # 4) Add a Vegetation System Settings Level component and set Sector Point Snap Mode to Center + veg_system_settings_component = hydra.add_level_component("Vegetation System Settings") + editor.EditorComponentAPIBus(bus.Broadcast, "SetComponentProperty", veg_system_settings_component, + 'Configuration|Area System Settings|Sector Point Snap Mode', 1) + editor.EditorComponentAPIBus(bus.Broadcast, "SetComponentProperty", veg_system_settings_component, + 'Configuration|Area System Settings|Sector Point Density', 16) - # 8) Change Radius Min to 16.0, refresh, and verify instance counts are accurate, only a single instance should plant - spawner_entity.get_set_test(2, "Configuration|Embedded Assets|[0]|Distance Between Filter (Radius)|Radius Min", 16.0) - num_expected_instances = 1 - final_check_success = self.wait_for_condition(lambda: dynveg.validate_instance_count_in_entity_shape(spawner_entity.id, num_expected_instances), 5.0) - self.test_success = self.test_success and final_check_success + # 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) + num_expected = 16 * 16 + initial_success = helper.wait_for_condition(lambda: dynveg.validate_instance_count_in_entity_shape(spawner_entity.id, num_expected), 5.0) + Report.result(Tests.initial_instance_counts, 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) + point_a_success = helper.wait_for_condition(lambda: dynveg.validate_instance_count(instance_query_point_a, 0.5, 1), 5.0) + point_b_success = helper.wait_for_condition(lambda: dynveg.validate_instance_count(instance_query_point_b, 0.5, 0), 5.0) + point_c_success = helper.wait_for_condition(lambda: dynveg.validate_instance_count(instance_query_point_c, 0.5, 1), 5.0) + Report.result(Tests.instance_counts_1m, 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) + point_a_success = helper.wait_for_condition(lambda: dynveg.validate_instance_count(instance_query_point_a, 0.5, 1), 5.0) + point_b_success = helper.wait_for_condition(lambda: dynveg.validate_instance_count(instance_query_point_b, 0.5, 0), 5.0) + point_c_success = helper.wait_for_condition(lambda: dynveg.validate_instance_count(instance_query_point_c, 0.5, 0), 5.0) + Report.result(Tests.instance_counts_2m, point_a_success and point_b_success and point_c_success) + + # 8) Change Radius Min to 16.0, refresh, and verify instance counts are accurate, only a single instance should plant + spawner_entity.get_set_test(2, "Configuration|Embedded Assets|[0]|Distance Between Filter (Radius)|Radius Min", 16.0) + num_expected_instances = 1 + final_check_success = helper.wait_for_condition(lambda: dynveg.validate_instance_count_in_entity_shape(spawner_entity.id, num_expected_instances), 5.0) + Report.result(Tests.instance_counts_16m, final_check_success) -test = TestDistanceBetweenFilterComponentOverrides() -test.run() +if __name__ == "__main__": + + from editor_python_test_tools.utils import Report + Report.start_test(DistanceBetweenFilterOverrides_InstancesPlantAtSpecifiedRadius) 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 5b978c6212..de0d9a14fe 100755 --- a/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/DistanceBetweenFilter_InstancesPlantAtSpecifiedRadius.py +++ b/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/DistanceBetweenFilter_InstancesPlantAtSpecifiedRadius.py @@ -5,104 +5,113 @@ For complete copyright and license terms please see the LICENSE at the root of t SPDX-License-Identifier: Apache-2.0 OR MIT """ -import os -import sys -sys.path.append(os.path.dirname(os.path.abspath(__file__))) -import azlmbr.editor as editor -import azlmbr.legacy.general as general -import azlmbr.bus as bus -import azlmbr.math as math -import azlmbr.paths - -sys.path.append(os.path.join(azlmbr.paths.devroot, 'AutomatedTesting', 'Gem', 'PythonTests')) -import editor_python_test_tools.hydra_editor_utils as hydra -from editor_python_test_tools.editor_test_helper import EditorTestHelper -from largeworlds.large_worlds_utils import editor_dynveg_test_helper as dynveg +class Tests: + initial_instance_counts = ( + "Initial instance counts are as expected", + "Unexpected number of initial instances found" + ) + instance_counts_1m = ( + "Instance counts with 1 meters between instances are as expected", + "Unexpected number of instances found with 1 meters between instances" + ) + instance_counts_2m = ( + "Instance counts with 2 meters between instances are as expected", + "Unexpected number of instances found with 2 meters between instances" + ) + instance_counts_16m = ( + "Instance counts with 16 meters between instances are as expected", + "Unexpected number of instances found with 16 meters between instances" + ) -class TestDistanceBetweenFilterComponent(EditorTestHelper): - def __init__(self): - EditorTestHelper.__init__(self, log_prefix="DistanceBetweenFilterComponent", args=["level"]) +def DistanceBetweenFilter_InstancesPlantAtSpecifiedRadius(): + """ + Summary: Creates a level with a simple vegetation area. A Vegetation Distance Between Filter is + added and the min radius is changed. Instance counts at specific points are validated. - def run_test(self): - """ - Summary: Creates a level with a simple vegetation area. A Vegetation Distance Between Filter is - added and the min radius is changed. Instance counts at specific points are validated. + Test Steps: + 1) Open a simple level + 2) Create a vegetation area + 3) Create a surface for planting + 4) Add the Vegetation System Settings component and setup for the test + 5-8) Add the Distance Between Filter, and validate expected instance counts with a few different Radius values - Test Steps: - 1) Create a new level - 2) Create a vegetation area - 3) Create a surface for planting - 4) Add the Vegetation System Settings component and setup for the test - 5-8) Add the Distance Between Filter, and validate expected instance counts with a few different Radius values + 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. - 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 + """ - :return: None - """ - instance_query_point_a = math.Vector3(512.5, 512.5, 32.0) - instance_query_point_b = math.Vector3(514.0, 512.5, 32.0) - instance_query_point_c = math.Vector3(515.0, 512.5, 32.0) + import os - # 1) Create a new, temporary level - self.test_success = self.create_level( - self.args["level"], - heightmap_resolution=1024, - heightmap_meters_per_pixel=1, - terrain_texture_resolution=4096, - use_terrain=False, - ) + import azlmbr.editor as editor + import azlmbr.legacy.general as general + import azlmbr.bus as bus + import azlmbr.math as math - general.set_current_view_position(512.0, 480.0, 38.0) + import editor_python_test_tools.hydra_editor_utils as hydra + from largeworlds.large_worlds_utils import editor_dynveg_test_helper as dynveg + from editor_python_test_tools.utils import Report + from editor_python_test_tools.utils import TestHelper as helper - # 2) Create a new entity with required vegetation area components - spawner_center_point = math.Vector3(520.0, 520.0, 32.0) - asset_path = os.path.join("Slices", "1m_cube.dynamicslice") - spawner_entity = dynveg.create_vegetation_area("Instance Spawner", spawner_center_point, 16.0, 16.0, 16.0, - asset_path) + instance_query_point_a = math.Vector3(512.5, 512.5, 32.0) + instance_query_point_b = math.Vector3(514.0, 512.5, 32.0) + instance_query_point_c = math.Vector3(515.0, 512.5, 32.0) - # 3) Create a surface to plant on - surface_center_point = math.Vector3(512.0, 512.0, 32.0) - dynveg.create_surface_entity("Planting Surface", surface_center_point, 128.0, 128.0, 1.0) + # 1) Open an existing simple level + helper.init_idle() + helper.open_level("Physics", "Base") - # 4) Add a Vegetation System Settings Level component and set Sector Point Snap Mode to Center - veg_system_settings_component = hydra.add_level_component("Vegetation System Settings") - editor.EditorComponentAPIBus(bus.Broadcast, "SetComponentProperty", veg_system_settings_component, - 'Configuration|Area System Settings|Sector Point Snap Mode', 1) - editor.EditorComponentAPIBus(bus.Broadcast, "SetComponentProperty", veg_system_settings_component, - 'Configuration|Area System Settings|Sector Point Density', 16) + general.set_current_view_position(512.0, 480.0, 38.0) - # 5) Add a Vegetation Distance Between Filter and verify initial instance counts are accurate - spawner_entity.add_component("Vegetation Distance Between Filter") - 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 + # 2) Create a new entity with required vegetation area components + spawner_center_point = math.Vector3(520.0, 520.0, 32.0) + asset_path = os.path.join("Slices", "1m_cube.dynamicslice") + spawner_entity = dynveg.create_vegetation_area("Instance Spawner", spawner_center_point, 16.0, 16.0, 16.0, + asset_path) - # 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) - 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 + # 3) Create a surface to plant on + surface_center_point = math.Vector3(512.0, 512.0, 32.0) + dynveg.create_surface_entity("Planting Surface", surface_center_point, 128.0, 128.0, 1.0) - # 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) - 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 + # 4) Add a Vegetation System Settings Level component and set Sector Point Snap Mode to Center + veg_system_settings_component = hydra.add_level_component("Vegetation System Settings") + editor.EditorComponentAPIBus(bus.Broadcast, "SetComponentProperty", veg_system_settings_component, + 'Configuration|Area System Settings|Sector Point Snap Mode', 1) + editor.EditorComponentAPIBus(bus.Broadcast, "SetComponentProperty", veg_system_settings_component, + 'Configuration|Area System Settings|Sector Point Density', 16) - # 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) - 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 + # 5) Add a Vegetation Distance Between Filter and verify initial instance counts are accurate + spawner_entity.add_component("Vegetation Distance Between Filter") + num_expected = 16 * 16 + initial_success = helper.wait_for_condition(lambda: dynveg.validate_instance_count_in_entity_shape(spawner_entity.id, num_expected), 5.0) + Report.result(Tests.initial_instance_counts, 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) + point_a_success = helper.wait_for_condition(lambda: dynveg.validate_instance_count(instance_query_point_a, 0.5, 1), 5.0) + point_b_success = helper.wait_for_condition(lambda: dynveg.validate_instance_count(instance_query_point_b, 0.5, 0), 5.0) + point_c_success = helper.wait_for_condition(lambda: dynveg.validate_instance_count(instance_query_point_c, 0.5, 1), 5.0) + Report.result(Tests.instance_counts_1m, 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) + point_a_success = helper.wait_for_condition(lambda: dynveg.validate_instance_count(instance_query_point_a, 0.5, 1), 5.0) + point_b_success = helper.wait_for_condition(lambda: dynveg.validate_instance_count(instance_query_point_b, 0.5, 0), 5.0) + point_c_success = helper.wait_for_condition(lambda: dynveg.validate_instance_count(instance_query_point_c, 0.5, 0), 5.0) + Report.result(Tests.instance_counts_2m, 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) + num_expected_instances = 1 + final_check_success = helper.wait_for_condition(lambda: dynveg.validate_instance_count_in_entity_shape(spawner_entity.id, num_expected_instances), 5.0) + Report.result(Tests.instance_counts_16m, final_check_success) -test = TestDistanceBetweenFilterComponent() -test.run() +if __name__ == "__main__": + + from editor_python_test_tools.utils import Report + Report.start_test(DistanceBetweenFilter_InstancesPlantAtSpecifiedRadius) diff --git a/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/DynamicSliceInstanceSpawner_DynamicSliceSpawnerWorks.py b/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/DynamicSliceInstanceSpawner_DynamicSliceSpawnerWorks.py index 173be62829..fcbf85c59d 100755 --- a/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/DynamicSliceInstanceSpawner_DynamicSliceSpawnerWorks.py +++ b/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/DynamicSliceInstanceSpawner_DynamicSliceSpawnerWorks.py @@ -5,140 +5,178 @@ For complete copyright and license terms please see the LICENSE at the root of t SPDX-License-Identifier: Apache-2.0 OR MIT """ -import os -import sys -import azlmbr.legacy.general as general -import azlmbr.bus as bus -import azlmbr.math as math -import azlmbr.paths - -sys.path.append(os.path.join(azlmbr.paths.devroot, 'AutomatedTesting', 'Gem', 'PythonTests')) -import editor_python_test_tools.hydra_editor_utils as hydra -from editor_python_test_tools.editor_test_helper import EditorTestHelper -from largeworlds.large_worlds_utils import editor_dynveg_test_helper as dynveg +class BehaviorContextTests: + spawner_initialized = ( + "Successfully initialized a Dynamic Slice Instance Spawner", + "Failed to initialize a Dynamic Slice Instance Spawner" + ) + spawner_slice_asset_path_set = ( + "Successfully set a Dynamic Slice asset path", + "Failed to set a Dynamic Slice asset path" + ) + spawner_empty_slice_asset_path_set = ( + "Successfully set an empty Dynamic Slice asset path", + "Failed to set an empty Dynamic Slice asset path" + ) + desc_spawnertype_sets_spawner = ( + "Setting spawnerType sets spawner too", + "Setting spawnerType failed to set spawner to expected value" + ) + desc_spawner_sets_spawnertype = ( + "Setting spawner sets spawnerType too", + "Setting spawner failed to set spawnerType to expected value" + ) -class TestDynamicSliceInstanceSpawner(EditorTestHelper): - def __init__(self): - EditorTestHelper.__init__(self, log_prefix="DynamicSliceInstanceSpawner", args=["level"]) +class PropertyTreeTests: + entity_created = ( + "Spawner entity created successfully", + "Failed to create spawner entity" + ) + spawner_type_set = ( + "Successfully set spawner type", + "Failed to set spawner type" + ) + empty_instance_count_validation = ( + "Expected number of empty instances planted", + "Unexpected number of empty instances planted" + ) + no_instances_when_empty_disallowed = ( + "No empty instances found when Empty Assets are not allowed", + "Unexpectedly found empty instances when Empty Assets are not allowed" + ) + nonempty_asset_instance_count_validation = ( + "Expected number of instances planted", + "Unexpected number of instances planted" + ) - def run_test(self): - """ - Summary: - Test aspects of the DynamicSliceInstanceSpawner through the BehaviorContext and the Property Tree. - :return: None - """ - # 1) Open an empty level - self.test_success = self.create_level( - self.args["level"], - heightmap_resolution=1024, - heightmap_meters_per_pixel=1, - terrain_texture_resolution=4096, - use_terrain=False, +def DynamicSliceInstanceSpawner_DynamicSliceSpawnerWorks(): + """ + Summary: + Test aspects of the DynamicSliceInstanceSpawner through the BehaviorContext and the Property Tree. + + :return: None + """ + + import os + + import azlmbr.legacy.general as general + import azlmbr.math as math + + import editor_python_test_tools.hydra_editor_utils as hydra + from largeworlds.large_worlds_utils import editor_dynveg_test_helper as dynveg + from editor_python_test_tools.utils import Report + from editor_python_test_tools.utils import TestHelper as helper + + # 1) Open an existing simple level + helper.init_idle() + helper.open_level("Physics", "Base") + general.set_current_view_position(512.0, 480.0, 38.0) + + # Grab the UUID that we need for creating an Dynamic Slice Instance Spawner + dynamic_slice_spawner_uuid = azlmbr.math.Uuid_CreateString('{BBA5CC1E-B4CA-4792-89F7-93711E98FBD1}', 0) + + # Grab a path to a test dynamic slice asset + test_slice_asset_path = os.path.join("Slices", "PinkFlower.dynamicslice") + + # 2) Test DynamicSliceInstanceSpawner BehaviorContext + behavior_context_test_success = True + dynamic_slice_spawner = azlmbr.vegetation.DynamicSliceInstanceSpawner() + behavior_context_test_success = behavior_context_test_success and (dynamic_slice_spawner is not None) + behavior_context_test_success = behavior_context_test_success and (dynamic_slice_spawner.typename == 'DynamicSliceInstanceSpawner') + Report.critical_result(BehaviorContextTests.spawner_initialized, behavior_context_test_success) + # Try to get/set the slice asset path with a valid asset + dynamic_slice_spawner.SetSliceAssetPath(test_slice_asset_path) + validate_path = dynamic_slice_spawner.GetSliceAssetPath() + # We expect the path to get lowercased and normalized with a forward slash, so we compare our result + # vs that instead of directly against test_slice_asset_path. + behavior_context_test_success = behavior_context_test_success and hydra.compare_values('slices/pinkflower.dynamicslice', validate_path, 'GetSliceAssetPath - valid') + Report.result(BehaviorContextTests.spawner_slice_asset_path_set, behavior_context_test_success) + # Try to get/set the slice asset path with an empty path + dynamic_slice_spawner.SetSliceAssetPath('') + validate_path = dynamic_slice_spawner.GetSliceAssetPath() + behavior_context_test_success = behavior_context_test_success and hydra.compare_values('', validate_path, 'GetSliceAssetPath - empty') + Report.result(BehaviorContextTests.spawner_empty_slice_asset_path_set, behavior_context_test_success) + Report.info(f'DynamicSliceInstanceSpawner() BehaviorContext test: {behavior_context_test_success}') + + # 3) Test Descriptor BehaviorContext - setting spawnerType sets spawner too + spawner_type_test_success = True + descriptor = azlmbr.vegetation.Descriptor() + spawner_type_test_success = spawner_type_test_success and hydra.get_set_property_test(descriptor, 'spawnerType', dynamic_slice_spawner_uuid) + spawner_type_test_success = spawner_type_test_success and (descriptor.spawner.typename == 'DynamicSliceInstanceSpawner') + Report.result(BehaviorContextTests.desc_spawnertype_sets_spawner, spawner_type_test_success) + Report.info(f'Descriptor() BehaviorContext spawnerType test: {spawner_type_test_success}') + + # 4) Test Descriptor BehaviorContext - setting spawner sets spawnerType too + spawner_test_success = True + descriptor = azlmbr.vegetation.Descriptor() + descriptor.spawner = dynamic_slice_spawner + spawner_test_success = spawner_test_success and (descriptor.spawnerType.Equal(dynamic_slice_spawner_uuid)) + spawner_test_success = spawner_test_success and (descriptor.spawner.typename == 'DynamicSliceInstanceSpawner') + Report.result(BehaviorContextTests.desc_spawner_sets_spawnertype, spawner_test_success) + Report.info(f'Descriptor() BehaviorContext spawner test: {spawner_test_success}') + + ### Setup for Property Tree set of tests + + # Create a new entity with required vegetation area components + spawner_entity = hydra.Entity("Veg Area") + spawner_entity.create_entity( + math.Vector3(512.0, 512.0, 32.0), + ["Vegetation Layer Spawner", "Box Shape", "Vegetation Asset List"] ) - general.idle_wait(1.0) - general.set_current_view_position(512.0, 480.0, 38.0) + Report.critical_result(PropertyTreeTests.entity_created, spawner_entity.id.IsValid()) - # Grab the UUID that we need for creating an Dynamic Slice Instance Spawner - dynamic_slice_spawner_uuid = azlmbr.math.Uuid_CreateString('{BBA5CC1E-B4CA-4792-89F7-93711E98FBD1}', 0) + # Resize the Box Shape component + new_box_dimensions = math.Vector3(16.0, 16.0, 16.0) + box_dimensions_path = "Box Shape|Box Configuration|Dimensions" + spawner_entity.get_set_test(1, box_dimensions_path, new_box_dimensions) - # Grab a path to a test dynamic slice asset - test_slice_asset_path = os.path.join("Slices", "PinkFlower.dynamicslice") + # Create a surface to plant on + dynveg.create_surface_entity("Surface Entity", math.Vector3(512.0, 512.0, 32.0), 1024.0, 1024.0, 1.0) - # 2) Test DynamicSliceInstanceSpawner BehaviorContext - behavior_context_test_success = True - dynamic_slice_spawner = azlmbr.vegetation.DynamicSliceInstanceSpawner() - behavior_context_test_success = behavior_context_test_success and (dynamic_slice_spawner is not None) - behavior_context_test_success = behavior_context_test_success and (dynamic_slice_spawner.typename == 'DynamicSliceInstanceSpawner') - # Try to get/set the slice asset path with a valid asset - dynamic_slice_spawner.SetSliceAssetPath(test_slice_asset_path) - validate_path = dynamic_slice_spawner.GetSliceAssetPath() - # We expect the path to get lowercased and normalized with a forward slash, so we compare our result - # vs that instead of directly against test_slice_asset_path. - behavior_context_test_success = behavior_context_test_success and hydra.compare_values('slices/pinkflower.dynamicslice', validate_path, 'GetSliceAssetPath - valid') - # Try to get/set the slice asset path with an empty path - dynamic_slice_spawner.SetSliceAssetPath('') - validate_path = dynamic_slice_spawner.GetSliceAssetPath() - behavior_context_test_success = behavior_context_test_success and hydra.compare_values('', validate_path, 'GetSliceAssetPath - empty') - self.test_success = self.test_success and behavior_context_test_success - self.log(f'DynamicSliceInstanceSpawner() BehaviorContext test: {behavior_context_test_success}') + # 5) Descriptor Property Tree test: spawner type can be set - # 3) Test Descriptor BehaviorContext - setting spawnerType sets spawner too - spawner_type_test_success = True - descriptor = azlmbr.vegetation.Descriptor() - spawner_type_test_success = spawner_type_test_success and hydra.get_set_property_test(descriptor, 'spawnerType', dynamic_slice_spawner_uuid) - spawner_type_test_success = spawner_type_test_success and (descriptor.spawner.typename == 'DynamicSliceInstanceSpawner') - self.test_success = self.test_success and spawner_type_test_success - self.log(f'Descriptor() BehaviorContext spawnerType test: {spawner_type_test_success}') + # - Validate the dynamic slice spawner type can be set correctly. + property_tree_success = True + property_tree_success = property_tree_success and spawner_entity.get_set_test(2, 'Configuration|Embedded Assets|[0]|Instance Spawner', dynamic_slice_spawner_uuid) + Report.result(PropertyTreeTests.spawner_type_set, property_tree_success) - # 4) Test Descriptor BehaviorContext - setting spawner sets spawnerType too - spawner_test_success = True - descriptor = azlmbr.vegetation.Descriptor() - descriptor.spawner = dynamic_slice_spawner - spawner_test_success = spawner_test_success and (descriptor.spawnerType.Equal(dynamic_slice_spawner_uuid)) - spawner_test_success = spawner_test_success and (descriptor.spawner.typename == 'DynamicSliceInstanceSpawner') - self.test_success = self.test_success and spawner_test_success - self.log(f'Descriptor() BehaviorContext spawner test: {spawner_test_success}') + # This should result in 400 instances, since our box is 16 m x 16 m and by default the veg system plants + # 20 instances per 16 meters + spawner_entity.get_set_test(0, 'Configuration|Allow Empty Assets', True) + num_expected_instances = 20 * 20 + property_tree_success = property_tree_success and helper.wait_for_condition(lambda: dynveg.validate_instance_count_in_entity_shape(spawner_entity.id, num_expected_instances), 5.0) + Report.result(PropertyTreeTests.empty_instance_count_validation, property_tree_success) + Report.info(f'Property Tree spawner type test: {property_tree_success}') - ### Setup for Property Tree set of tests + # 6) Validate that the "Allow Empty Assets" setting affects the DynamicSliceInstanceSpawner + allow_empty_assets_success = True + # Since we have an empty slice path, we should have 0 instances once we disable 'Allow Empty Assets' + num_expected_instances = 0 + allow_empty_assets_success = allow_empty_assets_success and spawner_entity.get_set_test(0, 'Configuration|Allow Empty Assets', False) + Report.info('Allow Empty Assets test:') + allow_empty_assets_success = allow_empty_assets_success and helper.wait_for_condition(lambda: dynveg.validate_instance_count_in_entity_shape(spawner_entity.id, num_expected_instances), 5.0) + Report.result(PropertyTreeTests.no_instances_when_empty_disallowed, allow_empty_assets_success) + Report.info(f'Allow Empty Assets test: {allow_empty_assets_success}') - # Create a new entity with required vegetation area components - spawner_entity = hydra.Entity("Veg Area") - spawner_entity.create_entity( - math.Vector3(512.0, 512.0, 32.0), - ["Vegetation Layer Spawner", "Box Shape", "Vegetation Asset List"] - ) - if (spawner_entity.id.IsValid()): - self.log(f"'{spawner_entity.name}' created") - - # Resize the Box Shape component - new_box_dimensions = math.Vector3(16.0, 16.0, 16.0) - box_dimensions_path = "Box Shape|Box Configuration|Dimensions" - spawner_entity.get_set_test(1, box_dimensions_path, new_box_dimensions) - - # Create a surface to plant on - dynveg.create_surface_entity("Surface Entity", math.Vector3(512.0, 512.0, 32.0), 1024.0, 1024.0, 1.0) - - # 5) Descriptor Property Tree test: spawner type can be set - - # - Validate the dynamic slice spawner type can be set correctly. - property_tree_success = True - property_tree_success = property_tree_success and spawner_entity.get_set_test(2, 'Configuration|Embedded Assets|[0]|Instance Spawner', dynamic_slice_spawner_uuid) - - # This should result in 400 instances, since our box is 16 m x 16 m and by default the veg system plants - # 20 instances per 16 meters - spawner_entity.get_set_test(0, 'Configuration|Allow Empty Assets', True) - num_expected_instances = 20 * 20 - property_tree_success = property_tree_success and self.wait_for_condition(lambda: dynveg.validate_instance_count_in_entity_shape(spawner_entity.id, num_expected_instances), 5.0) - self.test_success = self.test_success and property_tree_success - self.log(f'Property Tree spawner type test: {property_tree_success}') - - # 6) Validate that the "Allow Empty Assets" setting affects the DynamicSliceInstanceSpawner - allow_empty_assets_success = True - # Since we have an empty slice path, we should have 0 instances once we disable 'Allow Empty Assets' - num_expected_instances = 0 - allow_empty_assets_success = allow_empty_assets_success and spawner_entity.get_set_test(0, 'Configuration|Allow Empty Assets', False) - self.log('Allow Empty Assets test:') - allow_empty_assets_success = allow_empty_assets_success and self.wait_for_condition(lambda: dynveg.validate_instance_count_in_entity_shape(spawner_entity.id, num_expected_instances), 5.0) - self.test_success = self.test_success and allow_empty_assets_success - self.log(f'Allow Empty Assets test: {allow_empty_assets_success}') - - # 7) Validate that with 'Allow Empty Assets' set to False, a non-empty slice asset gives us the number - # of instances we expect. - spawns_slices_success = True - num_expected_instances = 20 * 20 - dynamic_slice_spawner.SetSliceAssetPath(test_slice_asset_path) - spawns_slices_success = spawns_slices_success and spawner_entity.get_set_test(0, 'Configuration|Allow Empty Assets', False) - descriptor = hydra.get_component_property_value(spawner_entity.components[2], 'Configuration|Embedded Assets|[0]') - descriptor.spawner = dynamic_slice_spawner - spawns_slices_success = spawns_slices_success and spawner_entity.get_set_test(2, "Configuration|Embedded Assets|[0]", descriptor) - self.log('Spawn dynamic slices test:') - spawns_slices_success = spawns_slices_success and self.wait_for_condition(lambda: dynveg.validate_instance_count_in_entity_shape(spawner_entity.id, num_expected_instances), 5.0) - self.test_success = self.test_success and spawns_slices_success - self.log(f'Spawn dynamic slices test: {spawns_slices_success}') + # 7) Validate that with 'Allow Empty Assets' set to False, a non-empty slice asset gives us the number + # of instances we expect. + spawns_slices_success = True + num_expected_instances = 20 * 20 + dynamic_slice_spawner.SetSliceAssetPath(test_slice_asset_path) + spawns_slices_success = spawns_slices_success and spawner_entity.get_set_test(0, 'Configuration|Allow Empty Assets', False) + descriptor = hydra.get_component_property_value(spawner_entity.components[2], 'Configuration|Embedded Assets|[0]') + descriptor.spawner = dynamic_slice_spawner + spawns_slices_success = spawns_slices_success and spawner_entity.get_set_test(2, "Configuration|Embedded Assets|[0]", descriptor) + Report.info('Spawn dynamic slices test:') + spawns_slices_success = spawns_slices_success and helper.wait_for_condition(lambda: dynveg.validate_instance_count_in_entity_shape(spawner_entity.id, num_expected_instances), 5.0) + Report.result(PropertyTreeTests.nonempty_asset_instance_count_validation, spawns_slices_success) + Report.info(f'Spawn dynamic slices test: {spawns_slices_success}') -test = TestDynamicSliceInstanceSpawner() -test.run() +if __name__ == "__main__": + + from editor_python_test_tools.utils import Report + Report.start_test(DynamicSliceInstanceSpawner_DynamicSliceSpawnerWorks) diff --git a/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/DynamicSliceInstanceSpawner_Embedded_E2E.py b/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/DynamicSliceInstanceSpawner_Embedded_E2E.py index 6f2e711387..e51be58ec6 100755 --- a/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/DynamicSliceInstanceSpawner_Embedded_E2E.py +++ b/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/DynamicSliceInstanceSpawner_Embedded_E2E.py @@ -5,99 +5,115 @@ For complete copyright and license terms please see the LICENSE at the root of t SPDX-License-Identifier: Apache-2.0 OR MIT """ -import os -import sys -sys.path.append(os.path.dirname(os.path.abspath(__file__))) -import azlmbr.asset as asset -import azlmbr.components as components -import azlmbr.legacy.general as general -import azlmbr.bus as bus -import azlmbr.entity as entity -import azlmbr.editor as editor -import azlmbr.math as math -import azlmbr.paths - -sys.path.append(os.path.join(azlmbr.paths.devroot, 'AutomatedTesting', 'Gem', 'PythonTests')) -import editor_python_test_tools.hydra_editor_utils as hydra -from editor_python_test_tools.editor_test_helper import EditorTestHelper -from largeworlds.large_worlds_utils import editor_dynveg_test_helper as dynveg +class Tests: + level_created = ( + "Successfully created level", + "Failed to create level" + ) + spawner_entity_created = ( + "Spawner entity created successfully", + "Failed to create spawner entity" + ) + surface_entity_created = ( + "Surface entity created successfully", + "Failed to create surface entity" + ) + instance_count = ( + "Found the expected number of instances", + "Found an unexpected number of instances" + ) + saved_and_exported = ( + "Saved and exported level successfully", + "Failed to save and export level" + ) -class TestDynamicSliceInstanceSpawnerEmbeddedEditor(EditorTestHelper): - def __init__(self): - EditorTestHelper.__init__(self, log_prefix="DynamicSliceInstanceSpawnerEmbeddedEditor", args=["level"]) +def DynamicSliceInstanceSpawner_Embedded_E2E(): + """ + Summary: + A new temporary level is created. Surface for planting is created. Simple vegetation area is created using + Dynamic Slice Instance Spawner type. - def run_test(self): - """ - Summary: - A new temporary level is created. Surface for planting is created. Simple vegetation area is created using - Dynamic Slice Instance Spawner type. + Expected Behavior: + Instances plant as expected in the assigned area. - Expected Behavior: - Instances plant as expected in the assigned area. + Test Steps: + 1) Create level + 2) Create a Vegetation Layer Spawner setup using Dynamic Slice Instance Spawner type assets + 3) Create a surface to plant on + 4) Verify expected instance counts + 5) Add a camera component looking at the planting area for visual debugging + 6) Save and export to engine - Test Steps: - 1) Create level - 2) Create a Vegetation Layer Spawner setup using Dynamic Slice Instance Spawner type assets - 3) Create a surface to plant on - 4) Verify expected instance counts - 5) Add a camera component looking at the planting area for visual debugging - 6) Save and export to engine + 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. - 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 + """ - :return: None - """ + import os - # 1) Create a new, temporary level - self.test_success = self.create_level( - self.args["level"], - heightmap_resolution=1024, - heightmap_meters_per_pixel=1, - terrain_texture_resolution=4096, - use_terrain=False, - ) + import azlmbr.asset as asset + import azlmbr.legacy.general as general + import azlmbr.bus as bus + import azlmbr.components as components + import azlmbr.entity as entity + import azlmbr.math as math + import azlmbr.paths as paths - general.set_current_view_position(512.0, 480.0, 38.0) + import editor_python_test_tools.hydra_editor_utils as hydra + from largeworlds.large_worlds_utils import editor_dynveg_test_helper as dynveg + from editor_python_test_tools.utils import Report + from editor_python_test_tools.utils import TestHelper as helper - # 2) Create a new entity with required vegetation area components and Script Canvas component for launcher test - center_point = math.Vector3(512.0, 512.0, 32.0) - asset_path = os.path.join("Slices", "PinkFlower.dynamicslice") - spawner_entity = dynveg.create_vegetation_area("Instance Spawner", center_point, 16.0, 16.0, 1.0, asset_path) - spawner_entity.add_component("Script Canvas") - instance_counter_path = os.path.join("scriptcanvas", "instance_counter.scriptcanvas") - instance_counter_script = asset.AssetCatalogRequestBus(bus.Broadcast, "GetAssetIdByPath", instance_counter_path, - math.Uuid(), False) - spawner_entity.get_set_test(3, "Script Canvas Asset|Script Canvas Asset", instance_counter_script) + # 1) Create a new, temporary level + lvl_name = "tmp_level" + helper.init_idle() + level_created = general.create_level_no_prompt(lvl_name, 1024, 1, 4096, False) + general.idle_wait(1.0) + Report.critical_result(Tests.level_created, level_created == 0) + general.set_current_view_position(512.0, 480.0, 38.0) - # 3) Create a surface to plant on - dynveg.create_surface_entity("Planting Surface", center_point, 128.0, 128.0, 1.0) + # 2) Create a new entity with required vegetation area components and Script Canvas component for launcher test + center_point = math.Vector3(512.0, 512.0, 32.0) + asset_path = os.path.join("Slices", "PinkFlower.dynamicslice") + spawner_entity = dynveg.create_vegetation_area("Instance Spawner", center_point, 16.0, 16.0, 1.0, asset_path) + spawner_entity.add_component("Script Canvas") + instance_counter_path = os.path.join("scriptcanvas", "instance_counter.scriptcanvas") + instance_counter_script = asset.AssetCatalogRequestBus(bus.Broadcast, "GetAssetIdByPath", instance_counter_path, + math.Uuid(), False) + spawner_entity.get_set_test(3, "Script Canvas Asset|Script Canvas Asset", instance_counter_script) + Report.result(Tests.spawner_entity_created, spawner_entity.id.IsValid() and hydra.has_components(spawner_entity.id, + ["Script Canvas"])) - # 4) Verify instance counts are accurate - general.idle_wait(3.0) # Allow a few seconds for instances to spawn - num_expected_instances = 20 * 20 - box = azlmbr.shape.ShapeComponentRequestsBus(bus.Event, 'GetEncompassingAabb', spawner_entity.id) - num_found = azlmbr.areasystem.AreaSystemRequestBus(bus.Broadcast, 'GetInstanceCountInAabb', box) - self.log(f"Expected {num_expected_instances} instances - Found {num_found} instances") - self.test_success = self.test_success and num_found == num_expected_instances + # 3) Create a surface to plant on + surface_entity = dynveg.create_surface_entity("Planting Surface", center_point, 128.0, 128.0, 1.0) + Report.result(Tests.surface_entity_created, surface_entity.id.IsValid()) - # 5) Move the default Camera entity for testing in the launcher - cam_position = math.Vector3(512.0, 500.0, 35.0) - search_filter = entity.SearchFilter() - search_filter.names = ["Camera"] - search_entity_ids = entity.SearchBus(bus.Broadcast, 'SearchEntities', search_filter) - components.TransformBus(bus.Event, "MoveEntity", search_entity_ids[0], cam_position) + # 4) Verify instance counts are accurate + num_expected_instances = 20 * 20 + success = helper.wait_for_condition(lambda: dynveg.validate_instance_count_in_entity_shape(spawner_entity.id, + num_expected_instances), 5.0) + Report.result(Tests.instance_count, success) - # 6) Save and export to engine - general.save_level() - general.idle_wait(1.0) - general.export_to_engine() - general.idle_wait(1.0) + # 5) Move the default Camera entity for testing in the launcher + cam_position = math.Vector3(512.0, 500.0, 35.0) + search_filter = entity.SearchFilter() + search_filter.names = ["Camera"] + search_entity_ids = entity.SearchBus(bus.Broadcast, 'SearchEntities', search_filter) + components.TransformBus(bus.Event, "MoveEntity", search_entity_ids[0], cam_position) + + # 6) Save and export to engine + general.save_level() + general.export_to_engine() + pak_path = os.path.join(paths.devroot, "AutomatedTesting", "cache", "pc", "levels", lvl_name, "level.pak") + Report.result(Tests.saved_and_exported, os.path.exists(pak_path)) -test = TestDynamicSliceInstanceSpawnerEmbeddedEditor() -test.run() +if __name__ == "__main__": + + from editor_python_test_tools.utils import Report + Report.start_test(DynamicSliceInstanceSpawner_Embedded_E2E) diff --git a/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/DynamicSliceInstanceSpawner_External_E2E.py b/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/DynamicSliceInstanceSpawner_External_E2E.py index dfa4d8191e..7a0abdd969 100755 --- a/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/DynamicSliceInstanceSpawner_External_E2E.py +++ b/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/DynamicSliceInstanceSpawner_External_E2E.py @@ -5,122 +5,137 @@ For complete copyright and license terms please see the LICENSE at the root of t SPDX-License-Identifier: Apache-2.0 OR MIT """ -import os -import sys -sys.path.append(os.path.dirname(os.path.abspath(__file__))) -import azlmbr.legacy.general as general -import azlmbr.asset as asset -import azlmbr.bus as bus -import azlmbr.components as components -import azlmbr.entity as entity -import azlmbr.editor as editor -import azlmbr.math as math -import azlmbr.paths - -sys.path.append(os.path.join(azlmbr.paths.devroot, 'AutomatedTesting', 'Gem', 'PythonTests')) -import editor_python_test_tools.hydra_editor_utils as hydra -from editor_python_test_tools.editor_test_helper import EditorTestHelper -from largeworlds.large_worlds_utils import editor_dynveg_test_helper as dynveg +class Tests: + level_created = ( + "Successfully created level", + "Failed to create level" + ) + spawner_entity_created = ( + "Spawner entity created successfully", + "Failed to create spawner entity" + ) + surface_entity_created = ( + "Surface entity created successfully", + "Failed to create surface entity" + ) + instance_count = ( + "Found the expected number of instances", + "Found an unexpected number of instances" + ) + saved_and_exported = ( + "Saved and exported level successfully", + "Failed to save and export level" + ) -class TestDynamicSliceInstanceSpawnerExternalEditor(EditorTestHelper): - def __init__(self): - EditorTestHelper.__init__(self, log_prefix="DynamicSliceInstanceSpawnerExternalEditor", args=["level"]) +def DynamicSliceInstanceSpawner_External_E2E(): + """ + Summary: + A new temporary level is created. Surface for planting is created. Simple vegetation area is created using + Dynamic Slice Instance Spawner type using external assets. - def run_test(self): - """ - Summary: - A new temporary level is created. Surface for planting is created. Simple vegetation area is created using - Dynamic Slice Instance Spawner type using external assets. + Expected Behavior: + Instances plant as expected in the assigned area. - Expected Behavior: - Instances plant as expected in the assigned area. + Test Steps: + 1) Create level + 2) Create a Vegetation Layer Spawner setup using Dynamic Slice Instance Spawner type assets + 3) Create a surface to plant on + 4) Verify expected instance counts + 5) Add a camera component looking at the planting area for visual debugging + 6) Save and export to engine - Test Steps: - 1) Create level - 2) Create a Vegetation Layer Spawner setup using Dynamic Slice Instance Spawner type assets - 3) Create a surface to plant on - 4) Verify expected instance counts - 5) Add a camera component looking at the planting area for visual debugging - 6) Save and export to engine + 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. - 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 + """ - :return: None - """ + import os - # 1) Create a new, temporary level - self.test_success = self.create_level( - self.args["level"], - heightmap_resolution=1024, - heightmap_meters_per_pixel=1, - terrain_texture_resolution=4096, - use_terrain=False, - ) + import azlmbr.asset as asset + import azlmbr.components as components + import azlmbr.editor as editor + import azlmbr.entity as entity + import azlmbr.legacy.general as general + import azlmbr.bus as bus + import azlmbr.math as math + import azlmbr.paths as paths - general.set_current_view_position(512.0, 480.0, 38.0) + import editor_python_test_tools.hydra_editor_utils as hydra + from largeworlds.large_worlds_utils import editor_dynveg_test_helper as dynveg + from editor_python_test_tools.utils import Report + from editor_python_test_tools.utils import TestHelper as helper - # 2) Create a new entity with required vegetation area components and switch the Vegetation Asset List Source - # Type to External - entity_position = math.Vector3(512.0, 512.0, 32.0) - veg_area_required_components = ["Vegetation Layer Spawner", "Box Shape", "Vegetation Asset List", - "Script Canvas"] - new_entity_id = editor.ToolsApplicationRequestBus( - bus.Broadcast, "CreateNewEntityAtPosition", entity_position, entity.EntityId() - ) - if new_entity_id.IsValid(): - self.log("Spawner entity created") - spawner_entity = hydra.Entity("Spawner Entity", new_entity_id) - spawner_entity.components = [] - for component in veg_area_required_components: - spawner_entity.components.append(hydra.add_component(component, new_entity_id)) - hydra.get_set_test(spawner_entity, 2, "Configuration|Source Type", 1) + # 1) Create a new, temporary level + lvl_name = "tmp_level" + helper.init_idle() + level_created = general.create_level_no_prompt(lvl_name, 1024, 1, 4096, False) + general.idle_wait(1.0) + Report.critical_result(Tests.level_created, level_created == 0) + general.set_current_view_position(512.0, 480.0, 38.0) - # Add a Script Canvas component with instance_counter script for launcher tests - instance_counter_path = os.path.join("scriptcanvas", "instance_counter.scriptcanvas") - instance_counter_script = asset.AssetCatalogRequestBus(bus.Broadcast, "GetAssetIdByPath", instance_counter_path, - math.Uuid(), False) - spawner_entity.get_set_test(3, "Script Canvas Asset|Script Canvas Asset", instance_counter_script) + # 2) Create a new entity with required vegetation area components and switch the Vegetation Asset List Source + # Type to External + entity_position = math.Vector3(512.0, 512.0, 32.0) + veg_area_required_components = ["Vegetation Layer Spawner", "Box Shape", "Vegetation Asset List", + "Script Canvas"] + new_entity_id = editor.ToolsApplicationRequestBus( + bus.Broadcast, "CreateNewEntityAtPosition", entity_position, entity.EntityId() + ) + spawner_entity = hydra.Entity("Spawner Entity", new_entity_id) + spawner_entity.components = [] + for component in veg_area_required_components: + spawner_entity.components.append(hydra.add_component(component, new_entity_id)) + hydra.get_set_test(spawner_entity, 2, "Configuration|Source Type", 1) - # Assign a Vegetation Descriptor List asset to the Vegetation Asset List component - descriptor_asset = asset.AssetCatalogRequestBus( - bus.Broadcast, "GetAssetIdByPath", os.path.join("Assets", "VegDescriptorLists", "flower_pink.vegdescriptorlist"), math.Uuid(), - False) - hydra.get_set_test(spawner_entity, 2, "Configuration|External Assets", descriptor_asset) + # Add a Script Canvas component with instance_counter script for launcher tests + instance_counter_path = os.path.join("scriptcanvas", "instance_counter.scriptcanvas") + instance_counter_script = asset.AssetCatalogRequestBus(bus.Broadcast, "GetAssetIdByPath", instance_counter_path, + math.Uuid(), False) + spawner_entity.get_set_test(3, "Script Canvas Asset|Script Canvas Asset", instance_counter_script) + Report.result(Tests.spawner_entity_created, spawner_entity.id.IsValid() and hydra.has_components(spawner_entity.id, + ["Script Canvas"])) - # Resize the Box Shape component - new_box_dimensions = math.Vector3(16.0, 16.0, 16.0) - box_dimensions_path = "Box Shape|Box Configuration|Dimensions" - hydra.get_set_test(spawner_entity, 1, box_dimensions_path, new_box_dimensions) + # Assign a Vegetation Descriptor List asset to the Vegetation Asset List component + descriptor_asset = asset.AssetCatalogRequestBus( + bus.Broadcast, "GetAssetIdByPath", os.path.join("Assets", "VegDescriptorLists", "flower_pink.vegdescriptorlist"), math.Uuid(), + False) + hydra.get_set_test(spawner_entity, 2, "Configuration|External Assets", descriptor_asset) - # 3) Create a surface to plant on - dynveg.create_surface_entity("Planting Surface", entity_position, 128.0, 128.0, 1.0) + # Resize the Box Shape component + new_box_dimensions = math.Vector3(16.0, 16.0, 16.0) + box_dimensions_path = "Box Shape|Box Configuration|Dimensions" + hydra.get_set_test(spawner_entity, 1, box_dimensions_path, new_box_dimensions) - # 4) Verify instance counts are accurate - general.idle_wait(3.0) # Allow a few seconds for instances to spawn - num_expected_instances = 20 * 20 - box = azlmbr.shape.ShapeComponentRequestsBus(bus.Event, 'GetEncompassingAabb', spawner_entity.id) - num_found = azlmbr.areasystem.AreaSystemRequestBus(bus.Broadcast, 'GetInstanceCountInAabb', box) - self.log(f"Expected {num_expected_instances} instances - Found {num_found} instances") - self.test_success = self.test_success and num_found == num_expected_instances + # 3) Create a surface to plant on + surface_entity = dynveg.create_surface_entity("Planting Surface", entity_position, 128.0, 128.0, 1.0) + Report.result(Tests.surface_entity_created, surface_entity.id.IsValid()) - # 5) Move the default Camera entity for testing in the launcher - cam_position = math.Vector3(512.0, 500.0, 35.0) - search_filter = entity.SearchFilter() - search_filter.names = ["Camera"] - search_entity_ids = entity.SearchBus(bus.Broadcast, 'SearchEntities', search_filter) - components.TransformBus(bus.Event, "MoveEntity", search_entity_ids[0], cam_position) + # 4) Verify instance counts are accurate + num_expected_instances = 20 * 20 + success = helper.wait_for_condition(lambda: dynveg.validate_instance_count_in_entity_shape(spawner_entity.id, + num_expected_instances), 5.0) + Report.result(Tests.instance_count, success) - # 6) Save and export to engine - general.save_level() - general.idle_wait(1.0) - general.export_to_engine() - general.idle_wait(1.0) + # 5) Move the default Camera entity for testing in the launcher + cam_position = math.Vector3(512.0, 500.0, 35.0) + search_filter = entity.SearchFilter() + search_filter.names = ["Camera"] + search_entity_ids = entity.SearchBus(bus.Broadcast, 'SearchEntities', search_filter) + components.TransformBus(bus.Event, "MoveEntity", search_entity_ids[0], cam_position) + + # 6) Save and export to engine + general.save_level() + general.export_to_engine() + pak_path = os.path.join(paths.devroot, "AutomatedTesting", "cache", "pc", "levels", lvl_name, "level.pak") + Report.result(Tests.saved_and_exported, os.path.exists(pak_path)) -test = TestDynamicSliceInstanceSpawnerExternalEditor() -test.run() +if __name__ == "__main__": + + from editor_python_test_tools.utils import Report + Report.start_test(DynamicSliceInstanceSpawner_External_E2E) diff --git a/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/EmptyInstanceSpawner_EmptySpawnerWorks.py b/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/EmptyInstanceSpawner_EmptySpawnerWorks.py index 721d06f858..d0a51809b4 100755 --- a/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/EmptyInstanceSpawner_EmptySpawnerWorks.py +++ b/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/EmptyInstanceSpawner_EmptySpawnerWorks.py @@ -5,109 +5,131 @@ For complete copyright and license terms please see the LICENSE at the root of t SPDX-License-Identifier: Apache-2.0 OR MIT """ -import os -import sys -import azlmbr.legacy.general as general -import azlmbr.bus as bus -import azlmbr.math as math -import azlmbr.paths - -sys.path.append(os.path.join(azlmbr.paths.devroot, 'AutomatedTesting', 'Gem', 'PythonTests')) -import editor_python_test_tools.hydra_editor_utils as hydra -from editor_python_test_tools.editor_test_helper import EditorTestHelper -from largeworlds.large_worlds_utils import editor_dynveg_test_helper as dynveg +class BehaviorContextTests: + spawner_initialized = ( + "Successfully initialized an Empty Instance Spawner", + "Failed to initialize an Empty Instance Spawner" + ) + desc_spawnertype_sets_spawner = ( + "Setting spawnerType sets spawner too", + "Setting spawnerType failed to set spawner to expected value" + ) + desc_spawner_sets_spawnertype = ( + "Setting spawner sets spawnerType too", + "Setting spawner failed to set spawnerType to expected value" + ) -class TestEmptyInstanceSpawner(EditorTestHelper): - def __init__(self): - EditorTestHelper.__init__(self, log_prefix="EmptyInstanceSpawner", args=["level"]) +class PropertyTreeTests: + entity_created = ( + "Spawner entity created successfully", + "Failed to create spawner entity" + ) + spawner_type_set = ( + "Successfully set spawner type", + "Failed to set spawner type" + ) + empty_instance_count_validation = ( + "Expected number of empty instances planted", + "Unexpected number of empty instances planted" + ) + not_affected_by_allow_empty_assets = ( + "Instance count unaffected by Allow Empty Assets toggle", + "Instance count was unexpectedly affected by Allow Empty Assets toggle" + ) - def run_test(self): - """ - Summary: - Test aspects of the EmptyInstanceSpawner through the BehaviorContext and the Property Tree. - :return: None - """ - # 1) Open an empty level - self.test_success = self.create_level( - self.args["level"], - heightmap_resolution=1024, - heightmap_meters_per_pixel=1, - terrain_texture_resolution=4096, - use_terrain=False, +def EmptyInstanceSpawner_EmptySpawnerWorks(): + """ + Summary: + Test aspects of the EmptyInstanceSpawner through the BehaviorContext and the Property Tree. + + :return: None + """ + + import azlmbr.legacy.general as general + import azlmbr.math as math + + import editor_python_test_tools.hydra_editor_utils as hydra + from largeworlds.large_worlds_utils import editor_dynveg_test_helper as dynveg + from editor_python_test_tools.utils import Report + from editor_python_test_tools.utils import TestHelper as helper + + # 1) Open an existing simple level + helper.init_idle() + helper.open_level("Physics", "Base") + general.set_current_view_position(512.0, 480.0, 38.0) + + # Grab the UUID that we need for creating an Empty Spawner + empty_spawner_uuid = azlmbr.math.Uuid_CreateString('{23C40FD4-A55F-4BD3-BE5B-DC5423F217C2}', 0) + + # 2) Test EmptyInstanceSpawner BehaviorContext + behavior_context_test_success = True + empty_spawner = azlmbr.vegetation.EmptyInstanceSpawner() + behavior_context_test_success = behavior_context_test_success and (empty_spawner is not None) + behavior_context_test_success = behavior_context_test_success and (empty_spawner.typename == 'EmptyInstanceSpawner') + Report.critical_result(BehaviorContextTests.spawner_initialized, behavior_context_test_success) + Report.info(f'EmptyInstanceSpawner() BehaviorContext test: {behavior_context_test_success}') + + # 3) Test Descriptor BehaviorContext - setting spawnerType sets spawner too + spawner_type_test_success = True + descriptor = azlmbr.vegetation.Descriptor() + spawner_type_test_success = spawner_type_test_success and hydra.get_set_property_test(descriptor, 'spawnerType', empty_spawner_uuid) + spawner_type_test_success = spawner_type_test_success and (descriptor.spawner.typename == 'EmptyInstanceSpawner') + Report.result(BehaviorContextTests.desc_spawnertype_sets_spawner, spawner_type_test_success) + Report.info(f'Descriptor() BehaviorContext spawnerType test: {spawner_type_test_success}') + + # 4) Test Descriptor BehaviorContext - setting spawner sets spawnerType too + spawner_test_success = True + descriptor = azlmbr.vegetation.Descriptor() + descriptor.spawner = empty_spawner + spawner_test_success = spawner_test_success and (descriptor.spawnerType.Equal(empty_spawner_uuid)) + spawner_test_success = spawner_test_success and (descriptor.spawner.typename == 'EmptyInstanceSpawner') + Report.result(BehaviorContextTests.desc_spawner_sets_spawnertype, spawner_test_success) + Report.info(f'Descriptor() BehaviorContext spawner test: {spawner_test_success}') + + ### Setup for Property Tree set of tests + + # Create a new entity with required vegetation area components + spawner_entity = hydra.Entity("Veg Area") + spawner_entity.create_entity( + math.Vector3(512.0, 512.0, 32.0), + ["Vegetation Layer Spawner", "Box Shape", "Vegetation Asset List"] ) - general.idle_wait(1.0) - general.set_current_view_position(512.0, 480.0, 38.0) + Report.critical_result(PropertyTreeTests.entity_created, spawner_entity.id.IsValid()) - # Grab the UUID that we need for creating an Empty Spawner - empty_spawner_uuid = azlmbr.math.Uuid_CreateString('{23C40FD4-A55F-4BD3-BE5B-DC5423F217C2}', 0) + # Resize the Box Shape component + new_box_dimensions = math.Vector3(16.0, 16.0, 16.0) + box_dimensions_path = "Box Shape|Box Configuration|Dimensions" + spawner_entity.get_set_test(1, box_dimensions_path, new_box_dimensions) - # 2) Test EmptyInstanceSpawner BehaviorContext - behavior_context_test_success = True - empty_spawner = azlmbr.vegetation.EmptyInstanceSpawner() - behavior_context_test_success = behavior_context_test_success and (empty_spawner is not None) - behavior_context_test_success = behavior_context_test_success and (empty_spawner.typename == 'EmptyInstanceSpawner') - self.test_success = self.test_success and behavior_context_test_success - self.log(f'EmptyInstanceSpawner() BehaviorContext test: {behavior_context_test_success}') + # Create a surface to plant on + dynveg.create_surface_entity("Surface Entity", math.Vector3(512.0, 512.0, 32.0), 1024.0, 1024.0, 1.0) - # 3) Test Descriptor BehaviorContext - setting spawnerType sets spawner too - spawner_type_test_success = True - descriptor = azlmbr.vegetation.Descriptor() - spawner_type_test_success = spawner_type_test_success and hydra.get_set_property_test(descriptor, 'spawnerType', empty_spawner_uuid) - spawner_type_test_success = spawner_type_test_success and (descriptor.spawner.typename == 'EmptyInstanceSpawner') - self.test_success = self.test_success and spawner_type_test_success - self.log(f'Descriptor() BehaviorContext spawnerType test: {spawner_type_test_success}') + # 5) Descriptor Property Tree test: spawner type can be set - # 4) Test Descriptor BehaviorContext - setting spawner sets spawnerType too - spawner_test_success = True - descriptor = azlmbr.vegetation.Descriptor() - descriptor.spawner = empty_spawner - spawner_test_success = spawner_test_success and (descriptor.spawnerType.Equal(empty_spawner_uuid)) - spawner_test_success = spawner_test_success and (descriptor.spawner.typename == 'EmptyInstanceSpawner') - self.test_success = self.test_success and spawner_test_success - self.log(f'Descriptor() BehaviorContext spawner test: {spawner_test_success}') + # - Validate the empty spawner type can be set correctly. + property_tree_success = True + property_tree_success = property_tree_success and spawner_entity.get_set_test(2, 'Configuration|Embedded Assets|[0]|Instance Spawner', empty_spawner_uuid) + Report.result(PropertyTreeTests.spawner_type_set, property_tree_success) - ### Setup for Property Tree set of tests + # This should result in 400 instances, since our box is 16 m x 16 m and by default the veg system plants + # 20 instances per 16 meters + num_expected_instances = 20 * 20 + property_tree_success = property_tree_success and helper.wait_for_condition(lambda: dynveg.validate_instance_count_in_entity_shape(spawner_entity.id, num_expected_instances), 5.0) + Report.result(PropertyTreeTests.empty_instance_count_validation, property_tree_success) + Report.info(f'Property Tree spawner type test: {property_tree_success}') - # Create a new entity with required vegetation area components - spawner_entity = hydra.Entity("Veg Area") - spawner_entity.create_entity( - math.Vector3(512.0, 512.0, 32.0), - ["Vegetation Layer Spawner", "Box Shape", "Vegetation Asset List"] - ) - if spawner_entity.id.IsValid(): - self.log(f"'{spawner_entity.name}' created") - - # Resize the Box Shape component - new_box_dimensions = math.Vector3(16.0, 16.0, 16.0) - box_dimensions_path = "Box Shape|Box Configuration|Dimensions" - spawner_entity.get_set_test(1, box_dimensions_path, new_box_dimensions) - - # Create a surface to plant on - dynveg.create_surface_entity("Surface Entity", math.Vector3(512.0, 512.0, 32.0), 1024.0, 1024.0, 1.0) - - # 5) Descriptor Property Tree test: spawner type can be set - - # - Validate the empty spawner type can be set correctly. - property_tree_success = True - property_tree_success = property_tree_success and spawner_entity.get_set_test(2, 'Configuration|Embedded Assets|[0]|Instance Spawner', empty_spawner_uuid) - - # This should result in 400 instances, since our box is 16 m x 16 m and by default the veg system plants - # 20 instances per 16 meters - num_expected_instances = 20 * 20 - property_tree_success = property_tree_success and self.wait_for_condition(lambda: dynveg.validate_instance_count_in_entity_shape(spawner_entity.id, num_expected_instances), 5.0) - self.test_success = self.test_success and property_tree_success - self.log(f'Property Tree spawner type test: {property_tree_success}') - - # 6) Validate that the "Allow Empty Assets" setting doesn't affect the EmptyInstanceSpawner - allow_empty_assets_success = True - spawner_entity.get_set_test(0, 'Configuration|Allow Empty Assets', False) - allow_empty_assets_success = allow_empty_assets_success and self.wait_for_condition(lambda: dynveg.validate_instance_count_in_entity_shape(spawner_entity.id, num_expected_instances), 5.0) - self.test_success = self.test_success and allow_empty_assets_success - self.log(f'Allow Empty Assets test: {allow_empty_assets_success}') + # 6) Validate that the "Allow Empty Assets" setting doesn't affect the EmptyInstanceSpawner + allow_empty_assets_success = True + spawner_entity.get_set_test(0, 'Configuration|Allow Empty Assets', False) + allow_empty_assets_success = allow_empty_assets_success and helper.wait_for_condition(lambda: dynveg.validate_instance_count_in_entity_shape(spawner_entity.id, num_expected_instances), 5.0) + Report.result(PropertyTreeTests.not_affected_by_allow_empty_assets, allow_empty_assets_success) + Report.info(f'Allow Empty Assets test: {allow_empty_assets_success}') -test = TestEmptyInstanceSpawner() -test.run() +if __name__ == "__main__": + + from editor_python_test_tools.utils import Report + Report.start_test(EmptyInstanceSpawner_EmptySpawnerWorks) diff --git a/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/InstanceSpawnerPriority_LayerAndSubPriority.py b/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/InstanceSpawnerPriority_LayerAndSubPriority.py index e5ff0bf86f..98418c2432 100755 --- a/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/InstanceSpawnerPriority_LayerAndSubPriority.py +++ b/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/InstanceSpawnerPriority_LayerAndSubPriority.py @@ -5,111 +5,115 @@ For complete copyright and license terms please see the LICENSE at the root of t SPDX-License-Identifier: Apache-2.0 OR MIT """ -import os -import sys -sys.path.append(os.path.dirname(os.path.abspath(__file__))) -import azlmbr.editor as editor -import azlmbr.legacy.general as general -import azlmbr.bus as bus -import azlmbr.math as math -import azlmbr.paths -import azlmbr.vegetation as vegetation - -sys.path.append(os.path.join(azlmbr.paths.devroot, 'AutomatedTesting', 'Gem', 'PythonTests')) -import editor_python_test_tools.hydra_editor_utils as hydra -from editor_python_test_tools.editor_test_helper import EditorTestHelper -from largeworlds.large_worlds_utils import editor_dynveg_test_helper as dynveg +class Tests: + initial_instance_count = ( + "Initial instance count is as expected", + "Initial instance count does not match expected results" + ) + layer_priority_instance_count = ( + "Instance count is as expected after updating layer priorities", + "Instance count does not match expected results after updating layer priorities" + ) + sub_priority_instance_count = ( + "Instance count is as expected after updating sub priorities", + "Instance count does not match expected results after updating sub priorities" + ) -class TestInstanceSpawnerPriority(EditorTestHelper): - def __init__(self): - EditorTestHelper.__init__(self, log_prefix="InstanceSpawnerPriority", args=["level"]) +def InstanceSpawnerPriority_LayerAndSubPriority(): + """ + Summary: + A new level is created. An instance spawner area and blocker area are setup to overlap. Instance counts are + verified with the initial setup. Layer priority on the blocker area is set to lower than the instance spawner + area, and instance counts are re-verified. - def run_test(self): - """ - Summary: - A new level is created. An instance spawner area and blocker area are setup to overlap. Instance counts are - verified with the initial setup. Layer priority on the blocker area is set to lower than the instance spawner - area, and instance counts are re-verified. + Expected Behavior: + Vegetation areas with a higher Layer Priority plant over those with a lower Layer Priority - Expected Behavior: - Vegetation areas with a higher Layer Priority plant over those with a lower Layer Priority + Test Steps: + 1) Open a simple level + 2) Create overlapping instance spawner and blocker areas + 3) Create a surface to plant on + 4) Validate initial instance counts in the spawner area + 5) Reduce the Layer Priority of the blocker area + 6) Validate instance counts in the spawner area - Test Steps: - 1) Create a new level - 2) Create overlapping instance spawner and blocker areas - 3) Create a surface to plant on - 4) Validate initial instance counts in the spawner area - 5) Reduce the Layer Priority of the blocker area - 6) Validate instance counts in the spawner area - - 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. + 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 - """ + :return: None + """ - # 1) Create a new, temporary level - self.test_success = self.create_level( - self.args["level"], - heightmap_resolution=1024, - heightmap_meters_per_pixel=1, - terrain_texture_resolution=4096, - use_terrain=False, - ) + import os - # Set view of planting area for visual debugging - general.set_current_view_position(512.0, 500.0, 38.0) - general.set_current_view_rotation(-20.0, 0.0, 0.0) + import azlmbr.editor as editor + import azlmbr.legacy.general as general + import azlmbr.bus as bus + import azlmbr.math as math - # 2) Create overlapping areas: 1 instance spawner area, and 1 blocker area - spawner_center_point = math.Vector3(508.0, 508.0, 32.0) - asset_path = os.path.join("Slices", "PinkFlower.dynamicslice") - spawner_entity = dynveg.create_vegetation_area("Instance Spawner", spawner_center_point, 16.0, 16.0, 1.0, - asset_path) - blocker_center_point = math.Vector3(516.0, 516.0, 32.0) - blocker_entity = dynveg.create_blocker_area("Instance Blocker", blocker_center_point, 16.0, 16.0, 1.0) + import editor_python_test_tools.hydra_editor_utils as hydra + from largeworlds.large_worlds_utils import editor_dynveg_test_helper as dynveg + from editor_python_test_tools.utils import Report + from editor_python_test_tools.utils import TestHelper as helper - # 3) Create a surface for planting - planting_surface_center_point = math.Vector3(512.0, 512.0, 32.0) - dynveg.create_surface_entity("Planting Surface", planting_surface_center_point, 64.0, 64.0, 1.0) + # 1) Open an existing simple level + helper.init_idle() + helper.open_level("Physics", "Base") - # Set instances to spawn on a center snap point to avoid unexpected instances around the edges of the box shape - veg_system_settings_component = hydra.add_level_component("Vegetation System Settings") - editor.EditorComponentAPIBus(bus.Broadcast, "SetComponentProperty", veg_system_settings_component, - 'Configuration|Area System Settings|Sector Point Snap Mode', 1) + # Set view of planting area for visual debugging + general.set_current_view_position(512.0, 500.0, 38.0) + general.set_current_view_rotation(-20.0, 0.0, 0.0) - # 4) Validate the expected instance count with initial setup. GetAreaProductCount is used as - # GetInstanceCountInAabb does not filter out blocked instances - num_expected = (20 * 20) - (10 * 10) # 20 instances per 16m per side minus 1 blocked quadrant - result = 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 result + # 2) Create overlapping areas: 1 instance spawner area, and 1 blocker area + spawner_center_point = math.Vector3(508.0, 508.0, 32.0) + asset_path = os.path.join("Slices", "PinkFlower.dynamicslice") + spawner_entity = dynveg.create_vegetation_area("Instance Spawner", spawner_center_point, 16.0, 16.0, 1.0, + asset_path) + blocker_center_point = math.Vector3(516.0, 516.0, 32.0) + blocker_entity = dynveg.create_blocker_area("Instance Blocker", blocker_center_point, 16.0, 16.0, 1.0) - # 5) Change the Instance Spawner area to a higher layer priority than the Instance Blocker - blocker_entity.get_set_test(0, 'Configuration|Layer Priority', 0) + # 3) Create a surface for planting + planting_surface_center_point = math.Vector3(512.0, 512.0, 32.0) + dynveg.create_surface_entity("Planting Surface", planting_surface_center_point, 64.0, 64.0, 1.0) - # 6) Validate the expected instance count with changed area priorities - num_expected = 20 * 20 # 20 instances per 16m per side, no instances should be blocked at this point - result = 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 result + # Set instances to spawn on a center snap point to avoid unexpected instances around the edges of the box shape + veg_system_settings_component = hydra.add_level_component("Vegetation System Settings") + editor.EditorComponentAPIBus(bus.Broadcast, "SetComponentProperty", veg_system_settings_component, + 'Configuration|Area System Settings|Sector Point Snap Mode', 1) - # 7) Revert Layer Priority changes so both areas are equal, and change Sub Priority to a higher value on the - # Instance Spawner area - blocker_entity.get_set_test(0, 'Configuration|Layer Priority', 1) - spawner_entity.get_set_test(0, 'Configuration|Sub Priority', 100) - blocker_entity.get_set_test(0, 'Configuration|Sub Priority', 1) + # 4) Validate the expected instance count with initial setup. GetAreaProductCount is used as + # GetInstanceCountInAabb does not filter out blocked instances + num_expected = (20 * 20) - (10 * 10) # 20 instances per 16m per side minus 1 blocked quadrant + result = helper.wait_for_condition(lambda: dynveg.validate_instance_count_in_entity_shape(spawner_entity.id, + num_expected), 5.0) + Report.result(Tests.initial_instance_count, result) - # 8) Validate the expected instance count with changed area priorities - num_expected = 20 * 20 # 20 instances per 16m per side, no instances should be blocked at this point - result = 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 result + # 5) Change the Instance Spawner area to a higher layer priority than the Instance Blocker + blocker_entity.get_set_test(0, 'Configuration|Layer Priority', 0) + + # 6) Validate the expected instance count with changed area priorities + num_expected = 20 * 20 # 20 instances per 16m per side, no instances should be blocked at this point + result = helper.wait_for_condition(lambda: dynveg.validate_instance_count_in_entity_shape(spawner_entity.id, + num_expected), 5.0) + Report.result(Tests.layer_priority_instance_count, result) + + # 7) Revert Layer Priority changes so both areas are equal, and change Sub Priority to a higher value on the + # Instance Spawner area + blocker_entity.get_set_test(0, 'Configuration|Layer Priority', 1) + spawner_entity.get_set_test(0, 'Configuration|Sub Priority', 100) + blocker_entity.get_set_test(0, 'Configuration|Sub Priority', 1) + + # 8) Validate the expected instance count with changed area priorities + num_expected = 20 * 20 # 20 instances per 16m per side, no instances should be blocked at this point + result = helper.wait_for_condition(lambda: dynveg.validate_instance_count_in_entity_shape(spawner_entity.id, + num_expected), 5.0) + Report.result(Tests.sub_priority_instance_count, result) -test = TestInstanceSpawnerPriority() -test.run() +if __name__ == "__main__": + + from editor_python_test_tools.utils import Report + Report.start_test(InstanceSpawnerPriority_LayerAndSubPriority) diff --git a/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/LayerBlender_E2E_Editor.py b/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/LayerBlender_E2E_Editor.py index f03ea29613..f56c0b836e 100755 --- a/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/LayerBlender_E2E_Editor.py +++ b/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/LayerBlender_E2E_Editor.py @@ -5,151 +5,161 @@ For complete copyright and license terms please see the LICENSE at the root of t SPDX-License-Identifier: Apache-2.0 OR MIT """ -""" -C2627906: A simple Vegetation Layer Blender area can be created -""" -import os -from math import radians -import sys - -sys.path.append(os.path.dirname(os.path.abspath(__file__))) -import azlmbr.asset as asset -import azlmbr.areasystem as areasystem -import azlmbr.legacy.general as general -import azlmbr -import azlmbr.bus as bus -import azlmbr.components as components -import azlmbr.math as math -import azlmbr.entity as entity -import azlmbr.paths - -sys.path.append(os.path.join(azlmbr.paths.devroot, 'AutomatedTesting', 'Gem', 'PythonTests')) -import editor_python_test_tools.hydra_editor_utils as hydra -from editor_python_test_tools.editor_test_helper import EditorTestHelper -from largeworlds.large_worlds_utils import editor_dynveg_test_helper as dynveg +class Tests: + level_created = ( + "Successfully created level", + "Failed to create level" + ) + blender_entity_created = ( + "Blender entity created successfully", + "Failed to create Blender entity" + ) + instance_count = ( + "Found the expected number of instances in the Blender area", + "Found an unexpected number of instances in the Blender area" + ) + instances_blended = ( + "Instances from each spawner are blended as expected", + "Found an unexpected number of instances from each spawner" + ) + saved_and_exported = ( + "Saved and exported level successfully", + "Failed to save and export level" + ) -class TestVegLayerBlenderCreated(EditorTestHelper): - def __init__(self): - EditorTestHelper.__init__(self, log_prefix="LayerBlender_E2E_Editor", args=["level"]) - self.screenshot_count = 0 +def LayerBlender_E2E_Editor(): + """ + Summary: + A temporary level is loaded. Two vegetation areas with different meshes are added and then + pinned to a vegetation blender. Screenshots are taken in the editor normal mode and in game mode. - def run_test(self): - """ - Summary: - A temporary level is loaded. Two vegetation areas with different meshes are added and then - pinned to a vegetation blender. Screenshots are taken in the editor normal mode and in game mode. + Expected Behavior: + The specified assets plant in the specified blend area and are visible in the Viewport in + Edit Mode, Game Mode. - Expected Behavior: - The specified assets plant in the specified blend area and are visible in the Viewport in - Edit Mode, Game Mode. + Test Steps: + 1) Create level + 2) Create 2 vegetation areas with different meshes + 3) Create Blender entity and pin the vegetation areas + 4) Take screenshot in normal mode + 5) Create a new entity with a Camera component for testing in the launcher + 6) Save level and take screenshot in game mode + 7) Export to engine - Test Steps: - 1) Create level - 2) Create 2 vegetation areas with different meshes - 3) Create Blender entity and pin the vegetation areas - 4) Take screenshot in normal mode - 5) Create a new entity with a Camera component for testing in the launcher - 6) Save level and take screenshot in game mode - 7) Export to engine + 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. - 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 + """ - :return: None - """ + import os + from math import radians - # 1) Create/prepare a new level and set an appropriate view of blender area - self.test_success = self.create_level( - self.args["level"], - heightmap_resolution=1024, - heightmap_meters_per_pixel=1, - terrain_texture_resolution=4096, - use_terrain=False, - ) + import azlmbr.asset as asset + import azlmbr.areasystem as areasystem + import azlmbr.legacy.general as general + import azlmbr.paths as paths + import azlmbr.bus as bus + import azlmbr.components as components + import azlmbr.math as math + import azlmbr.entity as entity - general.set_current_view_position(500.49, 498.69, 46.66) - general.set_current_view_rotation(-42.05, 0.00, -36.33) + import editor_python_test_tools.hydra_editor_utils as hydra + from largeworlds.large_worlds_utils import editor_dynveg_test_helper as dynveg + from editor_python_test_tools.utils import Report + from editor_python_test_tools.utils import TestHelper as helper - # 2) Create 2 vegetation areas with different meshes - purple_position = math.Vector3(504.0, 512.0, 32.0) - purple_asset_path = os.path.join("Slices", "PurpleFlower.dynamicslice") - spawner_entity_1 = dynveg.create_vegetation_area("Purple Spawner", - purple_position, - 16.0, 16.0, 1.0, - purple_asset_path) + # 1) Create a new, temporary level + lvl_name = "tmp_level" + helper.init_idle() + level_created = general.create_level_no_prompt(lvl_name, 1024, 1, 4096, False) + general.idle_wait(1.0) + Report.critical_result(Tests.level_created, level_created == 0) - pink_position = math.Vector3(520.0, 512.0, 32.0) - pink_asset_path = os.path.join("Slices", "PinkFlower.dynamicslice") - spawner_entity_2 = dynveg.create_vegetation_area("Pink Spawner", - pink_position, - 16.0, 16.0, 1.0, - pink_asset_path) + general.set_current_view_position(500.49, 498.69, 46.66) + general.set_current_view_rotation(-42.05, 0.00, -36.33) - base_position = math.Vector3(512.0, 512.0, 32.0) - dynveg.create_surface_entity("Surface Entity", - base_position, - 16.0, 16.0, 1.0) + # 2) Create 2 vegetation areas with different meshes + purple_position = math.Vector3(504.0, 512.0, 32.0) + purple_asset_path = os.path.join("Slices", "PurpleFlower.dynamicslice") + spawner_entity_1 = dynveg.create_vegetation_area("Purple Spawner", + purple_position, + 16.0, 16.0, 1.0, + purple_asset_path) - hydra.add_level_component("Vegetation Debugger") + pink_position = math.Vector3(520.0, 512.0, 32.0) + pink_asset_path = os.path.join("Slices", "PinkFlower.dynamicslice") + spawner_entity_2 = dynveg.create_vegetation_area("Pink Spawner", + pink_position, + 16.0, 16.0, 1.0, + pink_asset_path) - # 3) Create Blender entity and pin the vegetation areas. We also add and attach a Lua script to validate in the - # launcher for the follow-up test - blender_entity = hydra.Entity("Blender") - blender_entity.create_entity( - base_position, - ["Box Shape", "Vegetation Layer Blender", "Lua Script"] - ) - if blender_entity.id.IsValid(): - print(f"'{blender_entity.name}' created") + base_position = math.Vector3(512.0, 512.0, 32.0) + dynveg.create_surface_entity("Surface Entity", + base_position, + 16.0, 16.0, 1.0) - blender_entity.get_set_test(0, "Box Shape|Box Configuration|Dimensions", math.Vector3(16.0, 16.0, 1.0)) - blender_entity.get_set_test(1, "Configuration|Vegetation Areas", [spawner_entity_1.id, spawner_entity_2.id]) - instance_counter_path = os.path.join("luascripts", "instance_counter_blender.lua") - instance_counter_script = asset.AssetCatalogRequestBus(bus.Broadcast, "GetAssetIdByPath", instance_counter_path, - math.Uuid(), False) - blender_entity.get_set_test(2, "Script properties|Asset", instance_counter_script) + hydra.add_level_component("Vegetation Debugger") - # 4) Verify instances in blender area are equally represented by both descriptors + # 3) Create Blender entity and pin the vegetation areas. We also add and attach a Lua script to validate in the + # launcher for the follow-up test + blender_entity = hydra.Entity("Blender") + blender_entity.create_entity( + base_position, + ["Box Shape", "Vegetation Layer Blender", "Lua Script"] + ) + Report.result(Tests.blender_entity_created, blender_entity.id.IsValid()) - # Wait for instances to spawn - general.run_console('veg_debugClearAllAreas') - num_expected = 20 * 20 - self.test_success = self.test_success and self.wait_for_condition( - lambda: dynveg.validate_instance_count(base_position, 8.0, num_expected), 5.0) + blender_entity.get_set_test(0, "Box Shape|Box Configuration|Dimensions", math.Vector3(16.0, 16.0, 1.0)) + blender_entity.get_set_test(1, "Configuration|Vegetation Areas", [spawner_entity_1.id, spawner_entity_2.id]) + instance_counter_path = os.path.join("luascripts", "instance_counter_blender.lua") + instance_counter_script = asset.AssetCatalogRequestBus(bus.Broadcast, "GetAssetIdByPath", instance_counter_path, + math.Uuid(), False) + blender_entity.get_set_test(2, "Script properties|Asset", instance_counter_script) - if self.test_success: - box = math.Aabb_CreateCenterRadius(base_position, 8.0) - instances = areasystem.AreaSystemRequestBus(bus.Broadcast, 'GetInstancesInAabb', box) - pink_count = 0 - purple_count = 0 - for instance in instances: - purple_asset_path = purple_asset_path.replace("\\", "/").lower() - pink_asset_path = pink_asset_path.replace("\\", "/").lower() - if instance.descriptor.spawner.GetSliceAssetPath() == pink_asset_path: - pink_count += 1 - elif instance.descriptor.spawner.GetSliceAssetPath() == purple_asset_path: - purple_count += 1 - self.test_success = pink_count == purple_count and (pink_count + purple_count == num_expected) and self.test_success + # 4) Verify instances in blender area are equally represented by both descriptors - # 5) Move the default Camera entity for testing in the launcher - cam_position = math.Vector3(500.0, 500.0, 47.0) - cam_rot_degrees_vector = math.Vector3(radians(-55.0), radians(28.5), radians(-17.0)) - search_filter = entity.SearchFilter() - search_filter.names = ["Camera"] - search_entity_ids = entity.SearchBus(bus.Broadcast, 'SearchEntities', search_filter) - components.TransformBus(bus.Event, "MoveEntity", search_entity_ids[0], cam_position) - azlmbr.components.TransformBus(bus.Event, "SetLocalRotation", search_entity_ids[0], cam_rot_degrees_vector) + # Wait for instances to spawn + general.run_console('veg_debugClearAllAreas') + num_expected = 20 * 20 + success = helper.wait_for_condition( + lambda: dynveg.validate_instance_count(base_position, 8.0, num_expected), 5.0) + Report.critical_result(Tests.instance_count, success) - # 6) Save and export level - general.save_level() - general.idle_wait(1.0) - general.export_to_engine() - general.idle_wait(1.0) + box = math.Aabb_CreateCenterRadius(base_position, 8.0) + instances = areasystem.AreaSystemRequestBus(bus.Broadcast, 'GetInstancesInAabb', box) + pink_count = 0 + purple_count = 0 + for instance in instances: + purple_asset_path = purple_asset_path.replace("\\", "/").lower() + pink_asset_path = pink_asset_path.replace("\\", "/").lower() + if instance.descriptor.spawner.GetSliceAssetPath() == pink_asset_path: + pink_count += 1 + elif instance.descriptor.spawner.GetSliceAssetPath() == purple_asset_path: + purple_count += 1 + Report.result(Tests.instances_blended, pink_count == purple_count and (pink_count + purple_count == num_expected)) + + # 5) Move the default Camera entity for testing in the launcher + cam_position = math.Vector3(500.0, 500.0, 47.0) + cam_rot_degrees_vector = math.Vector3(radians(-55.0), radians(28.5), radians(-17.0)) + search_filter = entity.SearchFilter() + search_filter.names = ["Camera"] + search_entity_ids = entity.SearchBus(bus.Broadcast, 'SearchEntities', search_filter) + components.TransformBus(bus.Event, "MoveEntity", search_entity_ids[0], cam_position) + azlmbr.components.TransformBus(bus.Event, "SetLocalRotation", search_entity_ids[0], cam_rot_degrees_vector) + + # 6) Save and export to engine + general.save_level() + general.export_to_engine() + pak_path = os.path.join(paths.devroot, "AutomatedTesting", "cache", "pc", "levels", lvl_name, "level.pak") + Report.result(Tests.saved_and_exported, os.path.exists(pak_path)) -test = TestVegLayerBlenderCreated() -test.run() +if __name__ == "__main__": + + from editor_python_test_tools.utils import Report + Report.start_test(LayerBlender_E2E_Editor) diff --git a/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/LayerBlocker_InstancesBlockedInConfiguredArea.py b/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/LayerBlocker_InstancesBlockedInConfiguredArea.py index 138ac27700..625b7d2265 100755 --- a/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/LayerBlocker_InstancesBlockedInConfiguredArea.py +++ b/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/LayerBlocker_InstancesBlockedInConfiguredArea.py @@ -5,102 +5,105 @@ For complete copyright and license terms please see the LICENSE at the root of t SPDX-License-Identifier: Apache-2.0 OR MIT """ -import os -import sys -import azlmbr.bus as bus -import azlmbr.editor as editor -import azlmbr.math as math -import azlmbr.legacy.general as general -import azlmbr.paths - -sys.path.append(os.path.join(azlmbr.paths.devroot, "AutomatedTesting", "Gem", "PythonTests")) -import editor_python_test_tools.hydra_editor_utils as hydra -from editor_python_test_tools.editor_test_helper import EditorTestHelper -from largeworlds.large_worlds_utils import editor_dynveg_test_helper as dynveg +class Tests: + initial_instance_count = ( + "Initial instance count is as expected", + "Unexpected number of initial instances found" + ) + blocked_instance_count = ( + "Expected number of instances found after configuring Blocker", + "Unexpected number of instances found after configuring Blocker" + ) -class TestLayerBlocker(EditorTestHelper): - def __init__(self): - EditorTestHelper.__init__(self, log_prefix="LayerBlocker_InstancesBlocked", args=["level"]) - def run_test(self): - """ - Summary: - An empty level is created. A Vegetation Layer Spawner area is configured. A Vegetation Layer Blocker area is - configured to block instances in the spawner area. +def LayerBlocker_InstancesBlockedInConfiguredArea(): + """ + Summary: + An empty level is created. A Vegetation Layer Spawner area is configured. A Vegetation Layer Blocker area is + configured to block instances in the spawner area. - Expected Behavior: - Vegetation is blocked by the configured Blocker area. + Expected Behavior: + Vegetation is blocked by the configured Blocker area. - Test Steps: - 1. A new level is created - 2. Vegetation Layer Spawner area is created - 3. Planting surface is created - 4. Vegetation System Settings level component is added, and Snap Mode set to center to ensure expected instance - counts are accurate in the configured vegetation area - 5. Initial instance counts pre-blocker are validated - 6. A Vegetation Layer Blocker area is created, overlapping the spawner area - 7. Post-blocker instance counts are validated + Test Steps: + 1. A simple level is opened + 2. Vegetation Layer Spawner area is created + 3. Planting surface is created + 4. Vegetation System Settings level component is added, and Snap Mode set to center to ensure expected instance + counts are accurate in the configured vegetation area + 5. Initial instance counts pre-blocker are validated + 6. A Vegetation Layer Blocker area is created, overlapping the spawner area + 7. Post-blocker instance counts are validated - 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. + 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 - """ + :return: None + """ - # 1) Create a new, temporary level - self.test_success = self.create_level( - self.args["level"], - heightmap_resolution=1024, - heightmap_meters_per_pixel=1, - terrain_texture_resolution=4096, - use_terrain=False, - ) + import os - # Set view of planting area for visual debugging - general.set_current_view_position(512.0, 500.0, 38.0) - general.set_current_view_rotation(-20.0, 0.0, 0.0) + import azlmbr.bus as bus + import azlmbr.editor as editor + import azlmbr.math as math + import azlmbr.legacy.general as general - # 2) Create a new instance spawner entity - spawner_center_point = math.Vector3(512.0, 512.0, 32.0) - asset_path = os.path.join("Slices", "PinkFlower.dynamicslice") - spawner_entity = dynveg.create_vegetation_area("Instance Spawner", spawner_center_point, 16.0, 16.0, 16.0, - asset_path) + import editor_python_test_tools.hydra_editor_utils as hydra + from largeworlds.large_worlds_utils import editor_dynveg_test_helper as dynveg + from editor_python_test_tools.utils import Report + from editor_python_test_tools.utils import TestHelper as helper - # 3) Create surface for planting on - dynveg.create_surface_entity("Surface Entity", spawner_center_point, 32.0, 32.0, 1.0) + # 1) Open an existing simple level + helper.init_idle() + helper.open_level("Physics", "Base") - # 4) Add a Vegetation System Settings Level component and set Sector Point Snap Mode to Center - veg_system_settings_component = hydra.add_level_component("Vegetation System Settings") - editor.EditorComponentAPIBus(bus.Broadcast, "SetComponentProperty", veg_system_settings_component, - 'Configuration|Area System Settings|Sector Point Snap Mode', 1) + # Set view of planting area for visual debugging + general.set_current_view_position(512.0, 500.0, 38.0) + general.set_current_view_rotation(-20.0, 0.0, 0.0) - # 5) Verify initial instance counts - num_expected = 20 * 20 - success = self.wait_for_condition(lambda: dynveg.validate_instance_count_in_entity_shape(spawner_entity.id, - num_expected), 5.0) - self.test_success = success and self.test_success + # 2) Create a new instance spawner entity + spawner_center_point = math.Vector3(512.0, 512.0, 32.0) + asset_path = os.path.join("Slices", "PinkFlower.dynamicslice") + spawner_entity = dynveg.create_vegetation_area("Instance Spawner", spawner_center_point, 16.0, 16.0, 16.0, + asset_path) - # 6) Create a new Vegetation Layer Blocker area overlapping the spawner area - blocker_entity = hydra.Entity("Blocker Area") - blocker_entity.create_entity( - spawner_center_point, - ["Vegetation Layer Blocker", "Box Shape"] - ) - if blocker_entity.id.IsValid(): - print(f"'{blocker_entity.name}' created") - blocker_entity.get_set_test(1, "Box Shape|Box Configuration|Dimensions", - math.Vector3(3.0, 3.0, 3.0)) + # 3) Create surface for planting on + dynveg.create_surface_entity("Surface Entity", spawner_center_point, 32.0, 32.0, 1.0) - # 7) Validate instance counts post-blocker. 16 instances should now be blocked in the center of the spawner area - num_expected = (20 * 20) - 16 - success = self.wait_for_condition(lambda: dynveg.validate_instance_count_in_entity_shape(spawner_entity.id, - num_expected), 5.0) - self.test_success = success and self.test_success + # 4) Add a Vegetation System Settings Level component and set Sector Point Snap Mode to Center + veg_system_settings_component = hydra.add_level_component("Vegetation System Settings") + editor.EditorComponentAPIBus(bus.Broadcast, "SetComponentProperty", veg_system_settings_component, + 'Configuration|Area System Settings|Sector Point Snap Mode', 1) + + # 5) Verify initial instance counts + num_expected = 20 * 20 + success = helper.wait_for_condition(lambda: dynveg.validate_instance_count_in_entity_shape(spawner_entity.id, + num_expected), 5.0) + Report.result(Tests.initial_instance_count, success) + + # 6) Create a new Vegetation Layer Blocker area overlapping the spawner area + blocker_entity = hydra.Entity("Blocker Area") + blocker_entity.create_entity( + spawner_center_point, + ["Vegetation Layer Blocker", "Box Shape"] + ) + if blocker_entity.id.IsValid(): + print(f"'{blocker_entity.name}' created") + blocker_entity.get_set_test(1, "Box Shape|Box Configuration|Dimensions", + math.Vector3(3.0, 3.0, 3.0)) + + # 7) Validate instance counts post-blocker. 16 instances should now be blocked in the center of the spawner area + num_expected = (20 * 20) - 16 + success = helper.wait_for_condition(lambda: dynveg.validate_instance_count_in_entity_shape(spawner_entity.id, + num_expected), 5.0) + Report.result(Tests.blocked_instance_count, success) -test = TestLayerBlocker() -test.run() +if __name__ == "__main__": + + from editor_python_test_tools.utils import Report + Report.start_test(LayerBlocker_InstancesBlockedInConfiguredArea) diff --git a/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/LayerSpawner_FilterStageToggle.py b/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/LayerSpawner_FilterStageToggle.py index a52f91ae5f..8592692c4b 100755 --- a/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/LayerSpawner_FilterStageToggle.py +++ b/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/LayerSpawner_FilterStageToggle.py @@ -5,85 +5,83 @@ For complete copyright and license terms please see the LICENSE at the root of t SPDX-License-Identifier: Apache-2.0 OR MIT """ -import os -import sys -import azlmbr.bus as bus -import azlmbr.editor as editor -import azlmbr.legacy.general as general -import azlmbr.math as math -import azlmbr.paths - -sys.path.append(os.path.join(azlmbr.paths.devroot, "AutomatedTesting", "Gem", "PythonTests")) -import editor_python_test_tools.hydra_editor_utils as hydra -from editor_python_test_tools.editor_test_helper import EditorTestHelper -from largeworlds.large_worlds_utils import editor_dynveg_test_helper as dynveg +class Tests: + preprocess_instance_count = ( + "Preprocess filter stage vegetation instance count is as expected", + "Preprocess filter stage instance count found an unexpected number of instances" + ) + postprocess_instance_count = ( + "Postprocess filter stage vegetation instance count is as expected", + "Postprocess filter stage instance count found an unexpected number of instances" + ) -class TestLayerSpawnerFilterStageToggle(EditorTestHelper): - def __init__(self): - EditorTestHelper.__init__(self, log_prefix="LayerSpawner_FilterStageToggle", args=["level"]) +def LayerSpawner_FilterStageToggle(): + """ + Summary: + Filter Stage toggle affects final vegetation position. - def run_test(self): - """ - Summary: - C4765973 Filter Stage toggle affects final vegetation position. + Expected Result: + Vegetation instances plant differently depending on the Filter Stage setting. - Expected Result: - Vegetation instances plant differently depending on the Filter Stage setting. + :return: None + """ - :return: None - """ + import os - PREPROCESS_INSTANCE_COUNT = 21 - POSTPROCESS_INSTANCE_COUNT = 19 + import azlmbr.legacy.general as general + import azlmbr.math as math - # Create empty level - self.test_success = self.create_level( - self.args["level"], - heightmap_resolution=1024, - heightmap_meters_per_pixel=1, - terrain_texture_resolution=4096, - use_terrain=False, - ) + import editor_python_test_tools.hydra_editor_utils as hydra + from largeworlds.large_worlds_utils import editor_dynveg_test_helper as dynveg + from editor_python_test_tools.utils import Report + from editor_python_test_tools.utils import TestHelper as helper - general.set_current_view_position(500.49, 498.69, 46.66) - general.set_current_view_rotation(-42.05, 0.00, -36.33) + PREPROCESS_INSTANCE_COUNT = 21 + POSTPROCESS_INSTANCE_COUNT = 19 - # Create a vegetation area with all needed components - position = math.Vector3(512.0, 512.0, 32.0) - asset_path = os.path.join("Slices", "PinkFlower.dynamicslice") - vegetation_entity = dynveg.create_vegetation_area("vegetation", position, 16.0, 16.0, 16.0, asset_path) - vegetation_entity.add_component("Vegetation Altitude Filter") - vegetation_entity.add_component("Vegetation Position Modifier") + # Open an existing simple level + helper.init_idle() + helper.open_level("Physics", "Base") - # Create a child entity under vegetation area - child_entity = hydra.Entity("child_entity") - components_to_add = ["Random Noise Gradient", "Gradient Transform Modifier", "Box Shape"] - child_entity.create_entity(position, components_to_add, vegetation_entity.id) + general.set_current_view_position(500.49, 498.69, 46.66) + general.set_current_view_rotation(-42.05, 0.00, -36.33) - # Set the Gradient Id in X and Y direction - vegetation_entity.get_set_test(4, "Configuration|Position X|Gradient|Gradient Entity Id", child_entity.id) - vegetation_entity.get_set_test(4, "Configuration|Position Y|Gradient|Gradient Entity Id", child_entity.id) + # Create a vegetation area with all needed components + position = math.Vector3(512.0, 512.0, 32.0) + asset_path = os.path.join("Slices", "PinkFlower.dynamicslice") + vegetation_entity = dynveg.create_vegetation_area("vegetation", position, 16.0, 16.0, 16.0, asset_path) + vegetation_entity.add_component("Vegetation Altitude Filter") + vegetation_entity.add_component("Vegetation Position Modifier") - # Set the min and max values for Altitude Filter - vegetation_entity.get_set_test(3, "Configuration|Altitude Min", 34.0) - vegetation_entity.get_set_test(3, "Configuration|Altitude Max", 38.0) + # Create a child entity under vegetation area + child_entity = hydra.Entity("child_entity") + components_to_add = ["Random Noise Gradient", "Gradient Transform Modifier", "Box Shape"] + child_entity.create_entity(position, components_to_add, vegetation_entity.id) - # Add entity with Mesh to replicate creation of hills and a flat surface to plant on - dynveg.create_surface_entity("Flat Surface", position, 32.0, 32.0, 1.0) - hill_entity = dynveg.create_mesh_surface_entity_with_slopes("hill", position, 4.0) + # Set the Gradient Id in X and Y direction + vegetation_entity.get_set_test(4, "Configuration|Position X|Gradient|Gradient Entity Id", child_entity.id) + vegetation_entity.get_set_test(4, "Configuration|Position Y|Gradient|Gradient Entity Id", child_entity.id) - # Set the filter stage to preprocess and postprocess respectively and verify instance count - vegetation_entity.get_set_test(0, "Configuration|Filter Stage", 1) - self.wait_for_condition(lambda: dynveg.validate_instance_count(position, 16.0, PREPROCESS_INSTANCE_COUNT), 3.0) - result = dynveg.validate_instance_count(position, 16.0, PREPROCESS_INSTANCE_COUNT) - self.log(f"Preprocess filter stage vegetation instance count is as expected: {result}") - vegetation_entity.get_set_test(0, "Configuration|Filter Stage", 2) - self.wait_for_condition(lambda: dynveg.validate_instance_count(position, 16.0, POSTPROCESS_INSTANCE_COUNT), 3.0) - result = dynveg.validate_instance_count(position, 16.0, POSTPROCESS_INSTANCE_COUNT) - self.log(f"Postprocess filter vegetation instance stage count is as expected: {result}") + # Set the min and max values for Altitude Filter + vegetation_entity.get_set_test(3, "Configuration|Altitude Min", 34.0) + vegetation_entity.get_set_test(3, "Configuration|Altitude Max", 38.0) + + # Add entity with Mesh to replicate creation of hills and a flat surface to plant on + dynveg.create_surface_entity("Flat Surface", position, 32.0, 32.0, 1.0) + hill_entity = dynveg.create_mesh_surface_entity_with_slopes("hill", position, 4.0) + + # Set the filter stage to preprocess and postprocess respectively and verify instance count + vegetation_entity.get_set_test(0, "Configuration|Filter Stage", 1) + result = helper.wait_for_condition(lambda: dynveg.validate_instance_count(position, 16.0, PREPROCESS_INSTANCE_COUNT), 3.0) + Report.result(Tests.preprocess_instance_count, result) + vegetation_entity.get_set_test(0, "Configuration|Filter Stage", 2) + result = helper.wait_for_condition(lambda: dynveg.validate_instance_count(position, 16.0, POSTPROCESS_INSTANCE_COUNT), 3.0) + Report.result(Tests.postprocess_instance_count, result) -test = TestLayerSpawnerFilterStageToggle() -test.run() +if __name__ == "__main__": + + from editor_python_test_tools.utils import Report + Report.start_test(LayerSpawner_FilterStageToggle) diff --git a/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/LayerSpawner_InheritBehaviorFlag.py b/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/LayerSpawner_InheritBehaviorFlag.py index 5e5c6410b0..649c7d0776 100755 --- a/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/LayerSpawner_InheritBehaviorFlag.py +++ b/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/LayerSpawner_InheritBehaviorFlag.py @@ -5,118 +5,116 @@ For complete copyright and license terms please see the LICENSE at the root of t SPDX-License-Identifier: Apache-2.0 OR MIT """ -import os -import sys -import azlmbr.math as math -import azlmbr.legacy.general as general -import azlmbr.paths -import azlmbr.surface_data as surface_data -import azlmbr.vegetation as vegetation - -sys.path.append(os.path.join(azlmbr.paths.devroot, "AutomatedTesting", "Gem", "PythonTests")) -import editor_python_test_tools.hydra_editor_utils as hydra -from editor_python_test_tools.editor_test_helper import EditorTestHelper -from largeworlds.large_worlds_utils import editor_dynveg_test_helper as dynveg +class Tests: + inherit_behavior_checked = ( + "Found no instances with Inherit Behavior checked as expected", + "Unexpectedly found instances with Inherit Behavior checked" + ) + inherit_behavior_unchecked = ( + "Found instances with Inherit Behavior unchecked as expected", + "Unexpectedly found no instances with Inherit Behavior unchecked" + ) -class TestLayerSpawnerInheritBehavior(EditorTestHelper): - def __init__(self): - EditorTestHelper.__init__(self, log_prefix="LayerSpawner_InheritBehavior", args=["level"]) +def LayerSpawner_InheritBehaviorFlag(): + """ + Summary: + Verifies if Inherit Behavior Flag works as expected. - def run_test(self): - """ - Summary: - C4762381 Verifies if Inherit Behavior Flag works as expected. + Expected Result: + The spawner with Inherit Behavior toggled off no longer obeys + Vegetation Surface Mask Filter of the Vegetation Layer Blender entity and plants on the surface. - Expected Result: - The spawner with Inherit Behavior toggled off no longer obeys - Vegetation Surface Mask Filter of the Vegetation Layer Blender entity and plants on the surface. + :return: None + """ + import os - :return: None - """ + import azlmbr.math as math + import azlmbr.legacy.general as general + import azlmbr.surface_data as surface_data + import azlmbr.vegetation as vegetation - SURFACE_TAG = "test_tag" + import editor_python_test_tools.hydra_editor_utils as hydra + from largeworlds.large_worlds_utils import editor_dynveg_test_helper as dynveg + from editor_python_test_tools.utils import Report + from editor_python_test_tools.utils import TestHelper as helper - def set_dynamic_slice_asset(entity_obj, component_index, dynamic_slice_asset_path): - dynamic_slice_spawner = vegetation.DynamicSliceInstanceSpawner() - dynamic_slice_spawner.SetSliceAssetPath(dynamic_slice_asset_path) - descriptor = hydra.get_component_property_value( - entity_obj.components[component_index], "Configuration|Embedded Assets|[0]" - ) - descriptor.spawner = dynamic_slice_spawner - entity_obj.get_set_test(2, "Configuration|Embedded Assets|[0]", descriptor) + SURFACE_TAG = "test_tag" - # Create empty level - self.test_success = self.create_level( - self.args["level"], - heightmap_resolution=1024, - heightmap_meters_per_pixel=1, - terrain_texture_resolution=4096, - use_terrain=False, + def set_dynamic_slice_asset(entity_obj, component_index, dynamic_slice_asset_path): + dynamic_slice_spawner = vegetation.DynamicSliceInstanceSpawner() + dynamic_slice_spawner.SetSliceAssetPath(dynamic_slice_asset_path) + descriptor = hydra.get_component_property_value( + entity_obj.components[component_index], "Configuration|Embedded Assets|[0]" ) + descriptor.spawner = dynamic_slice_spawner + entity_obj.get_set_test(2, "Configuration|Embedded Assets|[0]", descriptor) - general.set_current_view_position(512.0, 480.0, 38.0) + # Open an existing simple level + helper.init_idle() + helper.open_level("Physics", "Base") - # Create Emitter entity and add the required components - position = math.Vector3(512.0, 512.0, 32.0) - emitter_entity = dynveg.create_surface_entity("emitter_entity", position, 16.0, 16.0, 1.0) + general.set_current_view_position(512.0, 480.0, 38.0) - # Add surface tag to the Surface Tag Emitter - tag = surface_data.SurfaceTag() - tag.SetTag(SURFACE_TAG) - pte = hydra.get_property_tree(emitter_entity.components[1]) - path = "Configuration|Generated Tags" - pte.add_container_item(path, 0, tag) - emitter_entity.get_set_test(1, "Configuration|Generated Tags|[0]", tag) + # Create Emitter entity and add the required components + position = math.Vector3(512.0, 512.0, 32.0) + emitter_entity = dynveg.create_surface_entity("emitter_entity", position, 16.0, 16.0, 1.0) - # Create Blender entity and add required components - components_to_add = ["Box Shape", "Vegetation Layer Blender"] - blender_entity = hydra.Entity("blender_entity") - blender_entity.create_entity(position, components_to_add) - blender_entity.get_set_test(0, "Box Shape|Box Configuration|Dimensions", math.Vector3(16.0, 16.0, 1.0)) + # Add surface tag to the Surface Tag Emitter + tag = surface_data.SurfaceTag() + tag.SetTag(SURFACE_TAG) + pte = hydra.get_property_tree(emitter_entity.components[1]) + path = "Configuration|Generated Tags" + pte.add_container_item(path, 0, tag) + emitter_entity.get_set_test(1, "Configuration|Generated Tags|[0]", tag) - # Create Vegetation area and assign a valid asset - veg_1 = hydra.Entity("veg_1") - veg_1.create_entity( - position, ["Vegetation Layer Spawner", "Vegetation Reference Shape", "Vegetation Asset List"] - ) - set_dynamic_slice_asset(veg_1, 2, os.path.join("Slices", "PinkFlower.dynamicslice")) - veg_1.get_set_test(1, "Configuration|Shape Entity Id", blender_entity.id) + # Create Blender entity and add required components + components_to_add = ["Box Shape", "Vegetation Layer Blender"] + blender_entity = hydra.Entity("blender_entity") + blender_entity.create_entity(position, components_to_add) + blender_entity.get_set_test(0, "Box Shape|Box Configuration|Dimensions", math.Vector3(16.0, 16.0, 1.0)) - # Create second vegetation area and assign a valid asset - veg_2 = hydra.Entity("veg_2") - veg_2.create_entity( - position, ["Vegetation Layer Spawner", "Vegetation Reference Shape", "Vegetation Asset List"] - ) - set_dynamic_slice_asset(veg_2, 2, os.path.join("Slices", "PurpleFlower.dynamicslice")) - veg_2.get_set_test(1, "Configuration|Shape Entity Id", blender_entity.id) + # Create Vegetation area and assign a valid asset + veg_1 = hydra.Entity("veg_1") + veg_1.create_entity( + position, ["Vegetation Layer Spawner", "Vegetation Reference Shape", "Vegetation Asset List"] + ) + set_dynamic_slice_asset(veg_1, 2, os.path.join("Slices", "PinkFlower.dynamicslice")) + veg_1.get_set_test(1, "Configuration|Shape Entity Id", blender_entity.id) - # Assign the vegetation areas to the Blender entity - pte = hydra.get_property_tree(blender_entity.components[1]) - path = "Configuration|Vegetation Areas" - pte.update_container_item(path, 0, veg_1.id) - pte.add_container_item(path, 1, veg_2.id) + # Create second vegetation area and assign a valid asset + veg_2 = hydra.Entity("veg_2") + veg_2.create_entity( + position, ["Vegetation Layer Spawner", "Vegetation Reference Shape", "Vegetation Asset List"] + ) + set_dynamic_slice_asset(veg_2, 2, os.path.join("Slices", "PurpleFlower.dynamicslice")) + veg_2.get_set_test(1, "Configuration|Shape Entity Id", blender_entity.id) - # Add Vegetation Surface Mask Filter to the blender entity and add a Exclusion tag - tag = surface_data.SurfaceTag() - tag.SetTag(SURFACE_TAG) - blender_entity.add_component("Vegetation Surface Mask Filter") - pte = hydra.get_property_tree(blender_entity.components[2]) - path = "Configuration|Exclusion|Surface Tags" - pte.add_container_item(path, 0, tag) - blender_entity.get_set_test(2, "Configuration|Exclusion|Surface Tags|[0]", tag) + # Assign the vegetation areas to the Blender entity + pte = hydra.get_property_tree(blender_entity.components[1]) + path = "Configuration|Vegetation Areas" + pte.update_container_item(path, 0, veg_1.id) + pte.add_container_item(path, 1, veg_2.id) - # Toggle Inherit Behavior flag and verify vegetation instances - self.log( - f"Vegetation is not planted when Inherit Behavior flag is checked: {dynveg.validate_instance_count(position, 16.0, 0)}" - ) - veg_1.get_set_test(0, "Configuration|Inherit Behavior", False) - self.wait_for_condition(lambda: dynveg.validate_instance_count(position, 16.0, 400), 2.0) - self.log( - f"Vegetation plant when Inherit Behavior flag is unchecked: {dynveg.validate_instance_count(position, 16.0, 400)}" - ) + # Add Vegetation Surface Mask Filter to the blender entity and add a Exclusion tag + tag = surface_data.SurfaceTag() + tag.SetTag(SURFACE_TAG) + blender_entity.add_component("Vegetation Surface Mask Filter") + pte = hydra.get_property_tree(blender_entity.components[2]) + path = "Configuration|Exclusion|Surface Tags" + pte.add_container_item(path, 0, tag) + blender_entity.get_set_test(2, "Configuration|Exclusion|Surface Tags|[0]", tag) + + # Toggle Inherit Behavior flag and verify vegetation instances + flag_checked_instance_count = helper.wait_for_condition(lambda: dynveg.validate_instance_count(position, 16.0, 0), 2.0) + Report.result(Tests.inherit_behavior_checked, flag_checked_instance_count) + veg_1.get_set_test(0, "Configuration|Inherit Behavior", False) + flag_unchecked_instance_count = helper.wait_for_condition(lambda: dynveg.validate_instance_count(position, 16.0, 400), 2.0) + Report.result(Tests.inherit_behavior_unchecked, flag_unchecked_instance_count) -test = TestLayerSpawnerInheritBehavior() -test.run() +if __name__ == "__main__": + + from editor_python_test_tools.utils import Report + Report.start_test(LayerSpawner_InheritBehaviorFlag) diff --git a/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/LayerSpawner_InstancesPlantInAllSupportedShapes.py b/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/LayerSpawner_InstancesPlantInAllSupportedShapes.py index 8310583fe6..0da200d87a 100755 --- a/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/LayerSpawner_InstancesPlantInAllSupportedShapes.py +++ b/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/LayerSpawner_InstancesPlantInAllSupportedShapes.py @@ -5,134 +5,128 @@ For complete copyright and license terms please see the LICENSE at the root of t SPDX-License-Identifier: Apache-2.0 OR MIT """ -import os -import sys -sys.path.append(os.path.dirname(os.path.abspath(__file__))) -import azlmbr -import azlmbr.legacy.general as general -import azlmbr.entity as EntityId -import azlmbr.math as math +def LayerSpawner_InstancesPlantInAllSupportedShapes(): + """ + Summary: + The level is loaded and vegetation area is created. Then the Vegetation Reference Shape + component of vegetation area is pinned with entities of different shape components to check + if the vegetation plants in different shaped areas. -sys.path.append(os.path.join(azlmbr.paths.devroot, 'AutomatedTesting', 'Gem', 'PythonTests')) -import editor_python_test_tools.hydra_editor_utils as hydra -from editor_python_test_tools.editor_test_helper import EditorTestHelper -from largeworlds.large_worlds_utils import editor_dynveg_test_helper as dynveg + Expected Behavior: + Vegetation properly plants in areas of any shape. + Test Steps: + 1) Open a level + 2) Create basic vegetation area entity and set the properties + 3) Box Shape Entity: create, set properties and pin to vegetation + 4) Capsule Shape Entity: create, set properties and pin to vegetation + 5) Tube Shape Entity: create, set properties and pin to vegetation + 6) Sphere Shape Entity: create, set properties and pin to vegetation + 7) Cylinder Shape Entity: create, set properties and pin to vegetation + 8) Prism Shape Entity: create, set properties and pin to vegetation + 9) Compound Shape Entity: create, set properties and pin to vegetation -class TestLayerSpawner_AllShapesPlant(EditorTestHelper): - def __init__(self): - EditorTestHelper.__init__(self, log_prefix="TestLayerSpawner_AllShapesPlant", args=["level"]) + Note: + - 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. - def run_test(self): - """ - Summary: - The level is loaded and vegetation area is created. Then the Vegetation Reference Shape - component of vegetation area is pinned with entities of different shape components to check - if the vegetation plants in different shaped areas. + :return: None + """ - Expected Behavior: - Vegetation properly plants in areas of any shape. + import os - Test Steps: - 1) Create level - 2) Create basic vegetation area entity and set the properties - 3) Box Shape Entity: create, set properties and pin to vegetation - 4) Capsule Shape Entity: create, set properties and pin to vegetation - 5) Tube Shape Entity: create, set properties and pin to vegetation - 6) Sphere Shape Entity: create, set properties and pin to vegetation - 7) Cylinder Shape Entity: create, set properties and pin to vegetation - 8) Prism Shape Entity: create, set properties and pin to vegetation - 9) Compound Shape Entity: create, set properties and pin to vegetation + import azlmbr.legacy.general as general + import azlmbr.entity as EntityId + import azlmbr.math as math - Note: - - 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. + import editor_python_test_tools.hydra_editor_utils as hydra + from largeworlds.large_worlds_utils import editor_dynveg_test_helper as dynveg + from editor_python_test_tools.utils import Report + from editor_python_test_tools.utils import TestHelper as helper - :return: None - """ - - def pin_shape_and_check_count(entity_id, count): - hydra.get_set_test(vegetation, 2, "Configuration|Shape Entity Id", entity_id) - result = self.wait_for_condition(lambda: dynveg.validate_instance_count_in_entity_shape(vegetation.id, - count), 2.0) - self.test_success = self.test_success and result - - # 1) Create level - self.test_success = self.create_level( - self.args["level"], - heightmap_resolution=1024, - heightmap_meters_per_pixel=1, - terrain_texture_resolution=4096, - use_terrain=False, + def pin_shape_and_check_count(entity, count): + hydra.get_set_test(vegetation, 2, "Configuration|Shape Entity Id", entity.id) + result = helper.wait_for_condition(lambda: dynveg.validate_instance_count_in_entity_shape(vegetation.id, + count), 2.0) + success = ( + f"Found the expected number of instances in {entity.name} shape", + f"Unexpected number of instances found in {entity.name} shape" ) + Report.result(success, result) - # 2) Create basic vegetation area entity and set the properties - entity_position = math.Vector3(125.0, 136.0, 32.0) - asset_path = os.path.join("Slices", "PurpleFlower.dynamicslice") - vegetation = dynveg.create_vegetation_area("Instance Spawner", - entity_position, - 10.0, 10.0, 10.0, - asset_path) - vegetation.remove_component("Box Shape") - vegetation.add_component("Vegetation Reference Shape") + # 1) Open an existing simple level + helper.init_idle() + helper.open_level("Physics", "Base") - # Create surface for planting on - dynveg.create_surface_entity("Surface Entity", entity_position, 60.0, 60.0, 1.0) + # 2) Create basic vegetation area entity and set the properties + entity_position = math.Vector3(125.0, 136.0, 32.0) + asset_path = os.path.join("Slices", "PurpleFlower.dynamicslice") + vegetation = dynveg.create_vegetation_area("Instance Spawner", + entity_position, + 10.0, 10.0, 10.0, + asset_path) + vegetation.remove_component("Box Shape") + vegetation.add_component("Vegetation Reference Shape") - # Adjust camera to be close to the vegetation entity - general.set_current_view_position(135.0, 102.0, 39.0) - general.set_current_view_rotation(-15.0, 0, 0) + # Create surface for planting on + dynveg.create_surface_entity("Surface Entity", entity_position, 60.0, 60.0, 1.0) - # 3) Box Shape Entity: create, set properties and pin to vegetation - box = hydra.Entity("box") - box.create_entity(math.Vector3(124.0, 126.0, 32.0), ["Box Shape"]) - new_box_dimension = math.Vector3(10.0, 10.0, 1.0) - hydra.get_set_test(box, 0, "Box Shape|Box Configuration|Dimensions", new_box_dimension) - # This and subsequent counts are the number of "PurpleFlower" that spawn in the shape with given dimensions - pin_shape_and_check_count(box.id, 156) + # Adjust camera to be close to the vegetation entity + general.set_current_view_position(135.0, 102.0, 39.0) + general.set_current_view_rotation(-15.0, 0, 0) - # 4) Capsule Shape Entity: create, set properties and pin to vegetation - capsule = hydra.Entity("capsule") - capsule.create_entity(math.Vector3(120.0, 142.0, 32.0), ["Capsule Shape"]) - hydra.get_set_test(capsule, 0, "Capsule Shape|Capsule Configuration|Height", 10.0) - hydra.get_set_test(capsule, 0, "Capsule Shape|Capsule Configuration|Radius", 2.0) - pin_shape_and_check_count(capsule.id, 20) + # 3) Box Shape Entity: create, set properties and pin to vegetation + box = hydra.Entity("Box") + box.create_entity(math.Vector3(124.0, 126.0, 32.0), ["Box Shape"]) + new_box_dimension = math.Vector3(10.0, 10.0, 1.0) + hydra.get_set_test(box, 0, "Box Shape|Box Configuration|Dimensions", new_box_dimension) + # This and subsequent counts are the number of "PurpleFlower" that spawn in the shape with given dimensions + pin_shape_and_check_count(box, 156) - # 5) Tube Shape Entity: create, set properties and pin to vegetation - tube = hydra.Entity("tube") - tube.create_entity(math.Vector3(124.0, 136.0, 32.0), ["Tube Shape", "Spline"]) - pin_shape_and_check_count(tube.id, 27) + # 4) Capsule Shape Entity: create, set properties and pin to vegetation + capsule = hydra.Entity("Capsule") + capsule.create_entity(math.Vector3(120.0, 142.0, 32.0), ["Capsule Shape"]) + hydra.get_set_test(capsule, 0, "Capsule Shape|Capsule Configuration|Height", 10.0) + hydra.get_set_test(capsule, 0, "Capsule Shape|Capsule Configuration|Radius", 2.0) + pin_shape_and_check_count(capsule, 20) - # 6) Sphere Shape Entity: create, set properties and pin to vegetation - sphere = hydra.Entity("sphere") - sphere.create_entity(math.Vector3(112.0, 143.0, 32.0), ["Sphere Shape"]) - hydra.get_set_test(sphere, 0, "Sphere Shape|Sphere Configuration|Radius", 5.0) - pin_shape_and_check_count(sphere.id, 122) + # 5) Tube Shape Entity: create, set properties and pin to vegetation + tube = hydra.Entity("Tube") + tube.create_entity(math.Vector3(124.0, 136.0, 32.0), ["Tube Shape", "Spline"]) + pin_shape_and_check_count(tube, 27) - # 7) Cylinder Shape Entity: create, set properties and pin to vegetation - cylinder = hydra.Entity("cylinder") - cylinder.create_entity(math.Vector3(136.0, 143.0, 32.0), ["Cylinder Shape"]) - hydra.get_set_test(cylinder, 0, "Cylinder Shape|Cylinder Configuration|Radius", 5.0) - hydra.get_set_test(cylinder, 0, "Cylinder Shape|Cylinder Configuration|Height", 5.0) - pin_shape_and_check_count(cylinder.id, 124) + # 6) Sphere Shape Entity: create, set properties and pin to vegetation + sphere = hydra.Entity("Sphere") + sphere.create_entity(math.Vector3(112.0, 143.0, 32.0), ["Sphere Shape"]) + hydra.get_set_test(sphere, 0, "Sphere Shape|Sphere Configuration|Radius", 5.0) + pin_shape_and_check_count(sphere, 122) - # 8) Prism Shape Entity: create, set properties and pin to vegetation - polygon_prism = hydra.Entity("polygonprism") - polygon_prism.create_entity(math.Vector3(127.0, 142.0, 32.0), ["Polygon Prism Shape"]) - pin_shape_and_check_count(polygon_prism.id, 20) + # 7) Cylinder Shape Entity: create, set properties and pin to vegetation + cylinder = hydra.Entity("Cylinder") + cylinder.create_entity(math.Vector3(136.0, 143.0, 32.0), ["Cylinder Shape"]) + hydra.get_set_test(cylinder, 0, "Cylinder Shape|Cylinder Configuration|Radius", 5.0) + hydra.get_set_test(cylinder, 0, "Cylinder Shape|Cylinder Configuration|Height", 5.0) + pin_shape_and_check_count(cylinder, 124) - # 9) Compound Shape Entity: create, set properties and pin to vegetation - compound = hydra.Entity("Compound") - compound.create_entity(math.Vector3(125.0, 136.0, 32.0), ["Compound Shape"]) - pte = hydra.get_property_tree(compound.components[0]) - shapes = [box.id, capsule.id, tube.id, sphere.id, cylinder.id, polygon_prism.id] - for index in range(6): - pte.add_container_item("Configuration|Child Shape Entities", index, EntityId.EntityId()) - for index, element in enumerate(shapes): - hydra.get_set_test(compound, 0, f"Configuration|Child Shape Entities|[{index}]", element) - pin_shape_and_check_count(compound.id, 469) + # 8) Prism Shape Entity: create, set properties and pin to vegetation + polygon_prism = hydra.Entity("Polygon Prism") + polygon_prism.create_entity(math.Vector3(127.0, 142.0, 32.0), ["Polygon Prism Shape"]) + pin_shape_and_check_count(polygon_prism, 20) + + # 9) Compound Shape Entity: create, set properties and pin to vegetation + compound = hydra.Entity("Compound") + compound.create_entity(math.Vector3(125.0, 136.0, 32.0), ["Compound Shape"]) + pte = hydra.get_property_tree(compound.components[0]) + shapes = [box.id, capsule.id, tube.id, sphere.id, cylinder.id, polygon_prism.id] + for index in range(6): + pte.add_container_item("Configuration|Child Shape Entities", index, EntityId.EntityId()) + for index, element in enumerate(shapes): + hydra.get_set_test(compound, 0, f"Configuration|Child Shape Entities|[{index}]", element) + pin_shape_and_check_count(compound, 469) -test = TestLayerSpawner_AllShapesPlant() -test.run() +if __name__ == "__main__": + + from editor_python_test_tools.utils import Report + Report.start_test(LayerSpawner_InstancesPlantInAllSupportedShapes) diff --git a/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/LayerSpawner_InstancesRefreshUsingCorrectViewportCamera.py b/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/LayerSpawner_InstancesRefreshUsingCorrectViewportCamera.py index f17956e066..02d30fb0f3 100755 --- a/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/LayerSpawner_InstancesRefreshUsingCorrectViewportCamera.py +++ b/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/LayerSpawner_InstancesRefreshUsingCorrectViewportCamera.py @@ -5,115 +5,131 @@ For complete copyright and license terms please see the LICENSE at the root of t SPDX-License-Identifier: Apache-2.0 OR MIT """ -import os -import sys -sys.path.append(os.path.dirname(os.path.abspath(__file__))) -import azlmbr -import azlmbr.legacy.general as general -import azlmbr.math as math - -sys.path.append(os.path.join(azlmbr.paths.devroot, 'AutomatedTesting', 'Gem', 'PythonTests')) -from editor_python_test_tools.editor_test_helper import EditorTestHelper -from largeworlds.large_worlds_utils import editor_dynveg_test_helper as dynveg +class Tests: + viewport_config_updated = ( + "Viewport is now configured for test", + "Failed to configure viewport for test" + ) + first_viewport_active_instance_count = ( + "Expected number of instances found in left viewport", + "Unexpected number of instances found in left viewport" + ) + second_viewport_inactive_instance_count = ( + "No instances found in right viewport", + "Unexpectedly found instances in right viewport while not active" + ) + first_viewport_inactive_instance_count = ( + "No instances found in left viewport", + "Unexpectedly found instances in left viewport while not active" + ) + second_viewport_active_instance_count = ( + "Expected number of instances found in right viewport", + "Unexpected number of instances found in right viewport" + ) -class TestLayerSpawnerInstanceCameraRefresh(EditorTestHelper): - def __init__(self): - EditorTestHelper.__init__(self, log_prefix="LayerSpawner_InstanceCameraRefresh", args=["level"]) +def LayerSpawner_InstancesRefreshUsingCorrectViewportCamera(): + """ + Summary: + Test that the Dynamic Vegetation System is using the current Editor viewport camera as the center + of the spawn area for vegetation. To verify this, we create two separate Editor viewports pointed + at two different vegetation areas, and verify that as we switch between active viewports, only the + area directly underneath that viewport's camera has vegetation. + """ - def run_test(self): - """ - Summary: - Test that the Dynamic Vegetation System is using the current Editor viewport camera as the center - of the spawn area for vegetation. To verify this, we create two separate Editor viewports pointed - at two different vegetation areas, and verify that as we switch between active viewports, only the - area directly underneath that viewport's camera has vegetation. - """ - # Create an empty level - self.test_success = self.create_level( - self.args["level"], - heightmap_resolution=128, - heightmap_meters_per_pixel=1, - terrain_texture_resolution=4096, - use_terrain=False, - ) - # Set up a test environment to validate that switching viewports correctly changes which camera - # the vegetation system uses. - # The test environment consists of the following: - # - two 32 x 32 x 1 box shapes located far apart that emit a surface with no tags - # - two 32 x 32 x 32 vegetation areas that place vegetation on the boxes + import os - # Initialize some constants for our test. - # The boxes are intentionally shifted by 0.5 meters to ensure that we get a predictable number - # of vegetation points. By default, vegetation plants on grid corners, so if our boxes are aligned - # with grid corner points, the right/bottom edges will include more points than we might intuitively expect. - # By shifting by 0.5 meters, the vegetation grid points don't fall on the box edges, making the total count - # more predictable. - first_entity_center_point = math.Vector3(0.5, 0.5, 100.0) - # The second box needs to be far enough away from the first that the vegetation system will never spawn instances - # in both at the same time. - second_entity_center_point = math.Vector3(1024.5, 1024.5, 100.0) - box_size = 32.0 - surface_height = 1.0 - # By default, vegetation spawns 20 instances per 16 meters, so for our box of 32 meters, we should have - # ((20 instances / 16 m) * 32 m) ^ 2 instances. - filled_vegetation_area_instance_count = (20 * 2) * (20 * 2) + import azlmbr.legacy.general as general + import azlmbr.math as math - # Change the Editor view to contain two viewports - general.set_view_pane_layout(1) - get_view_pane_layout_success = self.wait_for_condition(lambda: (general.get_view_pane_layout() == 1), 2) - get_viewport_count_success = self.wait_for_condition(lambda: (general.get_viewport_count() == 2), 2) - self.test_success = get_view_pane_layout_success and self.test_success - self.test_success = get_viewport_count_success and self.test_success + from largeworlds.large_worlds_utils import editor_dynveg_test_helper as dynveg + from editor_python_test_tools.utils import Report + from editor_python_test_tools.utils import TestHelper as helper - # Set the view in the first viewport to point down at the first box - general.set_active_viewport(0) - self.wait_for_condition(lambda: general.get_active_viewport() == 0, 2) - general.set_current_view_position(first_entity_center_point.x, first_entity_center_point.y, - first_entity_center_point.z + 30.0) - general.set_current_view_rotation(-85.0, 0.0, 0.0) + # Open an existing simple level + helper.init_idle() + helper.open_level("Physics", "Base") - # Set the view in the second viewport to point down at the second box - general.set_active_viewport(1) - self.wait_for_condition(lambda: general.get_active_viewport() == 1, 2) - general.set_current_view_position(second_entity_center_point.x, second_entity_center_point.y, - second_entity_center_point.z + 30.0) - general.set_current_view_rotation(-85.0, 0.0, 0.0) + # Set up a test environment to validate that switching viewports correctly changes which camera + # the vegetation system uses. + # The test environment consists of the following: + # - two 32 x 32 x 1 box shapes located far apart that emit a surface with no tags + # - two 32 x 32 x 32 vegetation areas that place vegetation on the boxes - # Create the "flat surface" entities to use as our vegetation surfaces - first_surface_entity = dynveg.create_surface_entity("Surface 1", first_entity_center_point, box_size, box_size, - surface_height) - second_surface_entity = dynveg.create_surface_entity("Surface 2", second_entity_center_point, box_size, box_size, - surface_height) + # Initialize some constants for our test. + # The boxes are intentionally shifted by 0.5 meters to ensure that we get a predictable number + # of vegetation points. By default, vegetation plants on grid corners, so if our boxes are aligned + # with grid corner points, the right/bottom edges will include more points than we might intuitively expect. + # By shifting by 0.5 meters, the vegetation grid points don't fall on the box edges, making the total count + # more predictable. + first_entity_center_point = math.Vector3(0.5, 0.5, 100.0) + # The second box needs to be far enough away from the first that the vegetation system will never spawn instances + # in both at the same time. + second_entity_center_point = math.Vector3(1024.5, 1024.5, 100.0) + box_size = 32.0 + surface_height = 1.0 + # By default, vegetation spawns 20 instances per 16 meters, so for our box of 32 meters, we should have + # ((20 instances / 16 m) * 32 m) ^ 2 instances. + filled_vegetation_area_instance_count = (20 * 2) * (20 * 2) - # Create the two vegetation areas - test_slice_asset_path = os.path.join("Slices", "PurpleFlower.dynamicslice") - first_veg_entity = dynveg.create_vegetation_area("Veg Area 1", first_entity_center_point, box_size, box_size, - box_size, test_slice_asset_path) - second_veg_entity = dynveg.create_vegetation_area("Veg Area 2", second_entity_center_point, box_size, box_size, - box_size, test_slice_asset_path) + # Change the Editor view to contain two viewports + general.set_view_pane_layout(1) + get_view_pane_layout_success = helper.wait_for_condition(lambda: (general.get_view_pane_layout() == 1), 2) + get_viewport_count_success = helper.wait_for_condition(lambda: (general.get_viewport_count() == 2), 2) + Report.critical_result(Tests.viewport_config_updated, get_view_pane_layout_success and get_viewport_count_success) - # When the first viewport is active, the first area should be full of instances, and the second should be empty - general.set_active_viewport(0) - viewport_0_success = self.wait_for_condition(lambda: dynveg.validate_instance_count(first_entity_center_point, - box_size / 2.0, - filled_vegetation_area_instance_count), 5) - self.test_success = viewport_0_success and self.test_success - viewport_1_success = self.wait_for_condition(lambda: dynveg.validate_instance_count(second_entity_center_point, - box_size / 2.0, 0), 5) - self.test_success = viewport_1_success and self.test_success + # Set the view in the first viewport to point down at the first box + general.set_active_viewport(0) + helper.wait_for_condition(lambda: general.get_active_viewport() == 0, 2) + general.set_current_view_position(first_entity_center_point.x, first_entity_center_point.y, + first_entity_center_point.z + 30.0) + general.set_current_view_rotation(-85.0, 0.0, 0.0) - # When the second viewport is active, the second area should be full of instances, and the first should be empty - general.set_active_viewport(1) - viewport_0_success = self.wait_for_condition(lambda: dynveg.validate_instance_count(first_entity_center_point, - box_size / 2.0, 0), 5) - self.test_success = viewport_0_success and self.test_success - viewport_1_success = self.wait_for_condition(lambda: dynveg.validate_instance_count(second_entity_center_point, - box_size / 2.0, - filled_vegetation_area_instance_count), 5) - self.test_success = viewport_1_success and self.test_success + # Set the view in the second viewport to point down at the second box + general.set_active_viewport(1) + helper.wait_for_condition(lambda: general.get_active_viewport() == 1, 2) + general.set_current_view_position(second_entity_center_point.x, second_entity_center_point.y, + second_entity_center_point.z + 30.0) + general.set_current_view_rotation(-85.0, 0.0, 0.0) + + # Create the "flat surface" entities to use as our vegetation surfaces + first_surface_entity = dynveg.create_surface_entity("Surface 1", first_entity_center_point, box_size, box_size, + surface_height) + second_surface_entity = dynveg.create_surface_entity("Surface 2", second_entity_center_point, box_size, box_size, + surface_height) + + # Create the two vegetation areas + test_slice_asset_path = os.path.join("Slices", "PurpleFlower.dynamicslice") + first_veg_entity = dynveg.create_vegetation_area("Veg Area 1", first_entity_center_point, box_size, box_size, + box_size, test_slice_asset_path) + second_veg_entity = dynveg.create_vegetation_area("Veg Area 2", second_entity_center_point, box_size, box_size, + box_size, test_slice_asset_path) + + # When the first viewport is active, the first area should be full of instances, and the second should be empty + general.set_active_viewport(0) + helper.wait_for_condition(lambda: general.get_active_viewport() == 0, 2) + viewport_0_success = helper.wait_for_condition(lambda: dynveg.validate_instance_count(first_entity_center_point, + box_size / 2.0, + filled_vegetation_area_instance_count), 5) + viewport_1_success = helper.wait_for_condition(lambda: dynveg.validate_instance_count(second_entity_center_point, + box_size / 2.0, 0), 5) + Report.result(Tests.first_viewport_active_instance_count, viewport_0_success) + Report.result(Tests.second_viewport_inactive_instance_count, viewport_1_success) + + # When the second viewport is active, the second area should be full of instances, and the first should be empty + general.set_active_viewport(1) + helper.wait_for_condition(lambda: general.get_active_viewport() == 1, 2) + viewport_0_success = helper.wait_for_condition(lambda: dynveg.validate_instance_count(first_entity_center_point, + box_size / 2.0, 0), 5) + Report.result(Tests.first_viewport_inactive_instance_count, viewport_0_success) + viewport_1_success = helper.wait_for_condition(lambda: dynveg.validate_instance_count(second_entity_center_point, + box_size / 2.0, + filled_vegetation_area_instance_count), 5) + Report.result(Tests.second_viewport_active_instance_count, viewport_1_success) -test = TestLayerSpawnerInstanceCameraRefresh() -test.run() +if __name__ == "__main__": + + from editor_python_test_tools.utils import Report + Report.start_test(LayerSpawner_InstancesRefreshUsingCorrectViewportCamera) diff --git a/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/MeshBlocker_InstancesBlockedByMesh.py b/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/MeshBlocker_InstancesBlockedByMesh.py index 47e9c857c2..415673c215 100755 --- a/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/MeshBlocker_InstancesBlockedByMesh.py +++ b/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/MeshBlocker_InstancesBlockedByMesh.py @@ -5,92 +5,90 @@ For complete copyright and license terms please see the LICENSE at the root of t SPDX-License-Identifier: Apache-2.0 OR MIT """ -import os, sys -sys.path.append(os.path.dirname(os.path.abspath(__file__))) -import azlmbr.asset as asset -import azlmbr.bus as bus -import azlmbr.components as components -import azlmbr.editor as editor -import azlmbr.legacy.general as general -import azlmbr.math as math - -sys.path.append(os.path.join(azlmbr.paths.devroot, 'AutomatedTesting', 'Gem', 'PythonTests')) -import editor_python_test_tools.hydra_editor_utils as hydra -from editor_python_test_tools.editor_test_helper import EditorTestHelper -from largeworlds.large_worlds_utils import editor_dynveg_test_helper as dynveg +class Tests: + blocked_instance_count = ( + "Instance count is as expected wih a Blocker setup", + "Found unexpected instances with a Blocker setup" + ) -class test_MeshBlocker_InstancesBlockedByMesh(EditorTestHelper): - def __init__(self): - EditorTestHelper.__init__(self, log_prefix="MeshBlocker_InstancesBlockedByMesh", args=["level"]) +def MeshBlocker_InstancesBlockedByMesh(): + """ + Summary: + Level is created. An entity with a vegetation spawner and entity with vegetation blocker (Mesh) component are + added. Finally, the instance counts are checked to verify expected numbers after blocker is applied. - def run_test(self): - """ - Summary: - Level is created. An entity with a vegetation spawner and entity with vegetation blocker (Mesh) component are - added. Finally, the instance counts are checked to verify expected numbers after blocker is applied. + Expected Behavior: + The vegetation planted in the Spawner area is blocked by the Mesh of the Vegetation Blocker Mesh component. - Expected Behavior: - The vegetation planted in the Spawner area is blocked by the Mesh of the Vegetation Blocker Mesh component. + Test Steps: + --> Open a level + --> Create Spawner Entity + --> Create Surface Entity to spawn vegetation instances on + --> Create Blocker Entity with cube mesh + --> Verify spawned vegetation instance counts - Test Steps: - --> Create level - --> Create Spawner Entity - --> Create Surface Entity to spawn vegetation instances on - --> Create Blocker Entity with cube mesh - --> Verify spawned vegetation instance counts + Note: + - 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. - Note: - - 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 + """ - :return: None - """ + import os - # Create a new level - self.test_success = self.create_level( - self.args["level"], - heightmap_resolution=1024, - heightmap_meters_per_pixel=1, - terrain_texture_resolution=4096, - use_terrain=False, - ) + import azlmbr.asset as asset + import azlmbr.bus as bus + import azlmbr.components as components + import azlmbr.legacy.general as general + import azlmbr.math as math - general.set_current_view_position(500.49, 498.69, 46.66) - general.set_current_view_rotation(-42.05, 0.00, -36.33) + import editor_python_test_tools.hydra_editor_utils as hydra + from largeworlds.large_worlds_utils import editor_dynveg_test_helper as dynveg + from editor_python_test_tools.utils import Report + from editor_python_test_tools.utils import TestHelper as helper - # Create entity with components "Vegetation Layer Spawner", "Vegetation Asset List", "Box Shape" - entity_position = math.Vector3(512.0, 512.0, 32.0) - asset_path = os.path.join("Slices", "PurpleFlower.dynamicslice") - spawner_entity = dynveg.create_vegetation_area("Instance Spawner", - entity_position, - 10.0, 10.0, 10.0, - asset_path) + # Open an existing simple level + helper.init_idle() + helper.open_level("Physics", "Base") - # Create surface entity to plant on - dynveg.create_surface_entity("Surface Entity", entity_position, 10.0, 10.0, 1.0) + general.set_current_view_position(500.49, 498.69, 46.66) + general.set_current_view_rotation(-42.05, 0.00, -36.33) - # Create blocker entity with cube mesh - mesh_type_id = azlmbr.globals.property.EditorMeshComponentTypeId - blocker_entity = hydra.Entity("Blocker Entity") - blocker_entity.create_entity(entity_position, - ["Vegetation Layer Blocker (Mesh)"]) - blocker_entity.add_component_of_type(mesh_type_id) - if blocker_entity.id.IsValid(): - print(f"'{blocker_entity.name}' created") - cubeId = asset.AssetCatalogRequestBus( - bus.Broadcast, "GetAssetIdByPath", os.path.join("objects", "_primitives", "_box_1x1.azmodel"), math.Uuid(), - False) - blocker_entity.get_set_test(1, "Controller|Configuration|Mesh Asset", cubeId) - components.TransformBus(bus.Event, "SetLocalUniformScale", blocker_entity.id, 2.0) + # Create entity with components "Vegetation Layer Spawner", "Vegetation Asset List", "Box Shape" + entity_position = math.Vector3(512.0, 512.0, 32.0) + asset_path = os.path.join("Slices", "PurpleFlower.dynamicslice") + spawner_entity = dynveg.create_vegetation_area("Instance Spawner", + entity_position, + 10.0, 10.0, 10.0, + asset_path) - # Verify spawned instance counts are accurate after addition of Blocker Entity - num_expected = 160 # Number of "PurpleFlower"s that plant on a 10 x 10 surface minus 2m blocker cube - result = self.wait_for_condition(lambda: dynveg.validate_instance_count_in_entity_shape(spawner_entity.id, - num_expected), 2.0) - self.test_success = self.test_success and result + # Create surface entity to plant on + dynveg.create_surface_entity("Surface Entity", entity_position, 10.0, 10.0, 1.0) + + # Create blocker entity with cube mesh + mesh_type_id = azlmbr.globals.property.EditorMeshComponentTypeId + blocker_entity = hydra.Entity("Blocker Entity") + blocker_entity.create_entity(entity_position, + ["Vegetation Layer Blocker (Mesh)"]) + blocker_entity.add_component_of_type(mesh_type_id) + if blocker_entity.id.IsValid(): + print(f"'{blocker_entity.name}' created") + cubeId = asset.AssetCatalogRequestBus( + bus.Broadcast, "GetAssetIdByPath", os.path.join("objects", "_primitives", "_box_1x1.azmodel"), math.Uuid(), + False) + blocker_entity.get_set_test(1, "Controller|Configuration|Mesh Asset", cubeId) + components.TransformBus(bus.Event, "SetLocalUniformScale", blocker_entity.id, 2.0) + + # Verify spawned instance counts are accurate after addition of Blocker Entity + num_expected = 160 # Number of "PurpleFlower"s that plant on a 10 x 10 surface minus 2m blocker cube + result = helper.wait_for_condition(lambda: dynveg.validate_instance_count_in_entity_shape(spawner_entity.id, + num_expected), 2.0) + Report.result(Tests.blocked_instance_count, result) -test = test_MeshBlocker_InstancesBlockedByMesh() -test.run() +if __name__ == "__main__": + + from editor_python_test_tools.utils import Report + Report.start_test(MeshBlocker_InstancesBlockedByMesh) diff --git a/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/MeshBlocker_InstancesBlockedByMeshHeightTuning.py b/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/MeshBlocker_InstancesBlockedByMeshHeightTuning.py index f5dad6b64d..be15c9967c 100755 --- a/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/MeshBlocker_InstancesBlockedByMeshHeightTuning.py +++ b/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/MeshBlocker_InstancesBlockedByMeshHeightTuning.py @@ -5,104 +5,100 @@ For complete copyright and license terms please see the LICENSE at the root of t SPDX-License-Identifier: Apache-2.0 OR MIT """ -import os -import math as pymath -import sys -sys.path.append(os.path.dirname(os.path.abspath(__file__))) -import azlmbr -import azlmbr.asset as asset -import azlmbr.bus as bus -import azlmbr.components as components -import azlmbr.editor as editor -import azlmbr.legacy.general as general -import azlmbr.math as math +class Tests: + blocked_instance_count = ( + "Instance count is as expected wih a Blocker setup", + "Found unexpected instances with a Blocker setup" + ) -sys.path.append(os.path.join(azlmbr.paths.devroot, 'AutomatedTesting', 'Gem', 'PythonTests')) -import editor_python_test_tools.hydra_editor_utils as hydra -from editor_python_test_tools.editor_test_helper import EditorTestHelper -from largeworlds.large_worlds_utils import editor_dynveg_test_helper as dynveg +def MeshBlocker_InstancesBlockedByMeshHeightTuning(): + """ + Summary: + A temporary level is created, then a simple vegetation area is created. A blocker area is created and it is + verified that the tuning of the height percent blocker setting works as expected. + + Expected Behavior: + Vegetation is blocked only around the trunk of the tree, while it still plants under the areas covered by branches. + + Test Steps: + 1) Open a level + 2) Create entity with components "Vegetation Layer Spawner", "Vegetation Asset List", "Box Shape" + 3) Create surface entity + 4) Create blocker entity with sphere mesh + 5) Adjust the height Min/Max percentage values of blocker + 6) Verify spawned instance counts are accurate after adjusting height Max percentage of Blocker Entity + + Note: + - 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 + import math as pymath + + import azlmbr + import azlmbr.asset as asset + import azlmbr.bus as bus + import azlmbr.components as components + import azlmbr.legacy.general as general + import azlmbr.math as math + + import editor_python_test_tools.hydra_editor_utils as hydra + from largeworlds.large_worlds_utils import editor_dynveg_test_helper as dynveg + from editor_python_test_tools.utils import Report + from editor_python_test_tools.utils import TestHelper as helper + + # 1) Open an existing simple level + helper.init_idle() + helper.open_level("Physics", "Base") + + general.set_current_view_position(500.49, 498.69, 46.66) + general.set_current_view_rotation(-42.05, 0.00, -36.33) + + # 2) Create entity with components "Vegetation Layer Spawner", "Vegetation Asset List", "Box Shape" + entity_position = math.Vector3(512.0, 512.0, 32.0) + asset_path = os.path.join("Slices", "PurpleFlower.dynamicslice") + spawner_entity = dynveg.create_vegetation_area("Instance Spawner", + entity_position, + 10.0, 10.0, 10.0, + asset_path) + + # 3) Create surface entity to plant on + dynveg.create_surface_entity("Surface Entity", entity_position, 10.0, 10.0, 1.0) + + # 4) Create blocker entity with rotated cube mesh + y_rotation = pymath.radians(45.0) + mesh_type_id = azlmbr.globals.property.EditorMeshComponentTypeId + blocker_entity = hydra.Entity("Blocker Entity") + blocker_entity.create_entity(entity_position, + ["Vegetation Layer Blocker (Mesh)"]) + blocker_entity.add_component_of_type(mesh_type_id) + if blocker_entity.id.IsValid(): + Report.info(f"'{blocker_entity.name}' created") + sphere_id = asset.AssetCatalogRequestBus( + bus.Broadcast, "GetAssetIdByPath", os.path.join("objects", "_primitives", "_box_1x1.azmodel"), math.Uuid(), + False) + blocker_entity.get_set_test(1, "Controller|Configuration|Mesh Asset", sphere_id) + components.TransformBus(bus.Event, "SetLocalUniformScale", blocker_entity.id, 5.0) + components.TransformBus(bus.Event, "SetLocalRotation", blocker_entity.id, math.Vector3(0.0, y_rotation, 0.0)) + + # 5) Adjust the height Max percentage values of blocker + blocker_entity.get_set_test(0, "Configuration|Mesh Height Percent Max", 0.8) + + # 6) Verify spawned instance counts are accurate after adjusting height Max percentage of Blocker Entity + # The number of "PurpleFlower" instances that plant on a 10 x 10 surface minus those blocked by the rotated at + # 80% max height factored in. + num_expected = 127 + result = helper.wait_for_condition(lambda: dynveg.validate_instance_count_in_entity_shape(spawner_entity.id, + num_expected), 5.0) + Report.result(Tests.blocked_instance_count, result) -class test_MeshBlocker_InstancesBlockedByMeshHeightTuning(EditorTestHelper): - def __init__(self): - EditorTestHelper.__init__(self, log_prefix="MeshBlocker_InstancesBlockedByMeshHeightTuning", args=["level"]) +if __name__ == "__main__": - def run_test(self): - """ - Summary: - A temporary level is created, then a simple vegetation area is created. A blocker area is created and it is - verified that the tuning of the height percent blocker setting works as expected. - - Expected Behavior: - Vegetation is blocked only around the trunk of the tree, while it still plants under the areas covered by branches. - - Test Steps: - 1) Create level - 2) Create entity with components "Vegetation Layer Spawner", "Vegetation Asset List", "Box Shape" - 3) Create surface entity - 4) Create blocker entity with sphere mesh - 5) Adjust the height Min/Max percentage values of blocker - 6) Verify spawned instance counts are accurate after adjusting height Max percentage of Blocker Entity - - Note: - - 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 - """ - - # 1) Create level - self.test_success = self.create_level( - self.args["level"], - heightmap_resolution=1024, - heightmap_meters_per_pixel=1, - terrain_texture_resolution=4096, - use_terrain=False, - ) - - general.set_current_view_position(500.49, 498.69, 46.66) - general.set_current_view_rotation(-42.05, 0.00, -36.33) - - # 2) Create entity with components "Vegetation Layer Spawner", "Vegetation Asset List", "Box Shape" - entity_position = math.Vector3(512.0, 512.0, 32.0) - asset_path = os.path.join("Slices", "PurpleFlower.dynamicslice") - spawner_entity = dynveg.create_vegetation_area("Instance Spawner", - entity_position, - 10.0, 10.0, 10.0, - asset_path) - - # 3) Create surface entity to plant on - dynveg.create_surface_entity("Surface Entity", entity_position, 10.0, 10.0, 1.0) - - # 4) Create blocker entity with rotated cube mesh - y_rotation = pymath.radians(45.0) - mesh_type_id = azlmbr.globals.property.EditorMeshComponentTypeId - blocker_entity = hydra.Entity("Blocker Entity") - blocker_entity.create_entity(entity_position, - ["Vegetation Layer Blocker (Mesh)"]) - blocker_entity.add_component_of_type(mesh_type_id) - if blocker_entity.id.IsValid(): - print(f"'{blocker_entity.name}' created") - sphere_id = asset.AssetCatalogRequestBus( - bus.Broadcast, "GetAssetIdByPath", os.path.join("objects", "_primitives", "_box_1x1.azmodel"), math.Uuid(), - False) - blocker_entity.get_set_test(1, "Controller|Configuration|Mesh Asset", sphere_id) - components.TransformBus(bus.Event, "SetLocalUniformScale", blocker_entity.id, 5.0) - components.TransformBus(bus.Event, "SetLocalRotation", blocker_entity.id, math.Vector3(0.0, y_rotation, 0.0)) - - # 5) Adjust the height Max percentage values of blocker - blocker_entity.get_set_test(0, "Configuration|Mesh Height Percent Max", 0.8) - - # 6) Verify spawned instance counts are accurate after adjusting height Max percentage of Blocker Entity - # The number of "PurpleFlower" instances that plant on a 10 x 10 surface minus those blocked by the rotated at - # 80% max height factored in. - num_expected = 127 - result = 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 result - - -test = test_MeshBlocker_InstancesBlockedByMeshHeightTuning() -test.run() + from editor_python_test_tools.utils import Report + Report.start_test(MeshBlocker_InstancesBlockedByMeshHeightTuning) diff --git a/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/MeshSurfaceTagEmitter_DependentOnMeshComponent.py b/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/MeshSurfaceTagEmitter_DependentOnMeshComponent.py index c093529888..cee8ebe5b6 100755 --- a/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/MeshSurfaceTagEmitter_DependentOnMeshComponent.py +++ b/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/MeshSurfaceTagEmitter_DependentOnMeshComponent.py @@ -5,93 +5,87 @@ For complete copyright and license terms please see the LICENSE at the root of t SPDX-License-Identifier: Apache-2.0 OR MIT """ -import os -import sys -sys.path.append(os.path.dirname(os.path.abspath(__file__))) -import azlmbr.bus as bus -import azlmbr.editor as editor -import azlmbr.entity as EntityId -import azlmbr.math as math -import azlmbr.paths - -sys.path.append(os.path.join(azlmbr.paths.devroot, 'AutomatedTesting', 'Gem', 'PythonTests')) -import editor_python_test_tools.hydra_editor_utils as hydra -from editor_python_test_tools.editor_test_helper import EditorTestHelper +class Tests: + new_entity_created = ( + "Successfully created new entity", + "Failed to create new entity" + ) + emitter_disabled_before_mesh = ( + "Mesh Surface Tag Emitter is disabled without a Mesh component", + "Mesh Surface Tag Emitter is unexpectedly enabled without a Mesh component" + ) + emitter_enabled_after_mesh = ( + "Mesh Surface Tag Emitter is enabled after adding a Mesh component", + "Mesh Surface Tag Emitter is unexpectedly disabled after adding a Mesh component" + ) -class TestMeshSurfaceTagEmitter(EditorTestHelper): - def __init__(self): - EditorTestHelper.__init__(self, log_prefix="MeshSurfaceTagEmitter_DependentOnMeshComponent", args=["level"]) +def MeshSurfaceTagEmitter_DependentOnMeshComponent(): + """ + Summary: + A New level is loaded. A New entity is created with component "Mesh Surface Tag Emitter". Adding a component + "Mesh" to the same entity. - def run_test(self): - """ - Summary: - A New level is loaded. A New entity is created with component "Mesh Surface Tag Emitter". Adding a component - "Mesh" to the same entity. + Expected Behavior: + Mesh Surface Tag Emitter is disabled until the required Mesh component is added to the entity. - Expected Behavior: - Mesh Surface Tag Emitter is disabled until the required Mesh component is added to the entity. + Test Steps: + 1) Open level + 2) Create a new entity with component "Mesh Surface Tag Emitter" + 3) Make sure Mesh Surface Tag Emitter is disabled + 4) Add Mesh to the same entity + 5) Make sure Mesh Surface Tag Emitter is enabled after adding Mesh - Test Steps: - 1) Open level - 2) Create a new entity with component "Mesh Surface Tag Emitter" - 3) Make sure Mesh Surface Tag Emitter is disabled - 4) Add Mesh to the same entity - 5) Make sure Mesh Surface Tag Emitter is enabled after adding Mesh + 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. - 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 + """ - :return: None - """ + import azlmbr.bus as bus + import azlmbr.editor as editor + import azlmbr.entity as EntityId + import azlmbr.math as math - def is_component_enabled(EntityComponentIdPair): - return editor.EditorComponentAPIBus(bus.Broadcast, "IsComponentEnabled", EntityComponentIdPair) + import editor_python_test_tools.hydra_editor_utils as hydra + from editor_python_test_tools.utils import Report + from editor_python_test_tools.utils import TestHelper as helper - # 1) Open level - self.test_success = self.create_level( - self.args["level"], - heightmap_resolution=1024, - heightmap_meters_per_pixel=1, - terrain_texture_resolution=4096, - use_terrain=False, - ) + def is_component_enabled(EntityComponentIdPair): + return editor.EditorComponentAPIBus(bus.Broadcast, "IsComponentEnabled", EntityComponentIdPair) - # 2) Create a new entity with component "Mesh Surface Tag Emitter" - entity_position = math.Vector3(125.0, 136.0, 32.0) - component_to_add = "Mesh Surface Tag Emitter" - entity_id = editor.ToolsApplicationRequestBus( - bus.Broadcast, "CreateNewEntityAtPosition", entity_position, EntityId.EntityId() - ) - meshentity = hydra.Entity("meshentity", entity_id) - meshentity.components = [] - meshentity.components.append(hydra.add_component(component_to_add, entity_id)) - if entity_id.IsValid(): - print("New Entity Created") + # 1) Open an existing simple level + helper.init_idle() + helper.open_level("Physics", "Base") - # 3) Make sure Mesh Surface Tag Emitter is disabled - is_enabled = is_component_enabled(meshentity.components[0]) - self.test_success = self.test_success and not is_enabled - if not is_enabled: - print(f"{component_to_add} is Disabled") - elif is_enabled: - print(f"{component_to_add} is Enabled. But It should be disabled before adding Mesh") + # 2) Create a new entity with component "Mesh Surface Tag Emitter" + entity_position = math.Vector3(125.0, 136.0, 32.0) + component_to_add = "Mesh Surface Tag Emitter" + entity_id = editor.ToolsApplicationRequestBus( + bus.Broadcast, "CreateNewEntityAtPosition", entity_position, EntityId.EntityId() + ) + meshentity = hydra.Entity("meshentity", entity_id) + meshentity.components = [] + meshentity.components.append(hydra.add_component(component_to_add, entity_id)) + Report.critical_result(Tests.new_entity_created, entity_id.IsValid()) - # 4) Add Mesh to the same entity - component = "Mesh" - meshentity.components.append(hydra.add_component(component, entity_id)) + # 3) Make sure Mesh Surface Tag Emitter is disabled + is_enabled = is_component_enabled(meshentity.components[0]) + Report.result(Tests.emitter_disabled_before_mesh, not is_enabled) - # 5) Make sure Mesh Surface Tag Emitter is enabled after adding Mesh - is_enabled = is_component_enabled(meshentity.components[0]) - self.test_success = self.test_success and is_enabled - if is_enabled: - print(f"{component_to_add} is Enabled") - elif not is_enabled: - print(f"{component_to_add} is Disabled. But It should be enabled after adding Mesh") + # 4) Add Mesh to the same entity + component = "Mesh" + meshentity.components.append(hydra.add_component(component, entity_id)) + + # 5) Make sure Mesh Surface Tag Emitter is enabled after adding Mesh + is_enabled = is_component_enabled(meshentity.components[0]) + Report.result(Tests.emitter_enabled_after_mesh, is_enabled) -test = TestMeshSurfaceTagEmitter() -test.run() +if __name__ == "__main__": + + from editor_python_test_tools.utils import Report + Report.start_test(MeshSurfaceTagEmitter_DependentOnMeshComponent) diff --git a/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/MeshSurfaceTagEmitter_SurfaceTagsAddRemoveSuccessfully.py b/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/MeshSurfaceTagEmitter_SurfaceTagsAddRemoveSuccessfully.py index 83beb5d0c2..d7abc66106 100755 --- a/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/MeshSurfaceTagEmitter_SurfaceTagsAddRemoveSuccessfully.py +++ b/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/MeshSurfaceTagEmitter_SurfaceTagsAddRemoveSuccessfully.py @@ -5,75 +5,71 @@ For complete copyright and license terms please see the LICENSE at the root of t SPDX-License-Identifier: Apache-2.0 OR MIT """ -import os -import sys -sys.path.append(os.path.dirname(os.path.abspath(__file__))) -import azlmbr.math as math -import azlmbr.paths -import azlmbr.surface_data as surface_data - -sys.path.append(os.path.join(azlmbr.paths.devroot, 'AutomatedTesting', 'Gem', 'PythonTests')) -import editor_python_test_tools.hydra_editor_utils as hydra -from editor_python_test_tools.editor_test_helper import EditorTestHelper +class Tests: + add_surface_tag = ( + "Surface Tag added successfully", + "Failed to add Surface Tag" + ) + remove_surface_tag = ( + "Successfully removed Surface Tag", + "Failed to remove Surface Tag" + ) -class TestMeshSurfaceTagEmitter(EditorTestHelper): - def __init__(self): - EditorTestHelper.__init__(self, log_prefix="MeshSurfaceTagEmitter_SurfaceTagsAddRemoveSucessfully", - args=["level"]) +def MeshSurfaceTagEmitter_SurfaceTagsAddRemoveSuccessfully(): + """ + Summary: + An enity with Mesh Tag Emitter and a Mesh is added to the viewport to verify if we are able to + add/remove surface tags. - def run_test(self): - """ - Summary: - An enity with Mesh Tag Emitter and a Mesh is added to the viewport to verify if we are able to - add/remove surface tags. + Expected Behavior: + A new Surface Tag can be added and removed from the component. - Expected Behavior: - A new Surface Tag can be added and removed from the component. + Test Steps: + 1) Open level + 2) Create a new entity with components "Mesh Surface Tag Emitter", "Mesh" + 3) Add/ remove Surface Tags - Test Steps: - 1) Open level - 2) Create a new entity with components "Mesh Surface Tag Emitter", "Mesh" - 3) Add/ remove Surface Tags + 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. - 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 + """ - :return: None - """ + import azlmbr.math as math + import azlmbr.surface_data as surface_data - # 1) Open level - self.test_success = self.create_level( - self.args["level"], - heightmap_resolution=1024, - heightmap_meters_per_pixel=1, - terrain_texture_resolution=4096, - use_terrain=False, - ) + import editor_python_test_tools.hydra_editor_utils as hydra + from editor_python_test_tools.utils import Report + from editor_python_test_tools.utils import TestHelper as helper - # 2) Create a new entity with components "Mesh Surface Tag Emitter", "Mesh" - entity_position = math.Vector3(125.0, 136.0, 32.0) - components_to_add = ["Mesh Surface Tag Emitter", "Mesh"] - entity = hydra.Entity("entity") - entity.create_entity(entity_position, components_to_add) + # 1) Open an existing simple level + helper.init_idle() + helper.open_level("Physics", "Base") - # 3) Add/ remove Surface Tags - tag = surface_data.SurfaceTag() - tag.SetTag("water") - pte = hydra.get_property_tree(entity.components[0]) - path = "Configuration|Generated Tags" - pte.add_container_item(path, 0, tag) - success = self.wait_for_condition(lambda: pte.get_container_count(path).GetValue() == 1, 5.0) - self.test_success = self.test_success and success - print(f"Added SurfaceTag: container count is {pte.get_container_count(path).GetValue()}") - pte.remove_container_item(path, 0) - success = self.wait_for_condition(lambda: pte.get_container_count(path).GetValue() == 0, 5.0) - self.test_success = self.test_success and success - print(f"Removed SurfaceTag: container count is {pte.get_container_count(path).GetValue()}") + # 2) Create a new entity with components "Mesh Surface Tag Emitter", "Mesh" + entity_position = math.Vector3(125.0, 136.0, 32.0) + components_to_add = ["Mesh Surface Tag Emitter", "Mesh"] + entity = hydra.Entity("entity") + entity.create_entity(entity_position, components_to_add) + + # 3) Add/ remove Surface Tags + tag = surface_data.SurfaceTag() + tag.SetTag("water") + pte = hydra.get_property_tree(entity.components[0]) + path = "Configuration|Generated Tags" + pte.add_container_item(path, 0, tag) + success = helper.wait_for_condition(lambda: pte.get_container_count(path).GetValue() == 1, 5.0) + Report.result(Tests.add_surface_tag, success) + pte.remove_container_item(path, 0) + success = helper.wait_for_condition(lambda: pte.get_container_count(path).GetValue() == 0, 5.0) + Report.result(Tests.remove_surface_tag, success) -test = TestMeshSurfaceTagEmitter() -test.run() +if __name__ == "__main__": + + from editor_python_test_tools.utils import Report + Report.start_test(MeshSurfaceTagEmitter_SurfaceTagsAddRemoveSuccessfully) diff --git a/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/PhysXColliderSurfaceTagEmitter_E2E_Editor.py b/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/PhysXColliderSurfaceTagEmitter_E2E_Editor.py index 361dbdaea9..b5739c2386 100755 --- a/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/PhysXColliderSurfaceTagEmitter_E2E_Editor.py +++ b/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/PhysXColliderSurfaceTagEmitter_E2E_Editor.py @@ -5,27 +5,30 @@ For complete copyright and license terms please see the LICENSE at the root of t SPDX-License-Identifier: Apache-2.0 OR MIT """ -import os -import sys -sys.path.append(os.path.dirname(os.path.abspath(__file__))) -import azlmbr.asset as asset -import azlmbr.editor as editor -import azlmbr.legacy.general as general -import azlmbr.bus as bus -import azlmbr.math as math +def PhysXColliderSurfaceTagEmitter_E2E_Editor(): + """ + Summary: + Test aspects of the PhysX Collider Surface Tag Emitter Component through the BehaviorContext and the Property + Tree. -sys.path.append(os.path.join(azlmbr.paths.devroot, 'AutomatedTesting', 'Gem', 'PythonTests')) -import editor_python_test_tools.hydra_editor_utils as hydra -from editor_python_test_tools.editor_test_helper import EditorTestHelper -from largeworlds.large_worlds_utils import editor_dynveg_test_helper as dynveg + :return: None + """ + import os -class TestPhysXColliderSurfaceTagEmitter(EditorTestHelper): - def __init__(self): - EditorTestHelper.__init__(self, log_prefix="PhysXColliderSurfaceTagEmitter_E2E_Editor", args=["level"]) + import azlmbr.asset as asset + import azlmbr.editor as editor + import azlmbr.legacy.general as general + import azlmbr.bus as bus + import azlmbr.math as math - def validate_behavior_context(self): + import editor_python_test_tools.hydra_editor_utils as hydra + from largeworlds.large_worlds_utils import editor_dynveg_test_helper as dynveg + from editor_python_test_tools.utils import Report + from editor_python_test_tools.utils import TestHelper as helper + + def validate_behavior_context(): # Verify that we can create the component through the BehaviorContext behavior_context_test_success = True test_component = azlmbr.surface_data.SurfaceDataColliderComponent() @@ -38,163 +41,181 @@ class TestPhysXColliderSurfaceTagEmitter(EditorTestHelper): provider_tag2 = azlmbr.surface_data.SurfaceTag('provider_tag2') modifier_tag1 = azlmbr.surface_data.SurfaceTag('modifier_tag1') modifier_tag2 = azlmbr.surface_data.SurfaceTag('modifier_tag2') - behavior_context_test_success = behavior_context_test_success and hydra.get_set_property_test(test_component, - 'providerTags', - [provider_tag1, - provider_tag2]) - behavior_context_test_success = behavior_context_test_success and hydra.get_set_property_test(test_component, - 'modifierTags', - [modifier_tag1, - modifier_tag2]) - self.log(f'SurfaceDataColliderComponent() BehaviorContext test: {behavior_context_test_success}') + behavior_context_test_success = behavior_context_test_success and hydra.get_set_property_test( + test_component, + 'providerTags', + [provider_tag1, + provider_tag2]) + behavior_context_test_success = behavior_context_test_success and hydra.get_set_property_test( + test_component, + 'modifierTags', + [modifier_tag1, + modifier_tag2]) + Report.info(f'SurfaceDataColliderComponent() BehaviorContext test: {behavior_context_test_success}') return behavior_context_test_success - def run_test(self): - """ - Summary: - Test aspects of the PhysX Collider Surface Tag Emitter Component through the BehaviorContext and the Property Tree. + # Open an existing simple level + helper.init_idle() + helper.open_level("Physics", "Base") - :return: None - """ - # Create an empty level - self.test_success = self.create_level( - self.args["level"], - heightmap_resolution=1024, - heightmap_meters_per_pixel=1, - terrain_texture_resolution=4096, - use_terrain=False, + # Verify all of the BehaviorContext API: + behavior_context = ( + "SurfaceDataColliderComponent() Behavior Context tests were successful", + "SurfaceDataColliderComponent() Behavior Context tests failed" + ) + Report.result(behavior_context, validate_behavior_context()) + + # Set up a test environment to validate the PhysX Collider Surface Tag Emitter Component. + # The test environment will consist of the following: + # - a 32 x 32 x 1 box shape that emits a surface with no tags + # - a 32 x 32 x 32 vegetation area that will only place vegetation on surfaces with the 'test' tag + # With this setup, no vegetation will appear until a Surface Tag Emitter either emits new points with + # the correct tag, or modifies points on our box shape to emit the correct tag. + + # Initialize some arbitrary constants for our test + entity_center_point = math.Vector3(512.0, 512.0, 100.0) + invalid_tag = azlmbr.surface_data.SurfaceTag('invalid') + surface_tag = azlmbr.surface_data.SurfaceTag('test') + test_box_size = 32.0 + baseline_surface_height = 1.0 + collider_radius = 4.0 + collider_diameter = collider_radius * 2.0 + + # Set viewport view of area under test, and toggle helpers back on + general.set_current_view_position(512.0, 485.0, 110.0) + general.set_current_view_rotation(-35.0, 0.0, 0.0) + general.toggle_helpers() + + # Create the "flat surface" entity to use as our baseline surface + dynveg.create_surface_entity("Baseline Surface", entity_center_point, 32.0, 32.0, 1.0) + + # Create a new entity with required vegetation area components + asset_path = os.path.join("Slices", "PinkFlower.dynamicslice") + spawner_entity = dynveg.create_vegetation_area("Veg Area", entity_center_point, 32.0, 32.0, 32.0, asset_path) + + # Add a Vegetation Surface Mask Filter component to the spawner entity and set it to include the "test" tag + spawner_entity.add_component("Vegetation Surface Mask Filter") + spawner_entity.get_set_test(3, "Configuration|Inclusion|Surface Tags", [surface_tag]) + + # At this point, there should be 0 instances within our entire veg area + initial_instance_count = ( + "Found no instances as expected with initial setup", + "Unexpected found instances with initial setup" + ) + initial_success = helper.wait_for_condition(lambda: dynveg.validate_instance_count(entity_center_point, 16.0, 0), + 5.0) + Report.result(initial_instance_count, initial_success) + + # Create an entity with a PhysX Collider and our PhysX Collider Surface Tag Emitter + collider_entity_created = ( + "Successfully created a Collider entity", + "Failed to create Collider entity" + ) + collider_entity = hydra.Entity("Collider Surface") + collider_entity.create_entity( + entity_center_point, + ["PhysX Collider", "PhysX Collider Surface Tag Emitter"] ) + Report.result(collider_entity_created, collider_entity.id.IsValid()) - # Verify all of the BehaviorContext API: - self.test_success = self.test_success and self.validate_behavior_context() + # Set up the PhysX Collider so that each shape type (sphere, box, capsule) has the same test height. + hydra.get_set_test(collider_entity, 0, "Shape Configuration|Sphere|Radius", collider_radius) + hydra.get_set_test(collider_entity, 0, "Shape Configuration|Box|Dimensions", math.Vector3(collider_diameter, + collider_diameter, + collider_diameter)) + hydra.get_set_test(collider_entity, 0, "Shape Configuration|Capsule|Height", collider_diameter) - # Set up a test environment to validate the PhysX Collider Surface Tag Emitter Component. - # The test environment will consist of the following: - # - a 32 x 32 x 1 box shape that emits a surface with no tags - # - a 32 x 32 x 32 vegetation area that will only place vegetation on surfaces with the 'test' tag - # With this setup, no vegetation will appear until a Surface Tag Emitter either emits new points with - # the correct tag, or modifies points on our box shape to emit the correct tag. - - # Initialize some arbitrary constants for our test - entity_center_point = math.Vector3(512.0, 512.0, 100.0) - invalid_tag = azlmbr.surface_data.SurfaceTag('invalid') - surface_tag = azlmbr.surface_data.SurfaceTag('test') - test_box_size = 32.0 - baseline_surface_height = 1.0 - collider_radius = 4.0 - collider_diameter = collider_radius * 2.0 - - # Set viewport view of area under test, and toggle helpers back on - general.set_current_view_position(512.0, 485.0, 110.0) - general.set_current_view_rotation(-35.0, 0.0, 0.0) - general.toggle_helpers() - - # Create the "flat surface" entity to use as our baseline surface - dynveg.create_surface_entity("Baseline Surface", entity_center_point, 32.0, 32.0, 1.0) - - # Create a new entity with required vegetation area components - asset_path = os.path.join("Slices", "PinkFlower.dynamicslice") - spawner_entity = dynveg.create_vegetation_area("Veg Area", entity_center_point, 32.0, 32.0, 32.0, asset_path) - - # Add a Vegetation Surface Mask Filter component to the spawner entity and set it to include the "test" tag - spawner_entity.add_component("Vegetation Surface Mask Filter") - spawner_entity.get_set_test(3, "Configuration|Inclusion|Surface Tags", [surface_tag]) - - # At this point, there should be 0 instances within our entire veg area - initial_success = self.wait_for_condition(lambda: dynveg.validate_instance_count(entity_center_point, 16.0, 0), - 5.0) - self.test_success = self.test_success and initial_success - - # Create an entity with a PhysX Collider and our PhysX Collider Surface Tag Emitter - collider_entity = hydra.Entity("Collider Surface") - collider_entity.create_entity( - entity_center_point, - ["PhysX Collider", "PhysX Collider Surface Tag Emitter"] - ) - if collider_entity.id.IsValid(): - self.log(f"'{collider_entity.name}' created") - - # Set up the PhysX Collider so that each shape type (sphere, box, capsule) has the same test height. - hydra.get_set_test(collider_entity, 0, "Shape Configuration|Sphere|Radius", collider_radius) - hydra.get_set_test(collider_entity, 0, "Shape Configuration|Box|Dimensions", math.Vector3(collider_diameter, - collider_diameter, - collider_diameter)) - hydra.get_set_test(collider_entity, 0, "Shape Configuration|Capsule|Height", collider_diameter) - - # Run through each collider shape type (sphere, box, capsule) and verify the surface generation - # and surface modification of the PhysX Collision Surface Tag Emitter Component. - for collider_shape in range(0, 3): - hydra.get_set_test(collider_entity, 0, "Shape Configuration|Shape", collider_shape) - - # Test: Generate a new surface on the collider. - # There should be one instance at the very top of the collider sphere, and none on the baseline surface - # (We use a small query box to only check for one placed instance point) - hydra.get_set_test(collider_entity, 1, "Configuration|Generated Tags", [surface_tag]) - hydra.get_set_test(collider_entity, 1, "Configuration|Extended Tags", [invalid_tag]) - top_point = math.Vector3(entity_center_point.x, entity_center_point.y, entity_center_point.z + - collider_radius) - baseline_surface_point = math.Vector3(entity_center_point.x, entity_center_point.y, entity_center_point.z + - (baseline_surface_height / 2.0)) - top_point_success = self.wait_for_condition(lambda: dynveg.validate_instance_count(top_point, 0.25, 1), 5.0) - self.test_success = self.test_success and top_point_success - baseline_success = self.wait_for_condition(lambda: dynveg.validate_instance_count(baseline_surface_point, - 0.25, 0), 5.0) - self.test_success = self.test_success and baseline_success - - # Test: Modify an existing surface inside the collider. - # There should be no instances at the very top of the collider sphere, and one on the baseline surface - # within our query box. - # (We use a small query box to only check for one placed instance point) - hydra.get_set_test(collider_entity, 1, "Configuration|Generated Tags", [invalid_tag]) - hydra.get_set_test(collider_entity, 1, "Configuration|Extended Tags", [surface_tag]) - top_point_success = self.wait_for_condition(lambda: dynveg.validate_instance_count(top_point, 0.25, 0), 5.0) - self.test_success = self.test_success and top_point_success - baseline_success = self.wait_for_condition(lambda: dynveg.validate_instance_count(baseline_surface_point, - 0.25, 1), 5.0) - self.test_success = self.test_success and baseline_success - - # Setup collider entity with a PhysX Mesh - test_physx_mesh_asset_id = asset.AssetCatalogRequestBus( - bus.Broadcast, "GetAssetIdByPath", os.path.join("levels", "physics", - "Material_PerFaceMaterialGetsCorrectMaterial", - "test.pxmesh"), math.Uuid(), False) - - # Remove/re-add component due to LYN-5496 - collider_entity.remove_component("PhysX Collider") - collider_entity.add_component("PhysX Collider") - self.wait_for_condition(lambda: editor.EditorComponentAPIBus(bus.Broadcast, 'IsComponentEnabled', - collider_entity.components[1]), 5.0) - hydra.get_set_test(collider_entity, 1, "Shape Configuration|Shape", 7) - hydra.get_set_test(collider_entity, 1, "Shape Configuration|Asset|PhysX Mesh", test_physx_mesh_asset_id) - - # Set the asset scale to match the test heights of the shapes tested - asset_scale = math.Vector3(1.0, 1.0, 9.0) - collider_entity.get_set_test(1, "Shape Configuration|Asset|Configuration|Asset Scale", asset_scale) + # Run through each collider shape type (sphere, box, capsule) and verify the surface generation + # and surface modification of the PhysX Collision Surface Tag Emitter Component. + for collider_shape in range(0, 3): + collider_shapes = {0: "Sphere", 1: "Box", 2: "Capsule"} + hydra.get_set_test(collider_entity, 0, "Shape Configuration|Shape", collider_shape) # Test: Generate a new surface on the collider. - # There should be one instance at the very top of the collider mesh, and none on the baseline surface + # There should be one instance at the very top of the collider sphere, and none on the baseline surface # (We use a small query box to only check for one placed instance point) - self.log("Starting PhysX Mesh Collider Test") - hydra.get_set_test(collider_entity, 0, "Configuration|Generated Tags", [surface_tag]) - hydra.get_set_test(collider_entity, 0, "Configuration|Extended Tags", [invalid_tag]) - top_point_success = self.wait_for_condition(lambda: dynveg.validate_instance_count(top_point, 0.25, 1), 5.0) - self.test_success = self.test_success and top_point_success - baseline_success = self.wait_for_condition(lambda: dynveg.validate_instance_count(baseline_surface_point, - 0.25, 0), 5.0) - self.test_success = self.test_success and baseline_success + on_collider_top_point_count = ( + f"Expected number of instances found on the top point for {collider_shapes[collider_shape]} shape", + f"Found an unexpected number of instances on the top point for {collider_shapes[collider_shape]} shape" + ) + on_collider_baseline_count = ( + f"Expected number of instances found on the baseline point for {collider_shapes[collider_shape]} shape", + f"Found an unexpected number of instances on the baseline point for {collider_shapes[collider_shape]} shape" + ) + hydra.get_set_test(collider_entity, 1, "Configuration|Generated Tags", [surface_tag]) + hydra.get_set_test(collider_entity, 1, "Configuration|Extended Tags", [invalid_tag]) + top_point = math.Vector3(entity_center_point.x, entity_center_point.y, entity_center_point.z + + collider_radius) + baseline_surface_point = math.Vector3(entity_center_point.x, entity_center_point.y, entity_center_point.z + + (baseline_surface_height / 2.0)) + top_point_success = helper.wait_for_condition(lambda: dynveg.validate_instance_count(top_point, 0.25, 1), 5.0) + Report.result(on_collider_top_point_count, top_point_success) + baseline_success = helper.wait_for_condition(lambda: dynveg.validate_instance_count(baseline_surface_point, + 0.25, 0), 5.0) + Report.result(on_collider_baseline_count, baseline_success) # Test: Modify an existing surface inside the collider. - # There should be no instances at the very top of the collider mesh, and none on the baseline surface within - # our query box as PhysX meshes are treated as hollow shells, not solid volumes. + # There should be no instances at the very top of the collider sphere, and one on the baseline surface + # within our query box. # (We use a small query box to only check for one placed instance point) - hydra.get_set_test(collider_entity, 0, "Configuration|Generated Tags", [invalid_tag]) - hydra.get_set_test(collider_entity, 0, "Configuration|Extended Tags", [surface_tag]) - top_point_success = self.wait_for_condition(lambda: dynveg.validate_instance_count(top_point, 0.25, 0), 5.0) - self.test_success = self.test_success and top_point_success - baseline_success = self.wait_for_condition(lambda: dynveg.validate_instance_count(baseline_surface_point, - 0.25, 0), 5.0) - self.test_success = self.test_success and baseline_success + hydra.get_set_test(collider_entity, 1, "Configuration|Generated Tags", [invalid_tag]) + hydra.get_set_test(collider_entity, 1, "Configuration|Extended Tags", [surface_tag]) + top_point_success = helper.wait_for_condition(lambda: dynveg.validate_instance_count(top_point, 0.25, 0), 5.0) + Report.result(on_collider_top_point_count, top_point_success) + baseline_success = helper.wait_for_condition(lambda: dynveg.validate_instance_count(baseline_surface_point, + 0.25, 1), 5.0) + Report.result(on_collider_baseline_count, baseline_success) + + # Setup collider entity with a PhysX Mesh + test_physx_mesh_asset_id = asset.AssetCatalogRequestBus( + bus.Broadcast, "GetAssetIdByPath", os.path.join("levels", "physics", + "Material_PerFaceMaterialGetsCorrectMaterial", + "test.pxmesh"), math.Uuid(), False) + collider_entity.remove_component("PhysX Collider") + collider_entity.add_component("PhysX Collider") + helper.wait_for_condition(lambda: editor.EditorComponentAPIBus(bus.Broadcast, 'IsComponentEnabled', + collider_entity.components[1]), 5.0) + hydra.get_set_test(collider_entity, 1, "Shape Configuration|Shape", 7) + hydra.get_set_test(collider_entity, 1, "Shape Configuration|Asset|PhysX Mesh", test_physx_mesh_asset_id) + + # Set the asset scale to match the test heights of the shapes tested + asset_scale = math.Vector3(1.0, 1.0, 9.0) + collider_entity.get_set_test(1, "Shape Configuration|Asset|Configuration|Asset Scale", asset_scale) + + # Test: Generate a new surface on the collider. + # There should be one instance at the very top of the collider mesh, and none on the baseline surface + # (We use a small query box to only check for one placed instance point) + Report.info("Starting PhysX Mesh Collider Test") + on_collider_top_point_count = ( + f"Expected number of instances found on the top point for a PhysX Mesh", + f"Found an unexpected number of instances on the top point for a PhysX Mesh" + ) + on_collider_baseline_count = ( + f"Expected number of instances found on the baseline point for a PhysX Mesh", + f"Found an unexpected number of instances on the baseline point for a PhysX Mesh" + ) + hydra.get_set_test(collider_entity, 0, "Configuration|Generated Tags", [surface_tag]) + hydra.get_set_test(collider_entity, 0, "Configuration|Extended Tags", [invalid_tag]) + top_point_success = helper.wait_for_condition(lambda: dynveg.validate_instance_count(top_point, 0.25, 1), 5.0) + Report.result(on_collider_top_point_count, top_point_success) + baseline_success = helper.wait_for_condition(lambda: dynveg.validate_instance_count(baseline_surface_point, + 0.25, 0), 5.0) + Report.result(on_collider_baseline_count, baseline_success) + + # Test: Modify an existing surface inside the collider. + # There should be no instances at the very top of the collider mesh, and none on the baseline surface within + # our query box as PhysX meshes are treated as hollow shells, not solid volumes. + # (We use a small query box to only check for one placed instance point) + hydra.get_set_test(collider_entity, 0, "Configuration|Generated Tags", [invalid_tag]) + hydra.get_set_test(collider_entity, 0, "Configuration|Extended Tags", [surface_tag]) + top_point_success = helper.wait_for_condition(lambda: dynveg.validate_instance_count(top_point, 0.25, 0), 5.0) + Report.result(on_collider_top_point_count, top_point_success) + baseline_success = helper.wait_for_condition(lambda: dynveg.validate_instance_count(baseline_surface_point, + 0.25, 0), 5.0) + Report.result(on_collider_baseline_count, baseline_success) -test = TestPhysXColliderSurfaceTagEmitter() -test.run() +if __name__ == "__main__": + + from editor_python_test_tools.utils import Report + Report.start_test(PhysXColliderSurfaceTagEmitter_E2E_Editor) diff --git a/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/PositionModifier_AutoSnapToSurfaceWorks.py b/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/PositionModifier_AutoSnapToSurfaceWorks.py index a55e88488c..5a3ee70d22 100755 --- a/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/PositionModifier_AutoSnapToSurfaceWorks.py +++ b/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/PositionModifier_AutoSnapToSurfaceWorks.py @@ -5,136 +5,133 @@ For complete copyright and license terms please see the LICENSE at the root of t SPDX-License-Identifier: Apache-2.0 OR MIT """ -import os -import sys -sys.path.append(os.path.dirname(os.path.abspath(__file__))) -import azlmbr.bus as bus -import azlmbr.legacy.general as general -import azlmbr.editor as editor -import azlmbr.math as math -import azlmbr.paths - -sys.path.append(os.path.join(azlmbr.paths.devroot, 'AutomatedTesting', 'Gem', 'PythonTests')) -import editor_python_test_tools.hydra_editor_utils as hydra -from editor_python_test_tools.editor_test_helper import EditorTestHelper -from largeworlds.large_worlds_utils import editor_dynveg_test_helper as dynveg +class Tests: + initial_instance_count = ( + "Initial instance count is as expected", + "Found an unexpected number of initial instances" + ) + autosnap_enabled_instance_count = ( + "Found the expected number of instances with Auto Snap to Surface enabled", + "Found an unexpected number of instances with Auto Snap to Surface enabled" + ) + autosnap_disabled_instance_count = ( + "Found the expected number of instances with Auto Snap to Surface disabled", + "Found an unexpected number of instances with Auto Snap to Surface disabled" + ) -class TestPositionModifierAutoSnapToSurface(EditorTestHelper): - def __init__(self): - EditorTestHelper.__init__(self, log_prefix="PositionModifier_AutoSnapToSurface", args=["level"]) +def PositionModifier_AutoSnapToSurfaceWorks(): + """ + Summary: + Instance spawner is setup to plant on a spherical mesh. Offsets are set on the x-axis, and checks are performed + to ensure instances plant where expected depending on the toggle setting. - def run_test(self): - """ - Summary: - Instance spawner is setup to plant on a spherical mesh. Offsets are set on the x-axis, and checks are performed - to ensure instances plant where expected depending on the toggle setting. + Expected Behavior: + Offset instances snap to the expected surface when Auto Snap to Surface is enabled, and offset away from surface + when it is disabled. - Expected Behavior: - Offset instances snap to the expected surface when Auto Snap to Surface is enabled, and offset away from surface - when it is disabled. + Test Steps: + 1) Open a simple level + 2) Create a new entity with required vegetation area components and a Position Modifier + 3) Create a spherical planting surface + 4) Verify initial instance counts pre-filter + 5) Create a child entity of the spawner entity with a Constant Gradient component and pin to spawner + 6) Set the Position Modifier offset to 5 on the x-axis + 7) Validate instance counts on top of and inside the sphere mesh with Auto Snap to Surface enabled + 8) Validate instance counts on top of and inside the sphere mesh with Auto Snap to Surface disabled - Test Steps: - 1) Create a new, temporary level - 2) Create a new entity with required vegetation area components and a Position Modifier - 3) Create a spherical planting surface - 4) Verify initial instance counts pre-filter - 5) Create a child entity of the spawner entity with a Constant Gradient component and pin to spawner - 6) Set the Position Modifier offset to 5 on the x-axis - 7) Validate instance counts on top of and inside the sphere mesh with Auto Snap to Surface enabled - 8) Validate instance counts on top of and inside the sphere mesh with Auto Snap to Surface disabled + 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. - 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 + """ - :return: None - """ - position_modifier_paths = ['Configuration|Position X|Range Min', 'Configuration|Position X|Range Max', - 'Configuration|Position Y|Range Min', 'Configuration|Position Y|Range Max', - 'Configuration|Position Z|Range Min', 'Configuration|Position Z|Range Max'] + import os - # 1) Create a new, temporary level - self.test_success = self.create_level( - self.args["level"], - heightmap_resolution=1024, - heightmap_meters_per_pixel=1, - terrain_texture_resolution=4096, - use_terrain=False, - ) + import azlmbr.legacy.general as general + import azlmbr.math as math - # Set view of planting area for visual debugging - general.set_current_view_position(512.0, 500.0, 38.0) - general.set_current_view_rotation(-20.0, 0.0, 0.0) + import editor_python_test_tools.hydra_editor_utils as hydra + from largeworlds.large_worlds_utils import editor_dynveg_test_helper as dynveg + from editor_python_test_tools.utils import Report + from editor_python_test_tools.utils import TestHelper as helper - # 2) Create a new entity with required vegetation area components and a Position Modifier - spawner_center_point = math.Vector3(512.0, 512.0, 32.0) - asset_path = os.path.join("Slices", "PinkFlower.dynamicslice") - spawner_entity = dynveg.create_vegetation_area("Instance Spawner", spawner_center_point, 16.0, 16.0, 16.0, - asset_path) + position_modifier_paths = ['Configuration|Position X|Range Min', 'Configuration|Position X|Range Max', + 'Configuration|Position Y|Range Min', 'Configuration|Position Y|Range Max', + 'Configuration|Position Z|Range Min', 'Configuration|Position Z|Range Max'] - # Add a Vegetation Position Modifier and set offset values to 0 - spawner_entity.add_component("Vegetation Position Modifier") - for path in position_modifier_paths: - spawner_entity.get_set_test(3, path, 0) + # 1) Open an existing simple level + helper.init_idle() + helper.open_level("Physics", "Base") - # 3) Create a spherical planting surface and a flat surface - flat_entity = dynveg.create_surface_entity("Flat Surface", spawner_center_point, 32.0, 32.0, 1.0) - hill_entity = dynveg.create_mesh_surface_entity_with_slopes("Planting Surface", spawner_center_point, 5.0) + # Set view of planting area for visual debugging + general.set_current_view_position(512.0, 500.0, 38.0) + general.set_current_view_rotation(-20.0, 0.0, 0.0) - # Disable the Flat Surface Box Shape component, and temporarily ignore initial instance counts due to LYN-2245 - editor.EditorComponentAPIBus(bus.Broadcast, 'DisableComponents', [flat_entity.components[0]]) - """ - # 4) Verify initial instance counts pre-filter - num_expected = 121 - spawner_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 spawner_success - """ + # 2) Create a new entity with required vegetation area components and a Position Modifier + spawner_center_point = math.Vector3(512.0, 512.0, 32.0) + asset_path = os.path.join("Slices", "PinkFlower.dynamicslice") + spawner_entity = dynveg.create_vegetation_area("Instance Spawner", spawner_center_point, 16.0, 16.0, 16.0, + asset_path) - # 5) Create a child entity of the spawner entity with a Constant Gradient component and pin to spawner - components_to_add = ["Constant Gradient"] - gradient_entity = hydra.Entity("Gradient Entity") - gradient_entity.create_entity(spawner_center_point, components_to_add, parent_id=spawner_entity.id) + # Add a Vegetation Position Modifier and set offset values to 0 + spawner_entity.add_component("Vegetation Position Modifier") + for path in position_modifier_paths: + spawner_entity.get_set_test(3, path, 0) - # Pin the Constant Gradient to the X axis of the spawner's Position Modifier component - spawner_entity.get_set_test(3, 'Configuration|Position X|Gradient|Gradient Entity Id', gradient_entity.id) + # 3) Create a spherical planting surface + hill_entity = dynveg.create_mesh_surface_entity_with_slopes("Planting Surface", spawner_center_point, 5.0) - # 6) Set the Position Modifier offset to 2.5 on the x-axis - spawner_entity.get_set_test(3, position_modifier_paths[0], 2.5) - spawner_entity.get_set_test(3, position_modifier_paths[1], 2.5) + # 4) Verify initial instance counts pre-filter + num_expected = 29 + spawner_success = helper.wait_for_condition( + lambda: dynveg.validate_instance_count_in_entity_shape(spawner_entity.id, num_expected), 5.0) + Report.result(Tests.initial_instance_count, spawner_success) - # 7) Validate instance count at the top of the sphere mesh and inside the sphere mesh while Auto Snap to Surface - # is enabled - top_point = math.Vector3(512.0, 512.0, 37.0) - inside_point = math.Vector3(512.0, 512.0, 35.0) - radius = 0.5 - num_expected = 1 - self.log(f"Checking for instances in a {radius * 2}m area at {top_point.ToString()}") - top_success = self.wait_for_condition(lambda: dynveg.validate_instance_count(top_point, radius, num_expected), - 5.0) - self.test_success = top_success and self.test_success - num_expected = 0 - self.log(f"Checking for instances in a {radius * 2}m area at {inside_point.ToString()}") - inside_success = self.wait_for_condition(lambda: dynveg.validate_instance_count(inside_point, radius, - num_expected), 5.0) - self.test_success = inside_success and self.test_success + # 5) Create a child entity of the spawner entity with a Constant Gradient component and pin to spawner + components_to_add = ["Constant Gradient"] + gradient_entity = hydra.Entity("Gradient Entity") + gradient_entity.create_entity(spawner_center_point, components_to_add, parent_id=spawner_entity.id) - # 8) Toggle off Auto Snap to Surface. Instances should now plant inside the sphere and no longer on top - spawner_entity.get_set_test(3, "Configuration|Auto Snap To Surface", False) - num_expected = 0 - self.log(f"Checking for instances in a {radius * 2}m area at {top_point.ToString()}") - top_success = self.wait_for_condition(lambda: dynveg.validate_instance_count(top_point, radius, num_expected), - 5.0) - self.test_success = top_success and self.test_success - num_expected = 1 - self.log(f"Checking for instances in a {radius * 2}m area at {inside_point.ToString()}") - inside_success = self.wait_for_condition(lambda: dynveg.validate_instance_count(inside_point, radius, - num_expected), 5.0) - self.test_success = inside_success and self.test_success + # Pin the Constant Gradient to the X axis of the spawner's Position Modifier component + spawner_entity.get_set_test(3, 'Configuration|Position X|Gradient|Gradient Entity Id', gradient_entity.id) + + # 6) Set the Position Modifier offset to 2.5 on the x-axis + spawner_entity.get_set_test(3, position_modifier_paths[0], 2.5) + spawner_entity.get_set_test(3, position_modifier_paths[1], 2.5) + + # 7) Validate instance count at the top of the sphere mesh and inside the sphere mesh while Auto Snap to Surface + # is enabled + top_point = math.Vector3(512.0, 512.0, 37.0) + inside_point = math.Vector3(512.0, 512.0, 35.0) + radius = 0.5 + num_expected = 1 + Report.info(f"Checking for instances in a {radius * 2}m area at {top_point.ToString()}") + top_success = helper.wait_for_condition(lambda: dynveg.validate_instance_count(top_point, radius, num_expected), + 5.0) + num_expected = 0 + Report.info(f"Checking for instances in a {radius * 2}m area at {inside_point.ToString()}") + inside_success = helper.wait_for_condition(lambda: dynveg.validate_instance_count(inside_point, radius, + num_expected), 5.0) + Report.result(Tests.autosnap_enabled_instance_count, top_success and inside_success) + + # 8) Toggle off Auto Snap to Surface. Instances should now plant inside the sphere and no longer on top + spawner_entity.get_set_test(3, "Configuration|Auto Snap To Surface", False) + num_expected = 0 + Report.info(f"Checking for instances in a {radius * 2}m area at {top_point.ToString()}") + top_success = helper.wait_for_condition(lambda: dynveg.validate_instance_count(top_point, radius, num_expected), + 5.0) + num_expected = 1 + Report.info(f"Checking for instances in a {radius * 2}m area at {inside_point.ToString()}") + inside_success = helper.wait_for_condition(lambda: dynveg.validate_instance_count(inside_point, radius, + num_expected), 5.0) + Report.result(Tests.autosnap_disabled_instance_count, top_success and inside_success) -test = TestPositionModifierAutoSnapToSurface() -test.run() +if __name__ == "__main__": + + from editor_python_test_tools.utils import Report + Report.start_test(PositionModifier_AutoSnapToSurfaceWorks) diff --git a/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/PositionModifier_ComponentAndOverrides_InstancesPlantAtSpecifiedOffsets.py b/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/PositionModifier_ComponentAndOverrides_InstancesPlantAtSpecifiedOffsets.py index 9597f79339..c4fa91f886 100755 --- a/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/PositionModifier_ComponentAndOverrides_InstancesPlantAtSpecifiedOffsets.py +++ b/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/PositionModifier_ComponentAndOverrides_InstancesPlantAtSpecifiedOffsets.py @@ -5,159 +5,164 @@ For complete copyright and license terms please see the LICENSE at the root of t SPDX-License-Identifier: Apache-2.0 OR MIT """ -import os -import random -import sys -sys.path.append(os.path.dirname(os.path.abspath(__file__))) -import azlmbr.editor as editor -import azlmbr.legacy.general as general -import azlmbr.bus as bus -import azlmbr.math as math -import azlmbr.paths - -sys.path.append(os.path.join(azlmbr.paths.devroot, 'AutomatedTesting', 'Gem', 'PythonTests')) -import editor_python_test_tools.hydra_editor_utils as hydra -from editor_python_test_tools.editor_test_helper import EditorTestHelper -from largeworlds.large_worlds_utils import editor_dynveg_test_helper as dynveg +class Tests: + initial_instance_count = ( + "Initial instance count is as expected", + "Found an unexpected number of initial instances" + ) + position_offset = ( + "Found instances at all expected locations with Position Modifier offsets configured", + "Failed to find all expected instances at all locations with Position Modifier offsets configured" + ) + position_offset_overrides = ( + "Found instances at all expected locations with Position Modifier offset overrides configured", + "Failed to find all expected instances at all locations with Position Modifier offset overrides configured" + ) -class TestPositionModifierComponentAndOverrides(EditorTestHelper): - def __init__(self): - EditorTestHelper.__init__(self, log_prefix="PositionModifierComponentAndOverrides_InstanceOffset", args=["level"]) +def PositionModifier_ComponentAndOverrides_InstancesPlantAtSpecifiedOffsets(): + """ + Summary: Range Min/Max in the Vegetation Position Modifier component and component overrides can be set for all + axes, and functions as expected when fed a gradient signal. - def run_test(self): - """ - Summary: Range Min/Max in the Vegetation Position Modifier component and component overrides can be set for all - axes, and functions as expected when fed a gradient signal. + Expected Behavior: Instances are offset by the specified amount. - Expected Behavior: Instances are offset by the specified amount. + Test Steps: + 1) Open an existing level + 2) Spawner area is setup with all necessary components + 3) Surface for planting is created + 4) Initial instance count validation pre-filter is performed + 5) An entity with a Constant Gradient of 1 is added as a child to the spawner entity, and pinned to the Position + Modifier Gradient Entity Id fields + 6) Sector size is adjusted on a Vegetation System Settings component to allow for offset instances to not fall + outside of the queried sector + 7) Random offsets are set for each axis of the Position Modifier component, and instance counts are validated + 8) Overrides are enabled on the Position Modifier component + 9) Random offsets are set for each axis of the descriptor's Position Modifier overrides, and instance counts + are validated - Test Steps: - 1) New test level is created - 2) Spawner area is setup with all necessary components - 3) Surface for planting is created - 4) Initial instance count validation pre-filter is performed - 5) An entity with a Constant Gradient of 1 is added as a child to the spawner entity, and pinned to the Position - Modifier Gradient Entity Id fields - 6) Sector size is adjusted on a Vegetation System Settings component to allow for offset instances to not fall - outside of the queried sector - 7) Random offsets are set for each axis of the Position Modifier component, and instance counts are validated - 8) Overrides are enabled on the Position Modifier component - 9) Random offsets are set for each axis of the descriptor's Position Modifier overrides, and instance counts - are validated + 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. - 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 + """ - :return: None - """ - position_modifier_paths = ['Configuration|Position X|Range Min', 'Configuration|Position X|Range Max', - 'Configuration|Position Y|Range Min', 'Configuration|Position Y|Range Max', - 'Configuration|Position Z|Range Min', 'Configuration|Position Z|Range Max'] + import os + import random - override_position_modifier_paths = ['Configuration|Embedded Assets|[0]|Position Modifier|Min X', - 'Configuration|Embedded Assets|[0]|Position Modifier|Max X', - 'Configuration|Embedded Assets|[0]|Position Modifier|Min Y', - 'Configuration|Embedded Assets|[0]|Position Modifier|Max Y', - 'Configuration|Embedded Assets|[0]|Position Modifier|Min Z', - 'Configuration|Embedded Assets|[0]|Position Modifier|Max Z'] + import azlmbr.editor as editor + import azlmbr.legacy.general as general + import azlmbr.bus as bus + import azlmbr.math as math - def generate_random_offset_list(): - offset_list = [] - while len(offset_list) < 10: - offset = round(random.uniform(-8.0, 8.0), 2) - if not -1.0 <= offset <= 1.0: - offset_list.append(offset) - print("List of values to test against = " + str(offset_list)) - return offset_list + import editor_python_test_tools.hydra_editor_utils as hydra + from largeworlds.large_worlds_utils import editor_dynveg_test_helper as dynveg + from editor_python_test_tools.utils import Report + from editor_python_test_tools.utils import TestHelper as helper - def set_offset_and_verify_instance_counts(offset_to_test, center, is_override=False): - print(f"Starting test with an offset of {offset_to_test}") - # Set min/max values to the offset value - if not is_override: - for path in position_modifier_paths: - spawner_entity.get_set_test(3, path, offset_to_test) - else: - spawner_entity.get_set_test(2, "Configuration|Embedded Assets|[0]|Position Modifier|Override Enabled", - True) - for path in override_position_modifier_paths: - spawner_entity.get_set_test(2, path, offset_to_test) - center_point = math.Vector3(center.x + offset_to_test, center.y + offset_to_test, center.z + offset_to_test) - radius = 0.5 - print(f"Querying for instances in a {radius * 2}m area around {center_point.ToString()}") - offset_success = self.wait_for_condition(lambda: dynveg.validate_instance_count(center_point, radius, 1), 5.0) - offset_success2 = self.wait_for_condition(lambda: dynveg.validate_instance_count(center, radius, 0), 5.0) - self.test_success = offset_success and offset_success2 and self.test_success + position_modifier_paths = ['Configuration|Position X|Range Min', 'Configuration|Position X|Range Max', + 'Configuration|Position Y|Range Min', 'Configuration|Position Y|Range Max', + 'Configuration|Position Z|Range Min', 'Configuration|Position Z|Range Max'] - # 1) Create a new, temporary level - self.test_success = self.create_level( - self.args["level"], - heightmap_resolution=1024, - heightmap_meters_per_pixel=1, - terrain_texture_resolution=4096, - use_terrain=False, - ) + override_position_modifier_paths = ['Configuration|Embedded Assets|[0]|Position Modifier|Min X', + 'Configuration|Embedded Assets|[0]|Position Modifier|Max X', + 'Configuration|Embedded Assets|[0]|Position Modifier|Min Y', + 'Configuration|Embedded Assets|[0]|Position Modifier|Max Y', + 'Configuration|Embedded Assets|[0]|Position Modifier|Min Z', + 'Configuration|Embedded Assets|[0]|Position Modifier|Max Z'] - # Set view of planting area for visual debugging - general.set_current_view_position(16.0, -5.0, 32.0) + def generate_random_offset_list(): + offset_list = [] + while len(offset_list) < 10: + offset = round(random.uniform(-8.0, 8.0), 2) + if not -1.0 <= offset <= 1.0: + offset_list.append(offset) + Report.info("List of values to test against = " + str(offset_list)) + return offset_list - # 2) Create a new entity with required vegetation area components - spawner_center_point = math.Vector3(16.0, 16.0, 32.0) - asset_path = os.path.join("Slices", "PinkFlower.dynamicslice") - spawner_entity = dynveg.create_vegetation_area("Instance Spawner", spawner_center_point, 1.0, 1.0, 1.0, asset_path) + def set_offset_and_verify_instance_counts(offset_to_test, center, is_override=False): + Report.info(f"Starting test with an offset of {offset_to_test}") + # Set min/max values to the offset value + if not is_override: + for path in position_modifier_paths: + spawner_entity.get_set_test(3, path, offset_to_test) + else: + spawner_entity.get_set_test(2, "Configuration|Embedded Assets|[0]|Position Modifier|Override Enabled", + True) + for path in override_position_modifier_paths: + spawner_entity.get_set_test(2, path, offset_to_test) + center_point = math.Vector3(center.x + offset_to_test, center.y + offset_to_test, center.z + offset_to_test) + radius = 0.5 + Report.info(f"Querying for instances in a {radius * 2}m area around {center_point.ToString()}") + offset_success = helper.wait_for_condition(lambda: dynveg.validate_instance_count(center_point, radius, 1), 5.0) + offset_success2 = helper.wait_for_condition(lambda: dynveg.validate_instance_count(center, radius, 0), 5.0) + return offset_success and offset_success2 - # Add a Vegetation Position Modifier and set offset values to 0 - spawner_entity.add_component("Vegetation Position Modifier") - for path in position_modifier_paths: - spawner_entity.get_set_test(3, path, 0) + # 1) Open an existing simple level + helper.init_idle() + helper.open_level("Physics", "Base") - # 3) Add flat surface to plant on - dynveg.create_surface_entity("Planting Surface", spawner_center_point, 32.0, 32.0, 0.0) + # Set view of planting area for visual debugging + general.set_current_view_position(16.0, -5.0, 32.0) - # 4) Verify initial instance counts pre-filter - num_expected = 1 # Single instance planted - spawner_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 spawner_success + # 2) Create a new entity with required vegetation area components + spawner_center_point = math.Vector3(16.0, 16.0, 32.0) + asset_path = os.path.join("Slices", "PinkFlower.dynamicslice") + spawner_entity = dynveg.create_vegetation_area("Instance Spawner", spawner_center_point, 1.0, 1.0, 1.0, asset_path) - # 5) Create a child entity of the spawner entity with a Constant Gradient component - components_to_add = ["Constant Gradient"] - gradient_entity = hydra.Entity("Gradient Entity") - gradient_entity.create_entity(spawner_center_point, components_to_add, parent_id=spawner_entity.id) + # Add a Vegetation Position Modifier and set offset values to 0 + spawner_entity.add_component("Vegetation Position Modifier") + for path in position_modifier_paths: + spawner_entity.get_set_test(3, path, 0) - # Pin the Constant Gradient to each axis of the Position Modifier - position_modifier_gradient_paths = ['Configuration|Position X|Gradient|Gradient Entity Id', - 'Configuration|Position Y|Gradient|Gradient Entity Id', - 'Configuration|Position Z|Gradient|Gradient Entity Id'] - for path in position_modifier_gradient_paths: - spawner_entity.get_set_test(3, path, gradient_entity.id) + # 3) Add flat surface to plant on + dynveg.create_surface_entity("Planting Surface", spawner_center_point, 32.0, 32.0, 0.0) - # 6) Add a Vegetation System Settings Level component and change sector size to 32 sq meters so instances can - # offset to a greater range and still be validated - veg_system_settings_component = hydra.add_level_component("Vegetation System Settings") - editor.EditorComponentAPIBus(bus.Broadcast, "SetComponentProperty", veg_system_settings_component, - "Configuration|Area System Settings|Sector Size In Meters", 32) - sector_size = hydra.get_component_property_value(veg_system_settings_component, - "Configuration|Area System Settings|Sector Size In Meters") - self.test_success = (sector_size == 32) and self.test_success + # 4) Verify initial instance counts pre-filter + num_expected = 1 # Single instance planted + spawner_success = helper.wait_for_condition( + lambda: dynveg.validate_instance_count_in_entity_shape(spawner_entity.id, num_expected), 5.0) + Report.result(Tests.initial_instance_count, spawner_success) - # 7) Set offsets on all axes and verify instance counts - offsets_to_test = generate_random_offset_list() - for offset in offsets_to_test: - if self.test_success: - set_offset_and_verify_instance_counts(offset, spawner_center_point) + # 5) Create a child entity of the spawner entity with a Constant Gradient component + components_to_add = ["Constant Gradient"] + gradient_entity = hydra.Entity("Gradient Entity") + gradient_entity.create_entity(spawner_center_point, components_to_add, parent_id=spawner_entity.id) - # 8) Toggle on allow overrides on the Position Modifier Component - spawner_entity.get_set_test(3, "Configuration|Allow Per-Item Overrides", True) + # Pin the Constant Gradient to each axis of the Position Modifier + position_modifier_gradient_paths = ['Configuration|Position X|Gradient|Gradient Entity Id', + 'Configuration|Position Y|Gradient|Gradient Entity Id', + 'Configuration|Position Z|Gradient|Gradient Entity Id'] + for path in position_modifier_gradient_paths: + spawner_entity.get_set_test(3, path, gradient_entity.id) - # 9) Set offsets on all axes on descriptor overrides and verify instance counts - for offset in offsets_to_test: - if self.test_success: - set_offset_and_verify_instance_counts(offset, spawner_center_point, is_override=True) + # 6) Add a Vegetation System Settings Level component and change sector size to 32 sq meters so instances can + # offset to a greater range and still be validated + veg_system_settings_component = hydra.add_level_component("Vegetation System Settings") + editor.EditorComponentAPIBus(bus.Broadcast, "SetComponentProperty", veg_system_settings_component, + "Configuration|Area System Settings|Sector Size In Meters", 32) + + # 7) Set offsets on all axes and verify instance counts + offsets_to_test = generate_random_offset_list() + success = True + for offset in offsets_to_test: + success = success and set_offset_and_verify_instance_counts(offset, spawner_center_point) + Report.result(Tests.position_offset, success) + + # 8) Toggle on allow overrides on the Position Modifier Component + spawner_entity.get_set_test(3, "Configuration|Allow Per-Item Overrides", True) + + # 9) Set offsets on all axes on descriptor overrides and verify instance counts + success = True + for offset in offsets_to_test: + success = success and set_offset_and_verify_instance_counts(offset, spawner_center_point, is_override=True) + Report.result(Tests.position_offset_overrides, success) -test = TestPositionModifierComponentAndOverrides() -test.run() +if __name__ == "__main__": + + from editor_python_test_tools.utils import Report + Report.start_test(PositionModifier_ComponentAndOverrides_InstancesPlantAtSpecifiedOffsets) diff --git a/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/RotationModifierOverrides_InstancesRotateWithinRange.py b/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/RotationModifierOverrides_InstancesRotateWithinRange.py index b428459032..4d8019bb33 100755 --- a/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/RotationModifierOverrides_InstancesRotateWithinRange.py +++ b/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/RotationModifierOverrides_InstancesRotateWithinRange.py @@ -5,139 +5,138 @@ For complete copyright and license terms please see the LICENSE at the root of t SPDX-License-Identifier: Apache-2.0 OR MIT """ -""" -C4814460: A level with simple vegetation is created. A child entity with required components is then created, -and pinned to the gradient entity id in Z direction for vegetation entity. The changes in vegetation area are observed. -""" -import os -import sys - -sys.path.append(os.path.dirname(os.path.abspath(__file__))) -import azlmbr.legacy.general as general -import azlmbr.math as math -import azlmbr.bus as bus -import azlmbr.areasystem as areasystem - -sys.path.append(os.path.join(azlmbr.paths.devroot, 'AutomatedTesting', 'Gem', 'PythonTests')) -import editor_python_test_tools.hydra_editor_utils as hydra -from editor_python_test_tools.editor_test_helper import EditorTestHelper -from largeworlds.large_worlds_utils import editor_dynveg_test_helper as dynveg +class Tests: + gradient_entity_created = ( + "Successfully created new Gradient entity", + "Failed to create Gradient entity" + ) + non_override_rotation_check = ( + "Instances are rotated at expected values after initial setup", + "Found unexpectedly rotated instances after initial setup" + ) + override_rotation_check = ( + "Instances are rotated at expected values after configuring overrides", + "Found unexpectedly rotated instances after configuring overrides" + ) -class TestRotationModifierOverrides_InstancesRotateWithinRange(EditorTestHelper): - def __init__(self): - EditorTestHelper.__init__(self, log_prefix="RotationModifierOverrides_InstancesRotateWithinRange", args=["level"]) +def RotationModifierOverrides_InstancesRotateWithinRange(): + """ + Summary: + A level with simple vegetation is created. A child entity with required components is then created, + and pinned to the gradient entity id in Z direction for vegetation entity. The changes in vegetation + area are observed. - def run_test(self): - """ - Summary: - A level with simple vegetation is created. A child entity with required components is then created, - and pinned to the gradient entity id in Z direction for vegetation entity. The changes in vegetation - area are observed. + Expected Behavior: + Vegetation instances all rotate randomly between 0-360 degrees on the Z-axis. - Expected Behavior: - Vegetation instances all rotate randomly between 0-360 degrees on the Z-axis. + Test Steps: + 1) Open a new level + 2) Create vegetation entity and add components + 3) Set properties for vegetation entity + 4) Create new child entity + 5) Pin the child entity to vegetation entity as gradient entity id + 6) Verify rotation without per-item overrides + 7) Verify rotation with per-item overrides - Test Steps: - 1) Create level - 2) Create vegetation entity and add components - 3) Set properties for vegetation entity - 4) Create new child entity - 5) Pin the child entity to vegetation entity as gradient entity id - 6) Verify rotation without per-item overrides - 7) Verify rotation with per-item overrides + Note: + - 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. - Note: - - 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 + """ - :return: None - """ + import os - def get_expected_rotation(min, max, gradient_value): - return min + ((max - min) * gradient_value) + import azlmbr.legacy.general as general + import azlmbr.math as math + import azlmbr.bus as bus + import azlmbr.areasystem as areasystem - def validate_rotation(center, radius, num_expected, rot_degrees_vector): - # Verify that every instance in the given area has the expected rotation. - box = math.Aabb_CreateCenterRadius(center, radius) - instances = areasystem.AreaSystemRequestBus(bus.Broadcast, 'GetInstancesInAabb', box) - num_found = len(instances) - num_validated = 0 - result = (num_found == num_expected) - print(f'instance count validation: {result} (found={num_found}, expected={num_expected})') - expected_rotation = math.Quaternion() - expected_rotation.SetFromEulerDegrees(rot_degrees_vector) - for instance in instances: - is_close = instance.rotation.IsClose(expected_rotation) - result = result and is_close - if is_close: - num_validated = num_validated + 1 - #else: - # print(f'instance rotation validation: {is_close} (rotation={instance.rotation} expected={expected_rotation})') - print(f'instance rotation validation: {result} (num_validated={num_validated})') - return result + import editor_python_test_tools.hydra_editor_utils as hydra + from largeworlds.large_worlds_utils import editor_dynveg_test_helper as dynveg + from editor_python_test_tools.utils import Report + from editor_python_test_tools.utils import TestHelper as helper - # 1) Create level - self.test_success = self.create_level( - self.args["level"], - heightmap_resolution=1024, - heightmap_meters_per_pixel=1, - terrain_texture_resolution=4096, - use_terrain=False, - ) - general.set_current_view_position(512.0, 480.0, 38.0) + def get_expected_rotation(min, max, gradient_value): + return min + ((max - min) * gradient_value) - # 2) Create vegetation entity and add components - entity_position = math.Vector3(512.0, 512.0, 32.0) - asset_path = os.path.join("Slices", "PurpleFlower.dynamicslice") - spawner_entity = dynveg.create_vegetation_area("Spawner Entity", entity_position, 16.0, 16.0, 16.0, asset_path) - spawner_entity.add_component("Vegetation Rotation Modifier") - # Our default vegetation settings places 20 instances per 16 meters, so we expect 20 * 20 total instances. - num_expected = 20 * 20 - # This is technically twice as big as we need, but we want to make sure our query radius is large enough to discover every - # instance we've created. - area_radius = 16.0 + def validate_rotation(center, radius, num_expected, rot_degrees_vector): + # Verify that every instance in the given area has the expected rotation. + box = math.Aabb_CreateCenterRadius(center, radius) + instances = areasystem.AreaSystemRequestBus(bus.Broadcast, 'GetInstancesInAabb', box) + num_found = len(instances) + num_validated = 0 + result = (num_found == num_expected) + Report.info(f'instance count validation: {result} (found={num_found}, expected={num_expected})') + expected_rotation = math.Quaternion() + expected_rotation.SetFromEulerDegrees(rot_degrees_vector) + for instance in instances: + is_close = instance.rotation.IsClose(expected_rotation) + result = result and is_close + if is_close: + num_validated = num_validated + 1 + Report.info(f'instance rotation validation: {result} (num_validated={num_validated})') + return result - # Create surface to spawn on - dynveg.create_surface_entity("Surface Entity", entity_position, 16.0, 16.0, 1.0) + # 1) Open an existing simple level + helper.init_idle() + helper.open_level("Physics", "Base") + general.set_current_view_position(512.0, 480.0, 38.0) - # 3) Set properties for the rotation override on the descriptor, but don't set "allow overrides" on the rotation modifier yet. - spawner_entity.get_set_test(2, "Configuration|Embedded Assets|[0]|Rotation Modifier|Override Enabled", True) - spawner_entity.get_set_test(2, "Configuration|Embedded Assets|[0]|Rotation Modifier|Min Z", -70.0) - spawner_entity.get_set_test(2, "Configuration|Embedded Assets|[0]|Rotation Modifier|Max Z", 30.0) + # 2) Create vegetation entity and add components + entity_position = math.Vector3(512.0, 512.0, 32.0) + asset_path = os.path.join("Slices", "PurpleFlower.dynamicslice") + spawner_entity = dynveg.create_vegetation_area("Spawner Entity", entity_position, 16.0, 16.0, 16.0, asset_path) + spawner_entity.add_component("Vegetation Rotation Modifier") + # Our default vegetation settings places 20 instances per 16 meters, so we expect 20 * 20 total instances. + num_expected = 20 * 20 + # This is technically twice as big as we need, but we want to make sure our query radius is large enough to discover + # every instance we've created. + area_radius = 16.0 - # 4) Create new child entity with a constant gradient - constant_gradient_value = 0.25 - gradient_entity = hydra.Entity("Gradient Entity") - gradient_entity.create_entity( - entity_position, - ["Constant Gradient"], - parent_id=spawner_entity.id - ) - if gradient_entity.id.IsValid(): - self.log(f"'{gradient_entity.name}' created") - gradient_entity.get_set_test(0, "Configuration|Value", constant_gradient_value) + # Create surface to spawn on + dynveg.create_surface_entity("Surface Entity", entity_position, 16.0, 16.0, 1.0) - # 5) Pin the child entity to vegetation entity as gradient entity id - spawner_entity.get_set_test(3, "Configuration|Rotation Z|Gradient|Gradient Entity Id", gradient_entity.id) + # 3) Set properties for the rotation override on the descriptor, but don't set "allow overrides" on the rotation + # modifier yet + spawner_entity.get_set_test(2, "Configuration|Embedded Assets|[0]|Rotation Modifier|Override Enabled", True) + spawner_entity.get_set_test(2, "Configuration|Embedded Assets|[0]|Rotation Modifier|Min Z", -70.0) + spawner_entity.get_set_test(2, "Configuration|Embedded Assets|[0]|Rotation Modifier|Max Z", 30.0) - # 6) Verify that without per-item overrides, the rotation matches the one calculated from the default rotation range. - general.idle_wait(1.0) - rotation_degrees = get_expected_rotation(-180.0, 180.0, constant_gradient_value) - rotation_success = self.wait_for_condition( - lambda: validate_rotation(entity_position, area_radius, num_expected, math.Vector3(0.0, 0.0, rotation_degrees)), - 5.0) - self.test_success = self.test_success and rotation_success + # 4) Create new child entity with a constant gradient + constant_gradient_value = 0.25 + gradient_entity = hydra.Entity("Gradient Entity") + gradient_entity.create_entity( + entity_position, + ["Constant Gradient"], + parent_id=spawner_entity.id + ) + Report.critical_result(Tests.gradient_entity_created, gradient_entity.id.IsValid()) + gradient_entity.get_set_test(0, "Configuration|Value", constant_gradient_value) - # 7) Verify that with per-item overrides enabled, the rotation matches the one calculated from the override range. - spawner_entity.get_set_test(3, "Configuration|Allow Per-Item Overrides", True) - rotation_degrees = get_expected_rotation(-70.0, 30.0, constant_gradient_value) - rotation_success = self.wait_for_condition( - lambda: validate_rotation(entity_position, area_radius, num_expected, math.Vector3(0.0, 0.0, rotation_degrees)), - 5.0) - self.test_success = self.test_success and rotation_success + # 5) Pin the child entity to vegetation entity as gradient entity id + spawner_entity.get_set_test(3, "Configuration|Rotation Z|Gradient|Gradient Entity Id", gradient_entity.id) + + # 6) Verify that without per-item overrides, the rotation matches the one calculated from the default rotation range + general.idle_wait(1.0) + rotation_degrees = get_expected_rotation(-180.0, 180.0, constant_gradient_value) + rotation_success = helper.wait_for_condition( + lambda: validate_rotation(entity_position, area_radius, num_expected, math.Vector3(0.0, 0.0, rotation_degrees)), + 5.0) + Report.result(Tests.non_override_rotation_check, rotation_success) + + # 7) Verify that with per-item overrides enabled, the rotation matches the one calculated from the override range. + spawner_entity.get_set_test(3, "Configuration|Allow Per-Item Overrides", True) + rotation_degrees = get_expected_rotation(-70.0, 30.0, constant_gradient_value) + rotation_success = helper.wait_for_condition( + lambda: validate_rotation(entity_position, area_radius, num_expected, math.Vector3(0.0, 0.0, rotation_degrees)), + 5.0) + Report.result(Tests.override_rotation_check, rotation_success) -test = TestRotationModifierOverrides_InstancesRotateWithinRange() -test.run() +if __name__ == "__main__": + + from editor_python_test_tools.utils import Report + Report.start_test(RotationModifierOverrides_InstancesRotateWithinRange) diff --git a/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/RotationModifier_InstancesRotateWithinRange.py b/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/RotationModifier_InstancesRotateWithinRange.py index 6b6f66467b..c261415958 100755 --- a/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/RotationModifier_InstancesRotateWithinRange.py +++ b/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/RotationModifier_InstancesRotateWithinRange.py @@ -5,207 +5,226 @@ For complete copyright and license terms please see the LICENSE at the root of t SPDX-License-Identifier: Apache-2.0 OR MIT """ -import os -import sys -sys.path.append(os.path.dirname(os.path.abspath(__file__))) -import azlmbr.math as math -import azlmbr.legacy.general as general -import azlmbr.bus as bus -import azlmbr.areasystem as areasystem - -sys.path.append(os.path.join(azlmbr.paths.devroot, 'AutomatedTesting', 'Gem', 'PythonTests')) -import editor_python_test_tools.hydra_editor_utils as hydra -from editor_python_test_tools.editor_test_helper import EditorTestHelper -from largeworlds.large_worlds_utils import editor_dynveg_test_helper as dynveg +class Tests: + gradient_entity_created = ( + "Successfully created new Gradient entity", + "Failed to create Gradient entity" + ) + rotation_baseline = ( + "Instances are not rotated after initial setup", + "Unexpectedly found rotated instances after initial setup" + ) + x_axis_rotation_180 = ( + "Instances rotated 180 degrees on X-axis as expected", + "Found unexpected instance rotation on X-axis" + ) + x_axis_rotation_90 = ( + "Instances rotated 90 degrees on X-axis as expected", + "Found unexpected instance rotation on X-axis" + ) + y_axis_rotation_180 = ( + "Instances rotated 180 degrees on Y-axis as expected", + "Found unexpected instance rotation on Y-axis" + ) + y_axis_rotation_90 = ( + "Instances rotated 90 degrees on Y-axis as expected", + "Found unexpected instance rotation on Y-axis" + ) + z_axis_rotation_180 = ( + "Instances rotated 180 degrees on Z-axis as expected", + "Found unexpected instance rotation on Z-axis" + ) + z_axis_rotation_90 = ( + "Instances rotated 90 degrees on Z-axis as expected", + "Found unexpected instance rotation on Z-axis" + ) -class TestRotationModifier_InstancesRotateWithinRange(EditorTestHelper): - def __init__(self): - EditorTestHelper.__init__(self, log_prefix="RotationModifier_InstancesRotateWithinRange", args=["level"]) +def RotationModifier_InstancesRotateWithinRange(): + """ + Summary: Range Min/Max in the Vegetation Rotation Modifier component can be set for all axes, + and functions as expected when fed a gradient signal - def run_test(self): - """ - Summary: Range Min/Max in the Vegetation Rotation Modifier component can be set for all axes, - and functions as expected when fed a gradient signal - - Vegetation Entity: Set in the middle of the level it holds a child entity and the following components: - Vegetation Asset List - Box Shape (size: <10, 10, 10>) - Vegetation Layer Spawner - Vegetation Rotation Modifier - Rotation X (gradient: child, Range Min: Variable, Range Max: Variable) - Rotation Y (gradient: child, Range Min: Variable, Range Max: Variable) - Rotation Z (gradient: child, Range Min: Variable, Range Max: Variable) + Vegetation Entity: Set in the middle of the level it holds a child entity and the following components: + Vegetation Asset List + Box Shape (size: <10, 10, 10>) + Vegetation Layer Spawner + Vegetation Rotation Modifier + Rotation X (gradient: child, Range Min: Variable, Range Max: Variable) + Rotation Y (gradient: child, Range Min: Variable, Range Max: Variable) + Rotation Z (gradient: child, Range Min: Variable, Range Max: Variable) - Child Entity: Child to Vegetation Entity has the following components: - Box Shape (size: <10, 10, 10>) - Gradient Transform Modifier - Constant Gradient + Child Entity: Child to Vegetation Entity has the following components: + Box Shape (size: <10, 10, 10>) + Gradient Transform Modifier + Constant Gradient - Expected Behavior: The vegetation area adjusts rotation based on the Constant Gradient component - and the min and max values for each component. Min max of each axis is checked + Expected Behavior: The vegetation area adjusts rotation based on the Constant Gradient component + and the min and max values for each component. Min max of each axis is checked - Test Steps: - 1) Create level - 2) Set up vegetation entities - 3) X-axis Check - 4) Y-axis Check - 5) Z-axis Check + Test Steps: + 1) Open a new level + 2) Set up vegetation entities + 3) X-axis Check + 4) Y-axis Check + 5) Z-axis Check - Note: - - 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. + Note: + - 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 - """ + :return: None + """ - # Test Constants - LEVEL_CENTER = math.Vector3(512.0, 512.0, 32.0) - constant_gradient_value = 0.15 + import os - # Helper Functions - def change_range_max(axis, value): - spawner_entity.get_set_test(3, f"Configuration|Rotation {axis}|Range Max", value) + import azlmbr.math as math + import azlmbr.legacy.general as general + import azlmbr.bus as bus + import azlmbr.areasystem as areasystem - def change_range_min(axis, value): - spawner_entity.get_set_test(3, f"Configuration|Rotation {axis}|Range Min", value) + import editor_python_test_tools.hydra_editor_utils as hydra + from largeworlds.large_worlds_utils import editor_dynveg_test_helper as dynveg + from editor_python_test_tools.utils import Report + from editor_python_test_tools.utils import TestHelper as helper - def get_expected_rotation(min, max, gradient_value): - return min + ((max - min) * gradient_value) + # Test Constants + LEVEL_CENTER = math.Vector3(512.0, 512.0, 32.0) + constant_gradient_value = 0.15 - def validate_rotation(center, radius, num_expected, rot_degrees_vector): - # Verify that every instance in the given area has the expected rotation. - box = math.Aabb_CreateCenterRadius(center, radius) - instances = areasystem.AreaSystemRequestBus(bus.Broadcast, 'GetInstancesInAabb', box) - num_found = len(instances) - result = (num_found == num_expected) - print(f'instance count validation: {result} (found={num_found}, expected={num_expected})') - expected_rotation = math.Quaternion() - expected_rotation.SetFromEulerDegrees(rot_degrees_vector) - for instance in instances: - result = result and instance.rotation.IsClose(expected_rotation) - print(f'instance rotation validation: {result} (rotation={instance.rotation} expected={expected_rotation})') - return result + # Helper Functions + def change_range_max(axis, value): + spawner_entity.get_set_test(3, f"Configuration|Rotation {axis}|Range Max", value) + def change_range_min(axis, value): + spawner_entity.get_set_test(3, f"Configuration|Rotation {axis}|Range Min", value) - # Main Script - # 1) Create Level - self.test_success = self.create_level( - self.args["level"], - heightmap_resolution=1024, - heightmap_meters_per_pixel=1, - terrain_texture_resolution=4096, - use_terrain=False, + def get_expected_rotation(min, max, gradient_value): + return min + ((max - min) * gradient_value) + + def validate_rotation(center, radius, num_expected, rot_degrees_vector): + # Verify that every instance in the given area has the expected rotation. + box = math.Aabb_CreateCenterRadius(center, radius) + instances = areasystem.AreaSystemRequestBus(bus.Broadcast, 'GetInstancesInAabb', box) + num_found = len(instances) + result = (num_found == num_expected) + Report.info(f'instance count validation: {result} (found={num_found}, expected={num_expected})') + expected_rotation = math.Quaternion() + expected_rotation.SetFromEulerDegrees(rot_degrees_vector) + for instance in instances: + result = result and instance.rotation.IsClose(expected_rotation) + Report.info(f'instance rotation validation: {result} (rotation={instance.rotation} expected={expected_rotation})') + return result + + # Main Script + # 1) Open an existing simple level + helper.init_idle() + helper.open_level("Physics", "Base") + general.set_current_view_position(512.0, 480.0, 38.0) + + # 2) Set up vegetation entities + asset_path = os.path.join("Slices", "PurpleFlower.dynamicslice") + spawner_entity = dynveg.create_vegetation_area("Spawner Entity", LEVEL_CENTER, 2.0, 2.0, 2.0, asset_path) + + additional_components = [ + "Vegetation Rotation Modifier" + ] + for component in additional_components: + spawner_entity.add_component(component) + + # Create surface to spawn vegetation on + dynveg.create_surface_entity("Surface Entity", LEVEL_CENTER, 10.0, 10.0, 1.0) + + # Create Gradient Entity + gradient_entity = hydra.Entity("Gradient Entity") + gradient_entity.create_entity( + LEVEL_CENTER, + ["Constant Gradient"], + parent_id=spawner_entity.id + ) + Report.critical_result(Tests.gradient_entity_created, gradient_entity.id.IsValid()) + gradient_entity.get_set_test(0, "Configuration|Value", constant_gradient_value) + + # Vegetation Rotation Modifier + for axis in ["X", "Y", "Z"]: + spawner_entity.get_set_test( + 3, f"Configuration|Rotation {axis}|Gradient|Gradient Entity Id", gradient_entity.id ) - general.set_current_view_position(512.0, 480.0, 38.0) - # 2) Set up vegetation entities - asset_path = os.path.join("Slices", "PurpleFlower.dynamicslice") - spawner_entity = dynveg.create_vegetation_area("Spawner Entity", LEVEL_CENTER, 2.0, 2.0, 2.0, asset_path) + # Set up constants used across all the rotation checks - additional_components = [ - "Vegetation Rotation Modifier" - ] - for component in additional_components: - spawner_entity.add_component(component) + # Choose an area large enough to contain all of the instances we spawned. + area_center = LEVEL_CENTER + area_radius = 20.0 + # We're spawning a 2x2 area, which will have 3 rows of 3 instances due to default vegetation system spacing, so + # we should have a total of 9 instances. + num_expected = 9 - # Create surface to spawn vegetation on - dynveg.create_surface_entity("Surface Entity", LEVEL_CENTER, 10.0, 10.0, 1.0) + # 3) X-axis check + # baseline, verify that we initially have no rotation + change_range_min("Z", 0.0) + change_range_max("Z", 0.0) + rotation_success = helper.wait_for_condition( + lambda: validate_rotation(area_center, area_radius, num_expected, math.Vector3(0.0, 0.0, 0.0)), 5.0) + Report.result(Tests.rotation_baseline, rotation_success) - # Create Gradient Entity - gradient_entity = hydra.Entity("Gradient Entity") - gradient_entity.create_entity( - LEVEL_CENTER, - ["Constant Gradient"], - parent_id=spawner_entity.id - ) - if gradient_entity.id.IsValid(): - self.log(f"'{gradient_entity.name}' created") - gradient_entity.get_set_test(0, "Configuration|Value", constant_gradient_value) + # Adjust x-axis range min / max to (-180, 0). + # Because we have a constant gradient of 0.25, our actual rotation should be (min + (max - min) * gradient), + # or (-180 + (0 - -180) * 0.25) + change_range_min("X", -180.0) + rotation_degrees = get_expected_rotation(-180.0, 0.0, constant_gradient_value) + rotation_success = helper.wait_for_condition( + lambda: validate_rotation(area_center, area_radius, num_expected, math.Vector3(rotation_degrees, 0.0, 0.0)), + 5.0) + Report.result(Tests.x_axis_rotation_180, rotation_success) - # Vegetation Rotation Modifier - for axis in ["X", "Y", "Z"]: - spawner_entity.get_set_test( - 3, f"Configuration|Rotation {axis}|Gradient|Gradient Entity Id", gradient_entity.id - ) + # Set the min / max to (0, 90), with an expected result of (0 + (90 - 0) * 0.25) + change_range_min("X", 0.0) + change_range_max("X", 90.0) + rotation_degrees = get_expected_rotation(0.0, 90.0, constant_gradient_value) + rotation_success = helper.wait_for_condition( + lambda: validate_rotation(area_center, area_radius, num_expected, math.Vector3(rotation_degrees, 0.0, 0.0)), + 5.0) + Report.result(Tests.x_axis_rotation_90, rotation_success) + change_range_max("X", 0.0) - # Set up constants used across all the rotation checks + # 4) Y-axis check + change_range_min("Y", -180.0) + rotation_degrees = get_expected_rotation(-180.0, 0.0, constant_gradient_value) + rotation_success = helper.wait_for_condition( + lambda: validate_rotation(area_center, area_radius, num_expected, math.Vector3(0.0, rotation_degrees, 0.0)), + 5.0) + Report.result(Tests.y_axis_rotation_180, rotation_success) - # Choose an area large enough to contain all of the instances we spawned. - area_center = LEVEL_CENTER - area_radius = 20.0 - # We're spawning a 2x2 area, which will have 3 rows of 3 instances due to default vegetation system spacing, so - # we should have a total of 9 instances. - num_expected = 9 - - # 3) X-axis check - general.idle_wait(3.0) # Allow mesh to load + change_range_min("Y", 0.0) + change_range_max("Y", 90.0) + rotation_degrees = get_expected_rotation(0.0, 90.0, constant_gradient_value) + rotation_success = helper.wait_for_condition( + lambda: validate_rotation(area_center, area_radius, num_expected, math.Vector3(0.0, rotation_degrees, 0.0)), + 5.0) + Report.result(Tests.y_axis_rotation_90, rotation_success) + change_range_max("Y", 0.0) - # baseline, verify that we initially have no rotation - change_range_min("Z", 0.0) - change_range_max("Z", 0.0) - rotation_success = self.wait_for_condition( - lambda: validate_rotation(area_center, area_radius, num_expected, math.Vector3(0.0, 0.0, 0.0)), - 5.0) - self.test_success = self.test_success and rotation_success + # 5) Z-axis check + change_range_min("Z", -180.0) + rotation_degrees = get_expected_rotation(-180.0, 0.0, constant_gradient_value) + rotation_success = helper.wait_for_condition( + lambda: validate_rotation(area_center, area_radius, num_expected, math.Vector3(0.0, 0.0, rotation_degrees)), + 5.0) + Report.result(Tests.z_axis_rotation_180, rotation_success) - # Adjust x-axis range min / max to (-180, 0). - # Because we have a constant gradient of 0.25, our actual rotation should be (min + (max - min) * gradient), - # or (-180 + (0 - -180) * 0.25) - change_range_min("X", -180.0) - rotation_degrees = get_expected_rotation(-180.0, 0.0, constant_gradient_value) - rotation_success = self.wait_for_condition( - lambda: validate_rotation(area_center, area_radius, num_expected, math.Vector3(rotation_degrees, 0.0, 0.0)), - 5.0) - self.test_success = self.test_success and rotation_success - - # Set the min / max to (0, 90), with an expected result of (0 + (90 - 0) * 0.25) - change_range_min("X", 0.0) - change_range_max("X", 90.0) - rotation_degrees = get_expected_rotation(0.0, 90.0, constant_gradient_value) - rotation_success = self.wait_for_condition( - lambda: validate_rotation(area_center, area_radius, num_expected, math.Vector3(rotation_degrees, 0.0, 0.0)), - 5.0) - self.test_success = self.test_success and rotation_success - - change_range_max("X", 0.0) - - # 4) Y-axis check - change_range_min("Y", -180.0) - rotation_degrees = get_expected_rotation(-180.0, 0.0, constant_gradient_value) - rotation_success = self.wait_for_condition( - lambda: validate_rotation(area_center, area_radius, num_expected, math.Vector3(0.0, rotation_degrees, 0.0)), - 5.0) - self.test_success = self.test_success and rotation_success - - change_range_min("Y", 0.0) - change_range_max("Y", 90.0) - rotation_degrees = get_expected_rotation(0.0, 90.0, constant_gradient_value) - rotation_success = self.wait_for_condition( - lambda: validate_rotation(area_center, area_radius, num_expected, math.Vector3(0.0, rotation_degrees, 0.0)), - 5.0) - self.test_success = self.test_success and rotation_success - - change_range_max("Y", 0.0) - - # 5) Z-axis check - change_range_min("Z", -180.0) - rotation_degrees = get_expected_rotation(-180.0, 0.0, constant_gradient_value) - rotation_success = self.wait_for_condition( - lambda: validate_rotation(area_center, area_radius, num_expected, math.Vector3(0.0, 0.0, rotation_degrees)), - 5.0) - self.test_success = self.test_success and rotation_success - - change_range_min("Z", 0.0) - change_range_max("Z", 90.0) - rotation_degrees = get_expected_rotation(0.0, 90.0, constant_gradient_value) - rotation_success = self.wait_for_condition( - lambda: validate_rotation(area_center, area_radius, num_expected, math.Vector3(0.0, 0.0, rotation_degrees)), - 5.0) - self.test_success = self.test_success and rotation_success + change_range_min("Z", 0.0) + change_range_max("Z", 90.0) + rotation_degrees = get_expected_rotation(0.0, 90.0, constant_gradient_value) + rotation_success = helper.wait_for_condition( + lambda: validate_rotation(area_center, area_radius, num_expected, math.Vector3(0.0, 0.0, rotation_degrees)), + 5.0) + Report.result(Tests.z_axis_rotation_90, rotation_success) -test = TestRotationModifier_InstancesRotateWithinRange() -test.run() +if __name__ == "__main__": + + from editor_python_test_tools.utils import Report + Report.start_test(RotationModifier_InstancesRotateWithinRange) diff --git a/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/ScaleModifierOverrides_InstancesProperlyScale.py b/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/ScaleModifierOverrides_InstancesProperlyScale.py index d065c821bf..9f2359ebe2 100755 --- a/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/ScaleModifierOverrides_InstancesProperlyScale.py +++ b/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/ScaleModifierOverrides_InstancesProperlyScale.py @@ -5,153 +5,155 @@ For complete copyright and license terms please see the LICENSE at the root of t SPDX-License-Identifier: Apache-2.0 OR MIT """ -import os -import sys -sys.path.append(os.path.dirname(os.path.abspath(__file__))) -import azlmbr.areasystem as areasystem -import azlmbr.bus as bus -import azlmbr.legacy.general as general -import azlmbr.math as math - -sys.path.append(os.path.join(azlmbr.paths.devroot, 'AutomatedTesting', 'Gem', 'PythonTests')) -import editor_python_test_tools.hydra_editor_utils as hydra -from editor_python_test_tools.editor_test_helper import EditorTestHelper -from largeworlds.large_worlds_utils import editor_dynveg_test_helper as dynveg - -# Constants -CLOSE_ENOUGH_THRESHOLD = 0.01 +class Tests: + gradient_entity_created = ( + "Successfully created Gradient entity", + "Failed to create Gradient entity" + ) + scale_values_set = ( + "Scale Min and Scale Max are set to 0.1 and 1.0 in Vegetation Asset List", + "Scale Min and Scale Max are not set to 0.1 and 1.0 in Vegetation Asset List" + ) + instance_count = ( + "Found the expected number of instances", + "Found an unexpected number of instances" + ) + instances_properly_scaled = ( + "All instances scaled within appropriate range", + "Found instances scaled outside of the appropriate range" + ) -class TestScaleModifierOverrides_InstancesProperlyScale(EditorTestHelper): - def __init__(self): - EditorTestHelper.__init__(self, log_prefix="ScaleModifierOverrides_InstancesProperlyScale", args=["level"]) +def ScaleModifierOverrides_InstancesProperlyScale(): + """ + Summary: + A level is created, then as simple vegetation area is created. Vegetation Scale Modifier component is + added to the vegetation area. A new child entity is created with Random Noise Gradient Generator, + Gradient Transform Modifier, and Box Shape. Child entity is set as gradient entity id in Vegetation + Scale Modifier, and scale of instances is validated to fall within expected range. - def run_test(self): - """ - Summary: - A level is created, then as simple vegetation area is created. Vegetation Scale Modifier component is - added to the vegetation area. A new child entity is created with Random Noise Gradient Generator, - Gradient Transform Modifier, and Box Shape. Child entity is set as gradient entity id in Vegetation - Scale Modifier, and scale of instances is validated to fall within expected range. + Expected Behavior: + Vegetation instances have random scale between Range Min and Range Max applied. - Expected Behavior: - Vegetation instances have random scale between Range Min and Range Max applied. + Test Steps: + 1) Open an existing level + 2) Create a new entity with components "Vegetation Layer Spawner", "Vegetation Asset List", "Box Shape" + 3) Set a valid mesh asset on the Vegetation Asset List + 4) Add Vegetation Scale Modifier component to the vegetation and set the values + 5) Toggle on Scale Modifier Override and verify Scale Min and Scale Max are set 0.1 and 1.0 + 6) Create a new child entity and add components + 7) Add child entity as gradient entity id in Vegetation Scale Modifier + 8) Validate scale of instances with a few different min/max override values - Test Steps: - 1) Create level - 2) Create a new entity with components "Vegetation Layer Spawner", "Vegetation Asset List", "Box Shape" - 3) Set a valid mesh asset on the Vegetation Asset List - 4) Add Vegetation Scale Modifier component to the vegetation and set the values - 5) Toggle on Scale Modifier Override and verify Scale Min and Scale Max are set 0.1 and 1.0 - 6) Create a new child entity and add components - 7) Add child entity as gradient entity id in Vegetation Scale Modifier - 8) Validate scale of instances with a few different min/max override values + Note: + - 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. - Note: - - 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 + """ - :return: None - """ + import os - def set_and_validate_scale(entity, min_scale, max_scale): - # Set Range Min/Max - entity.get_set_test(2, "Configuration|Embedded Assets|[0]|Scale Modifier|Min", min_scale) - entity.get_set_test(2, "Configuration|Embedded Assets|[0]|Scale Modifier|Max", max_scale) + import azlmbr.areasystem as areasystem + import azlmbr.bus as bus + import azlmbr.legacy.general as general + import azlmbr.math as math - # Clear all areas to force a refresh - general.run_console('veg_debugClearAllAreas') + import editor_python_test_tools.hydra_editor_utils as hydra + from largeworlds.large_worlds_utils import editor_dynveg_test_helper as dynveg + from editor_python_test_tools.utils import Report + from editor_python_test_tools.utils import TestHelper as helper - # Wait for instances to spawn - num_expected = 20 * 20 - self.test_success = self.test_success and self.wait_for_condition( - lambda: dynveg.validate_instance_count_in_entity_shape(spawner_entity.id, num_expected), 5.0) + # Constants + CLOSE_ENOUGH_THRESHOLD = 0.01 - # Validate scale values of instances - box = azlmbr.shape.ShapeComponentRequestsBus(bus.Event, 'GetEncompassingAabb', entity.id) - instances = areasystem.AreaSystemRequestBus(bus.Broadcast, 'GetInstancesInAabb', box) - if len(instances) == num_expected: - for instance in instances: - if min_scale <= instance.scale <= max_scale: - self.log("All instances scaled within appropriate range") - return True - self.log(f"Instance at {instance.position} scale is {instance.scale}. Expected between " - f"{min_scale}/{max_scale}") - return False - self.log(f"Failed to find all instances! Found {len(instances)}, expected {num_expected}.") - return False + def set_and_validate_scale(entity, min_scale, max_scale): + # Set Range Min/Max + entity.get_set_test(2, "Configuration|Embedded Assets|[0]|Scale Modifier|Min", min_scale) + entity.get_set_test(2, "Configuration|Embedded Assets|[0]|Scale Modifier|Max", max_scale) - # 1) Create level and set an appropriate view of spawner area - self.test_success = self.create_level( - self.args["level"], - heightmap_resolution=1024, - heightmap_meters_per_pixel=1, - terrain_texture_resolution=4096, - use_terrain=False, + # Refresh the planted instances + general.run_console("veg_DebugClearAllAreas") + + # Check the initial instance count + num_expected = 20 * 20 + success = helper.wait_for_condition( + lambda: dynveg.validate_instance_count_in_entity_shape(spawner_entity.id, num_expected), 5.0) + Report.critical_result(Tests.instance_count, success) + + # Validate scale values of instances + box = azlmbr.shape.ShapeComponentRequestsBus(bus.Event, 'GetEncompassingAabb', entity.id) + instances = areasystem.AreaSystemRequestBus(bus.Broadcast, 'GetInstancesInAabb', box) + for instance in instances: + if min_scale <= instance.scale <= max_scale: + return True + return False + + # 1) Open an existing simple level + helper.init_idle() + helper.open_level("Physics", "Base") + + general.set_current_view_position(500.49, 498.69, 46.66) + general.set_current_view_rotation(-42.05, 0.00, -36.33) + + # 2) Create a new entity with components "Vegetation Layer Spawner", "Vegetation Asset List", "Box Shape" + entity_position = math.Vector3(512.0, 512.0, 32.0) + asset_path = os.path.join("Slices", "PurpleFlower.dynamicslice") + spawner_entity = dynveg.create_vegetation_area("Spawner Entity", entity_position, 16.0, 16.0, 10.0, asset_path) + + # Create a surface to plant on and add a Vegetation Debugger Level component to allow refreshes + dynveg.create_surface_entity("Surface Entity", entity_position, 20.0, 20.0, 1.0) + hydra.add_level_component("Vegetation Debugger") + + # 4) Add Vegetation Scale Modifier component to the vegetation and set the values + spawner_entity.add_component("Vegetation Scale Modifier") + spawner_entity.get_set_test(3, "Configuration|Allow Per-Item Overrides", True) + + # 5) Toggle on Scale Modifier Override and verify Scale Min and Scale Max are set 0.1 and 1.0 + spawner_entity.get_set_test(2, "Configuration|Embedded Assets|[0]|Scale Modifier|Override Enabled", True) + scale_min = float( + format( + ( + hydra.get_component_property_value( + spawner_entity.components[2], "Configuration|Embedded Assets|[0]|Scale Modifier|Min" + ) + ), + ".1f", ) - - general.set_current_view_position(500.49, 498.69, 46.66) - general.set_current_view_rotation(-42.05, 0.00, -36.33) - - # 2) Create a new entity with components "Vegetation Layer Spawner", "Vegetation Asset List", "Box Shape" - entity_position = math.Vector3(512.0, 512.0, 32.0) - asset_path = os.path.join("Slices", "PurpleFlower.dynamicslice") - spawner_entity = dynveg.create_vegetation_area("Spawner Entity", entity_position, 16.0, 16.0, 10.0, asset_path) - - # Create a surface to plant on and add a Vegetation Debugger Level component to allow refreshes - dynveg.create_surface_entity("Surface Entity", entity_position, 20.0, 20.0, 1.0) - hydra.add_level_component("Vegetation Debugger") - - # 4) Add Vegetation Scale Modifier component to the vegetation and set the values - spawner_entity.add_component("Vegetation Scale Modifier") - spawner_entity.get_set_test(3, "Configuration|Allow Per-Item Overrides", True) - - # 5) Toggle on Scale Modifier Override and verify Scale Min and Scale Max are set 0.1 and 1.0 - spawner_entity.get_set_test(2, "Configuration|Embedded Assets|[0]|Scale Modifier|Override Enabled", True) - scale_min = float( - format( - ( - hydra.get_component_property_value( - spawner_entity.components[2], "Configuration|Embedded Assets|[0]|Scale Modifier|Min" - ) - ), - ".1f", - ) + ) + scale_max = float( + format( + ( + hydra.get_component_property_value( + spawner_entity.components[2], "Configuration|Embedded Assets|[0]|Scale Modifier|Max" + ) + ), + ".1f", ) - scale_max = float( - format( - ( - hydra.get_component_property_value( - spawner_entity.components[2], "Configuration|Embedded Assets|[0]|Scale Modifier|Max" - ) - ), - ".1f", - ) - ) - if ((scale_max - 1.0) < CLOSE_ENOUGH_THRESHOLD) and ((scale_min - 0.1) < CLOSE_ENOUGH_THRESHOLD): - self.log("Scale Min and Scale Max are set to 0.1 and 1.0 in Vegetation Asset List") - else: - self.log("Scale Min and Scale Max are not set to 0.1 and 1.0 in Vegetation Asset List") + ) + Report.result(Tests.scale_values_set, ((scale_max - 1.0) < CLOSE_ENOUGH_THRESHOLD) and + ((scale_min - 0.1) < CLOSE_ENOUGH_THRESHOLD)) - # 6) Create a new child entity and add components - gradient_entity = hydra.Entity("Gradient Entity") - gradient_entity.create_entity( - entity_position, - ["Random Noise Gradient", "Gradient Transform Modifier", "Box Shape"], - parent_id=spawner_entity.id - ) - if gradient_entity.id.IsValid(): - self.log(f"'{gradient_entity.name}' created") + # 6) Create a new child entity and add components + gradient_entity = hydra.Entity("Gradient Entity") + gradient_entity.create_entity( + entity_position, + ["Random Noise Gradient", "Gradient Transform Modifier", "Box Shape"], + parent_id=spawner_entity.id + ) + Report.result(Tests.gradient_entity_created, gradient_entity.id.IsValid()) - # 7) Add child entity as gradient entity id in Vegetation Scale Modifier - spawner_entity.get_set_test(3, "Configuration|Gradient|Gradient Entity Id", gradient_entity.id) + # 7) Add child entity as gradient entity id in Vegetation Scale Modifier + spawner_entity.get_set_test(3, "Configuration|Gradient|Gradient Entity Id", gradient_entity.id) - # 8) Validate instances are scaled properly via a few different Range Min/Max settings on the override - self.test_success = set_and_validate_scale(spawner_entity, 0.1, 1.0) and self.test_success - self.test_success = set_and_validate_scale(spawner_entity, 2.0, 2.5) and self.test_success - self.test_success = set_and_validate_scale(spawner_entity, 1.0, 5.0) and self.test_success + # 8) Validate instances are scaled properly via a few different Range Min/Max settings on the override + Report.result(Tests.instances_properly_scaled, set_and_validate_scale(spawner_entity, 0.1, 1.0)) + Report.result(Tests.instances_properly_scaled, set_and_validate_scale(spawner_entity, 2.0, 2.5)) + Report.result(Tests.instances_properly_scaled, set_and_validate_scale(spawner_entity, 1.0, 5.0)) -test = TestScaleModifierOverrides_InstancesProperlyScale() -test.run() +if __name__ == "__main__": + + from editor_python_test_tools.utils import Report + Report.start_test(ScaleModifierOverrides_InstancesProperlyScale) diff --git a/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/ScaleModifier_InstancesProperlyScale.py b/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/ScaleModifier_InstancesProperlyScale.py index e579495e42..b2fadaa703 100755 --- a/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/ScaleModifier_InstancesProperlyScale.py +++ b/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/ScaleModifier_InstancesProperlyScale.py @@ -5,123 +5,123 @@ For complete copyright and license terms please see the LICENSE at the root of t SPDX-License-Identifier: Apache-2.0 OR MIT """ -import os -import sys -sys.path.append(os.path.dirname(os.path.abspath(__file__))) -import azlmbr.areasystem as areasystem -import azlmbr.bus as bus -import azlmbr.legacy.general as general -import azlmbr.math as math - -sys.path.append(os.path.join(azlmbr.paths.devroot, 'AutomatedTesting', 'Gem', 'PythonTests')) -import editor_python_test_tools.hydra_editor_utils as hydra -from editor_python_test_tools.editor_test_helper import EditorTestHelper -from largeworlds.large_worlds_utils import editor_dynveg_test_helper as dynveg +class Tests: + gradient_entity_created = ( + "Successfully created Gradient entity", + "Failed to create Gradient entity" + ) + instance_count = ( + "Found the expected number of instances", + "Found an unexpected number of instances" + ) + instances_properly_scaled = ( + "All instances scaled within appropriate range", + "Found instances scaled outside of the appropriate range" + ) -class TestScaleModifier_InstancesProperlyScale(EditorTestHelper): - def __init__(self): - EditorTestHelper.__init__(self, log_prefix="ScaleModifier_InstancesProperlyScale", args=["level"]) +def ScaleModifier_InstancesProperlyScale(): + """ + Summary: + A New level is created. A New entity is created with components Vegetation Layer Spawner, Vegetation Asset List, + Box Shape and Vegetation Scale Modifier. A New child entity is created with components Random Noise Gradient, + Gradient Transform Modifier, and Box Shape. Pin the Random Noise entity to the Gradient Entity Id field for + the Gradient group. Range Min and Range Max are set to few values and values are validated. Range Min and Range + Max are set to few other values and values are validated. - def run_test(self): - """ - Summary: - A New level is created. A New entity is created with components Vegetation Layer Spawner, Vegetation Asset List, - Box Shape and Vegetation Scale Modifier. A New child entity is created with components Random Noise Gradient, - Gradient Transform Modifier, and Box Shape. Pin the Random Noise entity to the Gradient Entity Id field for - the Gradient group. Range Min and Range Max are set to few values and values are validated. Range Min and Range - Max are set to few other values and values are validated. + Expected Behavior: + Vegetation instances are scaled within Range Min/Range Max. - Expected Behavior: - Vegetation instances are scaled within Range Min/Range Max. + Test Steps: + 1) Open an existing level + 2) Create a new entity with components Vegetation Layer Spawner, Vegetation Asset List, Box Shape and + Vegetation Scale Modifier + 3) Create child entity with components Random Noise Gradient, Gradient Transform Modifier and Box Shape + 4) Pin the Random Noise entity to the Gradient Entity Id field for the Gradient group. + 5) Range Min/Max is set to few different values on the Vegetation Scale Modifier component and + scale of instances is validated - Test Steps: - 1) Create level - 2) Create a new entity with components Vegetation Layer Spawner, Vegetation Asset List, Box Shape and - Vegetation Scale Modifier - 3) Create child entity with components Random Noise Gradient, Gradient Transform Modifier and Box Shape - 4) Pin the Random Noise entity to the Gradient Entity Id field for the Gradient group. - 5) Range Min/Max is set to few different values on the Vegetation Scale Modifier component and - scale of instances is validated + Note: + - 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. - Note: - - 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 + """ - :return: None - """ + import os - def set_and_validate_scale(entity, min_scale, max_scale): - # Set Range Min/Max - entity.get_set_test(3, "Configuration|Range Min", min_scale) - entity.get_set_test(3, "Configuration|Range Max", max_scale) + import azlmbr.areasystem as areasystem + import azlmbr.bus as bus + import azlmbr.legacy.general as general + import azlmbr.math as math - # Clear all areas to force a refresh - general.run_console('veg_debugClearAllAreas') + import editor_python_test_tools.hydra_editor_utils as hydra + from largeworlds.large_worlds_utils import editor_dynveg_test_helper as dynveg + from editor_python_test_tools.utils import Report + from editor_python_test_tools.utils import TestHelper as helper - # Wait for instances to spawn - num_expected = 20 * 20 - self.test_success = self.test_success and self.wait_for_condition( - lambda: dynveg.validate_instance_count_in_entity_shape(spawner_entity.id, num_expected), 5.0) + def set_and_validate_scale(entity, min_scale, max_scale): + # Set Range Min/Max + entity.get_set_test(3, "Configuration|Range Min", min_scale) + entity.get_set_test(3, "Configuration|Range Max", max_scale) - # Validate scale values of instances - box = azlmbr.shape.ShapeComponentRequestsBus(bus.Event, 'GetEncompassingAabb', entity.id) - instances = areasystem.AreaSystemRequestBus(bus.Broadcast, 'GetInstancesInAabb', box) - if len(instances) == num_expected: - for instance in instances: - if min_scale <= instance.scale <= max_scale: - self.log("All instances scaled within appropriate range") - return True - self.log(f"Instance at {instance.position} scale is {instance.scale}. Expected between " - f"{min_scale}/{max_scale}") - return False - self.log(f"Failed to find all instances! Found {len(instances)}, expected {num_expected}.") - return False + # Refresh the planted instances + general.run_console("veg_DebugClearAllAreas") - # 1) Create level and set an appropriate view of spawner area - self.test_success = self.create_level( - self.args["level"], - heightmap_resolution=1024, - heightmap_meters_per_pixel=1, - terrain_texture_resolution=4096, - use_terrain=False, - ) + # Check the initial instance count + num_expected = 20 * 20 + success = helper.wait_for_condition( + lambda: dynveg.validate_instance_count_in_entity_shape(spawner_entity.id, num_expected), 5.0) + Report.critical_result(Tests.instance_count, success) - general.set_current_view_position(500.49, 498.69, 46.66) - general.set_current_view_rotation(-42.05, 0.00, -36.33) + # Validate scale values of instances + box = azlmbr.shape.ShapeComponentRequestsBus(bus.Event, 'GetEncompassingAabb', entity.id) + instances = areasystem.AreaSystemRequestBus(bus.Broadcast, 'GetInstancesInAabb', box) + for instance in instances: + if min_scale <= instance.scale <= max_scale: + return True + return False - # 2) Create a new entity with components Vegetation Layer Spawner, Vegetation Asset List, Box Shape and - # Vegetation Scale Modifier - entity_position = math.Vector3(512.0, 512.0, 32.0) - asset_path = os.path.join("Slices", "PurpleFlower.dynamicslice") - spawner_entity = dynveg.create_vegetation_area("Spawner Entity", entity_position, 16.0, 16.0, 16.0, - asset_path) - spawner_entity.add_component("Vegetation Scale Modifier") + # 1) Open an existing simple level + helper.init_idle() + helper.open_level("Physics", "Base") - # Create a surface to plant on and add a Vegetation Debugger Level component to allow refreshes - dynveg.create_surface_entity("Surface Entity", entity_position, 20.0, 20.0, 1.0) - hydra.add_level_component("Vegetation Debugger") + general.set_current_view_position(500.49, 498.69, 46.66) + general.set_current_view_rotation(-42.05, 0.00, -36.33) - # 3) Create child entity with components Random Noise Gradient, Gradient Transform Modifier and Box Shape - gradient_entity = hydra.Entity("Gradient Entity") - gradient_entity.create_entity( - entity_position, - ["Random Noise Gradient", "Gradient Transform Modifier", "Box Shape"], - parent_id=spawner_entity.id - ) - if gradient_entity.id.IsValid(): - self.log(f"'{gradient_entity.name}' created") + # 2) Create a new entity with components Vegetation Layer Spawner, Vegetation Asset List, Box Shape and + # Vegetation Scale Modifier + entity_position = math.Vector3(512.0, 512.0, 32.0) + asset_path = os.path.join("Slices", "PurpleFlower.dynamicslice") + spawner_entity = dynveg.create_vegetation_area("Spawner Entity", entity_position, 16.0, 16.0, 16.0, + asset_path) + spawner_entity.add_component("Vegetation Scale Modifier") - # 4) Pin the Random Noise entity to the Gradient Entity Id field for the Gradient group. - spawner_entity.get_set_test(3, "Configuration|Gradient|Gradient Entity Id", gradient_entity.id) + # Create a surface to plant on and add a Vegetation Debugger Level component to allow refreshes + dynveg.create_surface_entity("Surface Entity", entity_position, 20.0, 20.0, 1.0) + hydra.add_level_component("Vegetation Debugger") - # 5) Set Range Min/Max on the Vegetation Scale Modifier component to diff values, and verify instance scale is - # within bounds - self.test_success = set_and_validate_scale(spawner_entity, 2.0, 4.0) and self.test_success - self.test_success = set_and_validate_scale(spawner_entity, 12.0, 40.0) and self.test_success - self.test_success = set_and_validate_scale(spawner_entity, 0.5, 2.5) and self.test_success + # 3) Create child entity with components Random Noise Gradient, Gradient Transform Modifier and Box Shape + gradient_entity = hydra.Entity("Gradient Entity") + gradient_entity.create_entity( + entity_position, + ["Random Noise Gradient", "Gradient Transform Modifier", "Box Shape"], + parent_id=spawner_entity.id + ) + Report.critical_result(Tests.gradient_entity_created, gradient_entity.id.IsValid()) + + # 4) Pin the Random Noise entity to the Gradient Entity Id field for the Gradient group. + spawner_entity.get_set_test(3, "Configuration|Gradient|Gradient Entity Id", gradient_entity.id) + + # 5) Set Range Min/Max on the Vegetation Scale Modifier component to diff values, and verify instance scale is + # within bounds + Report.result(Tests.instances_properly_scaled, set_and_validate_scale(spawner_entity, 2.0, 4.0)) + Report.result(Tests.instances_properly_scaled, set_and_validate_scale(spawner_entity, 12.0, 40.0)) + Report.result(Tests.instances_properly_scaled, set_and_validate_scale(spawner_entity, 0.5, 2.5)) -test = TestScaleModifier_InstancesProperlyScale() -test.run() +if __name__ == "__main__": + + from editor_python_test_tools.utils import Report + Report.start_test(ScaleModifier_InstancesProperlyScale) diff --git a/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/ShapeIntersectionFilter_FilterStageToggle.py b/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/ShapeIntersectionFilter_FilterStageToggle.py new file mode 100644 index 0000000000..1b9c6aa5ea --- /dev/null +++ b/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/ShapeIntersectionFilter_FilterStageToggle.py @@ -0,0 +1,113 @@ +""" +Copyright (c) Contributors to the Open 3D Engine Project. +For complete copyright and license terms please see the LICENSE at the root of this distribution. + +SPDX-License-Identifier: Apache-2.0 OR MIT +""" + + +class Tests: + instance_count_in_box_shape = ( + "Only found instances in the configured Box Shape intersection area", + "Found instances outside of the configured Box Shape intersection area" + ) + instance_count_in_cylinder_shape = ( + "Only found instances in the configured Cylinder Shape intersection area", + "Found instances outside of the configured Cylinder Shape intersection area" + ) + preprocess_instance_count = ( + "Found the expected number of instances with preprocessing filter stage", + "Found an unexpected number of instances with preprocessing filter stage" + ) + postprocess_instance_count = ( + "Found the expected number of instances with postprocessing filter stage", + "Found an unexpected number of instances with postprocessing filter stage" + ) + + +def ShapeIntersectionFilter_FilterStageToggle(): + """ + Summary: + Filter Stage toggle affects final vegetation position + + Expected Result: + Vegetation instances plant differently depending on the Filter Stage setting. With PreProcess, some vegetation + instances can appear on slopes outside the filtered values. With PostProcess, vegetation instances only appear on + the correct slope values. + + :return: None + """ + + import os + + import azlmbr.math as math + import azlmbr.legacy.general as general + + import editor_python_test_tools.hydra_editor_utils as hydra + from largeworlds.large_worlds_utils import editor_dynveg_test_helper as dynveg + from editor_python_test_tools.utils import Report + from editor_python_test_tools.utils import TestHelper as helper + + # Open an existing simple level + helper.init_idle() + helper.open_level("Physics", "Base") + + general.set_current_view_position(512.0, 480.0, 38.0) + + # Create basic vegetation entity + position = math.Vector3(512.0, 512.0, 32.0) + asset_path = os.path.join("Slices", "PinkFlower.dynamicslice") + vegetation = dynveg.create_vegetation_area("vegetation", position, 16.0, 16.0, 16.0, asset_path) + + # Create Surface for instances to plant on + dynveg.create_surface_entity("Surface_Entity_Parent", position, 16.0, 16.0, 1.0) + + # Add a Vegetation Shape Intersection Filter to the vegetation area entity + vegetation.add_component("Vegetation Shape Intersection Filter") + + # Create a new entity as a child of the vegetation area entity with Box Shape + box = hydra.Entity("box") + box.create_entity(position, ["Box Shape"]) + box.get_set_test(0, "Box Shape|Box Configuration|Dimensions", math.Vector3(8.0, 8.0, 1.0)) + + # Create a new entity as a child of the vegetation area entity with Cylinder Shape. + cylinder = hydra.Entity("cylinder") + cylinder.create_entity(position, ["Cylinder Shape"]) + cylinder.get_set_test(0, "Cylinder Shape|Cylinder Configuration|Radius", 5.0) + cylinder.get_set_test(0, "Cylinder Shape|Cylinder Configuration|Height", 5.0) + box.set_test_parent_entity(vegetation) + cylinder.set_test_parent_entity(vegetation) + + # On the Shape Intersection Filter component, click the crosshair button, and add child entities one by one + vegetation.get_set_test(3, "Configuration|Shape Entity Id", box.id) + result = helper.wait_for_condition(lambda: dynveg.validate_instance_count(position, 8.0, 100), 2.0) + Report.result(Tests.instance_count_in_box_shape, result) + vegetation.get_set_test(3, "Configuration|Shape Entity Id", cylinder.id) + result = helper.wait_for_condition(lambda: dynveg.validate_instance_count(position, 5.0, 100), 2.0) + Report.result(Tests.instance_count_in_cylinder_shape, result) + + # Create a new entity as a child of the area entity with Random Noise Gradient, Gradient Transform Modifier, + # and Box Shape component + random_noise = hydra.Entity("random_noise") + random_noise.create_entity(position, ["Random Noise Gradient", "Gradient Transform Modifier", "Box Shape"]) + random_noise.set_test_parent_entity(vegetation) + + # Add a Vegetation Position Modifier to the vegetation area entity + vegetation.add_component("Vegetation Position Modifier") + + # Pin the Random Noise entity to the Gradient Entity Id field of the Position Modifier's Gradient X + vegetation.get_set_test(4, "Configuration|Position X|Gradient|Gradient Entity Id", random_noise.id) + + # Toggle between PreProcess and PostProcess + vegetation.get_set_test(3, "Configuration|Filter Stage", 1) + result = helper.wait_for_condition(lambda: dynveg.validate_instance_count(position, 5.0, 117), 2.0) + Report.result(Tests.preprocess_instance_count, result) + vegetation.get_set_test(3, "Configuration|Filter Stage", 2) + result = helper.wait_for_condition(lambda: dynveg.validate_instance_count(position, 5.0, 122), 2.0) + Report.result(Tests.postprocess_instance_count, result) + + +if __name__ == "__main__": + + from editor_python_test_tools.utils import Report + Report.start_test(ShapeIntersectionFilter_FilterStageToggle) diff --git a/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/ShapeIntersectionFilter_InstancesPlantInAssignedShape.py b/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/ShapeIntersectionFilter_InstancesPlantInAssignedShape.py index 83458fe153..e872b23054 100755 --- a/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/ShapeIntersectionFilter_InstancesPlantInAssignedShape.py +++ b/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/ShapeIntersectionFilter_InstancesPlantInAssignedShape.py @@ -5,124 +5,126 @@ For complete copyright and license terms please see the LICENSE at the root of t SPDX-License-Identifier: Apache-2.0 OR MIT """ -""" -C4874094: Shape reference can be replaced/removed -""" -import os -import sys - -sys.path.append(os.path.dirname(os.path.abspath(__file__))) -import azlmbr.editor as editor -import azlmbr.legacy.general as general -import azlmbr.bus as bus -import azlmbr.math as math -import azlmbr.paths - -sys.path.append(os.path.join(azlmbr.paths.devroot, 'AutomatedTesting', 'Gem', 'PythonTests')) -import editor_python_test_tools.hydra_editor_utils as hydra -from editor_python_test_tools.editor_test_helper import EditorTestHelper -from largeworlds.large_worlds_utils import editor_dynveg_test_helper as dynveg +class Tests: + instance_count_in_box_shape = ( + "Only found instances in the configured Box Shape intersection area", + "Found instances outside of the configured Box Shape intersection area" + ) + instance_count_in_cylinder_shape = ( + "Only found instances in the configured Cylinder Shape intersection area", + "Found instances outside of the configured Cylinder Shape intersection area" + ) + unfiltered_instance_count = ( + "Found instances in the entire Spawner area with no filter set", + "Failed to find all expected instances in the Spawner area with no filter set" + ) -class TestShapeIntersectionFilter(EditorTestHelper): - def __init__(self): - EditorTestHelper.__init__(self, log_prefix="ShapeIntersectionFilter_InstancePlanting", args=["level"]) +def ShapeIntersectionFilter_InstancesPlantInAssignedShape(): + """ + Summary: + A spawner area is created with a Vegetation Shape Intersection Filter. 2 different shape entities are created, + pinned to the Shape Intersection Filter, and instance counts are verified. - def run_test(self): - """ - Summary: - A spawner area is created with a Vegetation Shape Intersection Filter. 2 different shape entities are created, - pinned to the Shape Intersection Filter, and instance counts are verified. + Expected Behavior: + The Shape Entity Id reference can be successfully set/updated. Instances spawn only in the specified shape area. - Expected Behavior: - The Shape Entity Id reference can be successfully set/updated. Instances spawn only in the specified shape area. + Test Steps: + 1) Open an existing level, and set view for visual debugging + 2) Create an instance spawner and planting surface + 3) Create child entity with Box Shape + 4) Create child entity with Cylinder Shape + 5) Assign the Intersection Filter to the Box Shape and validate instance counts + 6) Assign the Intersection Filter to the Cylinder Shape and validate instance counts + 7) Remove the shape reference on the Intersection Filter and validate instance counts - Test Steps: - 1) Create a new level, and set view for visual debugging - 2) Create an instance spawner and planting surface - 3) Create child entity with Box Shape - 4) Create child entity with Cylinder Shape - 5) Assign the Intersection Filter to the Box Shape and validate instance counts - 6) Assign the Intersection Filter to the Cylinder Shape and validate instance counts - 7) Remove the shape reference on the Intersection Filter and validate instance counts + 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. - 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 + """ - :return: None - """ - # 1) Create a new, temporary level - self.test_success = self.create_level( - self.args["level"], - heightmap_resolution=1024, - heightmap_meters_per_pixel=1, - terrain_texture_resolution=4096, - use_terrain=False, - ) + import os - # Set view of planting area for visual debugging - general.set_current_view_position(512.0, 500.0, 38.0) - general.set_current_view_rotation(-20.0, 0.0, 0.0) + import azlmbr.editor as editor + import azlmbr.legacy.general as general + import azlmbr.bus as bus + import azlmbr.math as math - # 2) Create a new entity with required vegetation area components and Vegetation Shape Intersection Filter - center_point = math.Vector3(512.0, 512.0, 32.0) - asset_path = os.path.join("Slices", "PinkFlower.dynamicslice") - spawner_entity = dynveg.create_vegetation_area("Instance Spawner", center_point, 16.0, 16.0, 1.0, - asset_path) - spawner_entity.add_component("Vegetation Shape Intersection Filter") + import editor_python_test_tools.hydra_editor_utils as hydra + from largeworlds.large_worlds_utils import editor_dynveg_test_helper as dynveg + from editor_python_test_tools.utils import Report + from editor_python_test_tools.utils import TestHelper as helper - # Create a planting surface - dynveg.create_surface_entity("Planting Surface", center_point, 32.0, 32.0, 1.0) + # 1) Open an existing simple level + helper.init_idle() + helper.open_level("Physics", "Base") - # 3) Create a child entity with Box Shape - components_to_add = ["Box Shape"] - box_id = editor.ToolsApplicationRequestBus(bus.Broadcast, "CreateNewEntity", spawner_entity.id) - box = hydra.Entity("Box", box_id) - box.components = [] - for component in components_to_add: - box.components.append(hydra.add_component(component, box_id)) - new_box_dimension = math.Vector3(5.0, 5.0, 5.0) - hydra.get_set_test(box, 0, "Box Shape|Box Configuration|Dimensions", new_box_dimension) + # Set view of planting area for visual debugging + general.set_current_view_position(512.0, 500.0, 38.0) + general.set_current_view_rotation(-20.0, 0.0, 0.0) - # 4) Create a child entity with Cylinder Shape - components_to_add = ["Cylinder Shape"] - cylinder_id = editor.ToolsApplicationRequestBus(bus.Broadcast, "CreateNewEntity", spawner_entity.id) - cylinder = hydra.Entity("Cylinder", cylinder_id) - cylinder.components = [] - for component in components_to_add: - cylinder.components.append(hydra.add_component(component, cylinder_id)) - hydra.get_set_test(cylinder, 0, "Cylinder Shape|Cylinder Configuration|Radius", 5.0) + # 2) Create a new entity with required vegetation area components and Vegetation Shape Intersection Filter + center_point = math.Vector3(512.0, 512.0, 32.0) + asset_path = os.path.join("Slices", "PinkFlower.dynamicslice") + spawner_entity = dynveg.create_vegetation_area("Instance Spawner", center_point, 16.0, 16.0, 1.0, + asset_path) + spawner_entity.add_component("Vegetation Shape Intersection Filter") - # 5) Set the Intersection Filter's Shape Entity Id to the Box Shape entity - spawner_entity.get_set_test(3, "Configuration|Shape Entity Id", box_id) + # Create a planting surface + dynveg.create_surface_entity("Planting Surface", center_point, 32.0, 32.0, 1.0) - # Validate instance counts. Instances should only plant in the Box Shape area - num_expected = 49 - success = self.wait_for_condition(lambda: dynveg.validate_instance_count_in_entity_shape(spawner_entity.id, - num_expected), 5.0) - self.test_success = success and self.test_success - - # 6) Set the Intersection Filter's Shape Entity Id to the Cylinder Shape entity - spawner_entity.get_set_test(3, "Configuration|Shape Entity Id", cylinder_id) + # 3) Create a child entity with Box Shape + components_to_add = ["Box Shape"] + box_id = editor.ToolsApplicationRequestBus(bus.Broadcast, "CreateNewEntity", spawner_entity.id) + box = hydra.Entity("Box", box_id) + box.components = [] + for component in components_to_add: + box.components.append(hydra.add_component(component, box_id)) + new_box_dimension = math.Vector3(5.0, 5.0, 5.0) + hydra.get_set_test(box, 0, "Box Shape|Box Configuration|Dimensions", new_box_dimension) - # Validate instance counts. Instances should only plant in the Cylinder Shape area - num_expected = 121 - success = self.wait_for_condition(lambda: dynveg.validate_instance_count_in_entity_shape(spawner_entity.id, - num_expected), 5.0) - self.test_success = success and self.test_success + # 4) Create a child entity with Cylinder Shape + components_to_add = ["Cylinder Shape"] + cylinder_id = editor.ToolsApplicationRequestBus(bus.Broadcast, "CreateNewEntity", spawner_entity.id) + cylinder = hydra.Entity("Cylinder", cylinder_id) + cylinder.components = [] + for component in components_to_add: + cylinder.components.append(hydra.add_component(component, cylinder_id)) + hydra.get_set_test(cylinder, 0, "Cylinder Shape|Cylinder Configuration|Radius", 5.0) - # 7) Clear the Intersection Filter's Shape Entity Id reference - spawner_entity.get_set_test(3, "Configuration|Shape Entity Id", None) + # 5) Set the Intersection Filter's Shape Entity Id to the Box Shape entity + spawner_entity.get_set_test(3, "Configuration|Shape Entity Id", box_id) - # Validate instance counts. Instances should now fill the entire spawner_entity's area - num_expected = 20 * 20 - success = self.wait_for_condition(lambda: dynveg.validate_instance_count_in_entity_shape(spawner_entity.id, - num_expected), 5.0) - self.test_success = success and self.test_success + # Validate instance counts. Instances should only plant in the Box Shape area + num_expected = 49 + success = helper.wait_for_condition(lambda: dynveg.validate_instance_count_in_entity_shape(spawner_entity.id, + num_expected), 5.0) + Report.result(Tests.instance_count_in_box_shape, success) + + # 6) Set the Intersection Filter's Shape Entity Id to the Cylinder Shape entity + spawner_entity.get_set_test(3, "Configuration|Shape Entity Id", cylinder_id) + + # Validate instance counts. Instances should only plant in the Cylinder Shape area + num_expected = 121 + success = helper.wait_for_condition(lambda: dynveg.validate_instance_count_in_entity_shape(spawner_entity.id, + num_expected), 5.0) + Report.result(Tests.instance_count_in_cylinder_shape, success) + + # 7) Clear the Intersection Filter's Shape Entity Id reference + spawner_entity.get_set_test(3, "Configuration|Shape Entity Id", None) + + # Validate instance counts. Instances should now fill the entire spawner_entity's area + num_expected = 20 * 20 + success = helper.wait_for_condition(lambda: dynveg.validate_instance_count_in_entity_shape(spawner_entity.id, + num_expected), 5.0) + Report.result(Tests.unfiltered_instance_count, success) -test = TestShapeIntersectionFilter() -test.run() +if __name__ == "__main__": + + from editor_python_test_tools.utils import Report + Report.start_test(ShapeIntersectionFilter_InstancesPlantInAssignedShape) diff --git a/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/SlopeAlignmentModifierOverrides_InstanceSurfaceAlignment.py b/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/SlopeAlignmentModifierOverrides_InstanceSurfaceAlignment.py index abd3dc35d5..5855972f0c 100755 --- a/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/SlopeAlignmentModifierOverrides_InstanceSurfaceAlignment.py +++ b/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/SlopeAlignmentModifierOverrides_InstanceSurfaceAlignment.py @@ -5,121 +5,132 @@ For complete copyright and license terms please see the LICENSE at the root of t SPDX-License-Identifier: Apache-2.0 OR MIT """ -import os -from math import radians -import sys -import azlmbr.areasystem as areasystem -import azlmbr.asset as asset -import azlmbr.bus as bus -import azlmbr.components as components -import azlmbr.legacy.general as general -import azlmbr.math as math -import azlmbr.paths - -sys.path.append(os.path.join(azlmbr.paths.devroot, 'AutomatedTesting', 'Gem', 'PythonTests')) -import editor_python_test_tools.hydra_editor_utils as hydra -from editor_python_test_tools.editor_test_helper import EditorTestHelper -from largeworlds.large_worlds_utils import editor_dynveg_test_helper as dynveg +class Tests: + surface_entity_created = ( + "Successfully created Surface entity", + "Failed to create Surface entity" + ) + instance_count = ( + "Found the expected number of instances", + "Unexpected number of instances found" + ) + instances_aligned_0 = ( + "All instances are pointed straight up", + "Found instances not aligned to surface pointing straight up" + ) + instances_aligned_1 = ( + "All instances are planted perpendicularly to the surface", + "Found instances not aligned to surface perpendicularly" + ) -class TestSlopeAlignmentModifierOverrides(EditorTestHelper): - def __init__(self): - EditorTestHelper.__init__(self, log_prefix="SlopeAlignmentModifierOverrides", args=["level"]) +def SlopeAlignmentModifierOverrides_InstanceSurfaceAlignment(): + """ + Summary: + Verifies instances properly align to surfaces based on configuration of descriptor overrides of the + Vegetation Slope Alignment Modifier component. - def run_test(self): - """ - Summary: - C4814459 Verifies instances properly align to surfaces based on configuration of descriptor overrides of the - Vegetation Slope Alignment Modifier component. + :return: None + """ - :return: None - """ + import os + from math import radians - def verify_proper_alignment(instance, rot_degrees_vec): - expected_rotation = math.Quaternion() - expected_rotation.SetFromEulerDegrees(rot_degrees_vec) - if instance.alignment.IsClose(expected_rotation): - return True - self.log(f"Expected rotation of {expected_rotation}, Found {instance.alignment}") - return False + import azlmbr.areasystem as areasystem + import azlmbr.asset as asset + import azlmbr.bus as bus + import azlmbr.components as components + import azlmbr.legacy.general as general + import azlmbr.math as math - # Create empty level - self.test_success = self.create_level( - self.args["level"], - heightmap_resolution=1024, - heightmap_meters_per_pixel=1, - terrain_texture_resolution=4096, - use_terrain=False, - ) + import editor_python_test_tools.hydra_editor_utils as hydra + from largeworlds.large_worlds_utils import editor_dynveg_test_helper as dynveg + from editor_python_test_tools.utils import Report + from editor_python_test_tools.utils import TestHelper as helper - general.set_current_view_position(512.0, 480.0, 38.0) + def verify_proper_alignment(instance, rot_degrees_vec): + expected_rotation = math.Quaternion() + expected_rotation.SetFromEulerDegrees(rot_degrees_vec) + if instance.alignment.IsClose(expected_rotation): + return True + Report.info(f"Expected rotation of {expected_rotation}, Found {instance.alignment}") + return False - # Create a spawner entity setup with all needed components - center_point = math.Vector3(512.0, 512.0, 32.0) - asset_path = os.path.join("Slices", "PinkFlower.dynamicslice") - spawner_entity = dynveg.create_vegetation_area("Instance Spawner", center_point, 16.0, 16.0, 32.0, asset_path) + # Open an existing simple level + helper.init_idle() + helper.open_level("Physics", "Base") - # Create a sloped mesh surface for the instances to plant on - center_point = math.Vector3(502.0, 512.0, 24.0) - mesh_asset_path = os.path.join("objects", "_primitives", "_box_1x1.azmodel") - mesh_asset = asset.AssetCatalogRequestBus(bus.Broadcast, "GetAssetIdByPath", mesh_asset_path, math.Uuid(), - False) - rotation = math.Vector3(0.0, radians(45.0), 0.0) - surface_entity = hydra.Entity("Surface Entity") - surface_entity.create_entity( - center_point, - ["Mesh", "Mesh Surface Tag Emitter"] - ) - if surface_entity.id.IsValid(): - print(f"'{surface_entity.name}' created") - hydra.get_set_test(surface_entity, 0, "Controller|Configuration|Mesh Asset", mesh_asset) - components.TransformBus(bus.Event, "SetLocalRotation", surface_entity.id, rotation) - components.TransformBus(bus.Event, "SetLocalUniformScale", surface_entity.id, 30.0) + general.set_current_view_position(512.0, 480.0, 38.0) - # Add a Vegetation Debugger component to allow refreshing instances - hydra.add_level_component("Vegetation Debugger") + # Create a spawner entity setup with all needed components + center_point = math.Vector3(512.0, 512.0, 32.0) + asset_path = os.path.join("Slices", "PinkFlower.dynamicslice") + spawner_entity = dynveg.create_vegetation_area("Instance Spawner", center_point, 16.0, 16.0, 32.0, asset_path) - # Add Vegetation Slope Alignment Modifier to the spawner entity and toggle on Allow Per-Item Overrides - spawner_entity.add_component("Vegetation Slope Alignment Modifier") - spawner_entity.get_set_test(3, "Configuration|Allow Per-Item Overrides", True) + # Create a sloped mesh surface for the instances to plant on + center_point = math.Vector3(502.0, 512.0, 24.0) + mesh_asset_path = os.path.join("objects", "_primitives", "_box_1x1.azmodel") + mesh_asset = asset.AssetCatalogRequestBus(bus.Broadcast, "GetAssetIdByPath", mesh_asset_path, math.Uuid(), + False) + rotation = math.Vector3(0.0, radians(45.0), 0.0) + surface_entity = hydra.Entity("Surface Entity") + surface_entity.create_entity( + center_point, + ["Mesh", "Mesh Surface Tag Emitter"] + ) + Report.critical_result(Tests.surface_entity_created, surface_entity.id.IsValid()) + hydra.get_set_test(surface_entity, 0, "Controller|Configuration|Mesh Asset", mesh_asset) + components.TransformBus(bus.Event, "SetLocalRotation", surface_entity.id, rotation) + components.TransformBus(bus.Event, "SetLocalUniformScale", surface_entity.id, 30.0) - # Toggle on Surface Slope Alignment Override Enabled on the Vegetation Asset List component - spawner_entity.get_set_test(2, "Configuration|Embedded Assets|[0]|Surface Slope Alignment|Override Enabled", - True) + # Add a Vegetation Debugger component to allow refreshing instances + hydra.add_level_component("Vegetation Debugger") - # Set Surface Slope Alignment Override Min and Max to 0 and validate instance alignment - spawner_entity.get_set_test(2, "Configuration|Embedded Assets|[0]|Surface Slope Alignment|Max", 0.0) - spawner_entity.get_set_test(2, "Configuration|Embedded Assets|[0]|Surface Slope Alignment|Max", 0.0) + # Add Vegetation Slope Alignment Modifier to the spawner entity and toggle on Allow Per-Item Overrides + spawner_entity.add_component("Vegetation Slope Alignment Modifier") + spawner_entity.get_set_test(3, "Configuration|Allow Per-Item Overrides", True) - # Verify instances are have planted and are aligned to slope as expected - num_expected = 20 * 20 - self.test_success = self.test_success and self.wait_for_condition( - lambda: dynveg.validate_instance_count_in_entity_shape(spawner_entity.id, num_expected), 5.0) + # Toggle on Surface Slope Alignment Override Enabled on the Vegetation Asset List component + spawner_entity.get_set_test(2, "Configuration|Embedded Assets|[0]|Surface Slope Alignment|Override Enabled", + True) - box = azlmbr.shape.ShapeComponentRequestsBus(bus.Event, 'GetEncompassingAabb', spawner_entity.id) - instances = areasystem.AreaSystemRequestBus(bus.Broadcast, 'GetInstancesInAabb', box) + # Set Surface Slope Alignment Override Min and Max to 0 and validate instance alignment + spawner_entity.get_set_test(2, "Configuration|Embedded Assets|[0]|Surface Slope Alignment|Max", 0.0) + spawner_entity.get_set_test(2, "Configuration|Embedded Assets|[0]|Surface Slope Alignment|Max", 0.0) - if self.test_success and num_expected == len(instances): - for instance in instances: - self.test_success = verify_proper_alignment(instance, - math.Vector3(0.0, 0.0, 0.0)) and self.test_success + # Verify instances are have planted and are aligned to slope as expected + num_expected = 20 * 20 + instances_planted = helper.wait_for_condition( + lambda: dynveg.validate_instance_count_in_entity_shape(spawner_entity.id, num_expected), 5.0) + Report.critical_result(Tests.instance_count, instances_planted) - # Set Surface Slope Alignment Min and Max to 1 and validate instance alignment - spawner_entity.get_set_test(2, "Configuration|Embedded Assets|[0]|Surface Slope Alignment|Min", 1.0) - spawner_entity.get_set_test(2, "Configuration|Embedded Assets|[0]|Surface Slope Alignment|Max", 1.0) - general.run_console('veg_debugClearAllAreas') - self.test_success = self.test_success and self.wait_for_condition( - lambda: dynveg.validate_instance_count_in_entity_shape(spawner_entity.id, num_expected), 5.0) + box = azlmbr.shape.ShapeComponentRequestsBus(bus.Event, 'GetEncompassingAabb', spawner_entity.id) + instances = areasystem.AreaSystemRequestBus(bus.Broadcast, 'GetInstancesInAabb', box) - box = azlmbr.shape.ShapeComponentRequestsBus(bus.Event, 'GetEncompassingAabb', spawner_entity.id) - instances = areasystem.AreaSystemRequestBus(bus.Broadcast, 'GetInstancesInAabb', box) + success = True + for instance in instances: + success = verify_proper_alignment(instance, math.Vector3(0.0, 0.0, 0.0)) + Report.result(Tests.instances_aligned_0, success) - if self.test_success and num_expected == len(instances): - for instance in instances: - self.test_success = verify_proper_alignment(instance, math.Vector3(0.0, 45.0, 0.0)) and \ - self.test_success + # Set Surface Slope Alignment Min and Max to 1 and validate instance alignment + spawner_entity.get_set_test(2, "Configuration|Embedded Assets|[0]|Surface Slope Alignment|Min", 1.0) + spawner_entity.get_set_test(2, "Configuration|Embedded Assets|[0]|Surface Slope Alignment|Max", 1.0) + general.run_console('veg_debugClearAllAreas') + instances_planted = helper.wait_for_condition( + lambda: dynveg.validate_instance_count_in_entity_shape(spawner_entity.id, num_expected), 5.0) + Report.critical_result(Tests.instance_count, instances_planted) + + box = azlmbr.shape.ShapeComponentRequestsBus(bus.Event, 'GetEncompassingAabb', spawner_entity.id) + instances = areasystem.AreaSystemRequestBus(bus.Broadcast, 'GetInstancesInAabb', box) + + success = True + for instance in instances: + success = verify_proper_alignment(instance, math.Vector3(0.0, 45.0, 0.0)) + Report.result(Tests.instances_aligned_1, success) -test = TestSlopeAlignmentModifierOverrides() -test.run() +if __name__ == "__main__": + + from editor_python_test_tools.utils import Report + Report.start_test(SlopeAlignmentModifierOverrides_InstanceSurfaceAlignment) diff --git a/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/SlopeAlignmentModifier_InstanceSurfaceAlignment.py b/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/SlopeAlignmentModifier_InstanceSurfaceAlignment.py index 6e9e36957f..11427b9b0e 100755 --- a/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/SlopeAlignmentModifier_InstanceSurfaceAlignment.py +++ b/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/SlopeAlignmentModifier_InstanceSurfaceAlignment.py @@ -5,127 +5,139 @@ For complete copyright and license terms please see the LICENSE at the root of t SPDX-License-Identifier: Apache-2.0 OR MIT """ -import os -from math import radians -import sys -import azlmbr.areasystem as areasystem -import azlmbr.asset as asset -import azlmbr.bus as bus -import azlmbr.components as components -import azlmbr.editor as editor -import azlmbr.legacy.general as general -import azlmbr.math as math -import azlmbr.paths - -sys.path.append(os.path.join(azlmbr.paths.devroot, 'AutomatedTesting', 'Gem', 'PythonTests')) -import editor_python_test_tools.hydra_editor_utils as hydra -from editor_python_test_tools.editor_test_helper import EditorTestHelper -from largeworlds.large_worlds_utils import editor_dynveg_test_helper as dynveg +class Tests: + surface_entity_created = ( + "Successfully created Surface entity", + "Failed to create Surface entity" + ) + instance_count = ( + "Found the expected number of instances", + "Unexpected number of instances found" + ) + instances_aligned_1 = ( + "All instances are planted perpendicularly to the surface", + "Found instances not aligned to surface perpendicularly" + ) + instances_aligned_0 = ( + "All instances are pointed straight up", + "Found instances not aligned to surface pointing straight up" + ) -class TestSlopeAlignmentModifier(EditorTestHelper): - def __init__(self): - EditorTestHelper.__init__(self, log_prefix="SlopeAlignmentModifier", args=["level"]) +def SlopeAlignmentModifier_InstanceSurfaceAlignment(): + """ + Summary: + Verifies instances properly align to surfaces based on configuration of the Vegetation Slope Alignment + Modifier. - def run_test(self): - """ - Summary: - C4896941 Verifies instances properly align to surfaces based on configuration of the Vegetation Slope Alignment - Modifier. + :return: None + """ - :return: None - """ + import os + from math import radians - def verify_proper_alignment(instance, rot_degrees_vec): - expected_rotation = math.Quaternion() - expected_rotation.SetFromEulerDegrees(rot_degrees_vec) - if instance.alignment.IsClose(expected_rotation): - return True - self.log(f"Expected rotation of {expected_rotation}, Found {instance.alignment}") - return False + import azlmbr.areasystem as areasystem + import azlmbr.asset as asset + import azlmbr.bus as bus + import azlmbr.components as components + import azlmbr.editor as editor + import azlmbr.legacy.general as general + import azlmbr.math as math - # Create empty level - self.test_success = self.create_level( - self.args["level"], - heightmap_resolution=1024, - heightmap_meters_per_pixel=1, - terrain_texture_resolution=4096, - use_terrain=False, - ) + import editor_python_test_tools.hydra_editor_utils as hydra + from largeworlds.large_worlds_utils import editor_dynveg_test_helper as dynveg + from editor_python_test_tools.utils import Report + from editor_python_test_tools.utils import TestHelper as helper - general.set_current_view_position(512.0, 480.0, 38.0) + def verify_proper_alignment(instance, rot_degrees_vec): + expected_rotation = math.Quaternion() + expected_rotation.SetFromEulerDegrees(rot_degrees_vec) + if instance.alignment.IsClose(expected_rotation): + return True + Report.info(f"Expected rotation of {expected_rotation}, Found {instance.alignment}") + return False - # Create a spawner entity setup with all needed components - center_point = math.Vector3(512.0, 512.0, 32.0) - asset_path = os.path.join("Slices", "PinkFlower.dynamicslice") - spawner_entity = dynveg.create_vegetation_area("Instance Spawner", center_point, 16.0, 16.0, 32.0, asset_path) + # Open an existing simple level + helper.init_idle() + helper.open_level("Physics", "Base") - # Create a sloped mesh surface for the instances to plant on - center_point = math.Vector3(502.0, 512.0, 24.0) - mesh_asset_path = os.path.join("objects", "_primitives", "_box_1x1.azmodel") - mesh_asset = asset.AssetCatalogRequestBus(bus.Broadcast, "GetAssetIdByPath", mesh_asset_path, math.Uuid(), - False) - rotation = math.Vector3(0.0, radians(45.0), 0.0) - surface_entity = hydra.Entity("Surface Entity") - surface_entity.create_entity( - center_point, - ["Mesh", "Mesh Surface Tag Emitter"] - ) - if surface_entity.id.IsValid(): - print(f"'{surface_entity.name}' created") - hydra.get_set_test(surface_entity, 0, "Controller|Configuration|Mesh Asset", mesh_asset) - components.TransformBus(bus.Event, "SetLocalRotation", surface_entity.id, rotation) - components.TransformBus(bus.Event, "SetLocalUniformScale", surface_entity.id, 30.0) + general.set_current_view_position(512.0, 480.0, 38.0) - # Add a Vegetation Debugger component to allow refreshing instances - hydra.add_level_component("Vegetation Debugger") + # Create a spawner entity setup with all needed components + center_point = math.Vector3(512.0, 512.0, 32.0) + asset_path = os.path.join("Slices", "PinkFlower.dynamicslice") + spawner_entity = dynveg.create_vegetation_area("Instance Spawner", center_point, 16.0, 16.0, 32.0, asset_path) - # Add Vegetation Slope Alignment Modifier to the spawner entity - spawner_entity.add_component("Vegetation Slope Alignment Modifier") + # Create a sloped mesh surface for the instances to plant on + center_point = math.Vector3(502.0, 512.0, 24.0) + mesh_asset_path = os.path.join("objects", "_primitives", "_box_1x1.azmodel") + mesh_asset = asset.AssetCatalogRequestBus(bus.Broadcast, "GetAssetIdByPath", mesh_asset_path, math.Uuid(), + False) + rotation = math.Vector3(0.0, radians(45.0), 0.0) + surface_entity = hydra.Entity("Surface Entity") + surface_entity.create_entity( + center_point, + ["Mesh", "Mesh Surface Tag Emitter"] + ) + Report.critical_result(Tests.surface_entity_created, surface_entity.id.IsValid()) + hydra.get_set_test(surface_entity, 0, "Controller|Configuration|Mesh Asset", mesh_asset) + components.TransformBus(bus.Event, "SetLocalRotation", surface_entity.id, rotation) + components.TransformBus(bus.Event, "SetLocalUniformScale", surface_entity.id, 30.0) - # Set Alignment Coefficient Min/Max to 1 on the Slope Alignment Modifier - spawner_entity.get_set_test(3, "Configuration|Alignment Coefficient Min", 1.0) - spawner_entity.get_set_test(3, "Configuration|Alignment Coefficient Max", 1.0) + # Add a Vegetation Debugger component to allow refreshing instances + hydra.add_level_component("Vegetation Debugger") - # Create new child entity with a Constant Gradient - child_vegetation_id = editor.ToolsApplicationRequestBus(bus.Broadcast, "CreateNewEntity", spawner_entity.id) - child_vegetation = hydra.Entity("Child Vegetation Entity", child_vegetation_id) - components_to_add = ["Constant Gradient"] - child_vegetation.components = [] - for component in components_to_add: - child_vegetation.components.append(hydra.add_component(component, child_vegetation_id)) + # Add Vegetation Slope Alignment Modifier to the spawner entity + spawner_entity.add_component("Vegetation Slope Alignment Modifier") - # Reference the Constant Gradient on the Slope Alignment Modifier component - spawner_entity.get_set_test(3, "Configuration|Gradient|Gradient Entity Id", child_vegetation_id) + # Set Alignment Coefficient Min/Max to 1 on the Slope Alignment Modifier + spawner_entity.get_set_test(3, "Configuration|Alignment Coefficient Min", 1.0) + spawner_entity.get_set_test(3, "Configuration|Alignment Coefficient Max", 1.0) - # Verify instances are have planted and are aligned to slope as expected - num_expected = 20 * 20 - self.test_success = self.test_success and self.wait_for_condition( - lambda: dynveg.validate_instance_count_in_entity_shape(spawner_entity.id, num_expected), 5.0) + # Create new child entity with a Constant Gradient + child_vegetation_id = editor.ToolsApplicationRequestBus(bus.Broadcast, "CreateNewEntity", spawner_entity.id) + child_vegetation = hydra.Entity("Child Vegetation Entity", child_vegetation_id) + components_to_add = ["Constant Gradient"] + child_vegetation.components = [] + for component in components_to_add: + child_vegetation.components.append(hydra.add_component(component, child_vegetation_id)) - box = azlmbr.shape.ShapeComponentRequestsBus(bus.Event, 'GetEncompassingAabb', spawner_entity.id) - instances = areasystem.AreaSystemRequestBus(bus.Broadcast, 'GetInstancesInAabb', box) + # Reference the Constant Gradient on the Slope Alignment Modifier component + spawner_entity.get_set_test(3, "Configuration|Gradient|Gradient Entity Id", child_vegetation_id) - if self.test_success and num_expected == len(instances): - for instance in instances: - self.test_success = verify_proper_alignment(instance, math.Vector3(0.0, 45.0, 0.0)) and \ - self.test_success + # Verify instances are have planted and are aligned to slope as expected + num_expected = 20 * 20 + instances_planted = helper.wait_for_condition( + lambda: dynveg.validate_instance_count_in_entity_shape(spawner_entity.id, num_expected), 5.0) + Report.critical_result(Tests.instance_count, instances_planted) - # Change Min/Max to 0.0 and verify proper alignment - spawner_entity.get_set_test(3, "Configuration|Alignment Coefficient Min", 0.0) - spawner_entity.get_set_test(3, "Configuration|Alignment Coefficient Max", 0.0) - general.run_console('veg_debugClearAllAreas') - self.test_success = self.test_success and self.wait_for_condition( - lambda: dynveg.validate_instance_count_in_entity_shape(spawner_entity.id, num_expected), 5.0) + box = azlmbr.shape.ShapeComponentRequestsBus(bus.Event, 'GetEncompassingAabb', spawner_entity.id) + instances = areasystem.AreaSystemRequestBus(bus.Broadcast, 'GetInstancesInAabb', box) - box = azlmbr.shape.ShapeComponentRequestsBus(bus.Event, 'GetEncompassingAabb', spawner_entity.id) - instances = areasystem.AreaSystemRequestBus(bus.Broadcast, 'GetInstancesInAabb', box) + success = True + for instance in instances: + success = verify_proper_alignment(instance, math.Vector3(0.0, 45.0, 0.0)) + Report.result(Tests.instances_aligned_1, success) - if self.test_success and num_expected == len(instances): - for instance in instances: - self.test_success = verify_proper_alignment(instance, math.Vector3(0.0, 0.0, 0.0)) and self.test_success + # Change Min/Max to 0.0 and verify proper alignment + spawner_entity.get_set_test(3, "Configuration|Alignment Coefficient Min", 0.0) + spawner_entity.get_set_test(3, "Configuration|Alignment Coefficient Max", 0.0) + general.run_console('veg_debugClearAllAreas') + instances_planted = helper.wait_for_condition( + lambda: dynveg.validate_instance_count_in_entity_shape(spawner_entity.id, num_expected), 5.0) + Report.critical_result(Tests.instance_count, instances_planted) + + box = azlmbr.shape.ShapeComponentRequestsBus(bus.Event, 'GetEncompassingAabb', spawner_entity.id) + instances = areasystem.AreaSystemRequestBus(bus.Broadcast, 'GetInstancesInAabb', box) + + success = True + for instance in instances: + success = verify_proper_alignment(instance, math.Vector3(0.0, 0.0, 0.0)) + Report.result(Tests.instances_aligned_0, success) -test = TestSlopeAlignmentModifier() -test.run() +if __name__ == "__main__": + + from editor_python_test_tools.utils import Report + Report.start_test(SlopeAlignmentModifier_InstanceSurfaceAlignment) diff --git a/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/SlopeFilter_ComponentAndOverrides_InstancesPlantOnValidSlope.py b/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/SlopeFilter_ComponentAndOverrides_InstancesPlantOnValidSlope.py index d66716cee3..ee0851d552 100755 --- a/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/SlopeFilter_ComponentAndOverrides_InstancesPlantOnValidSlope.py +++ b/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/SlopeFilter_ComponentAndOverrides_InstancesPlantOnValidSlope.py @@ -5,121 +5,122 @@ For complete copyright and license terms please see the LICENSE at the root of t SPDX-License-Identifier: Apache-2.0 OR MIT """ -""" -C4874096 - Slope Min/Max properties can be set, and properly affect planted vegetation -C4814464 - Slope Filter overrides function as expected -""" -import os -import sys - -import azlmbr.bus as bus -import azlmbr.editor as editor -import azlmbr.legacy.general as general -import azlmbr.math as math -import azlmbr.paths - -sys.path.append(os.path.join(azlmbr.paths.devroot, "AutomatedTesting", "Gem", "PythonTests")) -import editor_python_test_tools.hydra_editor_utils as hydra -from editor_python_test_tools.editor_test_helper import EditorTestHelper -from largeworlds.large_worlds_utils import editor_dynveg_test_helper as dynveg +class Tests: + prefilter_instance_count = ( + "Found the expected number of instances before applying the Slope Filter", + "Found an unexpected number of instances before applying the Slope Filter" + ) + postfilter_instance_count = ( + "Found the expected number of instances after applying the Slope Filter", + "Found an unexpected number of instances after applying the Slope Filter" + ) + postfilter_overrides_instance_count = ( + "Found the expected number of instances after applying descriptor overrides to the Slope Filter", + "Found an unexpected number of instances after applying descriptor overrides to the Slope Filter" + ) -class TestSlopeFilterComponentAndOverrides(EditorTestHelper): - def __init__(self): - EditorTestHelper.__init__(self, log_prefix="SlopeFilter_InstancesPlantOnValidSlope", args=["level"]) +def SlopeFilter_ComponentAndOverrides_InstancesPlantOnValidSlopes(): + """ + Summary: + An existing level is opened. A spawner entity is added, along with a flat planting surface at 32 on Z, and sphere + mesh at 38 on Z to provide a sloped surface. A Slope Filter is added to the spawner entity, and Slope Min/Max + values are set. Instance counts are validated. The same test is then performed for Slope Filter overrides. - def run_test(self): - """ - Summary: - A new level is created. A spawner entity is added, along with a flat planting surface at 32 on Z, and sphere - mesh at 38 on Z to provide a sloped surface. A Slope Filter is added to the spawner entity, and Slope Min/Max - values are set. Instance counts are validated. The same test is then performed for Slope Filter overrides. + Expected Behavior: + Instances plant only on surfaces that fall between the Slope Filter Min/Max settings - Expected Behavior: - Instances plant only on surfaces that fall between the Slope Filter Min/Max settings + Test Steps: + 1) Open an existing level + 2) Create an instance spawner entity + 3) Create surfaces to plant on, one at 32 on Z and another sloped surface at 38 on Z. + 4) Initial instance counts pre-filter are verified. + 5) Slope Min/Max values are set on the Slope Filter component + 6) Instance counts are validated + 7) Setup for overrides tests + 8) Slope Min/Max values are set on the descriptor overrides + 9) Instance counts are validated - Test Steps: - 1) Create a new level - 2) Create an instance spawner entity - 3) Create surfaces to plant on, one at 32 on Z and another sloped surface at 38 on Z. - 4) Initial instance counts pre-filter are verified. - 5) Slope Min/Max values are set on the Slope Filter component - 6) Instance counts are validated - 7) Setup for overrides tests - 8) Slope Min/Max values are set on the descriptor overrides - 9) Instance counts are validated + 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. - 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 + """ - :return: None - """ + import os - # 1) Create a new, temporary level - self.test_success = self.create_level( - self.args["level"], - heightmap_resolution=1024, - heightmap_meters_per_pixel=1, - terrain_texture_resolution=4096, - use_terrain=False, - ) + import azlmbr.bus as bus + import azlmbr.editor as editor + import azlmbr.legacy.general as general + import azlmbr.math as math - # Set view of planting area for visual debugging - general.set_current_view_position(512.0, 475.0, 38.0) + import editor_python_test_tools.hydra_editor_utils as hydra + from largeworlds.large_worlds_utils import editor_dynveg_test_helper as dynveg + from editor_python_test_tools.utils import Report + from editor_python_test_tools.utils import TestHelper as helper - # 2) Create a new entity with required vegetation area components - center_point = math.Vector3(512.0, 512.0, 32.0) - asset_path = os.path.join("Slices", "PinkFlower.dynamicslice") - spawner_entity = dynveg.create_vegetation_area("Instance Spawner", center_point, 32.0, 32.0, 32.0, asset_path) + # 1) Open an existing simple level + helper.init_idle() + helper.open_level("Physics", "Base") - # Add a Vegetation Slope Filter - spawner_entity.add_component("Vegetation Slope Filter") + # Set view of planting area for visual debugging + general.set_current_view_position(512.0, 475.0, 38.0) - # 3) Add surfaces to plant on. This will include a flat surface and a sphere mesh to provide a sloped surface - dynveg.create_surface_entity("Planting Surface", center_point, 32.0, 32.0, 1.0) - sloped_surface_center = math.Vector3(512.0, 512.0, 38.0) - dynveg.create_mesh_surface_entity_with_slopes("Sloped Planting Surface", sloped_surface_center, 10.0) + # 2) Create a new entity with required vegetation area components + center_point = math.Vector3(512.0, 512.0, 32.0) + asset_path = os.path.join("Slices", "PinkFlower.dynamicslice") + spawner_entity = dynveg.create_vegetation_area("Instance Spawner", center_point, 32.0, 32.0, 32.0, asset_path) - # Set instances to spawn on a center snap point to avoid unexpected instances around the edges of the box shape - veg_system_settings_component = hydra.add_level_component("Vegetation System Settings") - editor.EditorComponentAPIBus(bus.Broadcast, "SetComponentProperty", veg_system_settings_component, - 'Configuration|Area System Settings|Sector Point Snap Mode', 1) + # Add a Vegetation Slope Filter + spawner_entity.add_component("Vegetation Slope Filter") - # 4) Validate instance counts pre-filter - num_expected_flat_surface = 40 * 40 # 20x20 instances per 16m - num_expected_slopes_pre_filter = 120 # Unfiltered planting on the top of the sphere mesh - num_expected = num_expected_flat_surface + num_expected_slopes_pre_filter - initial_success = self.wait_for_condition(lambda: dynveg.validate_instance_count_in_entity_shape( - spawner_entity.id, num_expected), 5.0) - self.test_success = initial_success and self.test_success + # 3) Add surfaces to plant on. This will include a flat surface and a sphere mesh to provide a sloped surface + dynveg.create_surface_entity("Planting Surface", center_point, 32.0, 32.0, 1.0) + sloped_surface_center = math.Vector3(512.0, 512.0, 38.0) + dynveg.create_mesh_surface_entity_with_slopes("Sloped Planting Surface", sloped_surface_center, 10.0) - # 5) Change Slope Min/Max on the Vegetation Slope Filter component - spawner_entity.get_set_test(3, "Configuration|Slope Min", 20) - spawner_entity.get_set_test(3, "Configuration|Slope Max", 45) + # Set instances to spawn on a center snap point to avoid unexpected instances around the edges of the box shape + veg_system_settings_component = hydra.add_level_component("Vegetation System Settings") + editor.EditorComponentAPIBus(bus.Broadcast, "SetComponentProperty", veg_system_settings_component, + 'Configuration|Area System Settings|Sector Point Snap Mode', 1) - # 6) Validate instance counts post-filter: instances should only plant on slopes between 20-45 degrees - num_expected_slopes_post_filter = 48 - slope_min_max_success = self.wait_for_condition(lambda: dynveg.validate_instance_count_in_entity_shape( - spawner_entity.id, num_expected_slopes_post_filter), 5.0) - self.test_success = slope_min_max_success and self.test_success + # 4) Validate instance counts pre-filter + num_expected_flat_surface = 40 * 40 # 20x20 instances per 16m + num_expected_slopes_pre_filter = 120 # Unfiltered planting on the top of the sphere mesh + num_expected = num_expected_flat_surface + num_expected_slopes_pre_filter + initial_success = helper.wait_for_condition(lambda: dynveg.validate_instance_count_in_entity_shape( + spawner_entity.id, num_expected), 5.0) + Report.result(Tests.prefilter_instance_count, initial_success) - # 7) Setup for overrides on the Slope Filter component and the spawner entity's descriptor - spawner_entity.get_set_test(3, "Configuration|Allow Per-Item Overrides", True) - spawner_entity.get_set_test(2, "Configuration|Embedded Assets|[0]|Slope Filter|Override Enabled", True) + # 5) Change Slope Min/Max on the Vegetation Slope Filter component + spawner_entity.get_set_test(3, "Configuration|Slope Min", 20) + spawner_entity.get_set_test(3, "Configuration|Slope Max", 45) - # 8) Set Slope Filter Min/Max overrides on the spawner entity's descriptor - spawner_entity.get_set_test(2, "Configuration|Embedded Assets|[0]|Slope Filter|Min", 5) - spawner_entity.get_set_test(2, "Configuration|Embedded Assets|[0]|Slope Filter|Max", 20) + # 6) Validate instance counts post-filter: instances should only plant on slopes between 20-45 degrees + num_expected_slopes_post_filter = 48 + slope_min_max_success = helper.wait_for_condition(lambda: dynveg.validate_instance_count_in_entity_shape( + spawner_entity.id, num_expected_slopes_post_filter), 5.0) + Report.result(Tests.postfilter_instance_count, slope_min_max_success) - # 9) Validate instance counts post-filter: instances should only plant on slopes between 5-20 degrees - num_expected_slopes_post_filter_overrides = 12 - overrides_min_max_success = self.wait_for_condition(lambda: dynveg.validate_instance_count_in_entity_shape( - spawner_entity.id, num_expected_slopes_post_filter_overrides), 5.0) - self.test_success = overrides_min_max_success and self.test_success + # 7) Setup for overrides on the Slope Filter component and the spawner entity's descriptor + spawner_entity.get_set_test(3, "Configuration|Allow Per-Item Overrides", True) + spawner_entity.get_set_test(2, "Configuration|Embedded Assets|[0]|Slope Filter|Override Enabled", True) + + # 8) Set Slope Filter Min/Max overrides on the spawner entity's descriptor + spawner_entity.get_set_test(2, "Configuration|Embedded Assets|[0]|Slope Filter|Min", 5) + spawner_entity.get_set_test(2, "Configuration|Embedded Assets|[0]|Slope Filter|Max", 20) + + # 9) Validate instance counts post-filter: instances should only plant on slopes between 5-20 degrees + num_expected_slopes_post_filter_overrides = 12 + overrides_min_max_success = helper.wait_for_condition(lambda: dynveg.validate_instance_count_in_entity_shape( + spawner_entity.id, num_expected_slopes_post_filter_overrides), 5.0) + Report.result(Tests.postfilter_overrides_instance_count, overrides_min_max_success) -test = TestSlopeFilterComponentAndOverrides() -test.run() +if __name__ == "__main__": + + from editor_python_test_tools.utils import Report + Report.start_test(SlopeFilter_ComponentAndOverrides_InstancesPlantOnValidSlopes) diff --git a/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/SlopeFilter_FilterStageToggle.py b/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/SlopeFilter_FilterStageToggle.py deleted file mode 100755 index 33275f2992..0000000000 --- a/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/SlopeFilter_FilterStageToggle.py +++ /dev/null @@ -1,103 +0,0 @@ -""" -Copyright (c) Contributors to the Open 3D Engine Project. -For complete copyright and license terms please see the LICENSE at the root of this distribution. - -SPDX-License-Identifier: Apache-2.0 OR MIT -""" - -import os -import sys -import azlmbr.math as math -import azlmbr.bus as bus -import azlmbr.paths -import azlmbr.editor as editor -import azlmbr.entity as EntityId -import azlmbr.components as components -import azlmbr.legacy.general as general - -sys.path.append(os.path.join(azlmbr.paths.devroot, "AutomatedTesting", "Gem", "PythonTests")) -import editor_python_test_tools.hydra_editor_utils as hydra -from editor_python_test_tools.editor_test_helper import EditorTestHelper -from largeworlds.large_worlds_utils import editor_dynveg_test_helper as dynveg - -class TestSlopeFilterFilterStageToggle(EditorTestHelper): - def __init__(self): - EditorTestHelper.__init__(self, log_prefix="SlopeFilter_FilterStageToggle", args=["level"]) - - def run_test(self): - """ - Summary: - Filter Stage toggle affects final vegetation position - - Expected Result: - Vegetation instances plant differently depending on the Filter Stage setting. With PreProcess, some vegetation instances can - appear on slopes outside the filtered values. With PostProcess, vegetation instances only appear on the correct slope values. - - :return: None - """ - - # Create empty level - self.test_success = self.create_level( - self.args["level"], - heightmap_resolution=1024, - heightmap_meters_per_pixel=1, - terrain_texture_resolution=4096, - use_terrain=False, - ) - - general.set_current_view_position(512.0, 480.0, 38.0) - - # Create basic vegetation entity - position = math.Vector3(512.0, 512.0, 32.0) - asset_path = os.path.join("Slices", "PinkFlower.dynamicslice") - vegetation = dynveg.create_vegetation_area("vegetation", position, 16.0, 16.0, 16.0, asset_path) - - # Create Surface for instances to plant on - dynveg.create_surface_entity("Surface_Entity_Parent", position, 16.0, 16.0, 1.0) - - # Add a Vegetation Shape Intersection Filter to the vegetation area entity - vegetation.add_component("Vegetation Shape Intersection Filter") - - # Create a new entity as a child of the vegetation area entity with Box Shape - box = hydra.Entity("box") - box.create_entity(position, ["Box Shape"]) - box.get_set_test(0, "Box Shape|Box Configuration|Dimensions", math.Vector3(8.0, 8.0, 1.0)) - - # Create a new entity as a child of the vegetation area entity with Cylinder Shape. - cylinder = hydra.Entity("cylinder") - cylinder.create_entity(position, ["Cylinder Shape"]) - cylinder.get_set_test(0, "Cylinder Shape|Cylinder Configuration|Radius", 5.0) - cylinder.get_set_test(0, "Cylinder Shape|Cylinder Configuration|Height", 5.0) - box.set_test_parent_entity(vegetation) - cylinder.set_test_parent_entity(vegetation) - - # # On the Vegetation Shape Intersection Filter component, click the crosshair button, and add child entities one by one - vegetation.get_set_test(3, "Configuration|Shape Entity Id", box.id) - result = self.wait_for_condition(lambda: dynveg.validate_instance_count(position, 8.0, 100), 2.0) - self.log(f"Vegetation plant only in the areas where the Box overlaps with the vegetation area's boundaries: {result}") - vegetation.get_set_test(3, "Configuration|Shape Entity Id", cylinder.id) - result = self.wait_for_condition(lambda: dynveg.validate_instance_count(position, 5.0, 100), 2.0) - self.log(f"Vegetation plant only in the areas where the Cylinder overlaps with the vegetation area's boundaries: {result}") - - # Create a new entity as a child of the vegetation area entity with Random Noise Gradient Generator, Gradient Transform Modifier, - # and Box Shape component - random_noise = hydra.Entity("random_noise") - random_noise.create_entity(position, ["Random Noise Gradient", "Gradient Transform Modifier", "Box Shape"]) - random_noise.set_test_parent_entity(vegetation) - - # Add a Vegetation Position Modifier to the vegetation area entity - vegetation.add_component("Vegetation Position Modifier") - - # Pin the Random Noise entity to the Gradient Entity Id field of the Position Modifier's Gradient X - vegetation.get_set_test(4, "Configuration|Position X|Gradient|Gradient Entity Id", random_noise.id) - - # Toggle between PreProcess and PostProcess - vegetation.get_set_test(3, "Configuration|Filter Stage", 1) - result = self.wait_for_condition(lambda: dynveg.validate_instance_count(position, 5.0, 117), 2.0) - self.log(f"Vegetation instances count equal to expected value for PREPROCESS filter stage: {result}") - vegetation.get_set_test(3, "Configuration|Filter Stage", 2) - result = self.wait_for_condition(lambda: dynveg.validate_instance_count(position, 5.0, 122), 2.0) - self.log(f"Vegetation instances count equal to expected value for POSTPROCESS filter stage: {result}") - -test = TestSlopeFilterFilterStageToggle() -test.run() \ No newline at end of file diff --git a/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/SpawnerSlices_SliceCreationAndVisibilityToggleWorks.py b/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/SpawnerSlices_SliceCreationAndVisibilityToggleWorks.py new file mode 100644 index 0000000000..1658ffc532 --- /dev/null +++ b/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/SpawnerSlices_SliceCreationAndVisibilityToggleWorks.py @@ -0,0 +1,126 @@ +""" +Copyright (c) Contributors to the Open 3D Engine Project. +For complete copyright and license terms please see the LICENSE at the root of this distribution. + +SPDX-License-Identifier: Apache-2.0 OR MIT +""" + + +class Tests: + spawner_slice_created = ( + "Spawner slice created successfully", + "Failed to create Spawner slice" + ) + instance_count_unhidden = ( + "Initial instance counts are as expected", + "Found an unexpected number of initial instances" + ) + instance_count_hidden = ( + "Instance counts upon hiding the Spawner slice are as expected", + "Unexpectedly found instances with the Spawner slice hidden" + ) + blender_slice_created = ( + "Blender slice created successfully", + "Failed to create Blender slice" + ) + + +def SpawnerSlices_SliceCreationAndVisibilityToggleWorks(): + """ + Summary: + C2627900 Verifies if a slice containing the component can be created. + C2627905 A slice containing the Vegetation Layer Blender component can be created. + C2627904: Hiding a slice containing the component clears any visuals from the Viewport. + + Expected Result: + C2627900, C2627905: Slice is created, and is properly processed in the Asset Processor. + C2627904: Vegetation area visuals are hidden from the Viewport. + + :return: None + """ + + import os + + import azlmbr.math as math + import azlmbr.legacy.general as general + import azlmbr.slice as slice + import azlmbr.bus as bus + import azlmbr.editor as editor + import azlmbr.asset as asset + + import editor_python_test_tools.hydra_editor_utils as hydra + from largeworlds.large_worlds_utils import editor_dynveg_test_helper as dynveg + from editor_python_test_tools.utils import Report + from editor_python_test_tools.utils import TestHelper as helper + + def path_is_valid_asset(asset_path): + asset_id = asset.AssetCatalogRequestBus(bus.Broadcast, "GetAssetIdByPath", asset_path, math.Uuid(), False) + return asset_id.invoke("IsValid") + + # 1) Open an existing simple level + helper.init_idle() + helper.open_level("Physics", "Base") + general.set_current_view_position(512.0, 480.0, 38.0) + + # 2) C2627900 Verifies if a slice containing the Vegetation Layer Spawner component can be created. + # 2.1) Create basic vegetation entity + position = math.Vector3(512.0, 512.0, 32.0) + asset_path = os.path.join("Slices", "PinkFlower.dynamicslice") + veg_1 = dynveg.create_vegetation_area("vegetation_1", position, 16.0, 16.0, 16.0, asset_path) + + # 2.2) Create slice from the entity + slice_path = os.path.join("slices", "TestSlice_1.slice") + slice.SliceRequestBus(bus.Broadcast, "CreateNewSlice", veg_1.id, slice_path) + + # 2.3) Verify if the slice has been created successfully + spawner_slice_success = helper.wait_for_condition(lambda: path_is_valid_asset(slice_path), 5.0) + Report.result(Tests.spawner_slice_created, spawner_slice_success) + + # 3) C2627904: Hiding a slice containing the component clears any visuals from the Viewport + # 3.1) Create Surface for instances to plant on + dynveg.create_surface_entity("Surface_Entity", position, 16.0, 16.0, 1.0) + + # 3.2) Initially verify instance count before hiding slice + initial_count_success = helper.wait_for_condition(lambda: dynveg.validate_instance_count(position, 16.0, 400), 5.0) + Report.result(Tests.instance_count_unhidden, initial_count_success) + + # 3.3) Hide the slice and verify instance count + editor.EditorEntityAPIBus(bus.Event, "SetVisibilityState", veg_1.id, False) + hidden_instance_count = helper.wait_for_condition(lambda: dynveg.validate_instance_count(position, 16.0, 0), 5.0) + Report.result(Tests.instance_count_hidden, hidden_instance_count) + + # 3.4) Unhide the slice + editor.EditorEntityAPIBus(bus.Event, "SetVisibilityState", veg_1.id, True) + + # 4) C2627905 A slice containing the Vegetation Layer Blender component can be created. + # 4.1) Create another vegetation entity to add to blender component + veg_2 = dynveg.create_vegetation_area("vegetation_2", position, 1.0, 1.0, 1.0, "") + + # 4.2) Create entity with Vegetation Layer Blender + components_to_add = ["Box Shape", "Vegetation Layer Blender"] + blender_entity = hydra.Entity("blender_entity") + blender_entity.create_entity(position, components_to_add) + + # 4.3) Pin both the vegetation areas to the blender entity + pte = hydra.get_property_tree(blender_entity.components[1]) + path = "Configuration|Vegetation Areas" + pte.update_container_item(path, 0, veg_1.id) + pte.add_container_item(path, 1, veg_2.id) + + # 4.4) Drag the simple vegetation areas under the Vegetation Layer Blender entity to create an entity hierarchy. + veg_1.set_test_parent_entity(blender_entity) + veg_2.set_test_parent_entity(blender_entity) + + # 4.5) Create slice from blender entity + slice_path = os.path.join("slices", "TestSlice_2.slice") + slice.SliceRequestBus(bus.Broadcast, "CreateNewSlice", blender_entity.id, slice_path) + + # 4.6) Verify if the slice has been created successfully + blender_slice_success = helper.wait_for_condition(lambda: path_is_valid_asset(slice_path), 5.0) + Report.result(Tests.blender_slice_created, blender_slice_success) + + +if __name__ == "__main__": + + from editor_python_test_tools.utils import Report + Report.start_test(SpawnerSlices_SliceCreationAndVisibilityToggleWorks) diff --git a/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/SurfaceDataRefreshes_RemainsStable.py b/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/SurfaceDataRefreshes_RemainsStable.py index 2f08d3963d..1ad4f305c3 100755 --- a/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/SurfaceDataRefreshes_RemainsStable.py +++ b/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/SurfaceDataRefreshes_RemainsStable.py @@ -5,99 +5,97 @@ For complete copyright and license terms please see the LICENSE at the root of t SPDX-License-Identifier: Apache-2.0 OR MIT """ -import os -import sys -sys.path.append(os.path.dirname(os.path.abspath(__file__))) -import azlmbr.legacy.general as general -import azlmbr.math as math +class Tests: + editor_remains_stable = ( + "Editor did not crash following rapid surface data updates", + "Editor crashed" + ) -sys.path.append(os.path.join(azlmbr.paths.devroot, 'AutomatedTesting', 'Gem', 'PythonTests')) -from editor_python_test_tools.editor_test_helper import EditorTestHelper -from largeworlds.large_worlds_utils import editor_dynveg_test_helper as dynveg +def SurfaceDataRefreshes_RemainsStable(): + """ + Summary: + The Vegetation Area System can intermittently crash when updating surface data and moving the camera + around rapidly. The situation occurs across multiple frames - the surface data updates, which triggers a bunch + of sector updates getting added to the update queue. Then in a subsequent frame, there is no active vegetation + area or surface data updates, which triggers "delete all sectors". The "delete all" wasn't deleting entries from + the update queue, so any unprocessed updates would continue to get processed. If any of those updates referenced + a sector that no longer exists, because the camera changed position, then it would assert and crash. + + To repro this bug, this test loads an empty level with a large box shape emitting a surface, and then runs a tight + loop of camera movements and "surface changed" events that invalidate all surface points. Because this is a timing + issue, there's no guarantee that the test below will successfully cause the condition to occur, but it successfully + crashed every time it was tested locally prior to the bugfix. + + :return: None + """ + + import azlmbr.legacy.general as general + import azlmbr.math as math + + from largeworlds.large_worlds_utils import editor_dynveg_test_helper as dynveg + from editor_python_test_tools.utils import Report + from editor_python_test_tools.utils import TestHelper as helper + + # 1) Open an existing simple level + helper.init_idle() + helper.open_level("Physics", "Base") + + world_center = math.Vector3(512.0, 512.0, 32.0) + + # Add an entity with a 1024 x 1024 box centered at 512,512. + surface_entity = dynveg.create_surface_entity("Surface Data", world_center, 1024.0, 1024.0, 1.0) + + # Move the camera to the world center + general.set_current_view_position(world_center.x, world_center.y, world_center.z) + + # 2) Perform the test. Since the conditions are extremely timing related, and every machine + # running the test can have different timing conditions, we run through a set of different + # combinations to try and cause the crash under as many scenarios as possible + + loops_per_surface_changed = [3, 5, 5] + loops_per_camera_reset = [20, 20, 20] + camera_speed_per_loop = [10.0, 10.0, 15.0] + + # Setting test success to false to make sure the toggle at the end accurately conveys the loop being successful + test_success = False + + # Loop through all our attempted timing test cases to cause the crash pretty consistently. + for test_case in range(0,3): + Report.info(f'Starting test case {test_case}') + Report.info(f'Loops per surface changed: {loops_per_surface_changed[test_case]}') + Report.info(f'Loops per camera reset: {loops_per_camera_reset[test_case]}') + Report.info(f'Camera speed per loop: {camera_speed_per_loop[test_case]}') + for test_counter in range(0, 100): + + # Every N loops, invalidate the entire set of surface data. It's mostly just important for this + # not to happen *every* iteration, since we need the vegetation system to bounce between having + # dirty surface points that cause sectors to be refreshed, and having no dirty surface points or + # active surface areas to trigger a "delete all sectors" condition. + if (test_counter % loops_per_surface_changed[test_case]) == 0: + azlmbr.surface_data.SurfaceDataSystemNotificationBus(azlmbr.bus.Broadcast, + 'OnSurfaceChanged', + surface_entity.id, + azlmbr.math.Aabb(), + azlmbr.math.Aabb()) + + # Move the camera back and forth along the X axis at just the right speed to invalidate sectors that are + # queued for updating but haven't updated yet, so that when they try to update they crash. + x_pos = world_center.x + ((test_counter % loops_per_camera_reset[test_case]) * camera_speed_per_loop[test_case]) + general.set_current_view_position(x_pos, world_center.y, world_center.z) + + Report.info(f'{test_counter}: {x_pos}') + + # Give a little processing time each iteration. + general.idle_wait(0.01) + + # If we haven't crashed, then we've succeeded. + test_success = True + Report.result(Tests.editor_remains_stable, test_success) -class TestSurfaceDataRefreshes_RemainsStable(EditorTestHelper): - def __init__(self): - EditorTestHelper.__init__(self, log_prefix="SurfaceDataRefreshes_RemainsStable", args=["level"]) +if __name__ == "__main__": - def run_test(self): - """ - Summary: - The Vegetation Area System can intermittently crash when updating surface data and moving the camera - around rapidly. The situation occurs across multiple frames - the surface data updates, which triggers a bunch - of sector updates getting added to the update queue. Then in a subsequent frame, there is no active vegetation - area or surface data updates, which triggers "delete all sectors". The "delete all" wasn't deleting entries from - the update queue, so any unprocessed updates would continue to get processed. If any of those updates referenced - a sector that no longer exists, because the camera changed position, then it would assert and crash. - - To repro this bug, this test creates an empty level with a large box shape emitting a surface, and then runs a tight - loop of camera movements and "surface changed" events that invalidate all surface points. Because this is a timing - issue, there's no guarantee that the test below will successfully cause the condition to occur, but it successfully - crashed every time it was tested locally prior to the bugfix. - - :return: None - """ - # 1) Create a test level with the needed test setup - self.test_success = self.create_level( - self.get_arg('level'), - heightmap_resolution=128, - heightmap_meters_per_pixel=1, - terrain_texture_resolution=128, - use_terrain=False) - - world_center = math.Vector3(512.0, 512.0, 32.0) - - # Add an entity with a 1024 x 1024 box centered at 512,512. - surface_entity = dynveg.create_surface_entity("Surface Data", world_center, 1024.0, 1024.0, 1.0) - - # Move the camera to the world center - general.set_current_view_position(world_center.x, world_center.y, world_center.z) - - # 2) Perform the test. Since the conditions are extremely timing related, and every machine - # running the test can have different timing conditions, we run through a set of different - # combinations to try and cause the crash under as many scenarios as possible - - loops_per_surface_changed = [3, 5, 5] - loops_per_camera_reset = [20, 20, 20] - camera_speed_per_loop = [10.0, 10.0, 15.0] - - # Setting test success to false to make sure the toggle at the end accurately conveys the loop being successful - self.test_success = False - - # Loop through all our attempted timing test cases to cause the crash pretty consistently. - for test_case in range(0,3): - self.log(f'Starting test case {test_case}') - self.log(f'Loops per surface changed: {loops_per_surface_changed[test_case]}') - self.log(f'Loops per camera reset: {loops_per_camera_reset[test_case]}') - self.log(f'Camera speed per loop: {camera_speed_per_loop[test_case]}') - for test_counter in range (0,100): - - # Every N loops, invalidate the entire set of surface data. It's mostly just important for this - # not to happen *every* iteration, since we need the vegetation system to bounce between having - # dirty surface points that cause sectors to be refreshed, and having no dirty surface points or - # active surface areas to trigger a "delete all sectors" condition. - if (test_counter % loops_per_surface_changed[test_case]) == 0: - azlmbr.surface_data.SurfaceDataSystemNotificationBus(azlmbr.bus.Broadcast, - 'OnSurfaceChanged', - surface_entity.id, - azlmbr.math.Aabb(), - azlmbr.math.Aabb()) - - # Move the camera back and forth along the X axis at just the right speed to invalidate sectors that are - # queued for updating but haven't updated yet, so that when they try to update they crash. - x_pos = world_center.x + ((test_counter % loops_per_camera_reset[test_case]) * camera_speed_per_loop[test_case]) - general.set_current_view_position(x_pos, world_center.y, world_center.z) - - self.log(f'{test_counter}: {x_pos}') - - # Give a little processing time each iteration. - general.idle_wait(0.01) - - # If we haven't crashed, then we've succeeded. - self.test_success = True - - -test = TestSurfaceDataRefreshes_RemainsStable() -test.run() + from editor_python_test_tools.utils import Report + Report.start_test(SurfaceDataRefreshes_RemainsStable) diff --git a/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/SurfaceMaskFilterOverrides_MultipleDescriptorOverridesPlantAsExpected.py b/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/SurfaceMaskFilterOverrides_MultipleDescriptorOverridesPlantAsExpected.py index 87aa7946b3..ba0f3e05e3 100755 --- a/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/SurfaceMaskFilterOverrides_MultipleDescriptorOverridesPlantAsExpected.py +++ b/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/SurfaceMaskFilterOverrides_MultipleDescriptorOverridesPlantAsExpected.py @@ -5,153 +5,160 @@ For complete copyright and license terms please see the LICENSE at the root of t SPDX-License-Identifier: Apache-2.0 OR MIT """ -""" -C3711666: Multiple Descriptors with different Surface Mask Filter overrides plant as expected. -""" -import os -import sys - -import azlmbr.legacy.general as general -import azlmbr.math as math -import azlmbr.paths -import azlmbr.surface_data as surface_data - -sys.path.append(os.path.join(azlmbr.paths.devroot, "AutomatedTesting", "Gem", "PythonTests")) -import editor_python_test_tools.hydra_editor_utils as hydra -from editor_python_test_tools.editor_test_helper import EditorTestHelper -from largeworlds.large_worlds_utils import editor_dynveg_test_helper as dynveg +class Tests: + initial_surface_validation = ( + "Found all expected instances on all surfaces with initial setup", + "Found an unexpected number of instances on all surfaces with initial setup" + ) + surface_a_validation = ( + "Found the expected number of instances on Surface A", + "Found an unexpected number of instances on Surface A" + ) + surface_b_validation = ( + "Found the expected number of instances on Surface B", + "Found an unexpected number of instances on Surface B" + ) + surface_c_validation = ( + "Found the expected number of instances on Surface C", + "Found an unexpected number of instances on Surface C" + ) -class TestSurfaceMaskFilterMultipleOverrides(EditorTestHelper): - def __init__(self): - EditorTestHelper.__init__(self, log_prefix="SurfaceMaskFilter_MultipleDescriptorOverrides", args=["level"]) +def SurfaceMaskFilterOverrides_MultipleDescriptorOverridesPlantAsExpected(): + """ + Summary: + A new level is created. An instance spawner with 3 descriptors is created. 3 planting surfaces of different + sizes are created and different surface tags are applied to each. Descriptor surface mask filter overrides are + set and instance counts are validated. - def run_test(self): - """ - Summary: - A new level is created. An instance spawner with 3 descriptors is created. 3 planting surfaces of different - sizes are created and different surface tags are applied to each. Descriptor surface mask filter overrides are - set and instance counts are validated. + Expected Behavior: + Instances plant on surfaces based on surface mask filter overrides. - Expected Behavior: - Instances plant on surfaces based on surface mask filter overrides. + Test Steps: + 1) Open an existing level + 2) An instance spawner with 3 descriptors is created, and a Surface Mask Filter is added to the entity + 3) 3 surfaces of different sizes are created, and set to emit different tags + 4) Pre-test validation of instances + 5) Test 1 setup and validation: Inclusion tag matching surface a is set on a single descriptor + 6) Test 2 setup and validation: Inclusion tag matching surface b is set on a single descriptor + 7) Test 3 setup and validation: Inclusion tag matching surface c is set on a single descriptor - Test Steps: - 1) A new level is created - 2) An instance spawner with 3 descriptors is created, and a Surface Mask Filter is added to the entity - 3) 3 surfaces of different sizes are created, and set to emit different tags - 4) Pre-test validation of instances - 5) Test 1 setup and validation: Inclusion tag matching surface a is set on a single descriptor - 6) Test 2 setup and validation: Inclusion tag matching surface b is set on a single descriptor - 7) Test 3 setup and validation: Inclusion tag matching surface c is set on a single descriptor + 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. - 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 + """ - :return: None - """ - surface_tag_list = [surface_data.SurfaceTag("test_tag"), surface_data.SurfaceTag("test_tag2"), - surface_data.SurfaceTag("test_tag3")] + import os - # 1) Create a new, temporary level - self.test_success = self.create_level( - self.args["level"], - heightmap_resolution=1024, - heightmap_meters_per_pixel=1, - terrain_texture_resolution=4096, - use_terrain=False, - ) + import azlmbr.legacy.general as general + import azlmbr.math as math + import azlmbr.surface_data as surface_data - # Set view of planting area for visual debugging - general.set_current_view_position(512.0, 500.0, 38.0) - general.set_current_view_rotation(-20.0, 0.0, 0.0) + import editor_python_test_tools.hydra_editor_utils as hydra + from largeworlds.large_worlds_utils import editor_dynveg_test_helper as dynveg + from editor_python_test_tools.utils import Report + from editor_python_test_tools.utils import TestHelper as helper - # 2) Create a new instance spawner entity with multiple Dynamic Slice Instance Spawner descriptors - spawner_center_point = math.Vector3(512.0, 512.0, 32.0) - asset_path = os.path.join("Slices", "PinkFlower.dynamicslice") - spawner_entity = dynveg.create_vegetation_area("Instance Spawner", spawner_center_point, 16.0, 16.0, 16.0, - asset_path) - asset_list_component = spawner_entity.components[2] - desc_asset = hydra.get_component_property_value(asset_list_component, - "Configuration|Embedded Assets")[0] - desc_list = [desc_asset, desc_asset, desc_asset] - spawner_entity.get_set_test(2, "Configuration|Embedded Assets", desc_list) - - # Add a Surface Mask Filter component to the spawner entity and toggle on Allow Overrides - spawner_entity.add_component("Vegetation Surface Mask Filter") - spawner_entity.get_set_test(3, "Configuration|Allow Per-Item Overrides", True) + surface_tag_list = [surface_data.SurfaceTag("test_tag"), surface_data.SurfaceTag("test_tag2"), + surface_data.SurfaceTag("test_tag3")] - # 3) Create 3 surfaces for planting, spaced out vertically, and set expected instance counts for each surface - surface_entity_a = dynveg.create_surface_entity("Surface Entity A", math.Vector3(512.0, 512.0, 32.0), - 16.0, 16.0, 1.0) - num_expected_surface_a = 20 * 20 # 20x20 instances on a 16x16 meter surface - surface_entity_b = dynveg.create_surface_entity("Surface Entity B", math.Vector3(512.0, 512.0, 35.0), - 12.0, 12.0, 1.0) - num_expected_surface_b = 15 * 15 # 15x15 instances on a 12x12 meter surface - surface_entity_c = dynveg.create_surface_entity("Surface Entity C", math.Vector3(512.0, 512.0, 38.0), - 8.0, 8.0, 1.0) - num_expected_surface_c = 10 * 10 # 10x10 instances on a 8x8 meter surface + # 1) Open an existing simple level + helper.init_idle() + helper.open_level("Physics", "Base") - # Set each surface to emit a different tag - surface_entity_a.get_set_test(1, "Configuration|Generated Tags", [surface_tag_list[0]]) - surface_entity_b.get_set_test(1, "Configuration|Generated Tags", [surface_tag_list[1]]) - surface_entity_c.get_set_test(1, "Configuration|Generated Tags", [surface_tag_list[2]]) + # Set view of planting area for visual debugging + general.set_current_view_position(512.0, 500.0, 38.0) + general.set_current_view_rotation(-20.0, 0.0, 0.0) - # 4) Initial Validation: Validate instance count in the spawner area. Instances should plant on all surfaces - num_expected = num_expected_surface_a + num_expected_surface_b + num_expected_surface_c - initial_success = self.wait_for_condition( - lambda: dynveg.validate_instance_count_in_entity_shape(spawner_entity.id, num_expected), 5.0) - self.test_success = initial_success and self.test_success + # 2) Create a new instance spawner entity with multiple Dynamic Slice Instance Spawner descriptors + spawner_center_point = math.Vector3(512.0, 512.0, 32.0) + asset_path = os.path.join("Slices", "PinkFlower.dynamicslice") + spawner_entity = dynveg.create_vegetation_area("Instance Spawner", spawner_center_point, 16.0, 16.0, 16.0, + asset_path) + asset_list_component = spawner_entity.components[2] + desc_asset = hydra.get_component_property_value(asset_list_component, + "Configuration|Embedded Assets")[0] + desc_list = [desc_asset, desc_asset, desc_asset] + spawner_entity.get_set_test(2, "Configuration|Embedded Assets", desc_list) - # 5) - # Test #1 Setup: Set test_tag to inclusion list for descriptor 1. Set other descriptors to exclude all surfaces + # Add a Surface Mask Filter component to the spawner entity and toggle on Allow Overrides + spawner_entity.add_component("Vegetation Surface Mask Filter") + spawner_entity.get_set_test(3, "Configuration|Allow Per-Item Overrides", True) - # Toggle on Display Per-Item Overrides and Surface Mask Filter Override for each descriptor - for index in range(3): - spawner_entity.get_set_test(2, f"Configuration|Embedded Assets|[{index}]|Display Per-Item Overrides", True) - spawner_entity.get_set_test(2, - f"Configuration|Embedded Assets|[{index}]|Surface Mask Filter|Override Mode", 1) + # 3) Create 3 surfaces for planting, spaced out vertically, and set expected instance counts for each surface + surface_entity_a = dynveg.create_surface_entity("Surface Entity A", math.Vector3(512.0, 512.0, 32.0), + 16.0, 16.0, 1.0) + num_expected_surface_a = 20 * 20 # 20x20 instances on a 16x16 meter surface + surface_entity_b = dynveg.create_surface_entity("Surface Entity B", math.Vector3(512.0, 512.0, 35.0), + 12.0, 12.0, 1.0) + num_expected_surface_b = 15 * 15 # 15x15 instances on a 12x12 meter surface + surface_entity_c = dynveg.create_surface_entity("Surface Entity C", math.Vector3(512.0, 512.0, 38.0), + 8.0, 8.0, 1.0) + num_expected_surface_c = 10 * 10 # 10x10 instances on a 8x8 meter surface + # Set each surface to emit a different tag + surface_entity_a.get_set_test(1, "Configuration|Generated Tags", [surface_tag_list[0]]) + surface_entity_b.get_set_test(1, "Configuration|Generated Tags", [surface_tag_list[1]]) + surface_entity_c.get_set_test(1, "Configuration|Generated Tags", [surface_tag_list[2]]) + + # 4) Initial Validation: Validate instance count in the spawner area. Instances should plant on all surfaces + num_expected = num_expected_surface_a + num_expected_surface_b + num_expected_surface_c + initial_success = helper.wait_for_condition( + lambda: dynveg.validate_instance_count_in_entity_shape(spawner_entity.id, num_expected), 5.0) + Report.result(Tests.initial_surface_validation, initial_success) + + # 5) + # Test #1 Setup: Set test_tag to inclusion list for descriptor 1. Set other descriptors to exclude all surfaces + + # Toggle on Display Per-Item Overrides and Surface Mask Filter Override for each descriptor + for index in range(3): + spawner_entity.get_set_test(2, f"Configuration|Embedded Assets|[{index}]|Display Per-Item Overrides", True) spawner_entity.get_set_test(2, - "Configuration|Embedded Assets|[0]|Surface Mask Filter|Inclusion Tags", - [surface_tag_list[0]]) - spawner_entity.get_set_test(2, - "Configuration|Embedded Assets|[1]|Surface Mask Filter|Exclusion Tags", - surface_tag_list) - spawner_entity.get_set_test(2, - "Configuration|Embedded Assets|[2]|Surface Mask Filter|Exclusion Tags", - surface_tag_list) + f"Configuration|Embedded Assets|[{index}]|Surface Mask Filter|Override Mode", 1) - # Test #1 Validation: Validate instance count. Should only plant on a single surface for 400 instances - test_1_success = self.wait_for_condition( - lambda: dynveg.validate_instance_count_in_entity_shape(spawner_entity.id, num_expected_surface_a), 5.0) - self.test_success = test_1_success and self.test_success + spawner_entity.get_set_test(2, + "Configuration|Embedded Assets|[0]|Surface Mask Filter|Inclusion Tags", + [surface_tag_list[0]]) + spawner_entity.get_set_test(2, + "Configuration|Embedded Assets|[1]|Surface Mask Filter|Exclusion Tags", + surface_tag_list) + spawner_entity.get_set_test(2, + "Configuration|Embedded Assets|[2]|Surface Mask Filter|Exclusion Tags", + surface_tag_list) - # 6) - # Test #2 Setup: Set test_tag2 to inclusion for descriptor 1. - spawner_entity.get_set_test(2, - "Configuration|Embedded Assets|[0]|Surface Mask Filter|Inclusion Tags", - [surface_tag_list[1]]) + # Test #1 Validation: Validate instance count. Should only plant on a single surface for 400 instances + test_1_success = helper.wait_for_condition( + lambda: dynveg.validate_instance_count_in_entity_shape(spawner_entity.id, num_expected_surface_a), 5.0) + Report.result(Tests.surface_a_validation, test_1_success) - # Test #2 Validation: Validate instance count. Should only plant on a single surface for 225 instances - test_2_success = self.wait_for_condition( - lambda: dynveg.validate_instance_count_in_entity_shape(spawner_entity.id, num_expected_surface_b), 5.0) - self.test_success = test_2_success and self.test_success + # 6) + # Test #2 Setup: Set test_tag2 to inclusion for descriptor 1. + spawner_entity.get_set_test(2, + "Configuration|Embedded Assets|[0]|Surface Mask Filter|Inclusion Tags", + [surface_tag_list[1]]) - # 7) - # Test #3 Setup: Set test_tag3 to inclusion for descriptor 1. - spawner_entity.get_set_test(2, - "Configuration|Embedded Assets|[0]|Surface Mask Filter|Inclusion Tags", - [surface_tag_list[2]]) + # Test #2 Validation: Validate instance count. Should only plant on a single surface for 225 instances + test_2_success = helper.wait_for_condition( + lambda: dynveg.validate_instance_count_in_entity_shape(spawner_entity.id, num_expected_surface_b), 5.0) + Report.result(Tests.surface_b_validation, test_2_success) - # Test #3 Validation: Validate instance count. Should only plant on a single surface for 100 instances - test_3_success = self.wait_for_condition( - lambda: dynveg.validate_instance_count_in_entity_shape(spawner_entity.id, num_expected_surface_c), 5.0) - self.test_success = test_3_success and self.test_success + # 7) + # Test #3 Setup: Set test_tag3 to inclusion for descriptor 1. + spawner_entity.get_set_test(2, + "Configuration|Embedded Assets|[0]|Surface Mask Filter|Inclusion Tags", + [surface_tag_list[2]]) + + # Test #3 Validation: Validate instance count. Should only plant on a single surface for 100 instances + test_3_success = helper.wait_for_condition( + lambda: dynveg.validate_instance_count_in_entity_shape(spawner_entity.id, num_expected_surface_c), 5.0) + Report.result(Tests.surface_c_validation, test_3_success) -test = TestSurfaceMaskFilterMultipleOverrides() -test.run() +if __name__ == "__main__": + + from editor_python_test_tools.utils import Report + Report.start_test(SurfaceMaskFilterOverrides_MultipleDescriptorOverridesPlantAsExpected) diff --git a/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/SurfaceMaskFilter_BasicSurfaceTagCreation.py b/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/SurfaceMaskFilter_BasicSurfaceTagCreation.py index 1baec7694d..fee62c04d1 100755 --- a/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/SurfaceMaskFilter_BasicSurfaceTagCreation.py +++ b/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/SurfaceMaskFilter_BasicSurfaceTagCreation.py @@ -5,66 +5,61 @@ For complete copyright and license terms please see the LICENSE at the root of t SPDX-License-Identifier: Apache-2.0 OR MIT """ -import os -import sys -import azlmbr.surface_data as surface_data - -sys.path.append(os.path.join(azlmbr.paths.devroot, 'AutomatedTesting', 'Gem', 'PythonTests')) -from editor_python_test_tools.editor_test_helper import EditorTestHelper +class Tests: + tags_same_value_equal = ( + "Two Surface Tags of the same value evaluated as equal", + "Two Surface Tags of the same value unexpectedly evaluated as unequal" + ) + tags_different_value_unequal = ( + "Two Surface Tags of different values evaluated as unequal", + "Two Surface Tags of different values unexpectedly evaluated as equal" + ) -class TestSurfaceMaskFilter_BasicSurfaceTagCreation(EditorTestHelper): - def __init__(self): - EditorTestHelper.__init__(self, log_prefix="TestSurfaceMaskFilter_BasicSurfaceTagCreation", args=["level"]) - - def run_test(self): - """ - Summary: - Verifies basic surface tag value equality +def SurfaceMaskFilter_BasicSurfaceTagCreation(): + """ + Summary: + Verifies basic surface tag value equality - Expected Behavior: - Surface tags of the same name are equal, and different names aren't. + Expected Behavior: + Surface tags of the same name are equal, and different names aren't. - Test Steps: - 1) Open level - 2) Create 2 new surface tags of identical names and verify they resolve as equal. - 3) Create another new tag of a different name and verify they resolve as different. + Test Steps: + 1) Open level + 2) Create 2 new surface tags of identical names and verify they resolve as equal. + 3) Create another new tag of a different name and verify they resolve as different. - 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. + 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 - """ - self.log("SurfaceTag test started") - - # Create a level - self.test_success = self.create_level( - self.args["level"], - heightmap_resolution=1024, - heightmap_meters_per_pixel=1, - terrain_texture_resolution=4096, - use_terrain=False, - ) - - tag1 = surface_data.SurfaceTag() - tag2 = surface_data.SurfaceTag() - - # Test 1: Verify that two tags with the same value are equal - tag1.SetTag('equal_test') - tag2.SetTag('equal_test') - self.log("SurfaceTag equal tag comparison is {} expected True".format(tag1.Equal(tag2))) - self.test_success = self.test_success and tag1.Equal(tag2) - - # Test 2: Verify that two tags with different values are not equal - tag2.SetTag('not_equal_test') - self.log("SurfaceTag not equal tag comparison is {} expected False".format(tag1.Equal(tag2))) - self.test_success = self.test_success and not tag1.Equal(tag2) - - self.log("SurfaceTag test finished") + :return: None + """ + + import azlmbr.surface_data as surface_data + from editor_python_test_tools.utils import Report + from editor_python_test_tools.utils import TestHelper as helper + + # Open an existing simple level + helper.init_idle() + helper.open_level("Physics", "Base") + + tag1 = surface_data.SurfaceTag() + tag2 = surface_data.SurfaceTag() + + # Test 1: Verify that two tags with the same value are equal + tag1.SetTag('equal_test') + tag2.SetTag('equal_test') + Report.result(Tests.tags_same_value_equal, tag1.Equal(tag2)) + + # Test 2: Verify that two tags with different values are not equal + tag2.SetTag('not_equal_test') + Report.result(Tests.tags_different_value_unequal, not tag1.Equal(tag2)) -test = TestSurfaceMaskFilter_BasicSurfaceTagCreation() -test.run() +if __name__ == "__main__": + + from editor_python_test_tools.utils import Report + Report.start_test(SurfaceMaskFilter_BasicSurfaceTagCreation) diff --git a/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/SurfaceMaskFilter_ExclusionList.py b/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/SurfaceMaskFilter_ExclusionList.py index 1ce7962e6a..6438124698 100755 --- a/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/SurfaceMaskFilter_ExclusionList.py +++ b/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/SurfaceMaskFilter_ExclusionList.py @@ -4,147 +4,141 @@ For complete copyright and license terms please see the LICENSE at the root of t SPDX-License-Identifier: Apache-2.0 OR MIT """ -""" -C2561342: Exclusive Surface Masks tags function -""" -import os -import sys - -sys.path.append(os.path.dirname(os.path.abspath(__file__))) -import azlmbr.areasystem as areasystem -import azlmbr.bus as bus -import azlmbr.editor as editor -import azlmbr.legacy.general as general -import azlmbr.math as math -import azlmbr.shape as shape -import azlmbr.surface_data as surface_data -sys.path.append(os.path.join(azlmbr.paths.devroot, 'AutomatedTesting', 'Gem', 'PythonTests')) -import editor_python_test_tools.hydra_editor_utils as hydra -from editor_python_test_tools.editor_test_helper import EditorTestHelper -from largeworlds.large_worlds_utils import editor_dynveg_test_helper as dynveg +class Tests: + default_exclusion_weight = ( + "Found the expected number of instances with Exclusion Weight set to defaults", + "Found an unexpected number of instances with Exclusion Weight set to defaults" + ) + exclusion_weight_below_one = ( + "Found the expected number of instances with Exclusion Weight set below 1", + "Found an unexpected number of instances with Exclusion Weight set below 1" + ) -class TestExclusiveSurfaceMasksTag(EditorTestHelper): - def __init__(self): - EditorTestHelper.__init__(self, log_prefix="SurfaceMaskFilter_ExclusionList", args=["level"]) +def SurfaceMaskFilter_ExclusionList(): + """ + Summary: + New level is created and set up with surface shapes with varying surface tags. A simple vegetation area has been + created and Vegetation Surface Mask Filter component is added to entity with terrain hole exclusion tag. - def run_test(self): - """ - Summary: - New level is created and set up with surface shapes with varying surface tags. A simple vegetation area has been - created and Vegetation Surface Mask Filter component is added to entity with terrain hole exclusion tag. + Expected Behavior: + With default Exclusion settings, vegetation does not plant over the terrain holes. + With Exclusion Weight Max below 1.0, vegetation plants over the terrain holes. - Expected Behavior: - With default Exclusion settings, vegetation does not plant over the terrain holes. - With Exclusion Weight Max below 1.0, vegetation plants over the terrain holes. + Test Steps: + 1) Open an existing level + 2) Create entity with components "Vegetation Layer Spawner", "Vegetation Asset List", "Box Shape" + 3) Add a Vegetation Surface Mask Filter component to the entity. + 4) Create 2 surface entities to represent terrain and terrain hole surfaces + 5) Add an Exclusion List tag to the component, and set it to terrainHole. + 6) Check spawn count with default Exclusion Weights + 7) Check spawn count with Exclusion Weight Max set below 1.0 - Test Steps: - 1) Create a new level. - 2) Create entity with components "Vegetation Layer Spawner", "Vegetation Asset List", "Box Shape" - 3) Add a Vegetation Surface Mask Filter component to the entity. - 4) Create 2 surface entities to represent terrain and terrain hole surfaces - 5) Add an Exclusion List tag to the component, and set it to terrainHole. - 6) Check spawn count with default Exclusion Weights - 7) Check spawn count with Exclusion Weight Max set below 1.0 - - Note: - - 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. + Note: + - 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 - """ + :return: None + """ - def update_surface_tag_exclusion_list(Entity, component_index, surface_tag): - tag_list = [surface_data.SurfaceTag()] + import os - # assign list with one surface tag to exclusion list - hydra.get_set_test(Entity, component_index, "Configuration|Exclusion|Surface Tags", tag_list) + import azlmbr.bus as bus + import azlmbr.editor as editor + import azlmbr.legacy.general as general + import azlmbr.math as math + import azlmbr.surface_data as surface_data - # set that one surface tag element to required surface tag - component = Entity.components[component_index] - path = "Configuration|Exclusion|Surface Tags|[0]|Surface Tag" - editor.EditorComponentAPIBus(bus.Broadcast, "SetComponentProperty", component, path, surface_tag) - new_value = hydra.get_component_property_value(component, path) + import editor_python_test_tools.hydra_editor_utils as hydra + from largeworlds.large_worlds_utils import editor_dynveg_test_helper as dynveg + from editor_python_test_tools.utils import Report + from editor_python_test_tools.utils import TestHelper as helper - if new_value == surface_tag: - self.log(f"Exclusive surface mask filter of {surface_tag} is added successfully") - else: - self.log(f"Failed to add an Exclusive surface mask filter of {surface_tag}") + def update_surface_tag_exclusion_list(Entity, component_index, surface_tag): + tag_list = [surface_data.SurfaceTag()] - def update_generated_surface_tag(Entity, component_index, surface_tag): - tag_list = [surface_data.SurfaceTag()] + # assign list with one surface tag to exclusion list + hydra.get_set_test(Entity, component_index, "Configuration|Exclusion|Surface Tags", tag_list) - # assign list with one surface tag to Generated Tags list - hydra.get_set_test(Entity, component_index, "Configuration|Generated Tags", tag_list) + # set that one surface tag element to required surface tag + component = Entity.components[component_index] + path = "Configuration|Exclusion|Surface Tags|[0]|Surface Tag" + editor.EditorComponentAPIBus(bus.Broadcast, "SetComponentProperty", component, path, surface_tag) + new_value = hydra.get_component_property_value(component, path) - # set that one surface tag element to required surface tag - component = Entity.components[component_index] - path = "Configuration|Generated Tags|[0]|Surface Tag" - editor.EditorComponentAPIBus(bus.Broadcast, "SetComponentProperty", component, path, surface_tag) - new_value = hydra.get_component_property_value(component, path) + if new_value == surface_tag: + Report.info(f"Exclusive surface mask filter of {surface_tag} is added successfully") + else: + Report.info(f"Failed to add an Exclusive surface mask filter of {surface_tag}") - if new_value == surface_tag: - self.log(f"Generated surface tag of {surface_tag} is added successfully") - else: - self.log(f"Failed to add Generated surface tag of {surface_tag}") + def update_generated_surface_tag(Entity, component_index, surface_tag): + tag_list = [surface_data.SurfaceTag()] - # 1) Create a new level - self.test_success = self.create_level( - self.args["level"], - heightmap_resolution=1024, - heightmap_meters_per_pixel=1, - terrain_texture_resolution=4096, - use_terrain=False, - ) + # assign list with one surface tag to Generated Tags list + hydra.get_set_test(Entity, component_index, "Configuration|Generated Tags", tag_list) - general.set_current_view_position(512.0, 480.0, 38.0) + # set that one surface tag element to required surface tag + component = Entity.components[component_index] + path = "Configuration|Generated Tags|[0]|Surface Tag" + editor.EditorComponentAPIBus(bus.Broadcast, "SetComponentProperty", component, path, surface_tag) + new_value = hydra.get_component_property_value(component, path) - # 2) Create entity with components "Vegetation Layer Spawner", "Vegetation Asset List", "Box Shape" - entity_position = math.Vector3(512.0, 512.0, 32.0) - asset_path = os.path.join("Slices", "PurpleFlower.dynamicslice") - spawner_entity = dynveg.create_vegetation_area("Instance Spawner", - entity_position, - 10.0, 10.0, 10.0, - asset_path) + if new_value == surface_tag: + Report.info(f"Generated surface tag of {surface_tag} is added successfully") + else: + Report.info(f"Failed to add Generated surface tag of {surface_tag}") - # 3) Add a Vegetation Surface Mask Filter component to the entity. - spawner_entity.add_component("Vegetation Surface Mask Filter") + # 1) Open an existing simple level + helper.init_idle() + helper.open_level("Physics", "Base") - # 4) Create 2 surface entities to represent terrain and terrain hole surfaces - surface_tags: dict = {"terrainHole": 1327698037, "terrain": 3363197873} - entity_position = math.Vector3(510.0, 512.0, 32.0) - surface_entity_1 = dynveg.create_surface_entity("Surface Entity 1", - entity_position, - 10.0, 10.0, 1.0) - update_generated_surface_tag(surface_entity_1, 1, surface_tags["terrainHole"]) + general.set_current_view_position(512.0, 480.0, 38.0) - entity_position = math.Vector3(520.0, 512.0, 32.0) - surface_entity_2 = dynveg.create_surface_entity("Surface Entity 2", - entity_position, - 10.0, 10.0, 1.0) - update_generated_surface_tag(surface_entity_2, 1, surface_tags["terrain"]) + # 2) Create entity with components "Vegetation Layer Spawner", "Vegetation Asset List", "Box Shape" + entity_position = math.Vector3(512.0, 512.0, 32.0) + asset_path = os.path.join("Slices", "PurpleFlower.dynamicslice") + spawner_entity = dynveg.create_vegetation_area("Instance Spawner", + entity_position, + 10.0, 10.0, 10.0, + asset_path) - # 5) Add an Exclusion List tag to the component, and set it to "terrainHole". - update_surface_tag_exclusion_list(spawner_entity, 3, surface_tags["terrainHole"]) + # 3) Add a Vegetation Surface Mask Filter component to the entity. + spawner_entity.add_component("Vegetation Surface Mask Filter") - # 6) Check spawn count with default Exclusion Weights - general.idle_wait(2.0) # Allow a few seconds for instances to spawn - num_expected_instances = 39 - box = shape.ShapeComponentRequestsBus(bus.Event, 'GetEncompassingAabb', spawner_entity.id) - num_found = areasystem.AreaSystemRequestBus(bus.Broadcast, 'GetInstanceCountInAabb', box) - self.log(f"Expected {num_expected_instances} instances - Found {num_found} instances") - self.test_success = self.test_success and num_found == num_expected_instances + # 4) Create 2 surface entities to represent terrain and terrain hole surfaces + surface_tags: dict = {"terrainHole": 1327698037, "terrain": 3363197873} + entity_position = math.Vector3(510.0, 512.0, 32.0) + surface_entity_1 = dynveg.create_surface_entity("Surface Entity 1", + entity_position, + 10.0, 10.0, 1.0) + update_generated_surface_tag(surface_entity_1, 1, surface_tags["terrainHole"]) - # 7) Check spawn count with Exclusion Weight Max set below 1.0 - hydra.get_set_test(spawner_entity, 3, "Configuration|Exclusion|Weight Max", 0.9) - general.idle_wait(2.0) # Allow a few seconds for instances to spawn - num_expected_instances = 169 - num_found = areasystem.AreaSystemRequestBus(bus.Broadcast, 'GetInstanceCountInAabb', box) - self.log(f"Expected {num_expected_instances} instances - Found {num_found} instances") - self.test_success = self.test_success and num_found == num_expected_instances + entity_position = math.Vector3(520.0, 512.0, 32.0) + surface_entity_2 = dynveg.create_surface_entity("Surface Entity 2", + entity_position, + 10.0, 10.0, 1.0) + update_generated_surface_tag(surface_entity_2, 1, surface_tags["terrain"]) + + # 5) Add an Exclusion List tag to the component, and set it to "terrainHole". + update_surface_tag_exclusion_list(spawner_entity, 3, surface_tags["terrainHole"]) + + # 6) Check spawn count with default Exclusion Weights + num_expected_instances = 39 + success = helper.wait_for_condition(lambda: dynveg.validate_instance_count_in_entity_shape(spawner_entity.id, + num_expected_instances), 2.0) + Report.result(Tests.default_exclusion_weight, success) + + # 7) Check spawn count with Exclusion Weight Max set below 1.0 + hydra.get_set_test(spawner_entity, 3, "Configuration|Exclusion|Weight Max", 0.9) + num_expected_instances = 169 + success = helper.wait_for_condition(lambda: dynveg.validate_instance_count_in_entity_shape(spawner_entity.id, + num_expected_instances), 2.0) + Report.result(Tests.exclusion_weight_below_one, success) -test = TestExclusiveSurfaceMasksTag() -test.run() +if __name__ == "__main__": + + from editor_python_test_tools.utils import Report + Report.start_test(SurfaceMaskFilter_ExclusionList) diff --git a/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/SurfaceMaskFilter_InclusionList.py b/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/SurfaceMaskFilter_InclusionList.py index e394bc0cde..bbd1235abc 100755 --- a/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/SurfaceMaskFilter_InclusionList.py +++ b/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/SurfaceMaskFilter_InclusionList.py @@ -4,148 +4,142 @@ For complete copyright and license terms please see the LICENSE at the root of t SPDX-License-Identifier: Apache-2.0 OR MIT """ -""" -C2561341: Inclusive Surface Masks tags function -""" -import os -import sys - -sys.path.append(os.path.dirname(os.path.abspath(__file__))) -import azlmbr.areasystem as areasystem -import azlmbr.bus as bus -import azlmbr.editor as editor -import azlmbr.legacy.general as general -import azlmbr.math as math -import azlmbr.shape as shape -import azlmbr.surface_data as surface_data -sys.path.append(os.path.join(azlmbr.paths.devroot, 'AutomatedTesting', 'Gem', 'PythonTests')) -import editor_python_test_tools.hydra_editor_utils as hydra -from editor_python_test_tools.editor_test_helper import EditorTestHelper -from largeworlds.large_worlds_utils import editor_dynveg_test_helper as dynveg +class Tests: + default_inclusion_weight = ( + "Found the expected number of instances with Inclusion Weight set to defaults", + "Found an unexpected number of instances with Inclusion Weight set to defaults" + ) + inclusion_weight_below_one = ( + "Found the expected number of instances with Inclusion Weight set below 1", + "Found an unexpected number of instances with Inclusion Weight set below 1" + ) -class TestInclusiveSurfaceMasksTag(EditorTestHelper): - def __init__(self): - EditorTestHelper.__init__(self, log_prefix="SurfaceMaskFilter_InclusionList", args=["level"]) - def run_test(self): - """ - Summary: - New level is created and set up with surface shapes with varying surface tags. A simple vegetation area has been - created and Vegetation Surface Mask Filter component is added to entity with terrain hole inclusion tag. +def SurfaceMaskFilter_InclusionList(): + """ + Summary: + New level is created and set up with surface shapes with varying surface tags. A simple vegetation area has been + created and Vegetation Surface Mask Filter component is added to entity with terrain hole inclusion tag. - Expected Behavior: - With default Inclusion Weights, vegetation draws over the terrain holes. - With Inclusion Weight Max set below 1.0, vegetation stops drawing over the terrain holes. + Expected Behavior: + With default Inclusion Weights, vegetation draws over the terrain holes. + With Inclusion Weight Max set below 1.0, vegetation stops drawing over the terrain holes. - Test Steps: - 1) Create a new level - 2) Create entity with components "Vegetation Layer Spawner", "Vegetation Asset List", "Box Shape" - 3) Add a Vegetation Surface Mask Filter component to the entity. - 4) Create 2 surface entities to represent terrain and terrain hole surfaces - 5) Add an Inclusion List tag to the component, and set it to "terrainHole". - 6) Check spawn count with default Inclusion Weights - 7) Check spawn count with Inclusion Weight Max set below 1.0 - - Note: - - 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. + Test Steps: + 1) Open an existing level + 2) Create entity with components "Vegetation Layer Spawner", "Vegetation Asset List", "Box Shape" + 3) Add a Vegetation Surface Mask Filter component to the entity. + 4) Create 2 surface entities to represent terrain and terrain hole surfaces + 5) Add an Inclusion List tag to the component, and set it to "terrainHole". + 6) Check spawn count with default Inclusion Weights + 7) Check spawn count with Inclusion Weight Max set below 1.0 - :return: None - """ + Note: + - 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. - def update_surface_tag_inclusion_list(Entity, component_index, surface_tag): - tag_list = [surface_data.SurfaceTag()] + :return: None + """ - # assign list with one surface tag to inclusion list - hydra.get_set_test(Entity, component_index, "Configuration|Inclusion|Surface Tags", tag_list) + import os - # set that one surface tag element to required surface tag - component = Entity.components[component_index] - path = "Configuration|Inclusion|Surface Tags|[0]|Surface Tag" - editor.EditorComponentAPIBus(bus.Broadcast, "SetComponentProperty", component, path, surface_tag) - new_value = hydra.get_component_property_value(component, path) + import azlmbr.bus as bus + import azlmbr.editor as editor + import azlmbr.legacy.general as general + import azlmbr.math as math + import azlmbr.surface_data as surface_data - if new_value == surface_tag: - print("Inclusive surface mask filter of terrainHole is added successfully") - else: - print("Failed to add an Inclusive surface mask filter of terrainHole") - general.idle_wait(2.0) + import editor_python_test_tools.hydra_editor_utils as hydra + from largeworlds.large_worlds_utils import editor_dynveg_test_helper as dynveg + from editor_python_test_tools.utils import Report + from editor_python_test_tools.utils import TestHelper as helper - def update_generated_surface_tag(Entity, component_index, surface_tag): - tag_list = [surface_data.SurfaceTag()] + def update_surface_tag_inclusion_list(Entity, component_index, surface_tag): + tag_list = [surface_data.SurfaceTag()] - # assign list with one surface tag to Generated Tags list - hydra.get_set_test(Entity, component_index, "Configuration|Generated Tags", tag_list) + # assign list with one surface tag to inclusion list + hydra.get_set_test(Entity, component_index, "Configuration|Inclusion|Surface Tags", tag_list) - # set that one surface tag element to required surface tag - component = Entity.components[component_index] - path = "Configuration|Generated Tags|[0]|Surface Tag" - editor.EditorComponentAPIBus(bus.Broadcast, "SetComponentProperty", component, path, surface_tag) - new_value = hydra.get_component_property_value(component, path) + # set that one surface tag element to required surface tag + component = Entity.components[component_index] + path = "Configuration|Inclusion|Surface Tags|[0]|Surface Tag" + editor.EditorComponentAPIBus(bus.Broadcast, "SetComponentProperty", component, path, surface_tag) + new_value = hydra.get_component_property_value(component, path) - if new_value == surface_tag: - self.log(f"Generated surface tag of {surface_tag} is added successfully") - else: - self.log(f"Failed to add Generated surface tag of {surface_tag}") + if new_value == surface_tag: + Report.info("Inclusive surface mask filter of terrainHole is added successfully") + else: + Report.info("Failed to add an Inclusive surface mask filter of terrainHole") - # 1) Create a new level - self.test_success = self.create_level( - self.args["level"], - heightmap_resolution=1024, - heightmap_meters_per_pixel=1, - terrain_texture_resolution=4096, - use_terrain=False, - ) + def update_generated_surface_tag(Entity, component_index, surface_tag): + tag_list = [surface_data.SurfaceTag()] - general.set_current_view_position(512.0, 480.0, 38.0) + # assign list with one surface tag to Generated Tags list + hydra.get_set_test(Entity, component_index, "Configuration|Generated Tags", tag_list) - # 2) Create entity with components "Vegetation Layer Spawner", "Vegetation Asset List", "Box Shape" - entity_position = math.Vector3(512.0, 512.0, 32.0) - asset_path = os.path.join("Slices", "PurpleFlower.dynamicslice") - spawner_entity = dynveg.create_vegetation_area("Instance Spawner", - entity_position, - 10.0, 10.0, 10.0, - asset_path) + # set that one surface tag element to required surface tag + component = Entity.components[component_index] + path = "Configuration|Generated Tags|[0]|Surface Tag" + editor.EditorComponentAPIBus(bus.Broadcast, "SetComponentProperty", component, path, surface_tag) + new_value = hydra.get_component_property_value(component, path) - # 3) Add a Vegetation Surface Mask Filter component to the entity. - spawner_entity.add_component("Vegetation Surface Mask Filter") + if new_value == surface_tag: + Report.info(f"Generated surface tag of {surface_tag} is added successfully") + else: + Report.info(f"Failed to add Generated surface tag of {surface_tag}") - # 4) Create 2 surface entities to represent terrain and terrain hole surfaces - surface_tags: dict = {"terrainHole": 1327698037, "terrain": 3363197873} - entity_position = math.Vector3(510.0, 512.0, 32.0) - surface_entity_1 = dynveg.create_surface_entity("Surface Entity 1", - entity_position, - 10.0, 10.0, 1.0) - update_generated_surface_tag(surface_entity_1, 1, surface_tags["terrainHole"]) + # 1) Open an existing simple level + helper.init_idle() + helper.open_level("Physics", "Base") - entity_position = math.Vector3(520.0, 512.0, 32.0) - surface_entity_2 = dynveg.create_surface_entity("Surface Entity 2", - entity_position, - 10.0, 10.0, 1.0) - update_generated_surface_tag(surface_entity_2, 1, surface_tags["terrain"]) + general.set_current_view_position(512.0, 480.0, 38.0) - # 5) Add an Inclusion List tag to the component, and set it to "terrainHole". - update_surface_tag_inclusion_list(spawner_entity, 3, surface_tags["terrainHole"]) + # 2) Create entity with components "Vegetation Layer Spawner", "Vegetation Asset List", "Box Shape" + entity_position = math.Vector3(512.0, 512.0, 32.0) + asset_path = os.path.join("Slices", "PurpleFlower.dynamicslice") + spawner_entity = dynveg.create_vegetation_area("Instance Spawner", + entity_position, + 10.0, 10.0, 10.0, + asset_path) - # 6) Check spawn count with default Inclusion Weights - general.idle_wait(2.0) # Allow a few seconds for instances to spawn - num_expected_instances = 130 - box = shape.ShapeComponentRequestsBus(bus.Event, 'GetEncompassingAabb', spawner_entity.id) - num_found = areasystem.AreaSystemRequestBus(bus.Broadcast, 'GetInstanceCountInAabb', box) - self.log(f"Expected {num_expected_instances} instances - Found {num_found} instances") - self.test_success = self.test_success and num_found == num_expected_instances + # 3) Add a Vegetation Surface Mask Filter component to the entity. + spawner_entity.add_component("Vegetation Surface Mask Filter") - # 7) Check spawn count with Inclusion Weight Max set below 1.0 - hydra.get_set_test(spawner_entity, 3, "Configuration|Inclusion|Weight Max", 0.9) - general.idle_wait(2.0) # Allow a few seconds for instances to update - num_expected_instances = 0 - num_found = areasystem.AreaSystemRequestBus(bus.Broadcast, 'GetInstanceCountInAabb', box) - self.log(f"Expected {num_expected_instances} instances - Found {num_found} instances") - self.test_success = self.test_success and num_found == num_expected_instances + # 4) Create 2 surface entities to represent terrain and terrain hole surfaces + surface_tags: dict = {"terrainHole": 1327698037, "terrain": 3363197873} + entity_position = math.Vector3(510.0, 512.0, 32.0) + surface_entity_1 = dynveg.create_surface_entity("Surface Entity 1", + entity_position, + 10.0, 10.0, 1.0) + update_generated_surface_tag(surface_entity_1, 1, surface_tags["terrainHole"]) + + entity_position = math.Vector3(520.0, 512.0, 32.0) + surface_entity_2 = dynveg.create_surface_entity("Surface Entity 2", + entity_position, + 10.0, 10.0, 1.0) + update_generated_surface_tag(surface_entity_2, 1, surface_tags["terrain"]) + + # 5) Add an Inclusion List tag to the component, and set it to "terrainHole". + update_surface_tag_inclusion_list(spawner_entity, 3, surface_tags["terrainHole"]) + + # 6) Check spawn count with default Inclusion Weights + num_expected_instances = 130 + success = helper.wait_for_condition(lambda: dynveg.validate_instance_count_in_entity_shape(spawner_entity.id, + num_expected_instances), 2.0) + Report.result(Tests.default_inclusion_weight, success) + + # 7) Check spawn count with Inclusion Weight Max set below 1.0 + hydra.get_set_test(spawner_entity, 3, "Configuration|Inclusion|Weight Max", 0.9) + num_expected_instances = 0 + success = helper.wait_for_condition(lambda: dynveg.validate_instance_count_in_entity_shape(spawner_entity.id, + num_expected_instances), 2.0) + Report.result(Tests.inclusion_weight_below_one, success) -test = TestInclusiveSurfaceMasksTag() -test.run() +if __name__ == "__main__": + + from editor_python_test_tools.utils import Report + Report.start_test(SurfaceMaskFilter_InclusionList) diff --git a/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/SystemSettings_SectorPointDensity.py b/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/SystemSettings_SectorPointDensity.py index f690e175de..d808d3f20b 100755 --- a/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/SystemSettings_SectorPointDensity.py +++ b/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/SystemSettings_SectorPointDensity.py @@ -5,89 +5,90 @@ For complete copyright and license terms please see the LICENSE at the root of t SPDX-License-Identifier: Apache-2.0 OR MIT """ -import os -import sys -import azlmbr.math as math -import azlmbr.paths -import azlmbr.editor as editor -import azlmbr.bus as bus -import azlmbr.legacy.general as general -sys.path.append(os.path.join(azlmbr.paths.devroot, "AutomatedTesting", "Gem", "PythonTests")) -import editor_python_test_tools.hydra_editor_utils as hydra -from editor_python_test_tools.editor_test_helper import EditorTestHelper -from largeworlds.large_worlds_utils import editor_dynveg_test_helper as dynveg +class Tests: + initial_density_instance_count = ( + "Found the expected number of instances with default sector density", + "Found an unexpected number of instances with default sector density" + ) + configured_density_instance_count = ( + "Found the expected number of instances with a sector density of 10", + "Found an unexpected number of instances with a sector density of 10" + ) -class TestSystemSettingsSectorPointDensity(EditorTestHelper): - def __init__(self): - EditorTestHelper.__init__(self, log_prefix="SystemSettings_SectorPointDensity", args=["level"]) +def SystemSettings_SectorPointDensity(): + """ + Summary: + Sector Point Density increases/reduces the number of vegetation points within a sector - def run_test(self): - """ - Summary: - Sector Point Density increases/reduces the number of vegetation points within a sector + Expected Result: + Default value for Sector Point Density is 20. + 20 vegetation meshes appear on each side of the established vegetation area with the default value. + When altered, the specified number of vegetation meshes along a side of a vegetation area matches the value set + in Sector Point Density. - Expected Result: - Default value for Sector Point Density is 20. - 20 vegetation meshes appear on each side of the established vegetation area with the default value. - When altered, the specified number of vegetation meshes along a side of a vegetation area matches the value set - in Sector Point Density. + :return: None + """ - :return: None - """ + import os - INSTANCE_COUNT_BEFORE_DENSITY_CHANGE = 400 - INSTANCE_COUNT_AFTER_DENSITY_CHANGE = 100 + import azlmbr.math as math + import azlmbr.editor as editor + import azlmbr.bus as bus + import azlmbr.legacy.general as general - # Create empty level - self.test_success = self.create_level( - self.args["level"], - heightmap_resolution=1024, - heightmap_meters_per_pixel=1, - terrain_texture_resolution=4096, - use_terrain=False, - ) + import editor_python_test_tools.hydra_editor_utils as hydra + from largeworlds.large_worlds_utils import editor_dynveg_test_helper as dynveg + from editor_python_test_tools.utils import Report + from editor_python_test_tools.utils import TestHelper as helper - general.set_current_view_position(512.0, 480.0, 38.0) + INSTANCE_COUNT_BEFORE_DENSITY_CHANGE = 400 + INSTANCE_COUNT_AFTER_DENSITY_CHANGE = 100 - # Create basic vegetation entity - position = math.Vector3(512.0, 512.0, 32.0) - asset_path = os.path.join("Slices", "PinkFlower.dynamicslice") - dynveg.create_vegetation_area("vegetation", position, 16.0, 16.0, 1.0, asset_path) - dynveg.create_surface_entity("Surface_Entity", position, 16.0, 16.0, 1.0) + # Open an existing simple level + helper.init_idle() + helper.open_level("Physics", "Base") - # Count the number of vegetation meshes along one side of the new vegetation area. # - result = self.wait_for_condition( - lambda: dynveg.validate_instance_count(position, 8.0, INSTANCE_COUNT_BEFORE_DENSITY_CHANGE), 2.0 - ) - self.log(f"Vegetation instances count equal to expected value before changing sector point density: {result}") + general.set_current_view_position(512.0, 480.0, 38.0) - # Add the Vegetation Debugger component to the Level Inspector - veg_system_settings_component = hydra.add_level_component("Vegetation System Settings") + # Create basic vegetation entity + position = math.Vector3(512.0, 512.0, 32.0) + asset_path = os.path.join("Slices", "PinkFlower.dynamicslice") + dynveg.create_vegetation_area("vegetation", position, 16.0, 16.0, 1.0, asset_path) + dynveg.create_surface_entity("Surface_Entity", position, 16.0, 16.0, 1.0) - # Change Sector Point Density to 10 - editor.EditorComponentAPIBus( - bus.Broadcast, - "SetComponentProperty", - veg_system_settings_component, - "Configuration|Area System Settings|Sector Point Snap Mode", - 1, - ) - editor.EditorComponentAPIBus( - bus.Broadcast, - "SetComponentProperty", - veg_system_settings_component, - "Configuration|Area System Settings|Sector Point Density", - 10, - ) + # Count the number of vegetation instances in the vegetation area + result = helper.wait_for_condition(lambda: dynveg.validate_instance_count(position, 8.0, + INSTANCE_COUNT_BEFORE_DENSITY_CHANGE), 2.0) + Report.result(Tests.initial_density_instance_count, result) - # Count the number of vegetation meshes along one side of the new vegetation area. - result = self.wait_for_condition( - lambda: dynveg.validate_instance_count(position, 8.0, INSTANCE_COUNT_AFTER_DENSITY_CHANGE), 2.0 - ) - self.log(f"Vegetation instances count equal to expected value after changing sector point density: {result}") + # Add the Vegetation Debugger component to the Level Inspector + veg_system_settings_component = hydra.add_level_component("Vegetation System Settings") + + # Change Sector Point Density to 10 + editor.EditorComponentAPIBus( + bus.Broadcast, + "SetComponentProperty", + veg_system_settings_component, + "Configuration|Area System Settings|Sector Point Snap Mode", + 1, + ) + editor.EditorComponentAPIBus( + bus.Broadcast, + "SetComponentProperty", + veg_system_settings_component, + "Configuration|Area System Settings|Sector Point Density", + 10, + ) + + # Count the number of vegetation instances in the vegetation area + result = helper.wait_for_condition(lambda: dynveg.validate_instance_count(position, 8.0, + INSTANCE_COUNT_AFTER_DENSITY_CHANGE), 2.0) + Report.result(Tests.configured_density_instance_count, result) -test = TestSystemSettingsSectorPointDensity() -test.run() +if __name__ == "__main__": + + from editor_python_test_tools.utils import Report + Report.start_test(SystemSettings_SectorPointDensity) diff --git a/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/SystemSettings_SectorSize.py b/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/SystemSettings_SectorSize.py index 61aaedcf7c..fb660c964a 100755 --- a/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/SystemSettings_SectorSize.py +++ b/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/SystemSettings_SectorSize.py @@ -5,88 +5,91 @@ For complete copyright and license terms please see the LICENSE at the root of t SPDX-License-Identifier: Apache-2.0 OR MIT """ -import os -import sys -import azlmbr.math as math -import azlmbr.paths -import azlmbr.editor as editor -import azlmbr.bus as bus -import azlmbr.legacy.general as general -sys.path.append(os.path.join(azlmbr.paths.devroot, "AutomatedTesting", "Gem", "PythonTests")) -import editor_python_test_tools.hydra_editor_utils as hydra -from editor_python_test_tools.editor_test_helper import EditorTestHelper -from largeworlds.large_worlds_utils import editor_dynveg_test_helper as dynveg +class Tests: + initial_sector_size_instance_count = ( + "Found the expected number of instances with default sector size", + "Found an unexpected number of instances with default sector size" + ) + configured_sector_size_instance_count = ( + "Found the expected number of instances with a sector size of 10", + "Found an unexpected number of instances with a sector size of 10" + ) -class TestSystemSettingsSectorSize(EditorTestHelper): - def __init__(self): - EditorTestHelper.__init__(self, log_prefix="SystemSettings_SectorSize", args=["level"]) +def SystemSettings_SectorSize(): + """ + Summary: + Sector Size In Meters increases/reduces the size of a sector - def run_test(self): - """ - Summary: - Sector Size In Meters increases/reduces the size of a sector + Expected Result: + The number of spawned vegetation meshes inside the vegetation area is identical after updating the Sector Size - Expected Result: - The number of spawned vegetation meshes inside the vegetation area is identical after updating the Sector Size + :return: None + """ - :return: None - """ + import os - VEGETATION_INSTANCE_COUNT = 400 + import azlmbr.math as math + import azlmbr.editor as editor + import azlmbr.bus as bus + import azlmbr.legacy.general as general - # Create empty level - self.test_success = self.create_level( - self.args["level"], - heightmap_resolution=1024, - heightmap_meters_per_pixel=1, - terrain_texture_resolution=4096, - use_terrain=False, - ) + import editor_python_test_tools.hydra_editor_utils as hydra + from largeworlds.large_worlds_utils import editor_dynveg_test_helper as dynveg + from editor_python_test_tools.utils import Report + from editor_python_test_tools.utils import TestHelper as helper - general.set_current_view_position(512.0, 480.0, 38.0) + VEGETATION_INSTANCE_COUNT = 400 - # Create basic vegetation entity - position = math.Vector3(512.0, 512.0, 32.0) - asset_path = os.path.join("Slices", "PinkFlower.dynamicslice") - vegetation = dynveg.create_vegetation_area("vegetation", position, 16.0, 16.0, 1.0, asset_path) - dynveg.create_surface_entity("Surface_Entity", position, 16.0, 16.0, 1.0) + # Open an existing simple level + helper.init_idle() + helper.open_level("Physics", "Base") - # Add the Vegetation Debugger component to the Level Inspector - veg_system_settings_component = hydra.add_level_component("Vegetation System Settings") + general.set_current_view_position(512.0, 480.0, 38.0) - # Count the number of vegetation meshes along one side of the new vegetation area. - result = self.wait_for_condition( - lambda: dynveg.validate_instance_count(position, 8.0, VEGETATION_INSTANCE_COUNT), 2.0 - ) - self.log(f"Vegetation instances count equal to expected value before changing sector size: {result}") + # Create basic vegetation entity + position = math.Vector3(512.0, 512.0, 32.0) + asset_path = os.path.join("Slices", "PinkFlower.dynamicslice") + vegetation = dynveg.create_vegetation_area("vegetation", position, 16.0, 16.0, 1.0, asset_path) + dynveg.create_surface_entity("Surface_Entity", position, 16.0, 16.0, 1.0) - # Change Sector Size in Meters to 10. - editor.EditorComponentAPIBus( - bus.Broadcast, - "SetComponentProperty", - veg_system_settings_component, - "Configuration|Area System Settings|Sector Point Snap Mode", - 1, - ) - editor.EditorComponentAPIBus( - bus.Broadcast, - "SetComponentProperty", - veg_system_settings_component, - "Configuration|Area System Settings|Sector Size In Meters", - 10, - ) + # Add the Vegetation Debugger component to the Level Inspector + veg_system_settings_component = hydra.add_level_component("Vegetation System Settings") - # Alter the Box Shape to be 10,10,1 - vegetation.get_set_test(1, "Box Shape|Box Configuration|Dimensions", math.Vector3(10.0, 10.0, 1.0)) + # Count the number of vegetation instances in the vegetation area + result = helper.wait_for_condition( + lambda: dynveg.validate_instance_count(position, 8.0, VEGETATION_INSTANCE_COUNT), 2.0 + ) + Report.result(Tests.initial_sector_size_instance_count, result) - # Count the number of vegetation meshes along one side of the new vegetation area. - result = self.wait_for_condition( - lambda: dynveg.validate_instance_count(position, 5.0, VEGETATION_INSTANCE_COUNT), 2.0 - ) - self.log(f"Vegetation instances count equal to expected value after changing sector size: {result}") + # Change Sector Size in Meters to 10. + editor.EditorComponentAPIBus( + bus.Broadcast, + "SetComponentProperty", + veg_system_settings_component, + "Configuration|Area System Settings|Sector Point Snap Mode", + 1, + ) + editor.EditorComponentAPIBus( + bus.Broadcast, + "SetComponentProperty", + veg_system_settings_component, + "Configuration|Area System Settings|Sector Size In Meters", + 10, + ) + + # Alter the Box Shape to be 10,10,1 + vegetation.get_set_test(1, "Box Shape|Box Configuration|Dimensions", math.Vector3(10.0, 10.0, 1.0)) + + # Count the number of vegetation instances in the vegetation area + result = helper.wait_for_condition( + lambda: dynveg.validate_instance_count(position, 5.0, VEGETATION_INSTANCE_COUNT), 2.0 + ) + Report.result(Tests.configured_sector_size_instance_count, result) -test = TestSystemSettingsSectorSize() -test.run() +if __name__ == "__main__": + + from editor_python_test_tools.utils import Report + Report.start_test(SystemSettings_SectorSize) diff --git a/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/VegetationInstances_DespawnWhenOutOfRange.py b/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/VegetationInstances_DespawnWhenOutOfRange.py index 6f40d04854..a0657f3949 100755 --- a/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/VegetationInstances_DespawnWhenOutOfRange.py +++ b/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/VegetationInstances_DespawnWhenOutOfRange.py @@ -5,89 +5,85 @@ For complete copyright and license terms please see the LICENSE at the root of t SPDX-License-Identifier: Apache-2.0 OR MIT """ -""" -This script tests for regressions of "vegetation instances don't despawn correctly -when the camera moves beyond the range of all active vegetation areas". -This creates a new level and a vegetation area with 400 instances. -The expectation is that we will have 400 instances in that area when the camera is centered on it, -and 0 instances when the camera is moved sufficiently far away. -""" - -import sys, os - -import azlmbr.legacy.general as general -import azlmbr.math as math - -sys.path.append(os.path.join(azlmbr.paths.devroot, 'AutomatedTesting', 'Gem', 'PythonTests')) -from editor_python_test_tools.editor_test_helper import EditorTestHelper -from largeworlds.large_worlds_utils import editor_dynveg_test_helper as dynveg +class Tests: + instance_validation_close = ( + "Instance count is as expected when within range of Spawner", + "Instance count was unexpected when within range of Spawner" + ) + instance_validation_far = ( + "No instances found when out of range of Spawner", + "Instances still found when out of range of Spawner" + ) -class TestVegetationInstances_DespawnWhenOutOfRange(EditorTestHelper): - def __init__(self): - EditorTestHelper.__init__(self, log_prefix='VegetationInstances_DespawnWhenOutOfRange', args=['level']) +def VegetationInstances_DespawnWhenOutOfRange(): + """ + Summary: + Verifies that vegetation instances properly spawn/despawn based on camera range. - def run_test(self): - """ - Summary: - Verifies that vegetation instances properly spawn/despawn based on camera range. + Expected Behavior: + Vegetation instances despawn when out of camera range. - Expected Behavior: - Vegetation instances despawn when out of camera range. + Test Steps: + 1) Open a simple level + 2) Create a simple vegetation area, and set the view position near the spawner. Verify instances plant. + 3) Move the view position away from the spawner. Verify instances despawn. - Test Steps: - 1) Create a new level - 2) Create a simple vegetation area, and set the view position near the spawner. Verify instances plant. - 3) Move the view position away from the spawner. Verify instances despawn. + 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. - 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 + """ - :return: None - """ + import os - # Create a new level - self.test_success = self.create_level( - self.get_arg('level'), - heightmap_resolution=128, - heightmap_meters_per_pixel=1, - terrain_texture_resolution=128, - use_terrain=False) + import azlmbr.legacy.general as general + import azlmbr.math as math - # Create vegetation layer spawner - world_center = math.Vector3(512.0, 512.0, 32.0) - asset_path = os.path.join("Slices", "PurpleFlower.dynamicslice") - spawner_entity = dynveg.create_vegetation_area("Spawner Instance", world_center, 16.0, 16.0, 16.0, asset_path) + from largeworlds.large_worlds_utils import editor_dynveg_test_helper as dynveg + from editor_python_test_tools.utils import Report + from editor_python_test_tools.utils import TestHelper as helper - # Create a surface to spawn on - dynveg.create_surface_entity("Spawner Entity", world_center, 16.0, 16.0, 1.0) + # Open an existing simple level + helper.init_idle() + helper.open_level("Physics", "Base") - # Get the root position of our veg area and use it to position our camera. - # This is useful both to ensure that vegetation is spawned where we're querying and to - # visually verify the number of instances in each box - position = azlmbr.components.TransformBus(azlmbr.bus.Event, "GetWorldTranslation", spawner_entity.id) - general.set_current_view_position(position.x, position.y, position.z + 30.0) - general.set_current_view_rotation(-90.0, 0.0, 0.0) + # Create vegetation layer spawner + world_center = math.Vector3(512.0, 512.0, 32.0) + asset_path = os.path.join("Slices", "PurpleFlower.dynamicslice") + spawner_entity = dynveg.create_vegetation_area("Spawner Instance", world_center, 16.0, 16.0, 16.0, asset_path) - # When centered over the veg area, we expect to find 400 instances. - # (16x16 area, 20 points per 16 meters) - num_expected = 400 - result = self.wait_for_condition(lambda: dynveg.validate_instance_count_in_entity_shape(spawner_entity.id, - num_expected), 2.0) - self.test_success = self.test_success and result + # Create a surface to spawn on + dynveg.create_surface_entity("Spawner Entity", world_center, 16.0, 16.0, 1.0) - # Move sufficiently far away from the veg area that it should all despawn. - general.set_current_view_position(position.x - 1000.0, position.y - 1000.0, position.z + 30.0) + # Get the root position of our veg area and use it to position our camera. + # This is useful both to ensure that vegetation is spawned where we're querying and to + # visually verify the number of instances in each box + position = azlmbr.components.TransformBus(azlmbr.bus.Event, "GetWorldTranslation", spawner_entity.id) + general.set_current_view_position(position.x, position.y, position.z + 30.0) + general.set_current_view_rotation(-90.0, 0.0, 0.0) - # We now expect to find 0 instances. If the bug exists, we will find 400 still. - num_expected = 0 - result = self.wait_for_condition(lambda: dynveg.validate_instance_count_in_entity_shape(spawner_entity.id, - num_expected), 2.0) - self.test_success = self.test_success and result + # When centered over the veg area, we expect to find 400 instances. + # (16x16 area, 20 points per 16 meters) + num_expected = 400 + result = helper.wait_for_condition(lambda: dynveg.validate_instance_count_in_entity_shape(spawner_entity.id, + num_expected), 2.0) + Report.result(Tests.instance_validation_close, result) + + # Move sufficiently far away from the veg area that it should all despawn. + general.set_current_view_position(position.x - 1000.0, position.y - 1000.0, position.z + 30.0) + + # We now expect to find 0 instances. If the bug exists, we will find 400 still. + num_expected = 0 + result = helper.wait_for_condition(lambda: dynveg.validate_instance_count_in_entity_shape(spawner_entity.id, + num_expected), 2.0) + Report.result(Tests.instance_validation_far, result) -test = TestVegetationInstances_DespawnWhenOutOfRange() -test.run() +if __name__ == "__main__": + + from editor_python_test_tools.utils import Report + Report.start_test(VegetationInstances_DespawnWhenOutOfRange) diff --git a/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/TestSuite_Main.py b/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/TestSuite_Main.py new file mode 100644 index 0000000000..4c02c887ef --- /dev/null +++ b/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/TestSuite_Main.py @@ -0,0 +1,27 @@ +""" +Copyright (c) Contributors to the Open 3D Engine Project. +For complete copyright and license terms please see the LICENSE at the root of this distribution. + +SPDX-License-Identifier: Apache-2.0 OR MIT +""" + +import os +import pytest +import sys + +sys.path.append(os.path.dirname(os.path.abspath(__file__)) + '/../../automatedtesting_shared') +from base import TestAutomationBase + + +@pytest.mark.SUITE_main +@pytest.mark.parametrize("launcher_platform", ['windows_editor']) +@pytest.mark.parametrize("project", ["AutomatedTesting"]) +class TestAutomation(TestAutomationBase): + + def test_DynamicSliceInstanceSpawner_DynamicSliceSpawnerWorks(self, request, workspace, editor, launcher_platform): + from .EditorScripts import DynamicSliceInstanceSpawner_DynamicSliceSpawnerWorks as test_module + self._run_test(request, workspace, editor, test_module) + + def test_EmptyInstanceSpawner_EmptySpawnerWorks(self, request, workspace, editor, launcher_platform): + from .EditorScripts import EmptyInstanceSpawner_EmptySpawnerWorks as test_module + self._run_test(request, workspace, editor, test_module) diff --git a/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/TestSuite_Main_Optimized.py b/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/TestSuite_Main_Optimized.py new file mode 100644 index 0000000000..ded2dda4e9 --- /dev/null +++ b/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/TestSuite_Main_Optimized.py @@ -0,0 +1,172 @@ +""" +Copyright (c) Contributors to the Open 3D Engine Project. +For complete copyright and license terms please see the LICENSE at the root of this distribution. + +SPDX-License-Identifier: Apache-2.0 OR MIT +""" + +import os +import pytest + +import ly_test_tools.environment.file_system as file_system +from ly_test_tools.o3de.editor_test import EditorSingleTest, EditorSharedTest, EditorParallelTest, EditorTestSuite + + +@pytest.mark.xfail(reason="Optimized tests are experimental, we will enable xfail and monitor them temporarily.") +@pytest.mark.SUITE_main +@pytest.mark.parametrize("launcher_platform", ['windows_editor']) +@pytest.mark.parametrize("project", ["AutomatedTesting"]) +class TestAutomation(EditorTestSuite): + + class test_DynamicSliceInstanceSpawner_DynamicSliceSpawnerWorks(EditorParallelTest): + from .EditorScripts import DynamicSliceInstanceSpawner_DynamicSliceSpawnerWorks as test_module + + class test_EmptyInstanceSpawner_EmptySpawnerWorks(EditorParallelTest): + from .EditorScripts import EmptyInstanceSpawner_EmptySpawnerWorks as test_module + + class test_AltitudeFilter_ComponentAndOverrides_InstancesPlantAtSpecifiedAltitude(EditorParallelTest): + from .EditorScripts import AltitudeFilter_ComponentAndOverrides_InstancesPlantAtSpecifiedAltitude as test_module + + class test_AltitudeFilter_ShapeSample_InstancesPlantAtSpecifiedAltitude(EditorParallelTest): + from .EditorScripts import AltitudeFilter_ShapeSample_InstancesPlantAtSpecifiedAltitude as test_module + + class test_AltitudeFilter_FilterStageToggle(EditorParallelTest): + from .EditorScripts import AltitudeFilter_FilterStageToggle as test_module + + class test_SpawnerSlices_SliceCreationAndVisibilityToggleWorks(EditorSingleTest): + # Custom teardown to remove slice asset created during test + def teardown(self, request, workspace, editor, editor_test_results, launcher_platform): + file_system.delete([os.path.join(workspace.paths.engine_root(), "AutomatedTesting", "slices", + "TestSlice_1.slice")], True, True) + file_system.delete([os.path.join(workspace.paths.engine_root(), "AutomatedTesting", "slices", + "TestSlice_2.slice")], True, True) + from .EditorScripts import SpawnerSlices_SliceCreationAndVisibilityToggleWorks as test_module + + class test_AssetListCombiner_CombinedDescriptorsExpressInConfiguredArea(EditorParallelTest): + from .EditorScripts import AssetListCombiner_CombinedDescriptorsExpressInConfiguredArea as test_module + + class test_AssetWeightSelector_InstancesExpressBasedOnWeight(EditorParallelTest): + from .EditorScripts import AssetWeightSelector_InstancesExpressBasedOnWeight as test_module + + @pytest.mark.skip(reason="https://github.com/o3de/o3de/issues/4155") + class test_DistanceBetweenFilter_InstancesPlantAtSpecifiedRadius(EditorParallelTest): + from .EditorScripts import DistanceBetweenFilter_InstancesPlantAtSpecifiedRadius as test_module + + @pytest.mark.skip(reason="https://github.com/o3de/o3de/issues/4155") + class test_DistanceBetweenFilterOverrides_InstancesPlantAtSpecifiedRadius(EditorParallelTest): + from .EditorScripts import DistanceBetweenFilterOverrides_InstancesPlantAtSpecifiedRadius as test_module + + class test_SurfaceDataRefreshes_RemainsStable(EditorParallelTest): + from .EditorScripts import SurfaceDataRefreshes_RemainsStable as test_module + + class test_VegetationInstances_DespawnWhenOutOfRange(EditorParallelTest): + from .EditorScripts import VegetationInstances_DespawnWhenOutOfRange as test_module + + class test_InstanceSpawnerPriority_LayerAndSubPriority_HigherValuesPlantOverLower(EditorParallelTest): + from .EditorScripts import InstanceSpawnerPriority_LayerAndSubPriority as test_module + + class test_LayerBlocker_InstancesBlockedInConfiguredArea(EditorParallelTest): + from .EditorScripts import LayerBlocker_InstancesBlockedInConfiguredArea as test_module + + class test_LayerSpawner_InheritBehaviorFlag(EditorParallelTest): + from .EditorScripts import LayerSpawner_InheritBehaviorFlag as test_module + + class test_LayerSpawner_InstancesPlantInAllSupportedShapes(EditorParallelTest): + from .EditorScripts import LayerSpawner_InstancesPlantInAllSupportedShapes as test_module + + class test_LayerSpawner_FilterStageToggle(EditorParallelTest): + from .EditorScripts import LayerSpawner_FilterStageToggle as test_module + + @pytest.mark.xfail(reason="https://github.com/o3de/o3de/issues/2038") + class test_LayerSpawner_InstancesRefreshUsingCorrectViewportCamera(EditorParallelTest): + from .EditorScripts import LayerSpawner_InstancesRefreshUsingCorrectViewportCamera as test_module + + class test_MeshBlocker_InstancesBlockedByMesh(EditorParallelTest): + from .EditorScripts import MeshBlocker_InstancesBlockedByMesh as test_module + + class test_MeshBlocker_InstancesBlockedByMeshHeightTuning(EditorParallelTest): + from .EditorScripts import MeshBlocker_InstancesBlockedByMeshHeightTuning as test_module + + class test_MeshSurfaceTagEmitter_DependentOnMeshComponent(EditorParallelTest): + from .EditorScripts import MeshSurfaceTagEmitter_DependentOnMeshComponent as test_module + + class test_MeshSurfaceTagEmitter_SurfaceTagsAddRemoveSuccessfully(EditorParallelTest): + from .EditorScripts import MeshSurfaceTagEmitter_SurfaceTagsAddRemoveSuccessfully as test_module + + class test_PhysXColliderSurfaceTagEmitter_E2E_Editor(EditorParallelTest): + from .EditorScripts import PhysXColliderSurfaceTagEmitter_E2E_Editor as test_module + + class test_PositionModifier_ComponentAndOverrides_InstancesPlantAtSpecifiedOffsets(EditorParallelTest): + from .EditorScripts import PositionModifier_ComponentAndOverrides_InstancesPlantAtSpecifiedOffsets as test_module + + class test_PositionModifier_AutoSnapToSurfaceWorks(EditorParallelTest): + from .EditorScripts import PositionModifier_AutoSnapToSurfaceWorks as test_module + + class test_RotationModifier_InstancesRotateWithinRange(EditorParallelTest): + from .EditorScripts import RotationModifier_InstancesRotateWithinRange as test_module + + class test_RotationModifierOverrides_InstancesRotateWithinRange(EditorParallelTest): + from .EditorScripts import RotationModifierOverrides_InstancesRotateWithinRange as test_module + + class test_ScaleModifier_InstancesProperlyScale(EditorParallelTest): + from .EditorScripts import ScaleModifier_InstancesProperlyScale as test_module + + class test_ScaleModifierOverrides_InstancesProperlyScale(EditorParallelTest): + from .EditorScripts import ScaleModifierOverrides_InstancesProperlyScale as test_module + + class test_ShapeIntersectionFilter_InstancesPlantInAssignedShape(EditorParallelTest): + from .EditorScripts import ShapeIntersectionFilter_InstancesPlantInAssignedShape as test_module + + class test_ShapeIntersectionFilter_FilterStageToggle(EditorParallelTest): + from .EditorScripts import ShapeIntersectionFilter_FilterStageToggle as test_module + + class test_SlopeAlignmentModifier_InstanceSurfaceAlignment(EditorParallelTest): + from .EditorScripts import SlopeAlignmentModifier_InstanceSurfaceAlignment as test_module + + class test_SlopeAlignmentModifierOverrides_InstanceSurfaceAlignment(EditorParallelTest): + from .EditorScripts import SlopeAlignmentModifierOverrides_InstanceSurfaceAlignment as test_module + + class test_SurfaceMaskFilter_BasicSurfaceTagCreation(EditorParallelTest): + from .EditorScripts import SurfaceMaskFilter_BasicSurfaceTagCreation as test_module + + class test_SurfaceMaskFilter_ExclusiveSurfaceTags_Function(EditorParallelTest): + from .EditorScripts import SurfaceMaskFilter_ExclusionList as test_module + + class test_SurfaceMaskFilter_InclusiveSurfaceTags_Function(EditorParallelTest): + from .EditorScripts import SurfaceMaskFilter_InclusionList as test_module + + class test_SurfaceMaskFilterOverrides_MultipleDescriptorOverridesPlantAsExpected(EditorParallelTest): + from .EditorScripts import SurfaceMaskFilterOverrides_MultipleDescriptorOverridesPlantAsExpected as test_module + + class test_SystemSettings_SectorPointDensity(EditorParallelTest): + from .EditorScripts import SystemSettings_SectorPointDensity as test_module + + class test_SystemSettings_SectorSize(EditorParallelTest): + from .EditorScripts import SystemSettings_SectorSize as test_module + + class test_SlopeFilter_ComponentAndOverrides_InstancesPlantOnValidSlopes(EditorParallelTest): + from .EditorScripts import SlopeFilter_ComponentAndOverrides_InstancesPlantOnValidSlope as test_module + + class test_DynamicSliceInstanceSpawner_Embedded_E2E_Editor(EditorSingleTest): + from .EditorScripts import DynamicSliceInstanceSpawner_Embedded_E2E as test_module + + # Custom teardown to remove test level created during test + def teardown(self, request, workspace, editor, editor_test_results, launcher_platform): + file_system.delete([os.path.join(workspace.paths.engine_root(), "AutomatedTesting", "Levels", "tmp_level")], + True, True) + + class test_DynamicSliceInstanceSpawner_External_E2E_Editor(EditorSingleTest): + from .EditorScripts import DynamicSliceInstanceSpawner_External_E2E as test_module + + # Custom teardown to remove test level created during test + def teardown(self, request, workspace, editor, editor_test_results, launcher_platform): + file_system.delete([os.path.join(workspace.paths.engine_root(), "AutomatedTesting", "Levels", "tmp_level")], + True, True) + + class test_LayerBlender_E2E_Editor(EditorSingleTest): + from .EditorScripts import LayerBlender_E2E_Editor as test_module + + # Custom teardown to remove test level created during test + def teardown(self, request, workspace, editor, editor_test_results, launcher_platform): + file_system.delete([os.path.join(workspace.paths.engine_root(), "AutomatedTesting", "Levels", "tmp_level")], + True, True) diff --git a/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/TestSuite_Periodic.py b/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/TestSuite_Periodic.py new file mode 100644 index 0000000000..2780c0f471 --- /dev/null +++ b/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/TestSuite_Periodic.py @@ -0,0 +1,283 @@ +""" +Copyright (c) Contributors to the Open 3D Engine Project. +For complete copyright and license terms please see the LICENSE at the root of this distribution. + +SPDX-License-Identifier: Apache-2.0 OR MIT +""" + +import os +import pytest +import sys + +import ly_test_tools.environment.waiter as waiter +import ly_test_tools.environment.file_system as file_system +import editor_python_test_tools.hydra_test_utils as hydra +from ly_remote_console.remote_console_commands import RemoteConsole as RemoteConsole + +sys.path.append(os.path.dirname(os.path.abspath(__file__)) + '/../../automatedtesting_shared') +from base import TestAutomationBase + + +@pytest.fixture +def remove_test_slice(request, workspace, project): + file_system.delete([os.path.join(workspace.paths.engine_root(), project, "slices", "TestSlice_1.slice")], True, + True) + file_system.delete([os.path.join(workspace.paths.engine_root(), project, "slices", "TestSlice_2.slice")], True, + True) + + def teardown(): + file_system.delete([os.path.join(workspace.paths.engine_root(), project, "slices", "TestSlice_1.slice")], True, + True) + file_system.delete([os.path.join(workspace.paths.engine_root(), project, "slices", "TestSlice_2.slice")], True, + True) + request.addfinalizer(teardown) + + +@pytest.fixture +def remote_console_instance(request): + console = RemoteConsole() + + def teardown(): + if console.connected: + console.stop() + + request.addfinalizer(teardown) + return console + + +@pytest.mark.SUITE_periodic +@pytest.mark.parametrize("launcher_platform", ['windows_editor']) +@pytest.mark.parametrize("project", ["AutomatedTesting"]) +class TestAutomation(TestAutomationBase): + + def test_AltitudeFilter_ComponentAndOverrides_InstancesPlantAtSpecifiedAltitude(self, request, workspace, editor, launcher_platform): + from .EditorScripts import AltitudeFilter_ComponentAndOverrides_InstancesPlantAtSpecifiedAltitude as test_module + self._run_test(request, workspace, editor, test_module) + + def test_AltitudeFilter_ShapeSample_InstancesPlantAtSpecifiedAltitude(self, request, workspace, editor, launcher_platform): + from .EditorScripts import AltitudeFilter_ShapeSample_InstancesPlantAtSpecifiedAltitude as test_module + self._run_test(request, workspace, editor, test_module) + + def test_AltitudeFilter_FilterStageToggle(self, request, workspace, editor, launcher_platform): + from .EditorScripts import AltitudeFilter_FilterStageToggle as test_module + self._run_test(request, workspace, editor, test_module) + + def test_SpawnerSlices_SliceCreationAndVisibilityToggleWorks(self, request, workspace, editor, remove_test_slice, launcher_platform): + from .EditorScripts import SpawnerSlices_SliceCreationAndVisibilityToggleWorks as test_module + self._run_test(request, workspace, editor, test_module) + + def test_AssetListCombiner_CombinedDescriptorsExpressInConfiguredArea(self, request, workspace, editor, launcher_platform): + from .EditorScripts import AssetListCombiner_CombinedDescriptorsExpressInConfiguredArea as test_module + self._run_test(request, workspace, editor, test_module) + + def test_AssetWeightSelector_InstancesExpressBasedOnWeight(self, request, workspace, editor, launcher_platform): + from .EditorScripts import AssetWeightSelector_InstancesExpressBasedOnWeight as test_module + self._run_test(request, workspace, editor, test_module) + + @pytest.mark.xfail(reason="https://github.com/o3de/o3de/issues/4155") + def test_DistanceBetweenFilter_InstancesPlantAtSpecifiedRadius(self, request, workspace, editor, launcher_platform): + from .EditorScripts import DistanceBetweenFilter_InstancesPlantAtSpecifiedRadius as test_module + self._run_test(request, workspace, editor, test_module) + + @pytest.mark.xfail(reason="https://github.com/o3de/o3de/issues/4155") + def test_DistanceBetweenFilterOverrides_InstancesPlantAtSpecifiedRadius(self, request, workspace, editor, launcher_platform): + from .EditorScripts import DistanceBetweenFilterOverrides_InstancesPlantAtSpecifiedRadius as test_module + self._run_test(request, workspace, editor, test_module) + + def test_SurfaceDataRefreshes_RemainsStable(self, request, workspace, editor, launcher_platform): + from .EditorScripts import SurfaceDataRefreshes_RemainsStable as test_module + self._run_test(request, workspace, editor, test_module) + + def test_VegetationInstances_DespawnWhenOutOfRange(self, request, workspace, editor, launcher_platform): + from .EditorScripts import VegetationInstances_DespawnWhenOutOfRange as test_module + self._run_test(request, workspace, editor, test_module) + + def test_InstanceSpawnerPriority_LayerAndSubPriority_HigherValuesPlantOverLower(self, request, workspace, editor, launcher_platform): + from .EditorScripts import InstanceSpawnerPriority_LayerAndSubPriority as test_module + self._run_test(request, workspace, editor, test_module) + + def test_LayerBlocker_InstancesBlockedInConfiguredArea(self, request, workspace, editor, launcher_platform): + from .EditorScripts import LayerBlocker_InstancesBlockedInConfiguredArea as test_module + self._run_test(request, workspace, editor, test_module) + + def test_LayerSpawner_InheritBehaviorFlag(self, request, workspace, editor, launcher_platform): + from .EditorScripts import LayerSpawner_InheritBehaviorFlag as test_module + self._run_test(request, workspace, editor, test_module) + + def test_LayerSpawner_InstancesPlantInAllSupportedShapes(self, request, workspace, editor, launcher_platform): + from .EditorScripts import LayerSpawner_InstancesPlantInAllSupportedShapes as test_module + self._run_test(request, workspace, editor, test_module) + + def test_LayerSpawner_FilterStageToggle(self, request, workspace, editor, launcher_platform): + from .EditorScripts import LayerSpawner_FilterStageToggle as test_module + self._run_test(request, workspace, editor, test_module) + + @pytest.mark.xfail(reason="https://github.com/o3de/o3de/issues/2038") + def test_LayerSpawner_InstancesRefreshUsingCorrectViewportCamera(self, request, workspace, editor, launcher_platform): + from .EditorScripts import LayerSpawner_InstancesRefreshUsingCorrectViewportCamera as test_module + self._run_test(request, workspace, editor, test_module) + + def test_MeshBlocker_InstancesBlockedByMesh(self, request, workspace, editor, launcher_platform): + from .EditorScripts import MeshBlocker_InstancesBlockedByMesh as test_module + self._run_test(request, workspace, editor, test_module) + + def test_MeshBlocker_InstancesBlockedByMeshHeightTuning(self, request, workspace, editor, launcher_platform): + from .EditorScripts import MeshBlocker_InstancesBlockedByMeshHeightTuning as test_module + self._run_test(request, workspace, editor, test_module) + + def test_MeshSurfaceTagEmitter_DependentOnMeshComponent(self, request, workspace, editor, launcher_platform): + from .EditorScripts import MeshSurfaceTagEmitter_DependentOnMeshComponent as test_module + self._run_test(request, workspace, editor, test_module) + + def test_MeshSurfaceTagEmitter_SurfaceTagsAddRemoveSuccessfully(self, request, workspace, editor, launcher_platform): + from .EditorScripts import MeshSurfaceTagEmitter_SurfaceTagsAddRemoveSuccessfully as test_module + self._run_test(request, workspace, editor, test_module) + + def test_PhysXColliderSurfaceTagEmitter_E2E_Editor(self, request, workspace, editor, launcher_platform): + from .EditorScripts import PhysXColliderSurfaceTagEmitter_E2E_Editor as test_module + self._run_test(request, workspace, editor, test_module) + + def test_PositionModifier_ComponentAndOverrides_InstancesPlantAtSpecifiedOffsets(self, request, workspace, editor, launcher_platform): + from .EditorScripts import PositionModifier_ComponentAndOverrides_InstancesPlantAtSpecifiedOffsets as test_module + self._run_test(request, workspace, editor, test_module) + + def test_PositionModifier_AutoSnapToSurfaceWorks(self, request, workspace, editor, launcher_platform): + from .EditorScripts import PositionModifier_AutoSnapToSurfaceWorks as test_module + self._run_test(request, workspace, editor, test_module) + + def test_RotationModifier_InstancesRotateWithinRange(self, request, workspace, editor, launcher_platform): + from .EditorScripts import RotationModifier_InstancesRotateWithinRange as test_module + self._run_test(request, workspace, editor, test_module) + + def test_RotationModifierOverrides_InstancesRotateWithinRange(self, request, workspace, editor, launcher_platform): + from .EditorScripts import RotationModifierOverrides_InstancesRotateWithinRange as test_module + self._run_test(request, workspace, editor, test_module) + + def test_ScaleModifier_InstancesProperlyScale(self, request, workspace, editor, launcher_platform): + from .EditorScripts import ScaleModifier_InstancesProperlyScale as test_module + self._run_test(request, workspace, editor, test_module) + + def test_ScaleModifierOverrides_InstancesProperlyScale(self, request, workspace, editor, launcher_platform): + from .EditorScripts import ScaleModifierOverrides_InstancesProperlyScale as test_module + self._run_test(request, workspace, editor, test_module) + + def test_ShapeIntersectionFilter_InstancesPlantInAssignedShape(self, request, workspace, editor, launcher_platform): + from .EditorScripts import ShapeIntersectionFilter_InstancesPlantInAssignedShape as test_module + self._run_test(request, workspace, editor, test_module) + + def test_ShapeIntersectionFilter_FilterStageToggle(self, request, workspace, editor, launcher_platform): + from .EditorScripts import ShapeIntersectionFilter_FilterStageToggle as test_module + self._run_test(request, workspace, editor, test_module) + + def test_SlopeAlignmentModifier_InstanceSurfaceAlignment(self, request, workspace, editor, launcher_platform): + from .EditorScripts import SlopeAlignmentModifier_InstanceSurfaceAlignment as test_module + self._run_test(request, workspace, editor, test_module) + + def test_SlopeAlignmentModifierOverrides_InstanceSurfaceAlignment(self, request, workspace, editor, launcher_platform): + from .EditorScripts import SlopeAlignmentModifierOverrides_InstanceSurfaceAlignment as test_module + self._run_test(request, workspace, editor, test_module) + + def test_SurfaceMaskFilter_BasicSurfaceTagCreation(self, request, workspace, editor, launcher_platform): + from .EditorScripts import SurfaceMaskFilter_BasicSurfaceTagCreation as test_module + self._run_test(request, workspace, editor, test_module) + + def test_SurfaceMaskFilter_ExclusiveSurfaceTags_Function(self, request, workspace, editor, launcher_platform): + from .EditorScripts import SurfaceMaskFilter_ExclusionList as test_module + self._run_test(request, workspace, editor, test_module) + + def test_SurfaceMaskFilter_InclusiveSurfaceTags_Function(self, request, workspace, editor, launcher_platform): + from .EditorScripts import SurfaceMaskFilter_InclusionList as test_module + self._run_test(request, workspace, editor, test_module) + + def test_SurfaceMaskFilterOverrides_MultipleDescriptorOverridesPlantAsExpected(self, request, workspace, editor, launcher_platform): + from .EditorScripts import SurfaceMaskFilterOverrides_MultipleDescriptorOverridesPlantAsExpected as test_module + self._run_test(request, workspace, editor, test_module) + + def test_SystemSettings_SectorPointDensity(self, request, workspace, editor, launcher_platform): + from .EditorScripts import SystemSettings_SectorPointDensity as test_module + self._run_test(request, workspace, editor, test_module) + + def test_SystemSettings_SectorSize(self, request, workspace, editor, launcher_platform): + from .EditorScripts import SystemSettings_SectorSize as test_module + self._run_test(request, workspace, editor, test_module) + + def test_SlopeFilter_ComponentAndOverrides_InstancesPlantOnValidSlopes(self, request, workspace, editor, launcher_platform): + from .EditorScripts import SlopeFilter_ComponentAndOverrides_InstancesPlantOnValidSlope as test_module + self._run_test(request, workspace, editor, test_module) + + +@pytest.mark.SUITE_periodic +@pytest.mark.parametrize("project", ["AutomatedTesting"]) +@pytest.mark.parametrize("level", ["tmp_level"]) +class TestAutomationE2E(TestAutomationBase): + + # The following tests must run in order, please do not move tests out of order + + @pytest.mark.parametrize("launcher_platform", ['windows_editor']) + def test_DynamicSliceInstanceSpawner_Embedded_E2E_Editor(self, request, workspace, project, level, editor, launcher_platform): + # Ensure our test level does not already exist + file_system.delete([os.path.join(workspace.paths.engine_root(), project, "Levels", level)], True, True) + + from .EditorScripts import DynamicSliceInstanceSpawner_Embedded_E2E as test_module + self._run_test(request, workspace, editor, test_module) + + @pytest.mark.parametrize("launcher_platform", ['windows']) + def test_DynamicSliceInstanceSpawner_Embedded_E2E_Launcher(self, workspace, launcher, level, + remote_console_instance, project, launcher_platform): + + expected_lines = [ + "Instances found in area = 400" + ] + + hydra.launch_and_validate_results_launcher(launcher, level, remote_console_instance, expected_lines, launch_ap=False) + + # Cleanup our temp level + file_system.delete([os.path.join(workspace.paths.engine_root(), project, "Levels", level)], True, True) + + @pytest.mark.parametrize("launcher_platform", ['windows_editor']) + def test_DynamicSliceInstanceSpawner_External_E2E_Editor(self, request, workspace, project, level, editor, launcher_platform): + # Ensure our test level does not already exist + file_system.delete([os.path.join(workspace.paths.engine_root(), project, "Levels", level)], True, True) + + from .EditorScripts import DynamicSliceInstanceSpawner_External_E2E as test_module + self._run_test(request, workspace, editor, test_module) + + @pytest.mark.parametrize("launcher_platform", ['windows']) + def test_DynamicSliceInstanceSpawner_External_E2E_Launcher(self, workspace, launcher, level, + remote_console_instance, project, launcher_platform): + + expected_lines = [ + "Instances found in area = 400" + ] + + hydra.launch_and_validate_results_launcher(launcher, level, remote_console_instance, expected_lines, launch_ap=False) + + # Cleanup our temp level + file_system.delete([os.path.join(workspace.paths.engine_root(), project, "Levels", level)], True, True) + + @pytest.mark.parametrize("launcher_platform", ['windows_editor']) + def test_LayerBlender_E2E_Editor(self, request, workspace, project, level, editor, launcher_platform): + # Ensure our test level does not already exist + file_system.delete([os.path.join(workspace.paths.engine_root(), project, "Levels", level)], True, True) + + from .EditorScripts import LayerBlender_E2E_Editor as test_module + self._run_test(request, workspace, editor, test_module) + + @pytest.mark.parametrize("launcher_platform", ['windows']) + @pytest.mark.xfail(reason="https://github.com/o3de/o3de/issues/4170") + def test_LayerBlender_E2E_Launcher(self, workspace, launcher, level, + remote_console_instance, project, launcher_platform): + + launcher.args.extend(["-rhi=Null"]) + launcher.start(launch_ap=False) + assert launcher.is_alive(), "Launcher failed to start" + + # Wait for test script to quit the launcher. If wait_for returns exc, test was not successful + waiter.wait_for(lambda: not launcher.is_alive(), timeout=300) + + # Verify launcher quit successfully and did not crash + ret_code = launcher.get_returncode() + assert ret_code == 0, "Test failed. See Game.log for details" + + # Cleanup our temp level + file_system.delete([os.path.join(workspace.paths.engine_root(), project, "Levels", level)], True, True) diff --git a/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/test_AltitudeFilter.py b/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/test_AltitudeFilter.py deleted file mode 100755 index ec8c225d3b..0000000000 --- a/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/test_AltitudeFilter.py +++ /dev/null @@ -1,111 +0,0 @@ -""" -Copyright (c) Contributors to the Open 3D Engine Project. -For complete copyright and license terms please see the LICENSE at the root of this distribution. - -SPDX-License-Identifier: Apache-2.0 OR MIT -""" - -import os -import pytest -import logging -# Bail on the test if ly_test_tools doesn't exist. -pytest.importorskip('ly_test_tools') -import ly_test_tools.environment.file_system as file_system -import editor_python_test_tools.hydra_test_utils as hydra - -logger = logging.getLogger(__name__) -test_directory = os.path.join(os.path.dirname(__file__), 'EditorScripts') - - -@pytest.mark.parametrize("project", ["AutomatedTesting"]) -@pytest.mark.parametrize("level", ["tmp_level"]) -@pytest.mark.usefixtures("automatic_process_killer") -@pytest.mark.parametrize("launcher_platform", ['windows_editor']) -class TestAltitudeFilter(object): - - @pytest.fixture(autouse=True) - def setup_teardown(self, request, workspace, project, level): - def teardown(): - file_system.delete([os.path.join(workspace.paths.engine_root(), project, "Levels", level)], True, True) - request.addfinalizer(teardown) - - file_system.delete([os.path.join(workspace.paths.engine_root(), project, "Levels", level)], True, True) - - @pytest.mark.test_case_id('C4814463', 'C4847477') - @pytest.mark.SUITE_periodic - @pytest.mark.dynveg_filter - def test_AltitudeFilter_ComponentAndOverrides_InstancesPlantAtSpecifiedAltitude(self, request, editor, level, - launcher_platform): - - expected_lines = [ - "'Instance Spawner' created", - "'Planting Surface' created", - "'Planting Surface Elevated' created", - "instance count validation: True (found=3200, expected=3200)", - "instance count validation: True (found=1600, expected=1600)", - "instance count validation: True (found=400, expected=400)", - "AltitudeFilterComponentAndOverrides: result=SUCCESS" - ] - - hydra.launch_and_validate_results( - request, - test_directory, - editor, - "AltitudeFilter_ComponentAndOverrides_InstancesPlantAtSpecifiedAltitude.py", - expected_lines, - cfg_args=[level] - ) - - @pytest.mark.test_case_id("C4847476") - @pytest.mark.SUITE_periodic - @pytest.mark.dynveg_filter - def test_AltitudeFilter_ShapeSample_InstancesPlantAtSpecifiedAltitude(self, request, editor, level, - launcher_platform): - - expected_lines = [ - "'Instance Spawner' created", - "'Planting Surface' created", - "'Planting Surface Elevated' created", - "instance count validation: True (found=800, expected=800)", - "'Shape Sampler' created", - "instance count validation: True (found=400, expected=400)", - "AltitudeFilterShapeSample: result=SUCCESS" - ] - - hydra.launch_and_validate_results( - request, - test_directory, - editor, - "AltitudeFilter_ShapeSample_InstancesPlantAtSpecifiedAltitude.py", - expected_lines, - cfg_args=[level] - ) - - @pytest.mark.test_case_id("C4847478") - @pytest.mark.SUITE_periodic - @pytest.mark.dynveg_filter - @pytest.mark.xfail(reason="https://github.com/o3de/o3de/issues/2303") - def test_AltitudeFilter_FilterStageToggle(self, request, editor, level, workspace, launcher_platform): - cfg_args = [level] - - expected_lines = [ - "AltitudeFilter_FilterStageToggle: test started", - "AltitudeFilter_FilterStageToggle: Vegetation instances count equal to expected value for PREPROCESS filter stage: True", - "AltitudeFilter_FilterStageToggle: Vegetation instances count equal to expected value for POSTPROCESS filter stage: True", - "AltitudeFilter_FilterStageToggle: result=SUCCESS", - ] - - unexpected_lines = [ - "AltitudeFilter_FilterStageToggle: Vegetation instances count equal to expected value for PREPROCESS filter stage: False", - "AltitudeFilter_FilterStageToggle: Vegetation instances count equal to expected value for POSTPROCESS filter stage: False", - ] - - hydra.launch_and_validate_results( - request, - test_directory, - editor, - "AltitudeFilter_FilterStageToggle.py", - expected_lines=expected_lines, - unexpected_lines=unexpected_lines, - cfg_args=cfg_args - ) diff --git a/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/test_AreaComponentSlices.py b/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/test_AreaComponentSlices.py deleted file mode 100755 index 7c72105957..0000000000 --- a/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/test_AreaComponentSlices.py +++ /dev/null @@ -1,72 +0,0 @@ -""" -Copyright (c) Contributors to the Open 3D Engine Project. -For complete copyright and license terms please see the LICENSE at the root of this distribution. - -SPDX-License-Identifier: Apache-2.0 OR MIT -""" - -import os -import pytest -import logging - -# Bail on the test if ly_test_tools doesn't exist. -pytest.importorskip("ly_test_tools") -import ly_test_tools.environment.file_system as file_system -import editor_python_test_tools.hydra_test_utils as hydra - -logger = logging.getLogger(__name__) -test_directory = os.path.join(os.path.dirname(__file__), "EditorScripts") - - -@pytest.mark.parametrize("project", ["AutomatedTesting"]) -@pytest.mark.parametrize("level", ["tmp_level"]) -@pytest.mark.usefixtures("automatic_process_killer") -@pytest.mark.parametrize("launcher_platform", ['windows_editor']) -class TestAreaComponents(object): - @pytest.fixture(autouse=True) - def setup_teardown(self, request, workspace, project, level): - # Cleanup our temp level - file_system.delete([os.path.join(workspace.paths.engine_root(), project, "Levels", level)], True, True) - - # Cleanup the test slices - file_system.delete([os.path.join(workspace.paths.engine_root(), project, "slices", "TestSlice_1.slice")], True, True) - file_system.delete([os.path.join(workspace.paths.engine_root(), project, "slices", "TestSlice_2.slice")], True, True) - - def teardown(): - # Cleanup our temp level - file_system.delete([os.path.join(workspace.paths.engine_root(), project, "Levels", level)], True, True) - - # Cleanup the test slices - file_system.delete( - [os.path.join(workspace.paths.engine_root(), project, "slices", "TestSlice_1.slice")], True, True - ) - file_system.delete( - [os.path.join(workspace.paths.engine_root(), project, "slices", "TestSlice_2.slice")], True, True - ) - - request.addfinalizer(teardown) - - @pytest.mark.test_case_id("C2627900", "C2627905", "C2627904") - @pytest.mark.SUITE_periodic - @pytest.mark.dynveg_misc - def test_AreaComponents_SliceCreationVisibilityToggleWorks(self, request, editor, level, workspace, - launcher_platform): - cfg_args = [level] - - expected_lines = [ - "AreaComponentSlices_SliceCreationAndVisibilityToggle: test started", - "AreaComponentSlices_SliceCreationAndVisibilityToggle: Slice has been created successfully (entity with spawner component): True", - "AreaComponentSlices_SliceCreationAndVisibilityToggle: Vegetation plants initially when slice is shown: True", - "AreaComponentSlices_SliceCreationAndVisibilityToggle: Vegetation is cleared when slice is hidden: True", - "AreaComponentSlices_SliceCreationAndVisibilityToggle: Slice has been created successfully (entity with blender component): True", - "AreaComponentSlices_SliceCreationAndVisibilityToggle: result=SUCCESS", - ] - - hydra.launch_and_validate_results( - request, - test_directory, - editor, - "AreaComponentSlices_SliceCreationAndVisibilityToggle.py", - expected_lines=expected_lines, - cfg_args=cfg_args - ) diff --git a/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/test_AssetListCombiner.py b/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/test_AssetListCombiner.py deleted file mode 100755 index 5deaa9199e..0000000000 --- a/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/test_AssetListCombiner.py +++ /dev/null @@ -1,63 +0,0 @@ -""" -Copyright (c) Contributors to the Open 3D Engine Project. -For complete copyright and license terms please see the LICENSE at the root of this distribution. - -SPDX-License-Identifier: Apache-2.0 OR MIT -""" - -import os -import pytest -import logging - -# Bail on the test if ly_test_tools doesn't exist. -pytest.importorskip("ly_test_tools") -import ly_test_tools.environment.file_system as file_system -import editor_python_test_tools.hydra_test_utils as hydra - -logger = logging.getLogger(__name__) -test_directory = os.path.join(os.path.dirname(__file__), "EditorScripts") - - -@pytest.mark.parametrize('project', ['AutomatedTesting']) -@pytest.mark.parametrize('level', ['tmp_level']) -@pytest.mark.usefixtures("automatic_process_killer") -@pytest.mark.parametrize("launcher_platform", ['windows_editor']) -class TestAssetListCombiner(object): - - @pytest.fixture(autouse=True) - def setup_teardown(self, request, workspace, project, level): - def teardown(): - file_system.delete([os.path.join(workspace.paths.engine_root(), project, "Levels", level)], True, True) - request.addfinalizer(teardown) - - file_system.delete([os.path.join(workspace.paths.engine_root(), project, "Levels", level)], True, True) - - @pytest.mark.test_case_id("C4762374", "C4762373") - @pytest.mark.SUITE_periodic - @pytest.mark.dynveg_misc - def test_AssetListCombiner_CombinedDescriptorsExpressInConfiguredArea(self, request, editor, level, - launcher_platform): - - expected_lines = [ - "'Asset List 1' created", - "'Asset List 2' created", - "'Asset List 3' created", - "'Surface Entity' created", - "'Spawner Entity' created", - "Spawner Entity Configuration|Descriptor Providers: SUCCESS", - "Spawner Entity Configuration|Gradient|Gradient Entity Id: SUCCESS", - "instance count validation: True (found=200, expected=200.0)", - "Spawner Entity Configuration|Descriptor Providers|[1]: SUCCESS", - "instance count validation: True (found=400, expected=400)", - "instance count validation: True (found=0, expected=0)", - "AssetListCombiner_CombinedDescriptors: result=SUCCESS" - ] - - hydra.launch_and_validate_results( - request, - test_directory, - editor, - "AssetListCombiner_CombinedDescriptorsExpressInConfiguredArea.py", - expected_lines=expected_lines, - cfg_args=[level] - ) diff --git a/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/test_AssetWeightSelector.py b/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/test_AssetWeightSelector.py deleted file mode 100755 index f3cb2f4647..0000000000 --- a/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/test_AssetWeightSelector.py +++ /dev/null @@ -1,60 +0,0 @@ -""" -Copyright (c) Contributors to the Open 3D Engine Project. -For complete copyright and license terms please see the LICENSE at the root of this distribution. - -SPDX-License-Identifier: Apache-2.0 OR MIT -""" - -""" -C6269654: Vegetation areas using weight selectors properly distribute instances according to Sort By Weight setting -""" - -import os -import pytest -import logging - -# Bail on the test if ly_test_tools doesn't exist. -pytest.importorskip('ly_test_tools') -import ly_test_tools.environment.file_system as file_system -import editor_python_test_tools.hydra_test_utils as hydra - -logger = logging.getLogger(__name__) -test_directory = os.path.join(os.path.dirname(__file__), 'EditorScripts') - - -@pytest.mark.parametrize("project", ["AutomatedTesting"]) -@pytest.mark.parametrize("level", ["tmp_level"]) -@pytest.mark.usefixtures("automatic_process_killer") -@pytest.mark.parametrize("launcher_platform", ['windows_editor']) -class TestAssetWeightSelector(object): - - @pytest.fixture(autouse=True) - def setup_teardown(self, request, workspace, project, level): - def teardown(): - file_system.delete([os.path.join(workspace.paths.engine_root(), project, "Levels", level)], True, True) - request.addfinalizer(teardown) - - file_system.delete([os.path.join(workspace.paths.engine_root(), project, "Levels", level)], True, True) - - @pytest.mark.test_case_id("C6269654", "C4762368") - @pytest.mark.SUITE_sandbox - @pytest.mark.dynveg_filter - def test_AssetWeightSelector_InstancesExpressBasedOnWeight(self, request, editor, level, launcher_platform): - - expected_lines = [ - "'Instance Spawner' created", - "Instance Spawner Configuration|Embedded Assets|[1]|Instance|Slice Asset: SUCCESS", - "'Planting Surface' created", - "Configuration|Embedded Assets|[0]|Weight set to 50.0", - "Instance Spawner Configuration|Allow Empty Assets: SUCCESS", - "AssetWeightSelector_SortByWeight: result=SUCCESS", - ] - - hydra.launch_and_validate_results( - request, - test_directory, - editor, - "AssetWeightSelector_InstancesExpressBasedOnWeight.py", - expected_lines, - cfg_args=[level] - ) diff --git a/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/test_DistanceBetweenFilter.py b/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/test_DistanceBetweenFilter.py deleted file mode 100755 index 6d1b688315..0000000000 --- a/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/test_DistanceBetweenFilter.py +++ /dev/null @@ -1,76 +0,0 @@ -""" -Copyright (c) Contributors to the Open 3D Engine Project. -For complete copyright and license terms please see the LICENSE at the root of this distribution. - -SPDX-License-Identifier: Apache-2.0 OR MIT -""" - -import os -import pytest -import logging - -# Bail on the test if ly_test_tools doesn't exist. -pytest.importorskip('ly_test_tools') -import ly_test_tools.environment.file_system as file_system -import editor_python_test_tools.hydra_test_utils as hydra - -logger = logging.getLogger(__name__) -test_directory = os.path.join(os.path.dirname(__file__), 'EditorScripts') - - -@pytest.mark.parametrize("project", ["AutomatedTesting"]) -@pytest.mark.parametrize("level", ["tmp_level"]) -@pytest.mark.usefixtures("automatic_process_killer") -@pytest.mark.parametrize("launcher_platform", ['windows_editor']) -class TestDistanceBetweenFilter(object): - - @pytest.fixture(autouse=True) - def setup_teardown(self, request, workspace, project, level): - def teardown(): - file_system.delete([os.path.join(workspace.paths.engine_root(), project, "Levels", level)], True, True) - request.addfinalizer(teardown) - - file_system.delete([os.path.join(workspace.paths.engine_root(), project, "Levels", level)], True, True) - - @pytest.mark.test_case_id("C4851066") - @pytest.mark.SUITE_periodic - @pytest.mark.dynveg_filter - def test_DistanceBetweenFilter_InstancesPlantAtSpecifiedRadius(self, request, editor, level, launcher_platform): - - expected_lines = [ - "Configuration|Radius Min set to 1.0", - "Configuration|Radius Min set to 2.0", - "Configuration|Radius Min set to 16.0", - "DistanceBetweenFilterComponent: result=SUCCESS" - ] - - hydra.launch_and_validate_results( - request, - test_directory, - editor, - "DistanceBetweenFilter_InstancesPlantAtSpecifiedRadius.py", - expected_lines, - cfg_args=[level] - ) - - @pytest.mark.test_case_id("C4814458") - @pytest.mark.SUITE_periodic - @pytest.mark.dynveg_filter - def test_DistanceBetweenFilterOverrides_InstancesPlantAtSpecifiedRadius(self, request, editor, level, - launcher_platform): - - expected_lines = [ - "Configuration|Embedded Assets|[0]|Distance Between Filter (Radius)|Radius Min set to 1.0", - "Configuration|Embedded Assets|[0]|Distance Between Filter (Radius)|Radius Min set to 2.0", - "Configuration|Embedded Assets|[0]|Distance Between Filter (Radius)|Radius Min set to 16.0", - "DistanceBetweenFilterComponentOverrides: result=SUCCESS" - ] - - hydra.launch_and_validate_results( - request, - test_directory, - editor, - "DistanceBetweenFilterOverrides_InstancesPlantAtSpecifiedRadius.py", - expected_lines, - cfg_args=[level] - ) diff --git a/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/test_DynVeg_Regressions.py b/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/test_DynVeg_Regressions.py deleted file mode 100755 index b15e1d552d..0000000000 --- a/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/test_DynVeg_Regressions.py +++ /dev/null @@ -1,78 +0,0 @@ -""" -Copyright (c) Contributors to the Open 3D Engine Project. -For complete copyright and license terms please see the LICENSE at the root of this distribution. - -SPDX-License-Identifier: Apache-2.0 OR MIT -""" - -import os -import pytest - -# Bail on the test if ly_test_tools doesn't exist. -pytest.importorskip('ly_test_tools') - -import editor_python_test_tools.hydra_test_utils as hydra -import ly_test_tools.environment.file_system as file_system - -test_directory = os.path.join(os.path.dirname(__file__), 'EditorScripts') - - -@pytest.mark.parametrize('project', ['AutomatedTesting']) -@pytest.mark.parametrize('level', ['tmp_level']) -@pytest.mark.usefixtures("automatic_process_killer") -@pytest.mark.parametrize("launcher_platform", ['windows_editor']) -class Test_DynVeg_Regressions(object): - @pytest.fixture(autouse=True) - def setup_teardown(self, request, workspace, project, level): - def teardown(): - # delete temp level - file_system.delete([os.path.join(workspace.paths.engine_root(), project, "Levels", level)], True, True) - - # Setup - add the teardown finalizer - request.addfinalizer(teardown) - - # Make sure the temp level doesn't already exist - file_system.delete([os.path.join(workspace.paths.engine_root(), project, "Levels", level)], True, True) - - @pytest.mark.test_case_id("C29470845") - @pytest.mark.SUITE_periodic - @pytest.mark.dynveg_regression - def test_SurfaceDataRefreshes_RemainsStable(self, request, editor, level, launcher_platform): - - expected_lines = [ - "SurfaceDataRefreshes_RemainsStable: test started", - "SurfaceDataRefreshes_RemainsStable: test finished", - "SurfaceDataRefreshes_RemainsStable: result=SUCCESS" - ] - - unexpected_lines = [ - "Sector update mode is 'RebuildSurfaceCache' but sector doesn't exist" - ] - - hydra.launch_and_validate_results( - request, - test_directory, - editor, - 'SurfaceDataRefreshes_RemainsStable.py', - expected_lines=expected_lines, - unexpected_lines=unexpected_lines, - cfg_args=[level] - ) - - @pytest.mark.SUITE_periodic - def test_VegetationInstances_DespawnWhenOutOfRange(self, request, editor, level, launcher_platform): - - expected_lines = [ - "VegetationInstances_DespawnWhenOutOfRange: test started", - "VegetationInstances_DespawnWhenOutOfRange: test finished", - "VegetationInstances_DespawnWhenOutOfRange: result=SUCCESS" - ] - - hydra.launch_and_validate_results( - request, - test_directory, - editor, - 'VegetationInstances_DespawnWhenOutOfRange.py', - expected_lines=expected_lines, - cfg_args=[level] - ) diff --git a/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/test_DynamicSliceInstanceSpawner.py b/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/test_DynamicSliceInstanceSpawner.py deleted file mode 100755 index 0f83f44094..0000000000 --- a/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/test_DynamicSliceInstanceSpawner.py +++ /dev/null @@ -1,140 +0,0 @@ -""" -Copyright (c) Contributors to the Open 3D Engine Project. -For complete copyright and license terms please see the LICENSE at the root of this distribution. - -SPDX-License-Identifier: Apache-2.0 OR MIT -""" - -import os -import pytest -import logging - -# Bail on the test if ly_test_tools doesn't exist. -pytest.importorskip('ly_test_tools') -import ly_test_tools.environment.file_system as file_system -import ly_test_tools._internal.pytest_plugin as internal_plugin -import editor_python_test_tools.hydra_test_utils as hydra -from ly_remote_console.remote_console_commands import RemoteConsole as RemoteConsole - -logger = logging.getLogger(__name__) -test_directory = os.path.join(os.path.dirname(__file__), 'EditorScripts') - - -@pytest.mark.parametrize('project', ['AutomatedTesting']) -@pytest.mark.parametrize('level', ['tmp_level']) -@pytest.mark.usefixtures("automatic_process_killer") -class TestDynamicSliceInstanceSpawner(object): - - @pytest.fixture - def remote_console_instance(self, request): - console = RemoteConsole() - - def teardown(): - if console.connected: - console.stop() - - request.addfinalizer(teardown) - - return console - - @pytest.mark.test_case_id("C28851763") - @pytest.mark.SUITE_main - @pytest.mark.dynveg_area - @pytest.mark.parametrize("launcher_platform", ['windows_editor']) - def test_DynamicSliceInstanceSpawner_DynamicSliceSpawnerWorks(self, request, editor, level, workspace, project, - launcher_platform): - - # Skip test if running against Debug build - if "debug" in internal_plugin.build_directory: - pytest.skip("Does not execute against debug builds.") - - # Ensure temp level does not already exist - file_system.delete([os.path.join(workspace.paths.engine_root(), project, "Levels", level)], True, True) - - cfg_args = [level] - - expected_lines = [ - "DynamicSliceInstanceSpawner: test started", - "DynamicSliceInstanceSpawner: test finished", - "DynamicSliceInstanceSpawner: result=SUCCESS" - ] - - hydra.launch_and_validate_results(request, test_directory, editor, - 'DynamicSliceInstanceSpawner_DynamicSliceSpawnerWorks.py', - expected_lines=expected_lines, cfg_args=cfg_args) - - # Cleanup our temp level - file_system.delete([os.path.join(workspace.paths.engine_root(), project, "Levels", level)], True, True) - - @pytest.mark.test_case_id('C2574330') - @pytest.mark.BAT - @pytest.mark.SUITE_periodic - @pytest.mark.dynveg_area - @pytest.mark.parametrize("launcher_platform", ['windows_editor']) - def test_DynamicSliceInstanceSpawner_Embedded_E2E_Editor(self, workspace, request, editor, level, project, - launcher_platform): - # Ensure temp level does not already exist - file_system.delete([os.path.join(workspace.paths.engine_root(), project, "Levels", level)], True, True) - - expected_lines = [ - "'Instance Spawner' created", - "'Planting Surface' created", - "DynamicSliceInstanceSpawnerEmbeddedEditor: Expected 400 instances - Found 400 instances", - "DynamicSliceInstanceSpawnerEmbeddedEditor: result=SUCCESS" - ] - - hydra.launch_and_validate_results(request, test_directory, editor, "DynamicSliceInstanceSpawner_Embedded_E2E.py", - expected_lines, cfg_args=[level]) - - @pytest.mark.test_case_id('C2574330') - @pytest.mark.BAT - @pytest.mark.SUITE_periodic - @pytest.mark.dynveg_area - @pytest.mark.parametrize("launcher_platform", ['windows']) - def test_DynamicSliceInstanceSpawner_Embedded_E2E_Launcher(self, workspace, launcher, level, - remote_console_instance, project, launcher_platform): - - expected_lines = [ - "Instances found in area = 400" - ] - - hydra.launch_and_validate_results_launcher(launcher, level, remote_console_instance, expected_lines) - - # Cleanup our temp level - file_system.delete([os.path.join(workspace.paths.engine_root(), project, "Levels", level)], True, True) - - @pytest.mark.test_case_id('C4762367') - @pytest.mark.SUITE_periodic - @pytest.mark.dynveg_area - @pytest.mark.parametrize("launcher_platform", ['windows_editor']) - def test_DynamicSliceInstanceSpawner_External_E2E_Editor(self, workspace, request, editor, level, project, - launcher_platform): - # Ensure temp level does not already exist - file_system.delete([os.path.join(workspace.paths.engine_root(), project, "Levels", level)], True, True) - - expected_lines = [ - "Spawner entity created", - "'Planting Surface' created", - "DynamicSliceInstanceSpawnerExternalEditor: Expected 400 instances - Found 400 instances", - "DynamicSliceInstanceSpawnerExternalEditor: result=SUCCESS" - ] - - hydra.launch_and_validate_results(request, test_directory, editor, "DynamicSliceInstanceSpawner_External_E2E.py", - expected_lines, cfg_args=[level]) - - @pytest.mark.test_case_id('C4762367') - @pytest.mark.SUITE_periodic - @pytest.mark.dynveg_area - @pytest.mark.parametrize("launcher_platform", ['windows']) - def test_DynamicSliceInstanceSpawner_External_E2E_Launcher(self, workspace, launcher, level, - remote_console_instance, project, launcher_platform): - - expected_lines = [ - "Instances found in area = 400" - ] - - hydra.launch_and_validate_results_launcher(launcher, level, remote_console_instance, expected_lines) - - # Cleanup our temp level - file_system.delete([os.path.join(workspace.paths.engine_root(), project, "Levels", level)], True, True) - diff --git a/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/test_EmptyInstanceSpawner.py b/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/test_EmptyInstanceSpawner.py deleted file mode 100755 index 1fc88b816f..0000000000 --- a/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/test_EmptyInstanceSpawner.py +++ /dev/null @@ -1,54 +0,0 @@ -""" -Copyright (c) Contributors to the Open 3D Engine Project. -For complete copyright and license terms please see the LICENSE at the root of this distribution. - -SPDX-License-Identifier: Apache-2.0 OR MIT -""" - -import os -import pytest -import logging - -# Bail on the test if ly_test_tools doesn't exist. -pytest.importorskip('ly_test_tools') -import ly_test_tools.environment.file_system as file_system -import ly_test_tools._internal.pytest_plugin as internal_plugin -import editor_python_test_tools.hydra_test_utils as hydra - -logger = logging.getLogger(__name__) -test_directory = os.path.join(os.path.dirname(__file__), 'EditorScripts') - - -@pytest.mark.parametrize('project', ['AutomatedTesting']) -@pytest.mark.parametrize('level', ['tmp_level']) -@pytest.mark.usefixtures("automatic_process_killer") -@pytest.mark.parametrize("launcher_platform", ['windows_editor']) -class TestEmptyInstanceSpawner(object): - - @pytest.fixture(autouse=True) - def setup_teardown(self, request, workspace, project, level): - def teardown(): - file_system.delete([os.path.join(workspace.paths.engine_root(), project, "Levels", level)], True, True) - request.addfinalizer(teardown) - - file_system.delete([os.path.join(workspace.paths.engine_root(), project, "Levels", level)], True, True) - - @pytest.mark.test_case_id("C28851762") - @pytest.mark.SUITE_main - @pytest.mark.dynveg_area - def test_EmptyInstanceSpawner_EmptySpawnerWorks(self, request, editor, level, launcher_platform): - - # Skip test if running against Debug build - if "debug" in internal_plugin.build_directory: - pytest.skip("Does not execute against debug builds.") - - cfg_args = [level] - - expected_lines = [ - "EmptyInstanceSpawner: test started", - "EmptyInstanceSpawner: test finished", - "EmptyInstanceSpawner: result=SUCCESS" - ] - - hydra.launch_and_validate_results(request, test_directory, editor, 'EmptyInstanceSpawner_EmptySpawnerWorks.py', - expected_lines=expected_lines, cfg_args=cfg_args) diff --git a/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/test_InstanceSpawnerPriority.py b/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/test_InstanceSpawnerPriority.py deleted file mode 100755 index 955c20a37d..0000000000 --- a/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/test_InstanceSpawnerPriority.py +++ /dev/null @@ -1,63 +0,0 @@ -""" -Copyright (c) Contributors to the Open 3D Engine Project. -For complete copyright and license terms please see the LICENSE at the root of this distribution. - -SPDX-License-Identifier: Apache-2.0 OR MIT -""" - -""" -C5747383: Vegetation areas with a higher Layer Priority plant over those with a lower Layer Priority -C4762382: Vegetation areas with a higher Sub Priority plant over those with a lower Sub Priority -""" - -import os -import pytest -import logging - -# Bail on the test if ly_test_tools doesn't exist. -pytest.importorskip('ly_test_tools') -import ly_test_tools.environment.file_system as file_system -import editor_python_test_tools.hydra_test_utils as hydra - -logger = logging.getLogger(__name__) -test_directory = os.path.join(os.path.dirname(__file__), 'EditorScripts') - - -@pytest.mark.parametrize("project", ["AutomatedTesting"]) -@pytest.mark.parametrize("level", ["tmp_level"]) -@pytest.mark.usefixtures("automatic_process_killer") -@pytest.mark.parametrize("launcher_platform", ['windows_editor']) -class TestInstanceSpawnerPriority(object): - - @pytest.fixture(autouse=True) - def setup_teardown(self, request, workspace, project, level): - def teardown(): - file_system.delete([os.path.join(workspace.paths.engine_root(), project, "Levels", level)], True, True) - request.addfinalizer(teardown) - - file_system.delete([os.path.join(workspace.paths.engine_root(), project, "Levels", level)], True, True) - - @pytest.mark.test_case_id("C5747383", "C4762382") - @pytest.mark.SUITE_periodic - @pytest.mark.dynveg_misc - def test_InstanceSpawnerPriority_LayerAndSubPriority_HigherValuesPlantOverLower(self, request, editor, level, - launcher_platform): - - expected_lines = [ - "'Instance Spawner' created", - "'Instance Blocker' created", - "'Planting Surface' created", - "Instance Blocker Configuration|Layer Priority: SUCCESS", - "Instance Spawner Configuration|Sub Priority: SUCCESS", - "Instance Blocker Configuration|Sub Priority: SUCCESS", - "InstanceSpawnerPriority: result=SUCCESS", - ] - - hydra.launch_and_validate_results( - request, - test_directory, - editor, - "InstanceSpawnerPriority_LayerAndSubPriority.py", - expected_lines, - cfg_args=[level] - ) diff --git a/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/test_LayerBlender.py b/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/test_LayerBlender.py deleted file mode 100755 index 13f2a569c1..0000000000 --- a/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/test_LayerBlender.py +++ /dev/null @@ -1,104 +0,0 @@ -""" -Copyright (c) Contributors to the Open 3D Engine Project. -For complete copyright and license terms please see the LICENSE at the root of this distribution. - -SPDX-License-Identifier: Apache-2.0 OR MIT -""" - -""" -C2627906: A simple Vegetation Layer Blender area can be created. -The specified assets plant in the specified blend area and are visible in the Viewport in -Edit Mode, Game Mode. -""" - -import os -import pytest - -pytest.importorskip("ly_test_tools") - -import ly_remote_console.remote_console_commands as remote_console_commands -import ly_test_tools.environment.waiter as waiter -import ly_test_tools.environment.file_system as file_system -import editor_python_test_tools.hydra_test_utils as hydra - - -test_directory = os.path.join(os.path.dirname(__file__), "EditorScripts") -remote_console_port = 4600 -listener_timeout = 120 - - -@pytest.mark.parametrize("project", ["AutomatedTesting"]) -@pytest.mark.parametrize("level", ["tmp_level"]) -@pytest.mark.usefixtures("automatic_process_killer") -class TestLayerBlender(object): - - @pytest.fixture - def remote_console_instance(self, request): - console = remote_console_commands.RemoteConsole() - - def teardown(): - if console.connected: - console.stop() - - request.addfinalizer(teardown) - - return console - - @pytest.mark.test_case_id("C2627906") - @pytest.mark.BAT - @pytest.mark.SUITE_periodic - @pytest.mark.dynveg_area - @pytest.mark.parametrize("launcher_platform", ['windows_editor']) - def test_LayerBlender_E2E_Editor(self, workspace, request, editor, project, level, launcher_platform): - # Make sure temp level doesn't already exist - file_system.delete([os.path.join(workspace.paths.engine_root(), project, "Levels", level)], True, True) - - expected_lines = [ - "'Purple Spawner' created", - "'Pink Spawner' created", - "'Surface Entity' created", - "Entity has a Vegetation Layer Spawner component", - "Entity has a Vegetation Asset List component", - "Entity has a Box Shape component", - "Purple Spawner Box Shape|Box Configuration|Dimensions: SUCCESS", - "Pink Spawner Box Shape|Box Configuration|Dimensions: SUCCESS", - "Purple Spawner Configuration|Embedded Assets|[0]: SUCCESS", - "Pink Spawner Configuration|Embedded Assets|[0]: SUCCESS", - "'Blender' created", - "Entity has a Vegetation Layer Blender component", - "Entity has a Box Shape component", - "Blender Configuration|Vegetation Areas: SUCCESS", - "Blender Box Shape|Box Configuration|Dimensions: SUCCESS", - "LayerBlender_E2E_Editor: result=SUCCESS" - ] - - hydra.launch_and_validate_results( - request, - test_directory, - editor, - "LayerBlender_E2E_Editor.py", - expected_lines, - cfg_args=[level] - ) - - @pytest.mark.test_case_id("C2627906") - @pytest.mark.BAT - @pytest.mark.SUITE_periodic - @pytest.mark.dynveg_area - @pytest.mark.parametrize("launcher_platform", ['windows']) - def test_LayerBlender_E2E_Launcher(self, workspace, project, launcher, level, remote_console_instance, - launcher_platform): - - launcher.args.extend(["-rhi=Null"]) - launcher.start() - assert launcher.is_alive(), "Launcher failed to start" - - # Wait for test script to quit the launcher. If wait_for returns exc, test was not successful - waiter.wait_for(lambda: not launcher.is_alive(), timeout=300) - - # Verify launcher quit successfully and did not crash - ret_code = launcher.get_returncode() - assert ret_code == 0, "Test failed. See Game.log for details" - - # Cleanup our temp level - file_system.delete([os.path.join(workspace.paths.engine_root(), project, "Levels", level)], True, True) diff --git a/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/test_LayerBlocker.py b/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/test_LayerBlocker.py deleted file mode 100755 index d0889f17a4..0000000000 --- a/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/test_LayerBlocker.py +++ /dev/null @@ -1,56 +0,0 @@ -""" -Copyright (c) Contributors to the Open 3D Engine Project. -For complete copyright and license terms please see the LICENSE at the root of this distribution. - -SPDX-License-Identifier: Apache-2.0 OR MIT -""" - -import os -import pytest -import logging - -# Bail on the test if ly_test_tools doesn't exist. -pytest.importorskip('ly_test_tools') -import ly_test_tools.environment.file_system as file_system -import editor_python_test_tools.hydra_test_utils as hydra - -logger = logging.getLogger(__name__) -test_directory = os.path.join(os.path.dirname(__file__), 'EditorScripts') - - -@pytest.mark.parametrize("project", ["AutomatedTesting"]) -@pytest.mark.parametrize("level", ["tmp_level"]) -@pytest.mark.usefixtures("automatic_process_killer") -@pytest.mark.parametrize("launcher_platform", ['windows_editor']) -class TestLayerBlocker(object): - - @pytest.fixture(autouse=True) - def setup_teardown(self, request, workspace, project, level): - def teardown(): - file_system.delete([os.path.join(workspace.paths.engine_root(), project, "Levels", level)], True, True) - request.addfinalizer(teardown) - - file_system.delete([os.path.join(workspace.paths.engine_root(), project, "Levels", level)], True, True) - - @pytest.mark.test_case_id("C2793772") - @pytest.mark.SUITE_periodic - @pytest.mark.dynveg_area - def test_LayerBlocker_InstancesBlockedInConfiguredArea(self, request, editor, level, launcher_platform): - - expected_lines = [ - "'Instance Spawner' created", - "'Surface Entity' created", - "instance count validation: True (found=400, expected=400)", - "'Blocker Area' created", - "instance count validation: True (found=384, expected=384)", - "LayerBlocker_InstancesBlocked: result=SUCCESS" - ] - - hydra.launch_and_validate_results( - request, - test_directory, - editor, - "LayerBlocker_InstancesBlockedInConfiguredArea.py", - expected_lines, - cfg_args=[level] - ) diff --git a/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/test_LayerSpawner.py b/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/test_LayerSpawner.py deleted file mode 100755 index 65d994f841..0000000000 --- a/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/test_LayerSpawner.py +++ /dev/null @@ -1,142 +0,0 @@ -""" -Copyright (c) Contributors to the Open 3D Engine Project. -For complete copyright and license terms please see the LICENSE at the root of this distribution. - -SPDX-License-Identifier: Apache-2.0 OR MIT -""" - -import os -import pytest -import logging - -# Bail on the test if ly_test_tools doesn't exist. -pytest.importorskip("ly_test_tools") -import ly_test_tools.environment.file_system as file_system -import editor_python_test_tools.hydra_test_utils as hydra - -logger = logging.getLogger(__name__) -test_directory = os.path.join(os.path.dirname(__file__), "EditorScripts") - - -@pytest.mark.parametrize("project", ["AutomatedTesting"]) -@pytest.mark.parametrize("level", ["tmp_level"]) -@pytest.mark.usefixtures("automatic_process_killer") -@pytest.mark.parametrize("launcher_platform", ['windows_editor']) -class TestLayerSpawner(object): - @pytest.fixture(autouse=True) - def setup_teardown(self, request, workspace, project, level): - # Cleanup our temp level - file_system.delete([os.path.join(workspace.paths.engine_root(), project, "Levels", level)], True, True) - - def teardown(): - # Cleanup our temp level - file_system.delete([os.path.join(workspace.paths.engine_root(), project, "Levels", level)], True, True) - - request.addfinalizer(teardown) - - @pytest.mark.test_case_id("C4762381") - @pytest.mark.SUITE_periodic - @pytest.mark.dynveg_misc - def test_LayerSpawner_InheritBehaviorFlag(self, request, editor, level, workspace, launcher_platform): - - expected_lines = [ - "LayerSpawner_InheritBehavior: test started", - "LayerSpawner_InheritBehavior: Vegetation is not planted when Inherit Behavior flag is checked: True", - "LayerSpawner_InheritBehavior: Vegetation plant when Inherit Behavior flag is unchecked: True", - "LayerSpawner_InheritBehavior: result=SUCCESS", - ] - - hydra.launch_and_validate_results( - request, - test_directory, - editor, - "LayerSpawner_InheritBehaviorFlag.py", - expected_lines=expected_lines, - cfg_args=[level] - ) - - @pytest.mark.test_case_id("C2802020") - @pytest.mark.SUITE_periodic - @pytest.mark.dynveg_misc - def test_LayerSpawner_InstancesPlantInAllSupportedShapes(self, request, editor, level, launcher_platform): - - expected_lines = [ - "'Instance Spawner' created", - "'Surface Entity' created", - "Entity has a Vegetation Reference Shape component", - "Entity has a Box Shape component", - "box Box Shape|Box Configuration|Dimensions: SUCCESS", - "Entity has a Capsule Shape component", - "capsule Capsule Shape|Capsule Configuration|Height: SUCCESS", - "capsule Capsule Shape|Capsule Configuration|Radius: SUCCESS", - "Entity has a Tube Shape component", - "Entity has a Spline component", - "Entity has a Sphere Shape component", - "sphere Sphere Shape|Sphere Configuration|Radius: SUCCESS", - "Entity has a Cylinder Shape component", - "cylinder Cylinder Shape|Cylinder Configuration|Radius: SUCCESS", - "cylinder Cylinder Shape|Cylinder Configuration|Height: SUCCESS", - "Entity has a Polygon Prism Shape component", - "Entity has a Compound Shape component", - "Compound Configuration|Child Shape Entities|[0]: SUCCESS", - "Compound Configuration|Child Shape Entities|[1]: SUCCESS", - "Compound Configuration|Child Shape Entities|[2]: SUCCESS", - "Compound Configuration|Child Shape Entities|[3]: SUCCESS", - "Compound Configuration|Child Shape Entities|[4]: SUCCESS", - "Compound Configuration|Child Shape Entities|[5]: SUCCESS", - "Instance Spawner Configuration|Shape Entity Id: SUCCESS", - "TestLayerSpawner_AllShapesPlant: result=SUCCESS", - ] - - hydra.launch_and_validate_results( - request, - test_directory, - editor, - "LayerSpawner_InstancesPlantInAllSupportedShapes.py", - expected_lines, - cfg_args=[level] - ) - - @pytest.mark.test_case_id("C4765973") - @pytest.mark.SUITE_periodic - @pytest.mark.dynveg_misc - @pytest.mark.xfail(reason="https://github.com/o3de/o3de/issues/2303") - def test_LayerSpawner_FilterStageToggle(self, request, editor, level, workspace, launcher_platform): - - expected_lines = [ - "LayerSpawner_FilterStageToggle: test started", - "LayerSpawner_FilterStageToggle: Preprocess filter stage vegetation instance count is as expected: True", - "LayerSpawner_FilterStageToggle: Postprocess filter vegetation instance stage count is as expected: True", - "LayerSpawner_FilterStageToggle: result=SUCCESS", - ] - - hydra.launch_and_validate_results( - request, - test_directory, - editor, - "LayerSpawner_FilterStageToggle.py", - expected_lines=expected_lines, - cfg_args=[level] - ) - - @pytest.mark.test_case_id("C30000751") - @pytest.mark.SUITE_sandbox - @pytest.mark.dynveg_misc - @pytest.mark.skip # https://github.com/o3de/o3de/issues/2038 - def test_LayerSpawner_InstancesRefreshUsingCorrectViewportCamera(self, request, editor, level, launcher_platform): - - expected_lines = [ - "LayerSpawner_InstanceCameraRefresh: test started", - "LayerSpawner_InstanceCameraRefresh: test finished", - "LayerSpawner_InstanceCameraRefresh: result=SUCCESS" - ] - - hydra.launch_and_validate_results( - request, - test_directory, - editor, - "LayerSpawner_InstancesRefreshUsingCorrectViewportCamera.py", - expected_lines, - cfg_args=[level], - null_renderer=False - ) diff --git a/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/test_MeshBlocker.py b/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/test_MeshBlocker.py deleted file mode 100755 index 197ab6e585..0000000000 --- a/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/test_MeshBlocker.py +++ /dev/null @@ -1,89 +0,0 @@ -""" -Copyright (c) Contributors to the Open 3D Engine Project. -For complete copyright and license terms please see the LICENSE at the root of this distribution. - -SPDX-License-Identifier: Apache-2.0 OR MIT -""" - - -import logging -import os -import pytest -# Bail on the test if ly_test_tools doesn't exist. -pytest.importorskip('ly_test_tools') - -import editor_python_test_tools.hydra_test_utils as hydra -import ly_test_tools.environment.file_system as file_system - -test_directory = os.path.join(os.path.dirname(__file__), 'EditorScripts') -logger = logging.getLogger(__name__) - - -@pytest.mark.parametrize("project", ["AutomatedTesting"]) -@pytest.mark.parametrize("level", ["tmp_level"]) -@pytest.mark.usefixtures("automatic_process_killer") -@pytest.mark.parametrize("launcher_platform", ['windows_editor']) -class TestMeshBlocker(object): - @pytest.fixture(autouse=True) - def setup_teardown(self, request, workspace, editor, project, level): - pass - - def teardown(): - # delete temp level - file_system.delete([os.path.join(workspace.paths.engine_root(), project, "Levels", level)], True, True) - - # Setup - add the teardown finalizer - request.addfinalizer(teardown) - # Make sure the temp level doesn't already exist - file_system.delete([os.path.join(workspace.paths.engine_root(), project, "Levels", level)], True, True) - - """ - C3980834: A simple Vegetation Blocker Mesh can be created - """ - @pytest.mark.test_case_id("C3980834") - @pytest.mark.SUITE_periodic - @pytest.mark.dynveg_area - @pytest.mark.xfail # LYN-3273 - def test_MeshBlocker_InstancesBlockedByMesh(self, request, editor, level, launcher_platform): - expected_lines = [ - "'Instance Spawner' created", - "'Surface Entity' created", - "'Blocker Entity' created", - "instance count validation: True (found=160, expected=160)", - "MeshBlocker_InstancesBlockedByMesh: result=SUCCESS" - ] - - hydra.launch_and_validate_results( - request, - test_directory, - editor, - "MeshBlocker_InstancesBlockedByMesh.py", - expected_lines, - cfg_args=[level] - ) - - """ - C4766030: Mesh Height Percent Min/Max values can be set to fine tune the blocked area - """ - @pytest.mark.test_case_id("C4766030") - @pytest.mark.SUITE_periodic - @pytest.mark.dynveg_area - @pytest.mark.xfail # LYN-3273 - def test_MeshBlocker_InstancesBlockedByMeshHeightTuning(self, request, editor, level, launcher_platform): - expected_lines = [ - "'Instance Spawner' created", - "'Surface Entity' created", - "'Blocker Entity' created", - "Blocker Entity Configuration|Mesh Height Percent Max: SUCCESS", - "instance count validation: True (found=127, expected=127)", - "MeshBlocker_InstancesBlockedByMeshHeightTuning: result=SUCCESS", - ] - - hydra.launch_and_validate_results( - request, - test_directory, - editor, - "MeshBlocker_InstancesBlockedByMeshHeightTuning.py", - expected_lines, - cfg_args=[level] - ) diff --git a/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/test_MeshSurfaceTagEmitter.py b/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/test_MeshSurfaceTagEmitter.py deleted file mode 100755 index fd3a2f6514..0000000000 --- a/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/test_MeshSurfaceTagEmitter.py +++ /dev/null @@ -1,82 +0,0 @@ -""" -Copyright (c) Contributors to the Open 3D Engine Project. -For complete copyright and license terms please see the LICENSE at the root of this distribution. - -SPDX-License-Identifier: Apache-2.0 OR MIT -""" - -import os -import pytest -import logging - -# Bail on the test if ly_test_tools doesn't exist. -pytest.importorskip("ly_test_tools") -import ly_test_tools.environment.file_system as file_system -import editor_python_test_tools.hydra_test_utils as hydra - -logger = logging.getLogger(__name__) -test_directory = os.path.join(os.path.dirname(__file__), "EditorScripts") - - -@pytest.mark.parametrize('project', ['AutomatedTesting']) -@pytest.mark.parametrize('level', ['tmp_level']) -@pytest.mark.usefixtures("automatic_process_killer") -@pytest.mark.parametrize("launcher_platform", ['windows_editor']) -class TestMeshSurfaceTagEmitter(object): - - @pytest.fixture(autouse=True) - def setup_teardown(self, request, workspace, project, level): - def teardown(): - file_system.delete([os.path.join(workspace.paths.engine_root(), project, "Levels", level)], True, True) - request.addfinalizer(teardown) - - file_system.delete([os.path.join(workspace.paths.engine_root(), project, "Levels", level)], True, True) - - @pytest.mark.test_case_id("C2908172") - @pytest.mark.SUITE_periodic - @pytest.mark.dynveg_surfacetagemitter - def test_MeshSurfaceTagEmitter_DependentOnMeshComponent(self, request, editor, level, launcher_platform): - - expected_lines = [ - "Entity has a Mesh Surface Tag Emitter component", - "New Entity Created", - "Mesh Surface Tag Emitter is Disabled", - "Entity has a Mesh component", - "Mesh Surface Tag Emitter is Enabled", - "MeshSurfaceTagEmitter_DependentOnMeshComponent: result=SUCCESS" - ] - - unexpected_lines = [ - "Mesh Surface Tag Emitter is Enabled. But It should be disabled before adding Mesh", - "Mesh Surface Tag Emitter is Disabled. But It should be enabled after adding Mesh", - ] - - hydra.launch_and_validate_results( - request, - test_directory, - editor, - "MeshSurfaceTagEmitter_DependentOnMeshComponent.py", - expected_lines, - unexpected_lines, - cfg_args=[level] - ) - - @pytest.mark.test_case_id("C2908174") - @pytest.mark.SUITE_periodic - @pytest.mark.dynveg_surfacetagemitter - def test_MeshSurfaceTagEmitter_SurfaceTagsAddRemoveSuccessfully(self, request, editor, level, launcher_platform): - - expected_lines = [ - "Added SurfaceTag: container count is 1", - "Removed SurfaceTag: container count is 0", - "MeshSurfaceTagEmitter_SurfaceTagsAddRemoveSucessfully: result=SUCCESS" - ] - - hydra.launch_and_validate_results( - request, - test_directory, - editor, - "MeshSurfaceTagEmitter_SurfaceTagsAddRemoveSuccessfully.py", - expected_lines, - cfg_args=[level] - ) diff --git a/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/test_PhysXColliderSurfaceTagEmitter.py b/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/test_PhysXColliderSurfaceTagEmitter.py deleted file mode 100755 index 03b7a968f8..0000000000 --- a/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/test_PhysXColliderSurfaceTagEmitter.py +++ /dev/null @@ -1,53 +0,0 @@ -""" -Copyright (c) Contributors to the Open 3D Engine Project. -For complete copyright and license terms please see the LICENSE at the root of this distribution. - -SPDX-License-Identifier: Apache-2.0 OR MIT -""" - -import os -import pytest -import logging - -# Bail on the test if ly_test_tools doesn't exist. -pytest.importorskip("ly_test_tools") -import ly_test_tools.environment.file_system as file_system -import editor_python_test_tools.hydra_test_utils as hydra - -logger = logging.getLogger(__name__) -test_directory = os.path.join(os.path.dirname(__file__), "EditorScripts") - - -@pytest.mark.parametrize('project', ['AutomatedTesting']) -@pytest.mark.parametrize('level', ['tmp_level']) -@pytest.mark.usefixtures("automatic_process_killer") -@pytest.mark.parametrize("launcher_platform", ['windows_editor']) -class TestPhysXColliderSurfaceTagEmitter(object): - - @pytest.fixture(autouse=True) - def setup_teardown(self, request, workspace, project, level): - def teardown(): - file_system.delete([os.path.join(workspace.paths.engine_root(), project, "Levels", level)], True, True) - request.addfinalizer(teardown) - - file_system.delete([os.path.join(workspace.paths.engine_root(), project, "Levels", level)], True, True) - - @pytest.mark.test_case_id("C29053640") - @pytest.mark.SUITE_periodic - @pytest.mark.dynveg_surfacetagemitter - def test_PhysXColliderSurfaceTagEmitter_E2E_Editor(self, request, editor, level, launcher_platform): - - expected_lines = [ - "PhysXColliderSurfaceTagEmitter_E2E_Editor: test started", - "PhysXColliderSurfaceTagEmitter_E2E_Editor: test finished", - "PhysXColliderSurfaceTagEmitter_E2E_Editor: result=SUCCESS" - ] - - hydra.launch_and_validate_results( - request, - test_directory, - editor, - "PhysXColliderSurfaceTagEmitter_E2E_Editor.py", - expected_lines=expected_lines, - cfg_args=[level] - ) diff --git a/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/test_PositionModifier.py b/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/test_PositionModifier.py deleted file mode 100755 index ebbd58557e..0000000000 --- a/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/test_PositionModifier.py +++ /dev/null @@ -1,79 +0,0 @@ -""" -Copyright (c) Contributors to the Open 3D Engine Project. -For complete copyright and license terms please see the LICENSE at the root of this distribution. - -SPDX-License-Identifier: Apache-2.0 OR MIT -""" - -import os -import pytest -import logging - -# Bail on the test if ly_test_tools doesn't exist. -pytest.importorskip('ly_test_tools') -import ly_test_tools.environment.file_system as file_system -import editor_python_test_tools.hydra_test_utils as hydra - -logger = logging.getLogger(__name__) -test_directory = os.path.join(os.path.dirname(__file__), 'EditorScripts') - - -@pytest.mark.parametrize("project", ["AutomatedTesting"]) -@pytest.mark.parametrize("level", ["tmp_level"]) -@pytest.mark.usefixtures("automatic_process_killer") -@pytest.mark.parametrize("launcher_platform", ['windows_editor']) -class TestPositionModifier(object): - - @pytest.fixture(autouse=True) - def setup_teardown(self, request, workspace, project, level): - def teardown(): - file_system.delete([os.path.join(workspace.paths.engine_root(), project, "Levels", level)], True, True) - request.addfinalizer(teardown) - - file_system.delete([os.path.join(workspace.paths.engine_root(), project, "Levels", level)], True, True) - - @pytest.mark.test_case_id("C4874099", "C4814461") - @pytest.mark.SUITE_periodic - @pytest.mark.dynveg_modifier - def test_PositionModifier_ComponentAndOverrides_InstancesPlantAtSpecifiedOffsets(self, request, editor, level, - launcher_platform): - - expected_lines = [ - "'Instance Spawner' created", - "Vegetation Position Modifier component was added to entity", - "'Planting Surface' created", - "Entity has a Constant Gradient component", - "PositionModifierComponentAndOverrides_InstanceOffset: result=SUCCESS", - ] - - hydra.launch_and_validate_results( - request, - test_directory, - editor, - "PositionModifier_ComponentAndOverrides_InstancesPlantAtSpecifiedOffsets.py", - expected_lines, - cfg_args=[level] - ) - - @pytest.mark.test_case_id("C4874100") - @pytest.mark.SUITE_periodic - @pytest.mark.dynveg_modifier - @pytest.mark.xfail(reason="https://github.com/o3de/o3de/issues/2303") - def test_PositionModifier_AutoSnapToSurfaceWorks(self, request, editor, level, launcher_platform): - - expected_lines = [ - "'Instance Spawner' created", - "'Planting Surface' created", - "Instance Spawner Configuration|Position X|Range Min: SUCCESS", - "Instance Spawner Configuration|Position X|Range Max: SUCCESS", - "PositionModifier_AutoSnapToSurface: result=SUCCESS" - ] - - hydra.launch_and_validate_results( - request, - test_directory, - editor, - "PositionModifier_AutoSnapToSurfaceWorks.py", - expected_lines, - cfg_args=[level] - ) diff --git a/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/test_RotationModifier.py b/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/test_RotationModifier.py deleted file mode 100755 index 1dea332f7d..0000000000 --- a/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/test_RotationModifier.py +++ /dev/null @@ -1,97 +0,0 @@ -""" -Copyright (c) Contributors to the Open 3D Engine Project. -For complete copyright and license terms please see the LICENSE at the root of this distribution. - -SPDX-License-Identifier: Apache-2.0 OR MIT -""" - -import logging -import os -import pytest - -# Bail on the test if ly_test_tools doesn't exist. -pytest.importorskip("ly_test_tools") - -import editor_python_test_tools.hydra_test_utils as hydra -import ly_test_tools.environment.file_system as file_system - -logger = logging.getLogger(__name__) - -test_directory = os.path.join(os.path.dirname(__file__), "EditorScripts") - - -@pytest.mark.parametrize("project", ["AutomatedTesting"]) -@pytest.mark.parametrize("level", ["tmp_level"]) -@pytest.mark.usefixtures("automatic_process_killer") -@pytest.mark.parametrize("launcher_platform", ['windows_editor']) -class TestRotationModifier(object): - @pytest.fixture(autouse=True) - def setup_teardown(self, request, workspace, project, level): - def teardown(): - # delete temp level - file_system.delete([os.path.join(workspace.paths.engine_root(), project, "Levels", level)], True, True) - - # Setup - add the teardown finalizer - request.addfinalizer(teardown) - - file_system.delete([os.path.join(workspace.paths.engine_root(), project, "Levels", level)], True, True) - - @pytest.mark.test_case_id("C4896922") - @pytest.mark.SUITE_periodic - @pytest.mark.dynveg_modifier - def test_RotationModifier_InstancesRotateWithinRange(self, request, editor, level, launcher_platform) -> None: - """ - Launches editor and run test script to test that rotation modifier works for all axis. - Manual test case: C4896922 - """ - - expected_lines = [ - "'Spawner Entity' created", - "'Surface Entity' created", - "'Gradient Entity' created", - "Entity has a Vegetation Asset List component", - "Entity has a Vegetation Layer Spawner component", - "Entity has a Vegetation Rotation Modifier component", - "Entity has a Box Shape component", - "Entity has a Constant Gradient component", - "RotationModifier_InstancesRotateWithinRange: result=SUCCESS" - ] - - hydra.launch_and_validate_results( - request, - test_directory, - editor, - "RotationModifier_InstancesRotateWithinRange.py", - expected_lines, - cfg_args=[level] - ) - - @pytest.mark.test_case_id("C4814460") - @pytest.mark.SUITE_periodic - @pytest.mark.dynveg_modifier - def test_RotationModifierOverrides_InstancesRotateWithinRange(self, request, editor, level, launcher_platform) -> None: - - expected_lines = [ - "'Spawner Entity' created", - "'Surface Entity' created", - "'Gradient Entity' created", - "Entity has a Vegetation Layer Spawner component", - "Entity has a Vegetation Asset List component", - "Spawner Entity Box Shape|Box Configuration|Dimensions: SUCCESS", - "Entity has a Vegetation Rotation Modifier component", - "Spawner Entity Configuration|Embedded Assets|[0]|Rotation Modifier|Override Enabled: SUCCESS", - "Spawner Entity Configuration|Allow Per-Item Overrides: SUCCESS", - "Entity has a Constant Gradient component", - "Entity has a Box Shape component", - "Spawner Entity Configuration|Rotation Z|Gradient|Gradient Entity Id: SUCCESS", - "RotationModifierOverrides_InstancesRotateWithinRange: result=SUCCESS" - ] - - hydra.launch_and_validate_results( - request, - test_directory, - editor, - "RotationModifierOverrides_InstancesRotateWithinRange.py", - expected_lines, - cfg_args=[level] - ) diff --git a/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/test_ScaleModifier.py b/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/test_ScaleModifier.py deleted file mode 100755 index 62f6c0bbad..0000000000 --- a/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/test_ScaleModifier.py +++ /dev/null @@ -1,91 +0,0 @@ -""" -Copyright (c) Contributors to the Open 3D Engine Project. -For complete copyright and license terms please see the LICENSE at the root of this distribution. - -SPDX-License-Identifier: Apache-2.0 OR MIT -""" - -""" -C4814462: Vegetation instances have random scale between 0.1 and 1.0 applied. -""" - -import os -import pytest - -# Bail on the test if ly_test_tools doesn't exist. -pytest.importorskip("ly_test_tools") - -import editor_python_test_tools.hydra_test_utils as hydra -import ly_test_tools.environment.file_system as file_system - -test_directory = os.path.join(os.path.dirname(__file__), "EditorScripts") - - -@pytest.mark.parametrize("project", ["AutomatedTesting"]) -@pytest.mark.parametrize("level", ["tmp_level"]) -@pytest.mark.usefixtures("automatic_process_killer") -@pytest.mark.parametrize("launcher_platform", ['windows_editor']) -class TestScaleOverrideWorksSuccessfully(object): - - @pytest.fixture(autouse=True) - def setup_teardown(self, request, workspace, project, level): - def teardown(): - file_system.delete([os.path.join(workspace.paths.engine_root(), project, "Levels", level)], True, True) - request.addfinalizer(teardown) - - file_system.delete([os.path.join(workspace.paths.engine_root(), project, "Levels", level)], True, True) - - @pytest.mark.test_case_id("C4814462") - @pytest.mark.SUITE_periodic - @pytest.mark.dynveg_modifier - def test_ScaleModifierOverrides_InstancesProperlyScale(self, request, editor, level, launcher_platform): - - expected_lines = [ - "'Spawner Entity' created", - "'Surface Entity' created", - "Entity has a Vegetation Scale Modifier component", - "'Gradient Entity' created", - "Scale Min and Scale Max are set to 0.1 and 1.0 in Vegetation Asset List", - "Entity has a Random Noise Gradient component", - "Entity has a Gradient Transform Modifier component", - "Entity has a Box Shape component", - "Spawner Entity Configuration|Gradient|Gradient Entity Id: SUCCESS", - "ScaleModifierOverrides_InstancesProperlyScale: result=SUCCESS" - ] - - unexpected_lines = ["Scale Min and Scale Max are not set to 0.1 and 1.0 in Vegetation Asset List"] - - hydra.launch_and_validate_results( - request, - test_directory, - editor, - "ScaleModifierOverrides_InstancesProperlyScale.py", - expected_lines, - unexpected_lines, - cfg_args=[level] - ) - - @pytest.mark.test_case_id("C4896937") - @pytest.mark.SUITE_periodic - @pytest.mark.dynveg_modifier - def test_ScaleModifier_InstancesProperlyScale(self, request, editor, level, launcher_platform): - - expected_lines = [ - "'Spawner Entity' created", - "Entity has a Vegetation Scale Modifier component", - "'Surface Entity' created", - "'Gradient Entity' created", - "Spawner Entity Configuration|Gradient|Gradient Entity Id: SUCCESS", - "Spawner Entity Configuration|Range Min: SUCCESS", - "Spawner Entity Configuration|Range Max: SUCCESS", - "ScaleModifier_InstancesProperlyScale: result=SUCCESS" - ] - - hydra.launch_and_validate_results( - request, - test_directory, - editor, - "ScaleModifier_InstancesProperlyScale.py", - expected_lines, - cfg_args=[level] - ) diff --git a/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/test_ShapeIntersectionFilter.py b/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/test_ShapeIntersectionFilter.py deleted file mode 100755 index d2ed0318ca..0000000000 --- a/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/test_ShapeIntersectionFilter.py +++ /dev/null @@ -1,56 +0,0 @@ -""" -Copyright (c) Contributors to the Open 3D Engine Project. -For complete copyright and license terms please see the LICENSE at the root of this distribution. - -SPDX-License-Identifier: Apache-2.0 OR MIT -""" - -import os -import pytest -import logging - -# Bail on the test if ly_test_tools doesn't exist. -pytest.importorskip('ly_test_tools') -import ly_test_tools.environment.file_system as file_system -import editor_python_test_tools.hydra_test_utils as hydra - -logger = logging.getLogger(__name__) -test_directory = os.path.join(os.path.dirname(__file__), 'EditorScripts') - - -@pytest.mark.parametrize("project", ["AutomatedTesting"]) -@pytest.mark.parametrize("level", ["tmp_level"]) -@pytest.mark.usefixtures("automatic_process_killer") -@pytest.mark.parametrize("launcher_platform", ['windows_editor']) -class TestShapeIntersectionFilter(object): - - @pytest.fixture(autouse=True) - def setup_teardown(self, request, workspace, project, level): - def teardown(): - file_system.delete([os.path.join(workspace.paths.engine_root(), project, "Levels", level)], True, True) - request.addfinalizer(teardown) - - file_system.delete([os.path.join(workspace.paths.engine_root(), project, "Levels", level)], True, True) - - @pytest.mark.test_case_id("C4874094") - @pytest.mark.SUITE_periodic - @pytest.mark.dynveg_filter - def test_ShapeIntersectionFilter_InstancesPlantInAssignedShape(self, request, editor, level, launcher_platform): - - expected_lines = [ - "'Instance Spawner' created", - "'Planting Surface' created", - "instance count validation: True (found=49, expected=49)", - "instance count validation: True (found=121, expected=121)", - "instance count validation: True (found=400, expected=400)", - "ShapeIntersectionFilter_InstancePlanting: result=SUCCESS" - ] - - hydra.launch_and_validate_results( - request, - test_directory, - editor, - "ShapeIntersectionFilter_InstancesPlantInAssignedShape.py", - expected_lines, - cfg_args=[level] - ) diff --git a/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/test_SlopeAlignmentModifier.py b/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/test_SlopeAlignmentModifier.py deleted file mode 100755 index 3a01521d8e..0000000000 --- a/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/test_SlopeAlignmentModifier.py +++ /dev/null @@ -1,82 +0,0 @@ -""" -Copyright (c) Contributors to the Open 3D Engine Project. -For complete copyright and license terms please see the LICENSE at the root of this distribution. - -SPDX-License-Identifier: Apache-2.0 OR MIT -""" - -""" -C4896941 - Surface Alignment functions as expected -C4814459 - Surface Alignment overrides function as expected -""" - -import os -import pytest - -# Bail on the test if ly_test_tools doesn't exist. -pytest.importorskip("ly_test_tools") -import editor_python_test_tools.hydra_test_utils as hydra -import ly_test_tools.environment.file_system as file_system - -test_directory = os.path.join(os.path.dirname(__file__), "EditorScripts") - - -@pytest.mark.parametrize("project", ["AutomatedTesting"]) -@pytest.mark.parametrize("level", ["tmp_level"]) -@pytest.mark.usefixtures("automatic_process_killer") -@pytest.mark.parametrize("launcher_platform", ['windows_editor']) -class TestSlopeAlignmentModifier(object): - - @pytest.fixture(autouse=True) - def setup_teardown(self, request, workspace, project, level): - def teardown(): - file_system.delete([os.path.join(workspace.paths.engine_root(), project, "Levels", level)], True, True) - request.addfinalizer(teardown) - - file_system.delete([os.path.join(workspace.paths.engine_root(), project, "Levels", level)], True, True) - - @pytest.mark.test_case_id("C4896941") - @pytest.mark.SUITE_periodic - @pytest.mark.dynveg_modifier - @pytest.mark.xfail(reason="https://github.com/o3de/o3de/issues/2303") - def test_SlopeAlignmentModifier_InstanceSurfaceAlignment(self, request, editor, level, launcher_platform): - - expected_lines = [ - "Vegetation Slope Alignment Modifier component was added to entity", - "Instance Spawner Configuration|Alignment Coefficient Min: SUCCESS", - "Constant Gradient component was added to entity", - "Instance Spawner Configuration|Gradient|Gradient Entity Id: SUCCESS", - "SlopeAlignmentModifier: result=SUCCESS" - ] - - hydra.launch_and_validate_results( - request, - test_directory, - editor, - "SlopeAlignmentModifier_InstanceSurfaceAlignment.py", - expected_lines, - cfg_args=[level] - ) - - @pytest.mark.test_case_id("C4814459") - @pytest.mark.SUITE_periodic - @pytest.mark.dynveg_modifier - @pytest.mark.xfail(reason="https://github.com/o3de/o3de/issues/2303") - def test_SlopeAlignmentModifierOverrides_InstanceSurfaceAlignment(self, request, editor, level, launcher_platform): - - expected_lines = [ - "Instance Spawner Configuration|Allow Per-Item Overrides: SUCCESS", - "Instance Spawner Configuration|Embedded Assets|[0]|Surface Slope Alignment|Override Enabled: SUCCESS", - "Instance Spawner Configuration|Embedded Assets|[0]|Surface Slope Alignment|Max: SUCCESS", - "Instance Spawner Configuration|Embedded Assets|[0]|Surface Slope Alignment|Min: SUCCESS", - "SlopeAlignmentModifierOverrides: result=SUCCESS" - ] - - hydra.launch_and_validate_results( - request, - test_directory, - editor, - "SlopeAlignmentModifierOverrides_InstanceSurfaceAlignment.py", - expected_lines, - cfg_args=[level] - ) diff --git a/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/test_SlopeFilter.py b/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/test_SlopeFilter.py deleted file mode 100755 index 3065b2df61..0000000000 --- a/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/test_SlopeFilter.py +++ /dev/null @@ -1,96 +0,0 @@ -""" -Copyright (c) Contributors to the Open 3D Engine Project. -For complete copyright and license terms please see the LICENSE at the root of this distribution. - -SPDX-License-Identifier: Apache-2.0 OR MIT -""" - -import os -import pytest -import logging - -# Bail on the test if ly_test_tools doesn't exist. -pytest.importorskip("ly_test_tools") -import ly_test_tools.environment.file_system as file_system -import editor_python_test_tools.hydra_test_utils as hydra - -logger = logging.getLogger(__name__) -test_directory = os.path.join(os.path.dirname(__file__), "EditorScripts") - - -@pytest.mark.parametrize("project", ["AutomatedTesting"]) -@pytest.mark.parametrize("level", ["tmp_level"]) -@pytest.mark.usefixtures("automatic_process_killer") -@pytest.mark.parametrize("launcher_platform", ['windows_editor']) -class TestSlopeFilter(object): - @pytest.fixture(autouse=True) - def setup_teardown(self, request, workspace, project, level): - # Cleanup our temp level - file_system.delete([os.path.join(workspace.paths.engine_root(), project, "Levels", level)], True, True) - - def teardown(): - # Cleanup our temp level - file_system.delete([os.path.join(workspace.paths.engine_root(), project, "Levels", level)], True, True) - request.addfinalizer(teardown) - - @pytest.mark.test_case_id("C4874097") - @pytest.mark.SUITE_periodic - @pytest.mark.dynveg_filter - def test_SlopeFilter_FilterStageToggle(self, request, editor, level, workspace, launcher_platform): - cfg_args = [level] - - expected_lines = [ - "SlopeFilter_FilterStageToggle: test started", - "SlopeFilter_FilterStageToggle: Vegetation plant only in the areas where the Box overlaps with the vegetation area's boundaries: True", - "SlopeFilter_FilterStageToggle: Vegetation plant only in the areas where the Cylinder overlaps with the vegetation area's boundaries: True", - "SlopeFilter_FilterStageToggle: Vegetation instances count equal to expected value for PREPROCESS filter stage: True", - "SlopeFilter_FilterStageToggle: Vegetation instances count equal to expected value for POSTPROCESS filter stage: True", - "SlopeFilter_FilterStageToggle: result=SUCCESS", - ] - - unexpected_lines = [ - "SlopeFilter_FilterStageToggle: Vegetation plant only in the areas where the Box overlaps with the vegetation area's boundaries: False", - "SlopeFilter_FilterStageToggle: Vegetation plant only in the areas where the Cylinder overlaps with the vegetation area's boundaries: False", - "SlopeFilter_FilterStageToggle: Vegetation instances count equal to expected value for PREPROCESS filter stage: False", - "SlopeFilter_FilterStageToggle: Vegetation instances count equal to expected value for POSTPROCESS filter stage: False", - ] - - hydra.launch_and_validate_results( - request, - test_directory, - editor, - "SlopeFilter_FilterStageToggle.py", - expected_lines=expected_lines, - unexpected_lines=unexpected_lines, - cfg_args=cfg_args - ) - - @pytest.mark.test_case_id("C4814464", "C4874096") - @pytest.mark.SUITE_periodic - @pytest.mark.dynveg_filter - @pytest.mark.xfail(reason="https://github.com/o3de/o3de/issues/2303") - def test_SlopeFilter_ComponentAndOverrides_InstancesPlantOnValidSlopes(self, request, editor, level, - launcher_platform): - - expected_lines = [ - "'Instance Spawner' created", - "'Planting Surface' created", - "'Sloped Planting Surface' created", - "instance count validation: True (found=1720, expected=1720)", - "Instance Spawner Configuration|Slope Min: SUCCESS", - "Instance Spawner Configuration|Slope Max: SUCCESS", - "instance count validation: True (found=48, expected=48)", - "Instance Spawner Configuration|Embedded Assets|[0]|Slope Filter|Min: SUCCESS", - "Instance Spawner Configuration|Embedded Assets|[0]|Slope Filter|Max: SUCCESS", - "instance count validation: True (found=12, expected=12)", - "SlopeFilter_InstancesPlantOnValidSlope: result=SUCCESS" - ] - - hydra.launch_and_validate_results( - request, - test_directory, - editor, - "SlopeFilter_ComponentAndOverrides_InstancesPlantOnValidSlope.py", - expected_lines, - cfg_args=[level] - ) diff --git a/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/test_SurfaceMaskFilter.py b/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/test_SurfaceMaskFilter.py deleted file mode 100755 index 7101a8e286..0000000000 --- a/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/test_SurfaceMaskFilter.py +++ /dev/null @@ -1,150 +0,0 @@ -""" -Copyright (c) Contributors to the Open 3D Engine Project. -For complete copyright and license terms please see the LICENSE at the root of this distribution. - -SPDX-License-Identifier: Apache-2.0 OR MIT -""" - -import os -import pytest - -# Bail on the test if ly_test_tools doesn't exist. -pytest.importorskip("ly_test_tools") - -import editor_python_test_tools.hydra_test_utils as hydra -import ly_test_tools.environment.file_system as file_system - -test_directory = os.path.join(os.path.dirname(__file__), "EditorScripts") - - -@pytest.mark.parametrize("project", ["AutomatedTesting"]) -@pytest.mark.parametrize("level", ["tmp_level"]) -@pytest.mark.usefixtures("automatic_process_killer") -@pytest.mark.parametrize("launcher_platform", ['windows_editor']) -class TestSurfaceMaskFilter(object): - @pytest.fixture(autouse=True) - def setup_teardown(self, request, workspace, project, level): - def teardown(): - # delete temp level - file_system.delete([os.path.join(workspace.paths.engine_root(), project, "Levels", level)], True, True) - - # Setup - add the teardown finalizer - request.addfinalizer(teardown) - - # Make sure the temp level doesn't already exist - file_system.delete([os.path.join(workspace.paths.engine_root(), project, "Levels", level)], True, True) - - # Simple validation test to ensure that SurfaceTag can be created, set to a value, and compared to another SurfaceTag. - @pytest.mark.SUITE_periodic - @pytest.mark.dynveg_filter - def test_SurfaceMaskFilter_BasicSurfaceTagCreation(self, request, level, editor, launcher_platform): - - expected_lines = [ - "SurfaceTag test started", - "SurfaceTag equal tag comparison is True expected True", - "SurfaceTag not equal tag comparison is False expected False", - "SurfaceTag test finished", - "TestSurfaceMaskFilter_BasicSurfaceTagCreation: result=SUCCESS" - ] - - hydra.launch_and_validate_results( - request, - test_directory, - editor, - 'SurfaceMaskFilter_BasicSurfaceTagCreation.py', - expected_lines=expected_lines, - cfg_args=[level] - ) - - @pytest.mark.test_case_id("C2561342") - @pytest.mark.SUITE_periodic - @pytest.mark.dynveg_filter - def test_SurfaceMaskFilter_ExclusiveSurfaceTags_Function(self, request, editor, level, launcher_platform): - - expected_lines = [ - "'Instance Spawner' created", - "Instance Spawner Box Shape|Box Configuration|Dimensions: SUCCESS", - "Instance Spawner Configuration|Embedded Assets|[0]: SUCCESS", - "'Surface Entity 1' created", - "Surface Entity 1 Box Shape|Box Configuration|Dimensions: SUCCESS", - "Surface Entity 1 Configuration|Generated Tags: SUCCESS", - "'Surface Entity 2' created", - "Surface Entity 2 Box Shape|Box Configuration|Dimensions: SUCCESS", - "Surface Entity 2 Configuration|Generated Tags: SUCCESS", - "SurfaceMaskFilter_ExclusionList: Expected 39 instances - Found 39 instances", - "Instance Spawner Configuration|Exclusion|Weight Max: SUCCESS", - "SurfaceMaskFilter_ExclusionList: Expected 169 instances - Found 169 instances", - "SurfaceMaskFilter_ExclusionList: result=SUCCESS" - ] - - unexpected_lines = ["Failed to add an Exclusive surface mask filter of terrainHole"] - - hydra.launch_and_validate_results( - request, - test_directory, - editor, - "SurfaceMaskFilter_ExclusionList.py", - expected_lines, - unexpected_lines, - cfg_args=[level] - ) - - @pytest.mark.test_case_id("C2561341") - @pytest.mark.SUITE_periodic - @pytest.mark.dynveg_filter - def test_SurfaceMaskFilter_InclusiveSurfaceTags_Function(self, request, editor, level, launcher_platform): - - expected_lines = [ - "'Instance Spawner' created", - "Instance Spawner Box Shape|Box Configuration|Dimensions: SUCCESS", - "Instance Spawner Configuration|Embedded Assets|[0]: SUCCESS", - "'Surface Entity 1' created", - "Surface Entity 1 Box Shape|Box Configuration|Dimensions: SUCCESS", - "Surface Entity 1 Configuration|Generated Tags: SUCCESS", - "'Surface Entity 2' created", - "Surface Entity 2 Box Shape|Box Configuration|Dimensions: SUCCESS", - "Surface Entity 2 Configuration|Generated Tags: SUCCESS", - "SurfaceMaskFilter_InclusionList: Expected 130 instances - Found 130 instances", - "Instance Spawner Configuration|Inclusion|Weight Max: SUCCESS", - "SurfaceMaskFilter_InclusionList: Expected 0 instances - Found 0 instances", - "SurfaceMaskFilter_InclusionList: result=SUCCESS" - ] - - unexpected_lines = ["Failed to add an Inclusive surface mask filter of terrainHole"] - - hydra.launch_and_validate_results( - request, - test_directory, - editor, - "SurfaceMaskFilter_InclusionList.py", - expected_lines, - unexpected_lines, - cfg_args=[level] - ) - - @pytest.mark.test_case_id("C3711666") - @pytest.mark.SUITE_periodic - @pytest.mark.dynveg_filter - def test_SurfaceMaskFilterOverrides_MultipleDescriptorOverridesPlantAsExpected(self, request, editor, level, - launcher_platform): - - expected_lines = [ - "'Instance Spawner' created", - "'Surface Entity A' created", - "'Surface Entity B' created", - "'Surface Entity C' created", - "instance count validation: True (found=725, expected=725)", - "instance count validation: True (found=400, expected=400)", - "instance count validation: True (found=225, expected=225)", - "instance count validation: True (found=100, expected=100)", - "SurfaceMaskFilter_MultipleDescriptorOverrides: result=SUCCESS" - ] - - hydra.launch_and_validate_results( - request, - test_directory, - editor, - "SurfaceMaskFilterOverrides_MultipleDescriptorOverridesPlantAsExpected.py", - expected_lines, - cfg_args=[level] - ) diff --git a/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/test_SystemSettings.py b/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/test_SystemSettings.py deleted file mode 100755 index 0b00a1fa83..0000000000 --- a/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/test_SystemSettings.py +++ /dev/null @@ -1,87 +0,0 @@ -""" -Copyright (c) Contributors to the Open 3D Engine Project. -For complete copyright and license terms please see the LICENSE at the root of this distribution. - -SPDX-License-Identifier: Apache-2.0 OR MIT -""" - -import os -import pytest -import logging - -# Bail on the test if ly_test_tools doesn't exist. -pytest.importorskip("ly_test_tools") -import ly_test_tools.environment.file_system as file_system -import editor_python_test_tools.hydra_test_utils as hydra - -logger = logging.getLogger(__name__) -test_directory = os.path.join(os.path.dirname(__file__), "EditorScripts") - - -@pytest.mark.parametrize("project", ["AutomatedTesting"]) -@pytest.mark.parametrize("level", ["tmp_level"]) -@pytest.mark.usefixtures("automatic_process_killer") -@pytest.mark.parametrize("launcher_platform", ['windows_editor']) -class TestSystemSettings(object): - @pytest.fixture(autouse=True) - def setup_teardown(self, request, workspace, project, level): - def teardown(): - file_system.delete([os.path.join(workspace.paths.engine_root(), project, "Levels", level)], True, True) - - request.addfinalizer(teardown) - - file_system.delete([os.path.join(workspace.paths.engine_root(), project, "Levels", level)], True, True) - - @pytest.mark.test_case_id("C2646869") - @pytest.mark.SUITE_periodic - @pytest.mark.dynveg_misc - def test_SystemSettings_SectorPointDensity(self, request, editor, level, launcher_platform): - - expected_lines = [ - "SystemSettings_SectorPointDensity: test started", - "SystemSettings_SectorPointDensity: Vegetation instances count equal to expected value before changing sector point density: True", - "SystemSettings_SectorPointDensity: Vegetation instances count equal to expected value after changing sector point density: True", - "SystemSettings_SectorPointDensity: result=SUCCESS", - ] - - unexpected_lines = [ - "SystemSettings_SectorPointDensity: Vegetation instances count equal to expected value before changing sector point density: False", - "SystemSettings_SectorPointDensity: Vegetation instances count equal to expected value after changing sector point density: False", - ] - - hydra.launch_and_validate_results( - request, - test_directory, - editor, - "SystemSettings_SectorPointDensity.py", - expected_lines, - unexpected_lines=unexpected_lines, - cfg_args=[level] - ) - - @pytest.mark.test_case_id("C2646870") - @pytest.mark.SUITE_periodic - @pytest.mark.dynveg_misc - def test_SystemSettings_SectorSize(self, request, editor, level, launcher_platform): - - expected_lines = [ - "SystemSettings_SectorSize: test started", - "SystemSettings_SectorSize: Vegetation instances count equal to expected value before changing sector size: True", - "SystemSettings_SectorSize: Vegetation instances count equal to expected value after changing sector size: True", - "SystemSettings_SectorSize: result=SUCCESS", - ] - - unexpected_lines = [ - "SystemSettings_SectorSize: Vegetation instances count equal to expected value before changing sector size: False", - "SystemSettings_SectorSize: Vegetation instances count equal to expected value after changing sector size: False", - ] - - hydra.launch_and_validate_results( - request, - test_directory, - editor, - "SystemSettings_SectorSize.py", - expected_lines, - unexpected_lines=unexpected_lines, - cfg_args=[level] - ) diff --git a/CMakeLists.txt b/CMakeLists.txt index 43b0dd240e..e659270f84 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -29,11 +29,11 @@ include(cmake/PAL.cmake) include(cmake/PALTools.cmake) include(cmake/RuntimeDependencies.cmake) include(cmake/Configurations.cmake) # Requires to be after PAL so we get platform variable definitions -include(cmake/Install.cmake) include(cmake/Dependencies.cmake) include(cmake/Deployment.cmake) include(cmake/3rdParty.cmake) include(cmake/LYPython.cmake) +include(cmake/Install.cmake) include(cmake/LYWrappers.cmake) include(cmake/Gems.cmake) include(cmake/UnitTest.cmake) diff --git a/Code/Editor/AzAssetBrowser/AzAssetBrowserWindow.ui b/Code/Editor/AzAssetBrowser/AzAssetBrowserWindow.ui index df7474d9d4..a345438aed 100644 --- a/Code/Editor/AzAssetBrowser/AzAssetBrowserWindow.ui +++ b/Code/Editor/AzAssetBrowser/AzAssetBrowserWindow.ui @@ -140,9 +140,6 @@ QAbstractItemView::ScrollPerPixel - - false - true @@ -201,6 +198,11 @@
AzToolsFramework/AssetBrowser/Search/SearchWidget.h
1 + + AzQtComponents::TableView + QTreeView +
AzQtComponents/Components/Widgets/TableView.h
+
AzToolsFramework::AssetBrowser::AssetBrowserTreeView QTreeView @@ -214,7 +216,7 @@ AzToolsFramework::AssetBrowser::AssetBrowserTableView - QTableView + AzQtComponents::TableView
AzToolsFramework/AssetBrowser/Views/AssetBrowserTableView.h
diff --git a/Code/Editor/Controls/SplineCtrlEx.cpp b/Code/Editor/Controls/SplineCtrlEx.cpp index 9e0a954c79..1dc2ff19e1 100644 --- a/Code/Editor/Controls/SplineCtrlEx.cpp +++ b/Code/Editor/Controls/SplineCtrlEx.cpp @@ -70,7 +70,7 @@ protected: m_splineEntries.resize(m_splineEntries.size() + 1); SplineEntry& entry = m_splineEntries.back(); ISplineSet* pSplineSet = (pCtrl ? pCtrl->m_pSplineSet : nullptr); - entry.id = (pSplineSet ? pSplineSet->GetIDFromSpline(pSpline) : nullptr); + entry.id = (pSplineSet ? pSplineSet->GetIDFromSpline(pSpline) : AZStd::string{}); entry.pSpline = pSpline; const int numKeys = pSpline->GetKeyCount(); diff --git a/Code/Editor/Core/QtEditorApplication_linux.cpp b/Code/Editor/Core/QtEditorApplication_linux.cpp index fa39609308..175bef0238 100644 --- a/Code/Editor/Core/QtEditorApplication_linux.cpp +++ b/Code/Editor/Core/QtEditorApplication_linux.cpp @@ -8,11 +8,21 @@ #include "QtEditorApplication.h" +#ifdef PAL_TRAIT_LINUX_WINDOW_MANAGER_XCB +#include +#endif + namespace Editor { - bool EditorQtApplication::nativeEventFilter(const QByteArray& , void* , long* ) + bool EditorQtApplication::nativeEventFilter([[maybe_unused]] const QByteArray& eventType, void* message, long*) { - // TODO_KDAB_LINUX + if (GetIEditor()->IsInGameMode()) + { +#ifdef PAL_TRAIT_LINUX_WINDOW_MANAGER_XCB + AzFramework::LinuxXcbEventHandlerBus::Broadcast(&AzFramework::LinuxXcbEventHandler::HandleXcbEvent, static_cast(message)); +#endif + return true; + } return false; } } diff --git a/Code/Editor/CryEditDoc.cpp b/Code/Editor/CryEditDoc.cpp index a61429fc87..07d946c609 100644 --- a/Code/Editor/CryEditDoc.cpp +++ b/Code/Editor/CryEditDoc.cpp @@ -1135,7 +1135,6 @@ bool CCryEditDoc::SaveLevel(const QString& filename) { // if we're saving to a new folder, we need to copy the old folder tree. auto pIPak = GetIEditor()->GetSystem()->GetIPak(); - pIPak->Lock(); const QString oldLevelPattern = QDir(oldLevelFolder).absoluteFilePath("*.*"); const QString oldLevelName = Path::GetFile(GetLevelPathName()); @@ -1199,7 +1198,6 @@ bool CCryEditDoc::SaveLevel(const QString& filename) QFile(filePath).setPermissions(QFile::ReadOther | QFile::WriteOther); }); - pIPak->Unlock(); } // Save level to XML archive. @@ -1813,8 +1811,8 @@ bool CCryEditDoc::BackupBeforeSave(bool force) QString subFolder = theTime.toString("yyyy-MM-dd [HH.mm.ss]"); QString levelName = GetIEditor()->GetGameEngine()->GetLevelName(); - QString backupPath = saveBackupPath + "/" + subFolder + "/"; - gEnv->pCryPak->MakeDir(backupPath.toUtf8().data()); + QString backupPath = saveBackupPath + "/" + subFolder; + AZ::IO::FileIOBase::GetDirectInstance()->CreatePath(backupPath.toUtf8().data()); QString sourcePath = QString::fromUtf8(resolvedLevelPath) + "/"; @@ -2028,7 +2026,7 @@ const char* CCryEditDoc::GetTemporaryLevelName() const void CCryEditDoc::DeleteTemporaryLevel() { QString tempLevelPath = (Path::GetEditingGameDataFolder() + "/Levels/" + GetTemporaryLevelName()).c_str(); - GetIEditor()->GetSystem()->GetIPak()->ClosePacks(tempLevelPath.toUtf8().data(), AZ::IO::IArchive::EPathResolutionRules::FLAGS_ADD_TRAILING_SLASH); + GetIEditor()->GetSystem()->GetIPak()->ClosePacks(tempLevelPath.toUtf8().data()); CFileUtil::Deltree(tempLevelPath.toUtf8().data(), true); } diff --git a/Code/Editor/EditorPreferencesPageViewportGeneral.cpp b/Code/Editor/EditorPreferencesPageViewportGeneral.cpp index a9eec22e69..77560e24f8 100644 --- a/Code/Editor/EditorPreferencesPageViewportGeneral.cpp +++ b/Code/Editor/EditorPreferencesPageViewportGeneral.cpp @@ -5,9 +5,11 @@ * SPDX-License-Identifier: Apache-2.0 OR MIT * */ + #include "EditorDefs.h" #include "EditorPreferencesPageViewportGeneral.h" +#include "EditorViewportSettings.h" #include @@ -15,7 +17,6 @@ #include "DisplaySettings.h" #include "Settings.h" - void CEditorPreferencesPage_ViewportGeneral::Reflect(AZ::SerializeContext& serialize) { serialize.Class() @@ -23,7 +24,8 @@ void CEditorPreferencesPage_ViewportGeneral::Reflect(AZ::SerializeContext& seria ->Field("Sync2DViews", &General::m_sync2DViews) ->Field("DefaultFOV", &General::m_defaultFOV) ->Field("DefaultAspectRatio", &General::m_defaultAspectRatio) - ->Field("EnableContextMenu", &General::m_enableContextMenu); + ->Field("EnableContextMenu", &General::m_contextMenuEnabled) + ->Field("StickySelect", &General::m_stickySelectEnabled); serialize.Class() ->Version(1) @@ -46,10 +48,12 @@ void CEditorPreferencesPage_ViewportGeneral::Reflect(AZ::SerializeContext& seria ->Field("ShowGridGuide", &Display::m_showGridGuide) ->Field("DisplayDimensions", &Display::m_displayDimension); + // clang-format off serialize.Class() ->Version(1) ->Field("SwapXY", &MapViewport::m_swapXY) ->Field("Resolution", &MapViewport::m_resolution); + // clang-format on serialize.Class() ->Version(1) @@ -80,31 +84,51 @@ void CEditorPreferencesPage_ViewportGeneral::Reflect(AZ::SerializeContext& seria editContext->Class("General Viewport Settings", "") ->DataElement(AZ::Edit::UIHandlers::CheckBox, &General::m_sync2DViews, "Synchronize 2D Viewports", "Synchronize 2D Viewports") ->DataElement(AZ::Edit::UIHandlers::SpinBox, &General::m_defaultFOV, "Perspective View FOV", "Perspective View FOV") - ->Attribute("Multiplier", RAD2DEG(1)) - ->Attribute(AZ::Edit::Attributes::Min, 1.0f) - ->Attribute(AZ::Edit::Attributes::Max, 120.0f) - ->DataElement(AZ::Edit::UIHandlers::SpinBox, &General::m_defaultAspectRatio, "Perspective View Aspect Ratio", "Perspective View Aspect Ratio") - ->DataElement(AZ::Edit::UIHandlers::CheckBox, &General::m_enableContextMenu, "Enable Right-Click Context Menu", "Enable Right-Click Context Menu"); + ->Attribute("Multiplier", RAD2DEG(1)) + ->Attribute(AZ::Edit::Attributes::Min, 1.0f) + ->Attribute(AZ::Edit::Attributes::Max, 120.0f) + ->DataElement( + AZ::Edit::UIHandlers::SpinBox, &General::m_defaultAspectRatio, "Perspective View Aspect Ratio", + "Perspective View Aspect Ratio") + ->DataElement( + AZ::Edit::UIHandlers::CheckBox, &General::m_contextMenuEnabled, "Enable Right-Click Context Menu", + "Enable Right-Click Context Menu") + ->DataElement(AZ::Edit::UIHandlers::CheckBox, &General::m_stickySelectEnabled, "Enable Sticky Select", "Enable Sticky Select"); editContext->Class("Viewport Display Settings", "") - ->DataElement(AZ::Edit::UIHandlers::CheckBox, &Display::m_showSafeFrame, "Show 4:3 Aspect Ratio Frame", "Show 4:3 Aspect Ratio Frame") - ->DataElement(AZ::Edit::UIHandlers::CheckBox, &Display::m_highlightSelGeom, "Highlight Selected Geometry", "Highlight Selected Geometry") - ->DataElement(AZ::Edit::UIHandlers::CheckBox, &Display::m_highlightSelVegetation, "Highlight Selected Vegetation", "Highlight Selected Vegetation") - ->DataElement(AZ::Edit::UIHandlers::CheckBox, &Display::m_highlightOnMouseOver, "Highlight Geometry On Mouse Over", "Highlight Geometry On Mouse Over") - ->DataElement(AZ::Edit::UIHandlers::CheckBox, &Display::m_hideMouseCursorWhenCaptured, "Hide Cursor When Captured", "Hide Mouse Cursor When Captured") + ->DataElement( + AZ::Edit::UIHandlers::CheckBox, &Display::m_showSafeFrame, "Show 4:3 Aspect Ratio Frame", "Show 4:3 Aspect Ratio Frame") + ->DataElement( + AZ::Edit::UIHandlers::CheckBox, &Display::m_highlightSelGeom, "Highlight Selected Geometry", "Highlight Selected Geometry") + ->DataElement( + AZ::Edit::UIHandlers::CheckBox, &Display::m_highlightSelVegetation, "Highlight Selected Vegetation", + "Highlight Selected Vegetation") + ->DataElement( + AZ::Edit::UIHandlers::CheckBox, &Display::m_highlightOnMouseOver, "Highlight Geometry On Mouse Over", + "Highlight Geometry On Mouse Over") + ->DataElement( + AZ::Edit::UIHandlers::CheckBox, &Display::m_hideMouseCursorWhenCaptured, "Hide Cursor When Captured", + "Hide Mouse Cursor When Captured") ->DataElement(AZ::Edit::UIHandlers::SpinBox, &Display::m_dragSquareSize, "Drag Square Size", "Drag Square Size") ->DataElement(AZ::Edit::UIHandlers::CheckBox, &Display::m_displayLinks, "Display Object Links", "Display Object Links") ->DataElement(AZ::Edit::UIHandlers::CheckBox, &Display::m_displayTracks, "Display Animation Tracks", "Display Animation Tracks") ->DataElement(AZ::Edit::UIHandlers::CheckBox, &Display::m_alwaysShowRadii, "Always Show Radii", "Always Show Radii") ->DataElement(AZ::Edit::UIHandlers::CheckBox, &Display::m_showBBoxes, "Show Bounding Boxes", "Show Bounding Boxes") - ->DataElement(AZ::Edit::UIHandlers::CheckBox, &Display::m_drawEntityLabels, "Always Draw Entity Labels", "Always Draw Entity Labels") - ->DataElement(AZ::Edit::UIHandlers::CheckBox, &Display::m_showTriggerBounds, "Always Show Trigger Bounds", "Always Show Trigger Bounds") + ->DataElement( + AZ::Edit::UIHandlers::CheckBox, &Display::m_drawEntityLabels, "Always Draw Entity Labels", "Always Draw Entity Labels") + ->DataElement( + AZ::Edit::UIHandlers::CheckBox, &Display::m_showTriggerBounds, "Always Show Trigger Bounds", "Always Show Trigger Bounds") ->DataElement(AZ::Edit::UIHandlers::CheckBox, &Display::m_showIcons, "Show Object Icons", "Show Object Icons") - ->DataElement(AZ::Edit::UIHandlers::CheckBox, &Display::m_distanceScaleIcons, "Scale Object Icons with Distance", "Scale Object Icons with Distance") - ->DataElement(AZ::Edit::UIHandlers::CheckBox, &Display::m_showFrozenHelpers, "Show Helpers of Frozen Objects", "Show Helpers of Frozen Objects") + ->DataElement( + AZ::Edit::UIHandlers::CheckBox, &Display::m_distanceScaleIcons, "Scale Object Icons with Distance", + "Scale Object Icons with Distance") + ->DataElement( + AZ::Edit::UIHandlers::CheckBox, &Display::m_showFrozenHelpers, "Show Helpers of Frozen Objects", + "Show Helpers of Frozen Objects") ->DataElement(AZ::Edit::UIHandlers::CheckBox, &Display::m_fillSelectedShapes, "Fill Selected Shapes", "Fill Selected Shapes") ->DataElement(AZ::Edit::UIHandlers::CheckBox, &Display::m_showGridGuide, "Show Snapping Grid Guide", "Show Snapping Grid Guide") - ->DataElement(AZ::Edit::UIHandlers::CheckBox, &Display::m_displayDimension, "Display Dimension Figures", "Display Dimension Figures"); + ->DataElement( + AZ::Edit::UIHandlers::CheckBox, &Display::m_displayDimension, "Display Dimension Figures", "Display Dimension Figures"); editContext->Class("Map Viewport Settings", "") ->DataElement(AZ::Edit::UIHandlers::CheckBox, &MapViewport::m_swapXY, "Swap X/Y Axis", "Swap X/Y Axis") @@ -113,42 +137,64 @@ void CEditorPreferencesPage_ViewportGeneral::Reflect(AZ::SerializeContext& seria editContext->Class("Text Label Settings", "") ->DataElement(AZ::Edit::UIHandlers::CheckBox, &TextLabels::m_labelsOn, "Enabled", "Enabled") ->DataElement(AZ::Edit::UIHandlers::CheckBox, &TextLabels::m_labelsDistance, "Distance", "Distance") - ->Attribute(AZ::Edit::Attributes::Min, 0.f) - ->Attribute(AZ::Edit::Attributes::Max, 100000.f); + ->Attribute(AZ::Edit::Attributes::Min, 0.f) + ->Attribute(AZ::Edit::Attributes::Max, 100000.f); editContext->Class("Selection Preview Color Settings", "") ->DataElement(AZ::Edit::UIHandlers::Color, &SelectionPreviewColor::m_colorGroupBBox, "Group Bounding Box", "Group Bounding Box") - ->DataElement(AZ::Edit::UIHandlers::Color, &SelectionPreviewColor::m_colorEntityBBox, "Entity Bounding Box", "Entity Bounding Box") - ->DataElement(AZ::Edit::UIHandlers::SpinBox, &SelectionPreviewColor::m_fBBoxAlpha, "Bounding Box Highlight Alpha", "Bounding Box Highlight Alpha") - ->Attribute(AZ::Edit::Attributes::Min, 0.0f) - ->Attribute(AZ::Edit::Attributes::Max, 1.0f) + ->DataElement( + AZ::Edit::UIHandlers::Color, &SelectionPreviewColor::m_colorEntityBBox, "Entity Bounding Box", "Entity Bounding Box") + ->DataElement( + AZ::Edit::UIHandlers::SpinBox, &SelectionPreviewColor::m_fBBoxAlpha, "Bounding Box Highlight Alpha", + "Bounding Box Highlight Alpha") + ->Attribute(AZ::Edit::Attributes::Min, 0.0f) + ->Attribute(AZ::Edit::Attributes::Max, 1.0f) ->DataElement(AZ::Edit::UIHandlers::Color, &SelectionPreviewColor::m_geometryHighlightColor, "Geometry Color", "Geometry Color") - ->DataElement(AZ::Edit::UIHandlers::Color, &SelectionPreviewColor::m_solidBrushGeometryColor, "Solid Brush Geometry Color", "Solid Brush Geometry Color") - ->DataElement(AZ::Edit::UIHandlers::SpinBox, &SelectionPreviewColor::m_fgeomAlpha, "Geometry Highlight Alpha", "Geometry Highlight Alpha") - ->Attribute(AZ::Edit::Attributes::Min, 0.0f) - ->Attribute(AZ::Edit::Attributes::Max, 1.0f) - ->DataElement(AZ::Edit::UIHandlers::SpinBox, &SelectionPreviewColor::m_childObjectGeomAlpha, "Child Geometry Highlight Alpha", "Child Geometry Highlight Alpha") - ->Attribute(AZ::Edit::Attributes::Min, 0.0f) - ->Attribute(AZ::Edit::Attributes::Max, 1.0f); + ->DataElement( + AZ::Edit::UIHandlers::Color, &SelectionPreviewColor::m_solidBrushGeometryColor, "Solid Brush Geometry Color", + "Solid Brush Geometry Color") + ->DataElement( + AZ::Edit::UIHandlers::SpinBox, &SelectionPreviewColor::m_fgeomAlpha, "Geometry Highlight Alpha", "Geometry Highlight Alpha") + ->Attribute(AZ::Edit::Attributes::Min, 0.0f) + ->Attribute(AZ::Edit::Attributes::Max, 1.0f) + ->DataElement( + AZ::Edit::UIHandlers::SpinBox, &SelectionPreviewColor::m_childObjectGeomAlpha, "Child Geometry Highlight Alpha", + "Child Geometry Highlight Alpha") + ->Attribute(AZ::Edit::Attributes::Min, 0.0f) + ->Attribute(AZ::Edit::Attributes::Max, 1.0f); editContext->Class("General Viewport Preferences", "General Viewport Preferences") ->ClassElement(AZ::Edit::ClassElements::EditorData, "") ->Attribute(AZ::Edit::Attributes::Visibility, AZ_CRC("PropertyVisibility_ShowChildrenOnly", 0xef428f20)) - ->DataElement(AZ::Edit::UIHandlers::Default, &CEditorPreferencesPage_ViewportGeneral::m_general, "General Viewport Settings", "General Viewport Settings") - ->DataElement(AZ::Edit::UIHandlers::Default, &CEditorPreferencesPage_ViewportGeneral::m_display, "Viewport Display Settings", "Viewport Display Settings") - ->DataElement(AZ::Edit::UIHandlers::Default, &CEditorPreferencesPage_ViewportGeneral::m_map, "Map Viewport Settings", "Map Viewport Settings") - ->DataElement(AZ::Edit::UIHandlers::Default, &CEditorPreferencesPage_ViewportGeneral::m_textLabels, "Text Label Settings", "Text Label Settings") - ->DataElement(AZ::Edit::UIHandlers::Default, &CEditorPreferencesPage_ViewportGeneral::m_selectionPreviewColor, "Selection Preview Color Settings", "Selection Preview Color Settings"); + ->DataElement( + AZ::Edit::UIHandlers::Default, &CEditorPreferencesPage_ViewportGeneral::m_general, "General Viewport Settings", + "General Viewport Settings") + ->DataElement( + AZ::Edit::UIHandlers::Default, &CEditorPreferencesPage_ViewportGeneral::m_display, "Viewport Display Settings", + "Viewport Display Settings") + ->DataElement( + AZ::Edit::UIHandlers::Default, &CEditorPreferencesPage_ViewportGeneral::m_map, "Map Viewport Settings", + "Map Viewport Settings") + ->DataElement( + AZ::Edit::UIHandlers::Default, &CEditorPreferencesPage_ViewportGeneral::m_textLabels, "Text Label Settings", + "Text Label Settings") + ->DataElement( + AZ::Edit::UIHandlers::Default, &CEditorPreferencesPage_ViewportGeneral::m_selectionPreviewColor, + "Selection Preview Color Settings", "Selection Preview Color Settings"); } } - CEditorPreferencesPage_ViewportGeneral::CEditorPreferencesPage_ViewportGeneral() { InitializeSettings(); m_icon = QIcon(":/res/Viewport.svg"); } +const char* CEditorPreferencesPage_ViewportGeneral::GetCategory() +{ + return "Viewports"; +} + const char* CEditorPreferencesPage_ViewportGeneral::GetTitle() { return "Viewport"; @@ -159,14 +205,25 @@ QIcon& CEditorPreferencesPage_ViewportGeneral::GetIcon() return m_icon; } +void CEditorPreferencesPage_ViewportGeneral::OnCancel() +{ + // noop +} + +bool CEditorPreferencesPage_ViewportGeneral::OnQueryCancel() +{ + return true; +} + void CEditorPreferencesPage_ViewportGeneral::OnApply() { CDisplaySettings* ds = GetIEditor()->GetDisplaySettings(); gSettings.viewports.fDefaultAspectRatio = m_general.m_defaultAspectRatio; gSettings.viewports.fDefaultFov = m_general.m_defaultFOV; - gSettings.viewports.bEnableContextMenu = m_general.m_enableContextMenu; + gSettings.viewports.bEnableContextMenu = m_general.m_contextMenuEnabled; gSettings.viewports.bSync2DViews = m_general.m_sync2DViews; + SandboxEditor::SetStickySelectEnabled(m_general.m_stickySelectEnabled); gSettings.viewports.bShowSafeFrame = m_display.m_showSafeFrame; gSettings.viewports.bHighlightSelectedGeometry = m_display.m_highlightSelGeom; @@ -202,19 +259,19 @@ void CEditorPreferencesPage_ViewportGeneral::OnApply() gSettings.objectColorSettings.fChildGeomAlpha = m_selectionPreviewColor.m_childObjectGeomAlpha; gSettings.objectColorSettings.entityHighlight = QColor( - static_cast(m_selectionPreviewColor.m_colorEntityBBox.GetR() * 255.0f), - static_cast(m_selectionPreviewColor.m_colorEntityBBox.GetG() * 255.0f), - static_cast(m_selectionPreviewColor.m_colorEntityBBox.GetB() * 255.0f)); + static_cast(m_selectionPreviewColor.m_colorEntityBBox.GetR() * 255.0f), + static_cast(m_selectionPreviewColor.m_colorEntityBBox.GetG() * 255.0f), + static_cast(m_selectionPreviewColor.m_colorEntityBBox.GetB() * 255.0f)); gSettings.objectColorSettings.groupHighlight = QColor( - static_cast(m_selectionPreviewColor.m_colorGroupBBox.GetR() * 255.0f), - static_cast(m_selectionPreviewColor.m_colorGroupBBox.GetG() * 255.0f), - static_cast(m_selectionPreviewColor.m_colorGroupBBox.GetB() * 255.0f)); + static_cast(m_selectionPreviewColor.m_colorGroupBBox.GetR() * 255.0f), + static_cast(m_selectionPreviewColor.m_colorGroupBBox.GetG() * 255.0f), + static_cast(m_selectionPreviewColor.m_colorGroupBBox.GetB() * 255.0f)); gSettings.objectColorSettings.fBBoxAlpha = m_selectionPreviewColor.m_fBBoxAlpha; gSettings.objectColorSettings.fGeomAlpha = m_selectionPreviewColor.m_fgeomAlpha; gSettings.objectColorSettings.geometryHighlightColor = QColor( - static_cast(m_selectionPreviewColor.m_geometryHighlightColor.GetR() * 255.0f), - static_cast(m_selectionPreviewColor.m_geometryHighlightColor.GetG() * 255.0f), - static_cast(m_selectionPreviewColor.m_geometryHighlightColor.GetB() * 255.0f)); + static_cast(m_selectionPreviewColor.m_geometryHighlightColor.GetR() * 255.0f), + static_cast(m_selectionPreviewColor.m_geometryHighlightColor.GetG() * 255.0f), + static_cast(m_selectionPreviewColor.m_geometryHighlightColor.GetB() * 255.0f)); gSettings.objectColorSettings.solidBrushGeometryColor = QColor( static_cast(m_selectionPreviewColor.m_solidBrushGeometryColor.GetR() * 255.0f), static_cast(m_selectionPreviewColor.m_solidBrushGeometryColor.GetG() * 255.0f), @@ -227,8 +284,9 @@ void CEditorPreferencesPage_ViewportGeneral::InitializeSettings() m_general.m_defaultAspectRatio = gSettings.viewports.fDefaultAspectRatio; m_general.m_defaultFOV = gSettings.viewports.fDefaultFov; - m_general.m_enableContextMenu = gSettings.viewports.bEnableContextMenu; + m_general.m_contextMenuEnabled = gSettings.viewports.bEnableContextMenu; m_general.m_sync2DViews = gSettings.viewports.bSync2DViews; + m_general.m_stickySelectEnabled = SandboxEditor::StickySelectEnabled(); m_display.m_showSafeFrame = gSettings.viewports.bShowSafeFrame; m_display.m_highlightSelGeom = gSettings.viewports.bHighlightSelectedGeometry; @@ -256,10 +314,22 @@ void CEditorPreferencesPage_ViewportGeneral::InitializeSettings() m_textLabels.m_labelsDistance = ds->GetLabelsDistance(); m_selectionPreviewColor.m_childObjectGeomAlpha = gSettings.objectColorSettings.fChildGeomAlpha; - m_selectionPreviewColor.m_colorEntityBBox.Set(static_cast(gSettings.objectColorSettings.entityHighlight.redF()), static_cast(gSettings.objectColorSettings.entityHighlight.greenF()), static_cast(gSettings.objectColorSettings.entityHighlight.blueF()), 1.0f); - m_selectionPreviewColor.m_colorGroupBBox.Set(static_cast(gSettings.objectColorSettings.groupHighlight.redF()), static_cast(gSettings.objectColorSettings.groupHighlight.greenF()), static_cast(gSettings.objectColorSettings.groupHighlight.blueF()), 1.0f); + m_selectionPreviewColor.m_colorEntityBBox.Set( + static_cast(gSettings.objectColorSettings.entityHighlight.redF()), + static_cast(gSettings.objectColorSettings.entityHighlight.greenF()), + static_cast(gSettings.objectColorSettings.entityHighlight.blueF()), 1.0f); + m_selectionPreviewColor.m_colorGroupBBox.Set( + static_cast(gSettings.objectColorSettings.groupHighlight.redF()), + static_cast(gSettings.objectColorSettings.groupHighlight.greenF()), + static_cast(gSettings.objectColorSettings.groupHighlight.blueF()), 1.0f); m_selectionPreviewColor.m_fBBoxAlpha = gSettings.objectColorSettings.fBBoxAlpha; m_selectionPreviewColor.m_fgeomAlpha = gSettings.objectColorSettings.fGeomAlpha; - m_selectionPreviewColor.m_geometryHighlightColor.Set(static_cast(gSettings.objectColorSettings.geometryHighlightColor.redF()), static_cast(gSettings.objectColorSettings.geometryHighlightColor.greenF()), static_cast(gSettings.objectColorSettings.geometryHighlightColor.blueF()), 1.0f); - m_selectionPreviewColor.m_solidBrushGeometryColor.Set(static_cast(gSettings.objectColorSettings.solidBrushGeometryColor.redF()), static_cast(gSettings.objectColorSettings.solidBrushGeometryColor.greenF()), static_cast(gSettings.objectColorSettings.solidBrushGeometryColor.blueF()), 1.0f); + m_selectionPreviewColor.m_geometryHighlightColor.Set( + static_cast(gSettings.objectColorSettings.geometryHighlightColor.redF()), + static_cast(gSettings.objectColorSettings.geometryHighlightColor.greenF()), + static_cast(gSettings.objectColorSettings.geometryHighlightColor.blueF()), 1.0f); + m_selectionPreviewColor.m_solidBrushGeometryColor.Set( + static_cast(gSettings.objectColorSettings.solidBrushGeometryColor.redF()), + static_cast(gSettings.objectColorSettings.solidBrushGeometryColor.greenF()), + static_cast(gSettings.objectColorSettings.solidBrushGeometryColor.blueF()), 1.0f); } diff --git a/Code/Editor/EditorPreferencesPageViewportGeneral.h b/Code/Editor/EditorPreferencesPageViewportGeneral.h index a042bcf19b..be89cc6df4 100644 --- a/Code/Editor/EditorPreferencesPageViewportGeneral.h +++ b/Code/Editor/EditorPreferencesPageViewportGeneral.h @@ -5,18 +5,17 @@ * SPDX-License-Identifier: Apache-2.0 OR MIT * */ + #pragma once #include "Include/IPreferencesPage.h" -#include -#include -#include #include +#include +#include +#include #include - -class CEditorPreferencesPage_ViewportGeneral - : public IPreferencesPage +class CEditorPreferencesPage_ViewportGeneral : public IPreferencesPage { public: AZ_RTTI(CEditorPreferencesPage_ViewportGeneral, "{8511FF7F-F774-47E1-A99B-3DE3A867E403}", IPreferencesPage) @@ -26,12 +25,12 @@ public: CEditorPreferencesPage_ViewportGeneral(); virtual ~CEditorPreferencesPage_ViewportGeneral() = default; - virtual const char* GetCategory() override { return "Viewports"; } + virtual const char* GetCategory() override; virtual const char* GetTitle() override; virtual QIcon& GetIcon() override; virtual void OnApply() override; - virtual void OnCancel() override {} - virtual bool OnQueryCancel() override { return true; } + virtual void OnCancel() override; + virtual bool OnQueryCancel() override; private: void InitializeSettings(); @@ -43,7 +42,8 @@ private: bool m_sync2DViews; float m_defaultFOV; float m_defaultAspectRatio; - bool m_enableContextMenu; + bool m_contextMenuEnabled; + bool m_stickySelectEnabled; }; struct Display @@ -106,5 +106,3 @@ private: SelectionPreviewColor m_selectionPreviewColor; QIcon m_icon; }; - - diff --git a/Code/Editor/EditorToolsApplication.cpp b/Code/Editor/EditorToolsApplication.cpp index 1e5d747e4a..26e608f657 100644 --- a/Code/Editor/EditorToolsApplication.cpp +++ b/Code/Editor/EditorToolsApplication.cpp @@ -34,10 +34,14 @@ namespace EditorInternal : ToolsApplication(argc, argv) { EditorToolsApplicationRequests::Bus::Handler::BusConnect(); + AzToolsFramework::ViewportInteraction::EditorModifierKeyRequestBus::Handler::BusConnect(); + AzToolsFramework::ViewportInteraction::EditorViewportInputTimeNowRequestBus::Handler::BusConnect(); } EditorToolsApplication::~EditorToolsApplication() { + AzToolsFramework::ViewportInteraction::EditorViewportInputTimeNowRequestBus::Handler::BusDisconnect(); + AzToolsFramework::ViewportInteraction::EditorModifierKeyRequestBus::Handler::BusDisconnect(); EditorToolsApplicationRequests::Bus::Handler::BusDisconnect(); Stop(); } @@ -48,7 +52,6 @@ namespace EditorInternal return m_StartupAborted; } - void EditorToolsApplication::RegisterCoreComponents() { AzToolsFramework::ToolsApplication::RegisterCoreComponents(); @@ -274,5 +277,14 @@ namespace EditorInternal Exit(); } -} + AzToolsFramework::ViewportInteraction::KeyboardModifiers EditorToolsApplication::QueryKeyboardModifiers() + { + return AzToolsFramework::ViewportInteraction::BuildKeyboardModifiers(QGuiApplication::queryKeyboardModifiers()); + } + AZStd::chrono::milliseconds EditorToolsApplication::EditorViewportInputTimeNow() + { + const auto now = AZStd::chrono::high_resolution_clock::now(); + return AZStd::chrono::time_point_cast(now).time_since_epoch(); + } +} // namespace EditorInternal diff --git a/Code/Editor/EditorToolsApplication.h b/Code/Editor/EditorToolsApplication.h index 422772cbc4..d4e6223445 100644 --- a/Code/Editor/EditorToolsApplication.h +++ b/Code/Editor/EditorToolsApplication.h @@ -7,7 +7,9 @@ */ #pragma once + #include +#include #include "Core/EditorMetricsPlainTextNameRegistration.h" #include "EditorToolsApplicationAPI.h" @@ -19,6 +21,8 @@ namespace EditorInternal class EditorToolsApplication : public AzToolsFramework::ToolsApplication , public EditorToolsApplicationRequests::Bus::Handler + , public AzToolsFramework::ViewportInteraction::EditorModifierKeyRequestBus::Handler + , public AzToolsFramework::ViewportInteraction::EditorViewportInputTimeNowRequestBus::Handler { public: EditorToolsApplication(int* argc, char*** argv); @@ -44,6 +48,12 @@ namespace EditorInternal void CreateReflectionManager() override; void Reflect(AZ::ReflectContext* context) override; + // EditorModifierKeyRequestBus overrides ... + AzToolsFramework::ViewportInteraction::KeyboardModifiers QueryKeyboardModifiers() override; + + // EditorViewportInputTimeNowRequestBus overrides ... + AZStd::chrono::milliseconds EditorViewportInputTimeNow() override; + protected: // From EditorToolsApplicationRequests bool OpenLevel(AZStd::string_view levelName) override; diff --git a/Code/Editor/EditorViewportSettings.cpp b/Code/Editor/EditorViewportSettings.cpp index c1bd85a174..063ec125ba 100644 --- a/Code/Editor/EditorViewportSettings.cpp +++ b/Code/Editor/EditorViewportSettings.cpp @@ -20,6 +20,7 @@ namespace SandboxEditor 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"; + constexpr AZStd::string_view StickySelectSetting = "/Amazon/Preferences/Editor/StickySelect"; constexpr AZStd::string_view ManipulatorLineBoundWidthSetting = "/Amazon/Preferences/Editor/Manipulator/LineBoundWidth"; constexpr AZStd::string_view ManipulatorCircleBoundWidthSetting = "/Amazon/Preferences/Editor/Manipulator/CircleBoundWidth"; constexpr AZStd::string_view CameraTranslateSpeedSetting = "/Amazon/Preferences/Editor/Camera/TranslateSpeed"; @@ -158,6 +159,16 @@ namespace SandboxEditor SetRegistry(ShowGridSetting, showing); } + bool StickySelectEnabled() + { + return GetRegistry(StickySelectSetting, false); + } + + void SetStickySelectEnabled(const bool enabled) + { + SetRegistry(StickySelectSetting, enabled); + } + float ManipulatorLineBoundWidth() { return aznumeric_cast(GetRegistry(ManipulatorLineBoundWidthSetting, 0.1)); diff --git a/Code/Editor/EditorViewportSettings.h b/Code/Editor/EditorViewportSettings.h index 8aeeee1384..20d397a29e 100644 --- a/Code/Editor/EditorViewportSettings.h +++ b/Code/Editor/EditorViewportSettings.h @@ -47,6 +47,9 @@ namespace SandboxEditor SANDBOX_API bool ShowingGrid(); SANDBOX_API void SetShowingGrid(bool showing); + SANDBOX_API bool StickySelectEnabled(); + SANDBOX_API void SetStickySelectEnabled(bool enabled); + SANDBOX_API float ManipulatorLineBoundWidth(); SANDBOX_API void SetManipulatorLineBoundWidth(float lineBoundWidth); diff --git a/Code/Editor/EditorViewportWidget.cpp b/Code/Editor/EditorViewportWidget.cpp index f009fe7602..5b5b52d28f 100644 --- a/Code/Editor/EditorViewportWidget.cpp +++ b/Code/Editor/EditorViewportWidget.cpp @@ -744,11 +744,15 @@ void EditorViewportWidget::RenderAll() { namespace AztfVi = AzToolsFramework::ViewportInteraction; + AztfVi::KeyboardModifiers keyboardModifiers; + AztfVi::EditorModifierKeyRequestBus::BroadcastResult( + keyboardModifiers, &AztfVi::EditorModifierKeyRequestBus::Events::QueryKeyboardModifiers); + m_debugDisplay->DepthTestOff(); m_manipulatorManager->DrawManipulators( *m_debugDisplay, GetCameraState(), BuildMouseInteractionInternal( - AztfVi::MouseButtons(AztfVi::TranslateMouseButtons(QGuiApplication::mouseButtons())), QueryKeyboardModifiers(), + AztfVi::MouseButtons(AztfVi::TranslateMouseButtons(QGuiApplication::mouseButtons())), keyboardModifiers, BuildMousePick(WidgetToViewport(mapFromGlobal(QCursor::pos()))))); m_debugDisplay->DepthTestOn(); } @@ -959,12 +963,13 @@ QWidget* EditorViewportWidget::GetWidgetForViewportContextMenu() bool EditorViewportWidget::ShowingWorldSpace() { - return QueryKeyboardModifiers().Shift(); -} + namespace AztfVi = AzToolsFramework::ViewportInteraction; -AzToolsFramework::ViewportInteraction::KeyboardModifiers EditorViewportWidget::QueryKeyboardModifiers() -{ - return AzToolsFramework::ViewportInteraction::BuildKeyboardModifiers(QGuiApplication::queryKeyboardModifiers()); + AztfVi::KeyboardModifiers keyboardModifiers; + AztfVi::EditorModifierKeyRequestBus::BroadcastResult( + keyboardModifiers, &AztfVi::EditorModifierKeyRequestBus::Events::QueryKeyboardModifiers); + + return keyboardModifiers.Shift(); } void EditorViewportWidget::SetViewportId(int id) @@ -1039,7 +1044,6 @@ void EditorViewportWidget::ConnectViewportInteractionRequestBus() { AzToolsFramework::ViewportInteraction::MainEditorViewportInteractionRequestBus::Handler::BusConnect(GetViewportId()); AzToolsFramework::ViewportInteraction::EditorEntityViewportInteractionRequestBus::Handler::BusConnect(GetViewportId()); - AzToolsFramework::ViewportInteraction::EditorModifierKeyRequestBus::Handler::BusConnect(); m_viewportUi.ConnectViewportUiBus(GetViewportId()); AzFramework::InputSystemCursorConstraintRequestBus::Handler::BusConnect(); @@ -1050,7 +1054,6 @@ void EditorViewportWidget::DisconnectViewportInteractionRequestBus() AzFramework::InputSystemCursorConstraintRequestBus::Handler::BusDisconnect(); m_viewportUi.DisconnectViewportUiBus(); - AzToolsFramework::ViewportInteraction::EditorModifierKeyRequestBus::Handler::BusDisconnect(); AzToolsFramework::ViewportInteraction::EditorEntityViewportInteractionRequestBus::Handler::BusDisconnect(); AzToolsFramework::ViewportInteraction::MainEditorViewportInteractionRequestBus::Handler::BusDisconnect(); } @@ -2522,6 +2525,11 @@ float EditorViewportSettings::ManipulatorCircleBoundWidth() const return SandboxEditor::ManipulatorCircleBoundWidth(); } +bool EditorViewportSettings::StickySelectEnabled() const +{ + return SandboxEditor::StickySelectEnabled(); +} + AZ_CVAR_EXTERNED(bool, ed_previewGameInFullscreen_once); bool EditorViewportWidget::ShouldPreviewFullscreen() const diff --git a/Code/Editor/EditorViewportWidget.h b/Code/Editor/EditorViewportWidget.h index c4a8e9fcca..49930a2a13 100644 --- a/Code/Editor/EditorViewportWidget.h +++ b/Code/Editor/EditorViewportWidget.h @@ -77,6 +77,7 @@ struct EditorViewportSettings : public AzToolsFramework::ViewportInteraction::Vi float AngleStep() const override; float ManipulatorLineBoundWidth() const override; float ManipulatorCircleBoundWidth() const override; + bool StickySelectEnabled() const override; }; // EditorViewportWidget window @@ -91,7 +92,6 @@ class SANDBOX_API EditorViewportWidget final , private AzFramework::InputSystemCursorConstraintRequestBus::Handler , private AzToolsFramework::ViewportInteraction::MainEditorViewportInteractionRequestBus::Handler , private AzToolsFramework::ViewportInteraction::EditorEntityViewportInteractionRequestBus::Handler - , private AzToolsFramework::ViewportInteraction::EditorModifierKeyRequestBus::Handler , private AzFramework::AssetCatalogEventBus::Handler , private AZ::RPI::SceneNotificationBus::Handler { @@ -211,9 +211,6 @@ private: // EditorEntityViewportInteractionRequestBus overrides ... void FindVisibleEntities(AZStd::vector& visibleEntities) override; - // EditorModifierKeyRequestBus overrides ... - AzToolsFramework::ViewportInteraction::KeyboardModifiers QueryKeyboardModifiers() override; - // Camera::EditorCameraRequestBus overrides ... void SetViewFromEntityPerspective(const AZ::EntityId& entityId) override; void SetViewAndMovementLockFromEntityPerspective(const AZ::EntityId& entityId, bool lockCameraMovement) override; diff --git a/Code/Editor/GameExporter.cpp b/Code/Editor/GameExporter.cpp index 00dc3d8de1..9315505e08 100644 --- a/Code/Editor/GameExporter.cpp +++ b/Code/Editor/GameExporter.cpp @@ -432,25 +432,6 @@ void CGameExporter::ExportFileList(const QString& path, const QString& levelName newFileNode->setAttr("src", handle.m_filename.data()); newFileNode->setAttr("dest", handle.m_filename.data()); newFileNode->setAttr("size", handle.m_fileDesc.nSize); - - unsigned char md5[16]; - AZStd::string filenameToHash = GetIEditor()->GetGameEngine()->GetLevelPath().toUtf8().data(); - filenameToHash += "/"; - filenameToHash += AZStd::string{ handle.m_filename.data(), handle.m_filename.size() }; - if (gEnv->pCryPak->ComputeMD5(filenameToHash.data(), md5)) - { - char md5string[33]; - sprintf_s(md5string, "%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x", - md5[0], md5[1], md5[2], md5[3], - md5[4], md5[5], md5[6], md5[7], - md5[8], md5[9], md5[10], md5[11], - md5[12], md5[13], md5[14], md5[15]); - newFileNode->setAttr("md5", md5string); - } - else - { - newFileNode->setAttr("md5", ""); - } } } } while (handle = gEnv->pCryPak->FindNext(handle)); diff --git a/Code/Editor/Include/IEditorClassFactory.h b/Code/Editor/Include/IEditorClassFactory.h index 0827dc96dc..dd47f803e2 100644 --- a/Code/Editor/Include/IEditorClassFactory.h +++ b/Code/Editor/Include/IEditorClassFactory.h @@ -14,8 +14,10 @@ #define CRYINCLUDE_EDITOR_INCLUDE_IEDITORCLASSFACTORY_H #pragma once +#include #include #include +#include #define DEFINE_UUID(l, w1, w2, b1, b2, b3, b4, b5, b6, b7, b8) \ static const GUID uuid() { return { l, w1, w2, { b1, b2, b3, b4, b5, b6, b7, b8 } }; } @@ -34,7 +36,7 @@ struct IUnknown #endif #define __uuidof(T) T::uuid() -#if defined(AZ_PLATFORM_LINUX) +#if defined(AZ_PLATFORM_LINUX) || defined(AZ_PLATFORM_MAC) # ifndef _REFGUID_DEFINED # define _REFGUID_DEFINED @@ -65,7 +67,7 @@ enum }; #endif -#endif // defined(AZ_PLATFORM_LINUX) +#endif // defined(AZ_PLATFORM_LINUX) || defined(AZ_PLATFORM_MAC) #include "SandboxAPI.h" diff --git a/Code/Editor/Platform/Mac/EditorEntitlements.plist b/Code/Editor/Platform/Mac/EditorEntitlements.plist new file mode 100644 index 0000000000..cefa2bf93b --- /dev/null +++ b/Code/Editor/Platform/Mac/EditorEntitlements.plist @@ -0,0 +1,10 @@ + + + + + com.apple.security.cs.allow-dyld-environment-variables + + com.apple.security.cs.disable-library-validation + + + diff --git a/Code/Editor/Platform/Mac/editor_mac.cmake b/Code/Editor/Platform/Mac/editor_mac.cmake index fdccfafb46..eed955f2e4 100644 --- a/Code/Editor/Platform/Mac/editor_mac.cmake +++ b/Code/Editor/Platform/Mac/editor_mac.cmake @@ -12,28 +12,5 @@ set_target_properties(Editor PROPERTIES MACOSX_BUNDLE_INFO_PLIST ${CMAKE_CURRENT_LIST_DIR}/gui_info.plist RESOURCE ${CMAKE_CURRENT_LIST_DIR}/Images.xcassets XCODE_ATTRIBUTE_ASSETCATALOG_COMPILER_APPICON_NAME EditorAppIcon + ENTITLEMENT_FILE_PATH ${CMAKE_CURRENT_LIST_DIR}/EditorEntitlements.plist ) - -# We cannot use ly_add_target here because we're already including this file from inside ly_add_target -# So we need to setup target, dependencies and install logic manually. -add_executable(EditorDummy Platform/Mac/main_dummy.cpp) -add_executable(AZ::EditorDummy ALIAS EditorDummy) - -ly_target_link_libraries(EditorDummy - PRIVATE - AZ::AzCore - AZ::AzFramework) - -ly_add_dependencies(Editor EditorDummy) - -# Store the aliased target into a DIRECTORY property -set_property(DIRECTORY APPEND PROPERTY LY_DIRECTORY_TARGETS AZ::EditorDummy) - -# Store the directory path in a GLOBAL property so that it can be accessed -# in the layout install logic. Skip if the directory has already been added -get_property(ly_all_target_directories GLOBAL PROPERTY LY_ALL_TARGET_DIRECTORIES) -if(NOT CMAKE_CURRENT_SOURCE_DIR IN_LIST ly_all_target_directories) - set_property(GLOBAL APPEND PROPERTY LY_ALL_TARGET_DIRECTORIES ${CMAKE_CURRENT_SOURCE_DIR}) -endif() - -ly_install_add_install_path_setreg(Editor) \ No newline at end of file diff --git a/Code/Editor/Platform/Mac/gui_info.plist b/Code/Editor/Platform/Mac/gui_info.plist index cc87cbbb47..5b5f94e977 100644 --- a/Code/Editor/Platform/Mac/gui_info.plist +++ b/Code/Editor/Platform/Mac/gui_info.plist @@ -3,7 +3,7 @@ CFBundleExecutable - EditorDummy + Editor CFBundleIdentifier org.O3DE.Editor CFBundlePackageType diff --git a/Code/Editor/Platform/Mac/main_dummy.cpp b/Code/Editor/Platform/Mac/main_dummy.cpp deleted file mode 100644 index 348a32ab47..0000000000 --- a/Code/Editor/Platform/Mac/main_dummy.cpp +++ /dev/null @@ -1,75 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project. - * For complete copyright and license terms please see the LICENSE at the root of this distribution. - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ - -#include -#include -#include -#include -#include - -#include - -int main(int argc, char* argv[]) -{ - // Create a ComponentApplication to initialize the AZ::SystemAllocator and initialize the SettingsRegistry - AZ::ComponentApplication::Descriptor desc; - AZ::ComponentApplication application; - application.Create(desc); - - AZStd::vector envVars; - - const char* homePath = std::getenv("HOME"); - envVars.push_back(AZStd::string::format("HOME=%s", homePath)); - - if (auto settingsRegistry = AZ::SettingsRegistry::Get(); settingsRegistry != nullptr) - { - const char* dyldLibPathOrig = std::getenv("DYLD_LIBRARY_PATH"); - AZStd::string dyldSearchPath = AZStd::string::format("DYLD_LIBRARY_PATH=%s", dyldLibPathOrig); - if (AZ::IO::FixedMaxPath projectModulePath; - settingsRegistry->Get(projectModulePath.Native(), AZ::SettingsRegistryMergeUtils::FilePathKey_ProjectConfigurationBinPath)) - { - dyldSearchPath.append(":"); - dyldSearchPath.append(projectModulePath.c_str()); - } - - if (AZ::IO::FixedMaxPath installedBinariesFolder; - settingsRegistry->Get(installedBinariesFolder.Native(), AZ::SettingsRegistryMergeUtils::FilePathKey_InstalledBinaryFolder)) - { - if (AZ::IO::FixedMaxPath engineRootFolder; - settingsRegistry->Get(engineRootFolder.Native(), AZ::SettingsRegistryMergeUtils::FilePathKey_EngineRootFolder)) - { - installedBinariesFolder = engineRootFolder / installedBinariesFolder; - dyldSearchPath.append(":"); - dyldSearchPath.append(installedBinariesFolder.c_str()); - } - } - envVars.push_back(dyldSearchPath); - } - - AZStd::string commandArgs; - for (int i = 1; i < argc; i++) - { - commandArgs.append(argv[i]); - commandArgs.append(" "); - } - - AzFramework::ProcessLauncher::ProcessLaunchInfo processLaunchInfo; - AZ::IO::Path processPath{ AZ::IO::PathView(AZ::Utils::GetExecutableDirectory()) }; - processPath /= "Editor"; - processLaunchInfo.m_processExecutableString = AZStd::move(processPath.Native()); - processLaunchInfo.m_commandlineParameters = commandArgs; - processLaunchInfo.m_environmentVariables = &envVars; - processLaunchInfo.m_showWindow = true; - - AzFramework::ProcessLauncher::LaunchUnwatchedProcess(processLaunchInfo); - - application.Destroy(); - - return 0; -} - diff --git a/Code/Editor/Plugins/EditorCommon/CMakeLists.txt b/Code/Editor/Plugins/EditorCommon/CMakeLists.txt index 2aff57cfb1..cd9f2e79c7 100644 --- a/Code/Editor/Plugins/EditorCommon/CMakeLists.txt +++ b/Code/Editor/Plugins/EditorCommon/CMakeLists.txt @@ -51,4 +51,5 @@ ly_add_target( AZ::AzCore AZ::AzToolsFramework AZ::AzQtComponents + Legacy::EditorCore ) diff --git a/Code/Editor/Plugins/PerforcePlugin/PerforceSourceControl.cpp b/Code/Editor/Plugins/PerforcePlugin/PerforceSourceControl.cpp index 10c43c3d1b..dd9ccaa832 100644 --- a/Code/Editor/Plugins/PerforcePlugin/PerforceSourceControl.cpp +++ b/Code/Editor/Plugins/PerforcePlugin/PerforceSourceControl.cpp @@ -6,6 +6,7 @@ * */ +#include #include "CryFile.h" #include "PerforceSourceControl.h" #include "PasswordDlg.h" diff --git a/Code/Editor/PythonEditorEventsBus.h b/Code/Editor/PythonEditorEventsBus.h index 5107a1c9cc..ffc357e64d 100644 --- a/Code/Editor/PythonEditorEventsBus.h +++ b/Code/Editor/PythonEditorEventsBus.h @@ -8,6 +8,7 @@ */ #pragma once +#include #include namespace AzToolsFramework @@ -138,7 +139,7 @@ namespace AzToolsFramework /* * Finds a pak file name for a given file. */ - virtual const char* GetPakFromFile(const char* filename) = 0; + virtual AZ::IO::Path GetPakFromFile(const char* filename) = 0; /* * Prints the message to the editor console window. diff --git a/Code/Editor/PythonEditorFuncs.cpp b/Code/Editor/PythonEditorFuncs.cpp index 200fd28f87..455cdfa17d 100644 --- a/Code/Editor/PythonEditorFuncs.cpp +++ b/Code/Editor/PythonEditorFuncs.cpp @@ -625,7 +625,7 @@ namespace } ////////////////////////////////////////////////////////////////////////// - const char* PyGetPakFromFile(const char* filename) + AZ::IO::Path PyGetPakFromFile(const char* filename) { auto pIPak = GetIEditor()->GetSystem()->GetIPak(); AZ::IO::HandleType fileHandle = pIPak->FOpen(filename, "rb"); @@ -633,8 +633,9 @@ namespace { throw std::logic_error("Invalid file name."); } - const char* pArchPath = pIPak->GetFileArchivePath(fileHandle); + AZ::IO::Path pArchPath = pIPak->GetFileArchivePath(fileHandle); pIPak->FClose(fileHandle); + return pArchPath; } @@ -1040,7 +1041,7 @@ namespace AzToolsFramework return PySetAxisConstraint(pConstrain); } - const char* PythonEditorComponent::GetPakFromFile(const char* filename) + AZ::IO::Path PythonEditorComponent::GetPakFromFile(const char* filename) { return PyGetPakFromFile(filename); } @@ -1114,7 +1115,7 @@ namespace AzToolsFramework addLegacyGeneral(behaviorContext->Method("get_axis_constraint", PyGetAxisConstraint, nullptr, "Gets axis.")); addLegacyGeneral(behaviorContext->Method("set_axis_constraint", PySetAxisConstraint, nullptr, "Sets axis.")); - addLegacyGeneral(behaviorContext->Method("get_pak_from_file", PyGetPakFromFile, nullptr, "Finds a pak file name for a given file.")); + addLegacyGeneral(behaviorContext->Method("get_pak_from_file", [](const char* filename) -> AZStd::string { return PyGetPakFromFile(filename).Native(); }, nullptr, "Finds a pak file name for a given file.")); addLegacyGeneral(behaviorContext->Method("log", PyLog, nullptr, "Prints the message to the editor console window.")); diff --git a/Code/Editor/PythonEditorFuncs.h b/Code/Editor/PythonEditorFuncs.h index 97ad8829ba..ef0c1327fa 100644 --- a/Code/Editor/PythonEditorFuncs.h +++ b/Code/Editor/PythonEditorFuncs.h @@ -91,7 +91,7 @@ namespace AzToolsFramework void SetAxisConstraint(AZStd::string_view pConstrain) override; - const char* GetPakFromFile(const char* filename) override; + AZ::IO::Path GetPakFromFile(const char* filename) override; void Log(const char* pMessage) override; diff --git a/Code/Editor/Settings.cpp b/Code/Editor/Settings.cpp index 80d248e1bf..05a6960695 100644 --- a/Code/Editor/Settings.cpp +++ b/Code/Editor/Settings.cpp @@ -171,7 +171,6 @@ SEditorSettings::SEditorSettings() bBackupOnSave = true; backupOnSaveMaxCount = 3; bApplyConfigSpecInEditor = true; - useLowercasePaths = 0; showErrorDialogOnLoad = 1; consoleBackgroundColorTheme = AzToolsFramework::ConsoleColorTheme::Dark; @@ -887,6 +886,7 @@ void SEditorSettings::Load() ////////////////////////////////////////////////////////////////////////// AZ_CVAR(bool, ed_previewGameInFullscreen_once, false, nullptr, AZ::ConsoleFunctorFlags::IsInvisible, "Preview the game (Ctrl+G, \"Play Game\", etc.) in fullscreen once"); +AZ_CVAR(bool, ed_lowercasepaths, false, nullptr, AZ::ConsoleFunctorFlags::Null, "Convert CCryFile paths to lowercase on Open"); void SEditorSettings::PostInitApply() { @@ -898,7 +898,6 @@ void SEditorSettings::PostInitApply() // Create CVars. REGISTER_CVAR2("ed_highlightGeometry", &viewports.bHighlightMouseOverGeometry, viewports.bHighlightMouseOverGeometry, 0, "Highlight geometry when mouse over it"); REGISTER_CVAR2("ed_showFrozenHelpers", &viewports.nShowFrozenHelpers, viewports.nShowFrozenHelpers, 0, "Show helpers of frozen objects"); - REGISTER_CVAR2("ed_lowercasepaths", &useLowercasePaths, useLowercasePaths, 0, "generate paths in lowercase"); gEnv->pConsole->RegisterInt("fe_fbx_savetempfile", 0, 0, "When importing an FBX file into Facial Editor, this will save out a conversion FSQ to the Animations/temp folder for trouble shooting"); REGISTER_CVAR2_CB("ed_toolbarIconSize", &gui.nToolbarIconSize, gui.nToolbarIconSize, VF_NULL, "Override size of the toolbar icons 0-default, 16,32,...", ToolbarIconSizeChanged); diff --git a/Code/Editor/Settings.h b/Code/Editor/Settings.h index a408822129..8bf22b43e5 100644 --- a/Code/Editor/Settings.h +++ b/Code/Editor/Settings.h @@ -340,8 +340,6 @@ AZ_POP_DISABLE_DLL_EXPORT_BASECLASS_WARNING //! how many save backups to keep int backupOnSaveMaxCount; - int useLowercasePaths; - ////////////////////////////////////////////////////////////////////////// // Autobackup. ////////////////////////////////////////////////////////////////////////// diff --git a/Code/Editor/Util/FileUtil.cpp b/Code/Editor/Util/FileUtil.cpp index 610a9c6e16..eeb6912acf 100644 --- a/Code/Editor/Util/FileUtil.cpp +++ b/Code/Editor/Util/FileUtil.cpp @@ -149,12 +149,13 @@ bool CFileUtil::ExtractFile(QString& file, bool bMsgBoxAskForExtraction, const c // Check if in pack. if (cryfile.IsInPak()) { - const char* sPakName = cryfile.GetPakPath(); - if (bMsgBoxAskForExtraction) { + AZ::IO::FixedMaxPath sPakName{ cryfile.GetPakPath() }; // Cannot edit file in pack, suggest to extract it for editing. - if (QMessageBox::critical(QApplication::activeWindow(), QString(), QObject::tr("File %1 is inside a PAK file %2\r\nDo you want it to be extracted for editing ?").arg(file, sPakName), QMessageBox::Yes | QMessageBox::No) == QMessageBox::No) + if (QMessageBox::critical(QApplication::activeWindow(), QString(), + QObject::tr("File %1 is inside a PAK file %2\r\nDo you want it to be extracted for editing ?").arg(file, sPakName.c_str()), + QMessageBox::Yes | QMessageBox::No) == QMessageBox::No) { return false; } @@ -173,10 +174,9 @@ bool CFileUtil::ExtractFile(QString& file, bool bMsgBoxAskForExtraction, const c if (diskFile.open(QFile::WriteOnly)) { // Copy data from packed file to disk file. - char* data = new char[cryfile.GetLength()]; - cryfile.ReadRaw(data, cryfile.GetLength()); - diskFile.write(data, cryfile.GetLength()); - delete []data; + auto data = AZStd::make_unique(cryfile.GetLength()); + cryfile.ReadRaw(data.get(), cryfile.GetLength()); + diskFile.write(data.get(), cryfile.GetLength()); } else { @@ -185,7 +185,14 @@ bool CFileUtil::ExtractFile(QString& file, bool bMsgBoxAskForExtraction, const c } else { - file = cryfile.GetAdjustedFilename(); + + if (auto fileIoBase = AZ::IO::FileIOBase::GetInstance(); fileIoBase != nullptr) + { + if (AZ::IO::FixedMaxPath resolvedFilePath; fileIoBase->ResolvePath(resolvedFilePath, cryfile.GetFilename())) + { + file = QString::fromUtf8(resolvedFilePath.c_str(), static_cast(resolvedFilePath.Native().size())); + } + } } return true; @@ -2157,13 +2164,13 @@ uint32 CFileUtil::GetAttributes(const char* filename, bool bUseSourceControl /*= return SCC_FILE_ATTRIBUTE_READONLY | SCC_FILE_ATTRIBUTE_INPAK; } - const char* adjustedFile = file.GetAdjustedFilename(); - if (!AZ::IO::SystemFile::Exists(adjustedFile)) + auto fileIoBase = AZ::IO::FileIOBase::GetInstance(); + if (!fileIoBase->Exists(file.GetFilename())) { return SCC_FILE_ATTRIBUTE_INVALID; } - if (!AZ::IO::SystemFile::IsWritable(adjustedFile)) + if (fileIoBase->IsReadOnly(file.GetFilename())) { return SCC_FILE_ATTRIBUTE_NORMAL | SCC_FILE_ATTRIBUTE_READONLY; } diff --git a/Code/Editor/Util/PakFile.cpp b/Code/Editor/Util/PakFile.cpp index fc8431ef24..b629b45f74 100644 --- a/Code/Editor/Util/PakFile.cpp +++ b/Code/Editor/Util/PakFile.cpp @@ -68,7 +68,7 @@ bool CPakFile::Open(const char* filename, bool bAbsolutePath) if (bAbsolutePath) { - m_pArchive = pCryPak->OpenArchive(filename, nullptr, AZ::IO::INestedArchive::FLAGS_ABSOLUTE_PATHS); + m_pArchive = pCryPak->OpenArchive(filename, {}, AZ::IO::INestedArchive::FLAGS_ABSOLUTE_PATHS); } else { @@ -93,7 +93,7 @@ bool CPakFile::OpenForRead(const char* filename) { return false; } - m_pArchive = pCryPak->OpenArchive(filename, nullptr, AZ::IO::INestedArchive::FLAGS_OPTIMIZED_READ_ONLY | AZ::IO::INestedArchive::FLAGS_ABSOLUTE_PATHS); + m_pArchive = pCryPak->OpenArchive(filename, {}, AZ::IO::INestedArchive::FLAGS_OPTIMIZED_READ_ONLY | AZ::IO::INestedArchive::FLAGS_ABSOLUTE_PATHS); if (m_pArchive) { return true; diff --git a/Code/Editor/Util/XmlArchive.cpp b/Code/Editor/Util/XmlArchive.cpp index e6bc93fdf4..18c3fc8e63 100644 --- a/Code/Editor/Util/XmlArchive.cpp +++ b/Code/Editor/Util/XmlArchive.cpp @@ -124,7 +124,7 @@ bool CXmlArchive::SaveToPak([[maybe_unused]] const QString& levelPath, CPakFile& if (pakFile.GetArchive()) { - CLogFile::FormatLine("Saving pak file %s", (const char*)pakFile.GetArchive()->GetFullPath()); + CLogFile::FormatLine("Saving pak file %.*s", AZ_STRING_ARG(pakFile.GetArchive()->GetFullPath().Native())); } pNamedData->Save(pakFile); diff --git a/Code/Editor/ViewportTitleDlg.cpp b/Code/Editor/ViewportTitleDlg.cpp index 1f04f71712..65d6de8944 100644 --- a/Code/Editor/ViewportTitleDlg.cpp +++ b/Code/Editor/ViewportTitleDlg.cpp @@ -154,6 +154,8 @@ void CViewportTitleDlg::SetupCameraDropdownMenu() cameraMenu->addMenu(GetFovMenu()); m_ui->m_cameraMenu->setMenu(cameraMenu); m_ui->m_cameraMenu->setPopupMode(QToolButton::InstantPopup); + QObject::connect(cameraMenu, &QMenu::aboutToShow, this, &CViewportTitleDlg::CheckForCameraSpeedUpdate); + QAction* gotoPositionAction = new QAction("Go to position", cameraMenu); connect(gotoPositionAction, &QAction::triggered, this, &CViewportTitleDlg::OnBnClickedGotoPosition); cameraMenu->addAction(gotoPositionAction); diff --git a/Code/Framework/AzCore/AzCore/Debug/Profiler.h b/Code/Framework/AzCore/AzCore/Debug/Profiler.h index 8af48e47f6..56103e8314 100644 --- a/Code/Framework/AzCore/AzCore/Debug/Profiler.h +++ b/Code/Framework/AzCore/AzCore/Debug/Profiler.h @@ -59,6 +59,20 @@ namespace AZStd namespace AZ::Debug { + // interface for externally defined profiler systems + class Profiler + { + public: + AZ_RTTI(Profiler, "{3E5D6329-72D1-41BA-9158-68A349D1A4D5}"); + + Profiler() = default; + virtual ~Profiler() = default; + + // support for the extra macro args (e.g. format strings) will come in a later PR + virtual void BeginRegion(const Budget* budget, const char* eventName) = 0; + virtual void EndRegion(const Budget* budget) = 0; + }; + class ProfileScope { public: diff --git a/Code/Framework/AzCore/AzCore/Debug/Profiler.inl b/Code/Framework/AzCore/AzCore/Debug/Profiler.inl index 8ca8368ce1..74c0f553c4 100644 --- a/Code/Framework/AzCore/AzCore/Debug/Profiler.inl +++ b/Code/Framework/AzCore/AzCore/Debug/Profiler.inl @@ -6,6 +6,8 @@ * */ +#include + namespace AZ::Debug { template @@ -22,9 +24,11 @@ namespace AZ::Debug PIXBeginEvent(PIX_COLOR_INDEX(budget->Crc() & 0xff), eventName, args...); #endif budget->BeginProfileRegion(); -// TODO: injecting instrumentation for other profilers -// NOTE: external profiler registration won't occur inline in a header necessarily in this manner, but the exact mechanism -// will be introduced in a future PR + + if (auto profiler = AZ::Interface::Get(); profiler) + { + profiler->BeginRegion(budget, eventName); + } #endif } @@ -39,6 +43,10 @@ namespace AZ::Debug #if defined(USE_PIX) PIXEndEvent(); #endif + if (auto profiler = AZ::Interface::Get(); profiler) + { + profiler->EndRegion(budget); + } #endif } diff --git a/Code/Framework/AzCore/AzCore/EBus/EBus.h b/Code/Framework/AzCore/AzCore/EBus/EBus.h index 1bff4ff297..58754ff9b8 100644 --- a/Code/Framework/AzCore/AzCore/EBus/EBus.h +++ b/Code/Framework/AzCore/AzCore/EBus/EBus.h @@ -1717,6 +1717,7 @@ AZ_POP_DISABLE_WARNING { EBusRouterNode m_routerNode; public: + virtual ~EBusNestedVersionRouter() = default; template void BusRouterConnect(Container& container, int order = 0); diff --git a/Code/Framework/AzCore/AzCore/Settings/SettingsRegistry.h b/Code/Framework/AzCore/AzCore/Settings/SettingsRegistry.h index 106e232904..3dc1be87c5 100644 --- a/Code/Framework/AzCore/AzCore/Settings/SettingsRegistry.h +++ b/Code/Framework/AzCore/AzCore/Settings/SettingsRegistry.h @@ -370,6 +370,11 @@ namespace AZ //! @param applyPatchSettings The ApplyPatchSettings which are using during JSON Merging virtual void SetApplyPatchSettings(const AZ::JsonApplyPatchSettings& applyPatchSettings) = 0; virtual void GetApplyPatchSettings(AZ::JsonApplyPatchSettings& applyPatchSettings) = 0; + + //! Stores option to indicate whether the FileIOBase instance should be used for file operations + //! @param useFileIo If true the FileIOBase instance will attempted to be used for FileIOBase + //! operations before falling back to use SystemFile + virtual void SetUseFileIO(bool useFileIo) = 0; }; inline SettingsRegistryInterface::Visitor::~Visitor() = default; diff --git a/Code/Framework/AzCore/AzCore/Settings/SettingsRegistryImpl.cpp b/Code/Framework/AzCore/AzCore/Settings/SettingsRegistryImpl.cpp index 6864dcd1c8..7ef1fa661d 100644 --- a/Code/Framework/AzCore/AzCore/Settings/SettingsRegistryImpl.cpp +++ b/Code/Framework/AzCore/AzCore/Settings/SettingsRegistryImpl.cpp @@ -9,11 +9,14 @@ #include #include #include +#include +#include #include #include #include #include #include +#include #include #include @@ -131,6 +134,12 @@ namespace AZ pointer.Create(m_settings, m_settings.GetAllocator()).SetArray(); } + SettingsRegistryImpl::SettingsRegistryImpl(bool useFileIo) + : SettingsRegistryImpl() + { + m_useFileIo = useFileIo; + } + void SettingsRegistryImpl::SetContext(SerializeContext* context) { AZStd::scoped_lock lock(m_settingMutex); @@ -723,15 +732,10 @@ namespace AZ RegistryFileList fileList; scratchBuffer->clear(); - AZ::IO::FixedMaxPathString folderPath{ path }; - constexpr AZStd::string_view pathSeparators{ AZ_CORRECT_AND_WRONG_DATABASE_SEPARATOR }; - if (pathSeparators.find_first_of(folderPath.back()) == AZStd::string_view::npos) - { - folderPath.push_back(AZ_CORRECT_DATABASE_SEPARATOR); - } + AZ::IO::FixedMaxPath folderPath{ path }; - const size_t platformKeyOffset = folderPath.size(); - folderPath.push_back('*'); + const size_t platformKeyOffset = folderPath.Native().size(); + folderPath /= '*'; Value specialzationArray(kArrayType); size_t specializationCount = specializations.GetCount(); @@ -741,47 +745,13 @@ namespace AZ specialzationArray.PushBack(Value(name.data(), aznumeric_caster(name.length()), m_settings.GetAllocator()), m_settings.GetAllocator()); } pointer.Create(m_settings, m_settings.GetAllocator()).SetObject() - .AddMember(StringRef("Folder"), Value(folderPath.c_str(), aznumeric_caster(folderPath.size()), m_settings.GetAllocator()), m_settings.GetAllocator()) + .AddMember(StringRef("Folder"), Value(folderPath.c_str(), aznumeric_caster(folderPath.Native().size()), m_settings.GetAllocator()), m_settings.GetAllocator()) .AddMember(StringRef("Specializations"), AZStd::move(specialzationArray), m_settings.GetAllocator()); - auto callback = [this, &fileList, &specializations, &pointer, &folderPath](const char* filename, bool isFile) -> bool + + auto CreateSettingsFindCallback = [this, &fileList, &specializations, &pointer, &folderPath](bool isPlatformFile) { - if (isFile) - { - if (fileList.size() >= MaxRegistryFolderEntries) - { - AZ_Error("Settings Registry", false, "Too many files in registry folder."); - AZStd::scoped_lock lock(m_settingMutex); - pointer.Create(m_settings, m_settings.GetAllocator()).SetObject() - .AddMember(StringRef("Error"), StringRef("Too many files in registry folder."), m_settings.GetAllocator()) - .AddMember(StringRef("Path"), Value(folderPath.c_str(), aznumeric_caster(folderPath.size()), m_settings.GetAllocator()), m_settings.GetAllocator()) - .AddMember(StringRef("File"), Value(filename, m_settings.GetAllocator()), m_settings.GetAllocator()); - return false; - } - - fileList.push_back(); - RegistryFile& registryFile = fileList.back(); - if (!ExtractFileDescription(registryFile, filename, specializations)) - { - fileList.pop_back(); - } - } - return true; - }; - SystemFile::FindFiles(folderPath.c_str(), callback); - - - if (!platform.empty()) - { - // Move the folderPath prefix back to the supplied path before the wildcard - folderPath.erase(platformKeyOffset); - folderPath += PlatformFolder; - folderPath.push_back(AZ_CORRECT_DATABASE_SEPARATOR); - folderPath += platform; - folderPath.push_back(AZ_CORRECT_DATABASE_SEPARATOR); - folderPath.push_back('*'); - - auto platformCallback = [this, &fileList, &specializations, &pointer, &folderPath](const char* filename, bool isFile) -> bool + return [this, &fileList, &specializations, &pointer, &folderPath, isPlatformFile](AZStd::string_view filename, bool isFile) -> bool { if (isFile) { @@ -791,8 +761,8 @@ namespace AZ AZStd::scoped_lock lock(m_settingMutex); pointer.Create(m_settings, m_settings.GetAllocator()).SetObject() .AddMember(StringRef("Error"), StringRef("Too many files in registry folder."), m_settings.GetAllocator()) - .AddMember(StringRef("Path"), Value(folderPath.c_str(), aznumeric_caster(folderPath.size()), m_settings.GetAllocator()), m_settings.GetAllocator()) - .AddMember(StringRef("File"), Value(filename, m_settings.GetAllocator()), m_settings.GetAllocator()); + .AddMember(StringRef("Path"), Value(folderPath.c_str(), aznumeric_caster(folderPath.Native().size()), m_settings.GetAllocator()), m_settings.GetAllocator()) + .AddMember(StringRef("File"), Value(filename.data(), aznumeric_caster(filename.size()), m_settings.GetAllocator()), m_settings.GetAllocator()); return false; } @@ -800,7 +770,7 @@ namespace AZ RegistryFile& registryFile = fileList.back(); if (ExtractFileDescription(registryFile, filename, specializations)) { - registryFile.m_isPlatformFile = true; + registryFile.m_isPlatformFile = isPlatformFile; } else { @@ -809,7 +779,42 @@ namespace AZ } return true; }; - SystemFile::FindFiles(folderPath.c_str(), platformCallback); + }; + + struct FindFilesPayload + { + bool m_isPlatformFile{}; + AZStd::fixed_vector m_pathSegmentsToAppend; + }; + + AZStd::fixed_vector findFilesPayloads{ {false} }; + if (!platform.empty()) + { + findFilesPayloads.push_back(FindFilesPayload{ true, { PlatformFolder, platform } }); + } + + for (const FindFilesPayload& findFilesPayload : findFilesPayloads) + { + // Erase back to initial path + folderPath.Native().erase(platformKeyOffset); + for (AZStd::string_view pathSegmentToAppend : findFilesPayload.m_pathSegmentsToAppend) + { + folderPath /= pathSegmentToAppend; + } + + auto findFilesCallback = CreateSettingsFindCallback(findFilesPayload.m_isPlatformFile); + if (AZ::IO::FileIOBase* fileIo = m_useFileIo ? AZ::IO::FileIOBase::GetInstance() : nullptr; fileIo != nullptr) + { + auto FileIoToSystemFileFindFiles = [findFilesCallback = AZStd::move(findFilesCallback), fileIo](const char* filePath) -> bool + { + return findFilesCallback(AZ::IO::PathView(filePath).Filename().Native(), !fileIo->IsDirectory(filePath)); + }; + fileIo->FindFiles(folderPath.c_str(), "*", FileIoToSystemFileFindFiles); + } + else + { + SystemFile::FindFiles((folderPath / "*").c_str(), findFilesCallback); + } } if (!fileList.empty()) @@ -831,16 +836,14 @@ namespace AZ // Load the registry files in the sorted order. for (RegistryFile& registryFile : fileList) { - folderPath.erase(platformKeyOffset); // Erase all characters after the platformKeyOffset + folderPath.Native().erase(platformKeyOffset); // Erase all characters after the platformKeyOffset if (registryFile.m_isPlatformFile) { - folderPath += PlatformFolder; - folderPath.push_back(AZ_CORRECT_DATABASE_SEPARATOR); - folderPath += platform; - folderPath.push_back(AZ_CORRECT_DATABASE_SEPARATOR); + folderPath /= PlatformFolder; + folderPath /= platform; } - folderPath += registryFile.m_relativePath; + folderPath /= registryFile.m_relativePath; if (!registryFile.m_isPatch) { @@ -1027,39 +1030,44 @@ namespace AZ return false; } - bool SettingsRegistryImpl::ExtractFileDescription(RegistryFile& output, const char* filename, const Specializations& specializations) + bool SettingsRegistryImpl::ExtractFileDescription(RegistryFile& output, AZStd::string_view filename, const Specializations& specializations) { - if (!filename || filename[0] == 0) + static constexpr auto PatchExtensionWithDot = AZStd::fixed_string<32>(".") + PatchExtension; + static constexpr auto ExtensionWithDot = AZStd::fixed_string<32>(".") + Extension; + static constexpr AZ::IO::PathView PatchExtensionView(PatchExtensionWithDot); + static constexpr AZ::IO::PathView ExtensionView(ExtensionWithDot); + + if (filename.empty()) { AZ_Error("Settings Registry", false, "Settings file without name found"); return false; } - AZStd::string_view filePath{ filename }; - const size_t filePathSize = filePath.size(); + AZ::IO::PathView filePath{ filename }; + const size_t filePathSize = filePath.Native().size(); // The filePath.empty() check makes sure that the file extension after the final isn't added to the output.m_tags - AZStd::optional pathTag = AZ::StringFunc::TokenizeNext(filePath, '.'); - for (; pathTag && !filePath.empty(); pathTag = AZ::StringFunc::TokenizeNext(filePath, '.')) + auto AppendSpecTags = [&output](AZStd::string_view pathTag) { - output.m_tags.push_back(Specializations::Hash(*pathTag)); - } + output.m_tags.push_back(Specializations::Hash(pathTag)); + }; + AZ::StringFunc::TokenizeVisitor(filePath.Stem().Native(), AppendSpecTags, '.'); // If token is invalid, then the filename has no characters and therefore no extension - if (pathTag) + if (AZ::IO::PathView fileExtension = filePath.Extension(); !fileExtension.empty()) { - if (pathTag->size() >= AZStd::char_traits::length(PatchExtension) && azstrnicmp(pathTag->data(), PatchExtension, pathTag->size()) == 0) + if (fileExtension == PatchExtensionView) { output.m_isPatch = true; } - else if (pathTag->size() != AZStd::char_traits::length(Extension) || azstrnicmp(pathTag->data(), Extension, pathTag->size()) != 0) + else if (fileExtension != ExtensionView) { return false; } } else { - AZ_Error("Settings Registry", false, R"(Settings file without extension found: "%s")", filename); + AZ_Error("Settings Registry", false, R"(Settings file without extension found: "%.*s")", AZ_STRING_ARG(filename)); return false; } @@ -1074,7 +1082,7 @@ namespace AZ { if (*currentIt == *(currentIt - 1)) { - AZ_Error("Settings Registry", false, R"(One or more tags are duplicated in registry file "%s")", filename); + AZ_Error("Settings Registry", false, R"(One or more tags are duplicated in registry file "%.*s")", AZ_STRING_ARG(filename)); return false; } ++currentIt; @@ -1103,11 +1111,123 @@ namespace AZ } else { - AZ_Error("Settings Registry", false, R"(Found relative path to settings file "%s" is too long.)", filename); + AZ_Error("Settings Registry", false, R"(Found relative path to settings file "%.*s" is too long.)", AZ_STRING_ARG(filename)); return false; } } + //! Structure which encapsulates Commands to either the FileIOBase or SystemFile classes based on + //! the SettingsRegistry option to use FileIO + struct SettingsRegistryFileReader + { + using FileHandleType = AZStd::variant; + + SettingsRegistryFileReader() = default; + SettingsRegistryFileReader(bool useFileIo, const char* filePath) + { + Open(useFileIo, filePath); + } + + ~SettingsRegistryFileReader() + { + if (auto fileHandle = AZStd::get_if(&m_file); fileHandle != nullptr) + { + if (AZ::IO::FileIOBase* fileIo = AZ::IO::FileIOBase::GetInstance(); fileIo != nullptr) + { + fileIo->Close(*fileHandle); + } + } + } + + bool Open(bool useFileIo, const char* filePath) + { + Close(); + if (AZ::IO::FileIOBase* fileIo = useFileIo ? AZ::IO::FileIOBase::GetInstance() : nullptr; fileIo != nullptr) + { + AZ::IO::HandleType fileHandle; + if (fileIo->Open(filePath, IO::OpenMode::ModeRead, fileHandle)) + { + m_file = fileHandle; + return true; + } + } + else + { + AZ::IO::SystemFile file; + if (file.Open(filePath, IO::SystemFile::OpenMode::SF_OPEN_READ_ONLY)) + { + m_file = AZStd::move(file); + return true; + } + } + + return false; + } + + bool IsOpen() const + { + if (auto fileHandle = AZStd::get_if(&m_file); fileHandle != nullptr) + { + return *fileHandle != AZ::IO::InvalidHandle; + } + else if (auto systemFile = AZStd::get_if(&m_file); systemFile != nullptr) + { + return systemFile->IsOpen(); + } + + return false; + } + + void Close() + { + if (auto fileHandle = AZStd::get_if(&m_file); fileHandle != nullptr) + { + if (AZ::IO::FileIOBase* fileIo = AZ::IO::FileIOBase::GetInstance(); fileIo != nullptr) + { + fileIo->Close(*fileHandle); + } + } + + m_file = AZStd::monostate{}; + } + + u64 Length() const + { + if (auto fileHandle = AZStd::get_if(&m_file); fileHandle != nullptr) + { + if (u64 fileSize{}; AZ::IO::FileIOBase::GetInstance()->Size(*fileHandle, fileSize)) + { + return fileSize; + } + } + else if (auto systemFile = AZStd::get_if(&m_file); systemFile != nullptr) + { + return systemFile->Length(); + } + + return 0; + } + + AZ::IO::SizeType Read(AZ::IO::SizeType byteSize, void* buffer) + { + if (auto fileHandle = AZStd::get_if(&m_file); fileHandle != nullptr) + { + if (AZ::u64 bytesRead{}; AZ::IO::FileIOBase::GetInstance()->Read(*fileHandle, buffer, byteSize, false, &bytesRead)) + { + return bytesRead; + } + } + else if (auto systemFile = AZStd::get_if(&m_file); systemFile != nullptr) + { + return systemFile->Read(byteSize, buffer); + } + + return 0; + } + + FileHandleType m_file; + }; + bool SettingsRegistryImpl::MergeSettingsFileInternal(const char* path, Format format, AZStd::string_view rootKey, AZStd::vector& scratchBuffer) { @@ -1116,8 +1236,8 @@ namespace AZ Pointer pointer(AZ_SETTINGS_REGISTRY_HISTORY_KEY "/-"); - SystemFile file; - if (!file.Open(path, SystemFile::OpenMode::SF_OPEN_READ_ONLY)) + SettingsRegistryFileReader fileReader(m_useFileIo, path); + if (!fileReader.IsOpen()) { AZ_Error("Settings Registry", false, R"(Unable to open registry file "%s".)", path); pointer.Create(m_settings, m_settings.GetAllocator()).SetObject() @@ -1126,7 +1246,7 @@ namespace AZ return false; } - u64 fileSize = file.Length(); + u64 fileSize = fileReader.Length(); if (fileSize == 0) { AZ_Warning("Settings Registry", false, R"(Registry file "%s" is 0 bytes in length. There is no nothing to merge)", path); @@ -1136,9 +1256,10 @@ namespace AZ .AddMember(StringRef("Path"), Value(path, m_settings.GetAllocator()), m_settings.GetAllocator()); return false; } + scratchBuffer.clear(); scratchBuffer.resize_no_construct(fileSize + 1); - if (file.Read(fileSize, scratchBuffer.data()) != fileSize) + if (fileReader.Read(fileSize, scratchBuffer.data()) != fileSize) { AZ_Error("Settings Registry", false, R"(Unable to read registry file "%s".)", path); pointer.Create(m_settings, m_settings.GetAllocator()).SetObject() @@ -1268,4 +1389,9 @@ namespace AZ { applyPatchSettings = m_applyPatchSettings; } + + void SettingsRegistryImpl::SetUseFileIO(bool useFileIo) + { + m_useFileIo = useFileIo; + } } // namespace AZ diff --git a/Code/Framework/AzCore/AzCore/Settings/SettingsRegistryImpl.h b/Code/Framework/AzCore/AzCore/Settings/SettingsRegistryImpl.h index 036f5c6596..ac214711b8 100644 --- a/Code/Framework/AzCore/AzCore/Settings/SettingsRegistryImpl.h +++ b/Code/Framework/AzCore/AzCore/Settings/SettingsRegistryImpl.h @@ -35,6 +35,10 @@ namespace AZ static constexpr size_t MaxRegistryFolderEntries = 128; SettingsRegistryImpl(); + //! @param useFileIo - If true attempt to redirect + //! file read operations through the FileIOBase instance first before falling back to SystemFile + //! otherwise always use SystemFile + explicit SettingsRegistryImpl(bool useFileIo); AZ_DISABLE_COPY_MOVE(SettingsRegistryImpl); ~SettingsRegistryImpl() override = default; @@ -83,6 +87,8 @@ namespace AZ void SetApplyPatchSettings(const AZ::JsonApplyPatchSettings& applyPatchSettings) override; void GetApplyPatchSettings(AZ::JsonApplyPatchSettings& applyPatchSettings) override; + void SetUseFileIO(bool useFileIo) override; + private: using TagList = AZStd::fixed_vector; struct RegistryFile @@ -104,7 +110,7 @@ namespace AZ // Compares if lhs is less than rhs in terms of processing order. This can also detect and report conflicts. bool IsLessThan(bool& collisionFound, const RegistryFile& lhs, const RegistryFile& rhs, const Specializations& specializations, const rapidjson::Pointer& historyPointer, AZStd::string_view folderPath); - bool ExtractFileDescription(RegistryFile& output, const char* filename, const Specializations& specializations); + bool ExtractFileDescription(RegistryFile& output, AZStd::string_view filename, const Specializations& specializations); bool MergeSettingsFileInternal(const char* path, Format format, AZStd::string_view rootKey, AZStd::vector& scratchBuffer); void SignalNotifier(AZStd::string_view jsonPath, Type type); @@ -119,5 +125,7 @@ namespace AZ JsonSerializerSettings m_serializationSettings; JsonDeserializerSettings m_deserializationSettings; JsonApplyPatchSettings m_applyPatchSettings; + + bool m_useFileIo{}; }; } // namespace AZ diff --git a/Code/Framework/AzCore/AzCore/UnitTest/Mocks/MockSettingsRegistry.h b/Code/Framework/AzCore/AzCore/UnitTest/Mocks/MockSettingsRegistry.h index 7e6bb3d7b4..91dc0924c8 100644 --- a/Code/Framework/AzCore/AzCore/UnitTest/Mocks/MockSettingsRegistry.h +++ b/Code/Framework/AzCore/AzCore/UnitTest/Mocks/MockSettingsRegistry.h @@ -57,6 +57,7 @@ namespace AZ MOCK_METHOD1(SetApplyPatchSettings, void(const JsonApplyPatchSettings&)); MOCK_METHOD1(GetApplyPatchSettings, void(JsonApplyPatchSettings&)); + MOCK_METHOD1(SetUseFileIO, void(bool)); }; } // namespace AZ diff --git a/Code/Framework/AzCore/AzCore/XML/rapidxml.h b/Code/Framework/AzCore/AzCore/XML/rapidxml.h index 694e0a1bf6..9e6d648293 100644 --- a/Code/Framework/AzCore/AzCore/XML/rapidxml.h +++ b/Code/Framework/AzCore/AzCore/XML/rapidxml.h @@ -13,6 +13,7 @@ // the intention is that you only include the customized version of rapidXML through this header, so that // you can override behavior here. +#include #include #endif // AZCORE_RAPIDXML_RAPIDXML_H_INCLUDED diff --git a/Code/Framework/AzCore/AzCore/std/string/fixed_string.h b/Code/Framework/AzCore/AzCore/std/string/fixed_string.h index 079fe40cda..b68f21784b 100644 --- a/Code/Framework/AzCore/AzCore/std/string/fixed_string.h +++ b/Code/Framework/AzCore/AzCore/std/string/fixed_string.h @@ -96,6 +96,10 @@ namespace AZStd && !is_convertible_v>> constexpr basic_fixed_string(const T& convertibleToView, size_type rhsOffset, size_type count); + + // #12 + constexpr basic_fixed_string(AZStd::nullptr_t) = delete; + constexpr operator AZStd::basic_string_view() const; constexpr auto begin() -> iterator; @@ -120,6 +124,7 @@ namespace AZStd constexpr auto operator=(const T& convertible_to_view) -> AZStd::enable_if_t> && !is_convertible_v, basic_fixed_string&>; + constexpr auto operator=(AZStd::nullptr_t) -> basic_fixed_string& = delete; constexpr auto operator+=(const basic_fixed_string& rhs) -> basic_fixed_string&; constexpr auto operator+=(const_pointer ptr) -> basic_fixed_string&; diff --git a/Code/Framework/AzCore/AzCore/std/string/string.h b/Code/Framework/AzCore/AzCore/std/string/string.h index c02c6805a1..9ef7ea3086 100644 --- a/Code/Framework/AzCore/AzCore/std/string/string.h +++ b/Code/Framework/AzCore/AzCore/std/string/string.h @@ -168,6 +168,9 @@ namespace AZStd { } + // C++23 overload to prevent initializing a string_view via a nullptr or integer type + constexpr basic_string(AZStd::nullptr_t) = delete; + inline ~basic_string() { // destroy the string @@ -197,6 +200,7 @@ namespace AZStd inline this_type& operator=(AZStd::basic_string_view view) { return assign(view); } inline this_type& operator=(const_pointer ptr) { return assign(ptr); } inline this_type& operator=(Element ch) { return assign(1, ch); } + inline this_type& operator=(AZStd::nullptr_t) = delete; inline this_type& operator+=(const this_type& rhs) { return append(rhs); } inline this_type& operator+=(const_pointer ptr) { return append(ptr); } inline this_type& operator+=(Element ch) { return append(1, ch); } diff --git a/Code/Framework/AzCore/AzCore/std/string/string_view.h b/Code/Framework/AzCore/AzCore/std/string/string_view.h index b2390c293a..30e61f95ce 100644 --- a/Code/Framework/AzCore/AzCore/std/string/string_view.h +++ b/Code/Framework/AzCore/AzCore/std/string/string_view.h @@ -502,6 +502,9 @@ namespace AZStd swap(other); } + // C++23 overload to prevent initializing a string_view via a nullptr or integer type + constexpr basic_string_view(AZStd::nullptr_t) = delete; + constexpr const_reference operator[](size_type index) const { return data()[index]; } /// Returns value, not reference. If index is out of bounds, 0 is returned (can't be reference). constexpr value_type at(size_type index) const diff --git a/Code/Framework/AzCore/Platform/Common/UnixLike/AzCore/Module/DynamicModuleHandle_UnixLike.cpp b/Code/Framework/AzCore/Platform/Common/UnixLike/AzCore/Module/DynamicModuleHandle_UnixLike.cpp index 5cf854d49f..1ca6a7c4c7 100644 --- a/Code/Framework/AzCore/Platform/Common/UnixLike/AzCore/Module/DynamicModuleHandle_UnixLike.cpp +++ b/Code/Framework/AzCore/Platform/Common/UnixLike/AzCore/Module/DynamicModuleHandle_UnixLike.cpp @@ -72,6 +72,7 @@ namespace AZ { if (auto settingsRegistry = AZ::SettingsRegistry::Get(); settingsRegistry != nullptr) { + bool fileFound = false; if (AZ::IO::FixedMaxPath projectModulePath; settingsRegistry->Get(projectModulePath.Native(), AZ::SettingsRegistryMergeUtils::FilePathKey_ProjectConfigurationBinPath)) { @@ -79,6 +80,23 @@ namespace AZ if (AZ::IO::SystemFile::Exists(projectModulePath.c_str())) { m_fileName.assign(projectModulePath.c_str(), projectModulePath.Native().size()); + fileFound = true; + } + } + if (!fileFound) + { + if (AZ::IO::FixedMaxPath installedBinariesPath; + settingsRegistry->Get(installedBinariesPath.Native(), AZ::SettingsRegistryMergeUtils::FilePathKey_InstalledBinaryFolder)) + { + if (AZ::IO::FixedMaxPath engineRootFolder; + settingsRegistry->Get(engineRootFolder.Native(), AZ::SettingsRegistryMergeUtils::FilePathKey_EngineRootFolder)) + { + installedBinariesPath = engineRootFolder / installedBinariesPath / fullFilePath; + if (AZ::IO::SystemFile::Exists(installedBinariesPath.c_str())) + { + m_fileName.assign(installedBinariesPath.c_str(), installedBinariesPath.Native().size()); + } + } } } } 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 9aff67a00f..2e31936057 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 @@ -9,6 +9,7 @@ #include #include +#include namespace AZ { @@ -39,6 +40,14 @@ namespace AZ AZ::IO::FixedMaxPath path{homePath}; return path.Native(); } + + struct passwd* pass = getpwuid(getuid()); + if (pass) + { + AZ::IO::FixedMaxPath path{pass->pw_dir}; + return path.Native(); + } + return {}; } diff --git a/Code/Framework/AzCore/Tests/AZStd/String.cpp b/Code/Framework/AzCore/Tests/AZStd/String.cpp index 91d2237ca2..68bdd311d5 100644 --- a/Code/Framework/AzCore/Tests/AZStd/String.cpp +++ b/Code/Framework/AzCore/Tests/AZStd/String.cpp @@ -1210,9 +1210,6 @@ namespace UnitTest AZStd::string findStr("Hay"); string_view view3(findStr); - string_view nullptrView4(nullptr); - - EXPECT_EQ(emptyView1, nullptrView4); // copy const size_t destBufferSize = 32; @@ -1264,9 +1261,6 @@ namespace UnitTest AZStd::size_t rfindResult = view3.rfind('a', 2); EXPECT_EQ(1, rfindResult); - rfindResult = nullptrView4.rfind(""); - EXPECT_EQ(string_view::npos, rfindResult); - rfindResult = emptyView1.rfind(""); EXPECT_EQ(string_view::npos, rfindResult); @@ -1373,17 +1367,11 @@ namespace UnitTest { string_view view1("The quick brown fox jumped over the lazy dog"); string_view view2("Needle in Haystack"); - string_view nullBeaverView(nullptr); string_view emptyBeaverView; string_view superEmptyBeaverView(""); - EXPECT_EQ(nullBeaverView, emptyBeaverView); - EXPECT_EQ(superEmptyBeaverView, nullBeaverView); - EXPECT_EQ(emptyBeaverView, superEmptyBeaverView); - EXPECT_EQ(nullBeaverView, ""); - EXPECT_EQ(nullBeaverView, nullptr); EXPECT_EQ("", emptyBeaverView); - EXPECT_EQ(nullptr, superEmptyBeaverView); + EXPECT_EQ("", superEmptyBeaverView); EXPECT_EQ("The quick brown fox jumped over the lazy dog", view1); EXPECT_NE("The slow brown fox jumped over the lazy dog", view1); @@ -1421,8 +1409,6 @@ namespace UnitTest EXPECT_LE(beaverView, "Busy Beaver"); EXPECT_LE("Likable Beaver", notBeaverView); EXPECT_LE("Busy Beaver", beaverView); - EXPECT_LE(nullBeaverView, nullBeaverView); - EXPECT_LE(nullBeaverView, lowerBeaverStr); EXPECT_LE(microBeaverStr, view1); EXPECT_LE(compareStr, beaverView); diff --git a/Code/Framework/AzCore/Tests/Name/NameTests.cpp b/Code/Framework/AzCore/Tests/Name/NameTests.cpp index 5417d36051..eb0a048e2f 100644 --- a/Code/Framework/AzCore/Tests/Name/NameTests.cpp +++ b/Code/Framework/AzCore/Tests/Name/NameTests.cpp @@ -362,7 +362,7 @@ namespace UnitTest // Test specific construction case that was failing. // The constructor calls Name::SetName() which does a move assignment // Name& Name::operator=(Name&& rhs) was leaving m_view pointing to the m_data in a temporary Name object. - AZ::Name emptyName(AZStd::string_view(nullptr)); + AZ::Name emptyName(AZStd::string_view{}); EXPECT_TRUE(emptyName.IsEmpty()); EXPECT_EQ(0, emptyName.GetStringView().data()[0]); } diff --git a/Code/Framework/AzCore/Tests/SettingsRegistryTests.cpp b/Code/Framework/AzCore/Tests/SettingsRegistryTests.cpp index 8485747991..2da5701207 100644 --- a/Code/Framework/AzCore/Tests/SettingsRegistryTests.cpp +++ b/Code/Framework/AzCore/Tests/SettingsRegistryTests.cpp @@ -1517,7 +1517,7 @@ namespace SettingsRegistryTests m_testFolder->push_back(AZ_CORRECT_DATABASE_SEPARATOR); *m_testFolder += AZ::SettingsRegistryInterface::RegistryFolder; - bool result = m_registry->MergeSettingsFolder(*m_testFolder, { "editor", "test" }, {}, nullptr); + bool result = m_registry->MergeSettingsFolder(*m_testFolder, { "editor", "test" }, {}); EXPECT_TRUE(result); EXPECT_EQ(4, counter); @@ -1559,7 +1559,7 @@ namespace SettingsRegistryTests m_testFolder->push_back(AZ_CORRECT_DATABASE_SEPARATOR); *m_testFolder += AZ::SettingsRegistryInterface::RegistryFolder; - bool result = m_registry->MergeSettingsFolder(*m_testFolder, { "editor", "test" }, "Special", nullptr); + bool result = m_registry->MergeSettingsFolder(*m_testFolder, { "editor", "test" }, "Special"); EXPECT_TRUE(result); EXPECT_EQ(6, counter); @@ -1598,7 +1598,7 @@ namespace SettingsRegistryTests m_testFolder->push_back(AZ_CORRECT_DATABASE_SEPARATOR); *m_testFolder += AZ::SettingsRegistryInterface::RegistryFolder; - bool result = m_registry->MergeSettingsFolder(*m_testFolder, { "editor", "test" }, {}, nullptr); + bool result = m_registry->MergeSettingsFolder(*m_testFolder, { "editor", "test" }, {}); EXPECT_TRUE(result); EXPECT_EQ(4, counter); @@ -1639,7 +1639,7 @@ namespace SettingsRegistryTests m_testFolder->push_back(AZ_CORRECT_DATABASE_SEPARATOR); *m_testFolder += AZ::SettingsRegistryInterface::RegistryFolder; - bool result = m_registry->MergeSettingsFolder(*m_testFolder, { "editor", "test" }, {}, nullptr); + bool result = m_registry->MergeSettingsFolder(*m_testFolder, { "editor", "test" }, {}); EXPECT_TRUE(result); EXPECT_EQ(4, counter); @@ -1672,7 +1672,7 @@ namespace SettingsRegistryTests m_testFolder->push_back(AZ_CORRECT_DATABASE_SEPARATOR); *m_testFolder += AZ::SettingsRegistryInterface::RegistryFolder; - bool result = m_registry->MergeSettingsFolder(*m_testFolder, { "editor", "test" }, "Special", nullptr); + bool result = m_registry->MergeSettingsFolder(*m_testFolder, { "editor", "test" }, "Special"); EXPECT_TRUE(result); EXPECT_EQ(1, counter); @@ -1722,7 +1722,7 @@ namespace SettingsRegistryTests TEST_F(SettingsRegistryTest, MergeSettingsFolder_EmptyFolder_ReportsSuccessButNothingAdded) { - bool result = m_registry->MergeSettingsFolder(*m_testFolder, { "editor", "test" }, {}, nullptr); + bool result = m_registry->MergeSettingsFolder(*m_testFolder, { "editor", "test" }, {}); EXPECT_TRUE(result); EXPECT_EQ(AZ::SettingsRegistryInterface::Type::Object, m_registry->GetType(AZ_SETTINGS_REGISTRY_HISTORY_KEY "/0")); // Folder and specialization settings. @@ -1734,7 +1734,7 @@ namespace SettingsRegistryTests constexpr AZStd::fixed_string path(AZ::IO::MaxPathLength + 1, 'a'); AZ_TEST_START_TRACE_SUPPRESSION; - bool result = m_registry->MergeSettingsFolder(path, { "editor", "test" }, {}, nullptr); + bool result = m_registry->MergeSettingsFolder(path, { "editor", "test" }, {}); AZ_TEST_STOP_TRACE_SUPPRESSION(1); EXPECT_FALSE(result); @@ -1751,7 +1751,7 @@ namespace SettingsRegistryTests AZ_TEST_START_TRACE_SUPPRESSION; m_testFolder->push_back(AZ_CORRECT_DATABASE_SEPARATOR); *m_testFolder += AZ::SettingsRegistryInterface::RegistryFolder; - bool result = m_registry->MergeSettingsFolder(*m_testFolder, { "editor", "test" }, {}, nullptr); + bool result = m_registry->MergeSettingsFolder(*m_testFolder, { "editor", "test" }, {}); EXPECT_GT(::UnitTest::TestRunner::Instance().StopAssertTests(), 0); EXPECT_FALSE(result); diff --git a/Code/Framework/AzFramework/AzFramework/Application/Application.cpp b/Code/Framework/AzFramework/AzFramework/Application/Application.cpp index 958dba2cc9..12974d03cf 100644 --- a/Code/Framework/AzFramework/AzFramework/Application/Application.cpp +++ b/Code/Framework/AzFramework/AzFramework/Application/Application.cpp @@ -81,71 +81,6 @@ namespace AzFramework static constexpr const char s_prefabSystemKey[] = "/Amazon/Preferences/EnablePrefabSystem"; static constexpr const char s_prefabWipSystemKey[] = "/Amazon/Preferences/EnablePrefabSystemWipFeatures"; static constexpr const char s_legacySlicesAssertKey[] = "/Amazon/Preferences/ShouldAssertForLegacySlicesUsage"; - - // A Helper function that can load an app descriptor from file. - AZ::Outcome, AZStd::string> LoadDescriptorFromFilePath(const char* appDescriptorFilePath, AZ::SerializeContext& serializeContext) - { - AZStd::unique_ptr loadedDescriptor; - - AZ::IO::SystemFile appDescriptorFile; - if (!appDescriptorFile.Open(appDescriptorFilePath, AZ::IO::SystemFile::SF_OPEN_READ_ONLY)) - { - return AZ::Failure(AZStd::string::format("Failed to open file: %s", appDescriptorFilePath)); - } - - AZ::IO::SystemFileStream appDescriptorFileStream(&appDescriptorFile, true); - if (!appDescriptorFileStream.IsOpen()) - { - return AZ::Failure(AZStd::string::format("Failed to stream file: %s", appDescriptorFilePath)); - } - - // Callback function for allocating the root elements in the file. - AZ::ObjectStream::InplaceLoadRootInfoCB inplaceLoadCb = - [](void** rootAddress, const AZ::SerializeContext::ClassData**, const AZ::Uuid& classId, AZ::SerializeContext*) - { - if (rootAddress && classId == azrtti_typeid()) - { - // ComponentApplication::Descriptor is normally a singleton. - // Force a unique instance to be created. - *rootAddress = aznew AZ::ComponentApplication::Descriptor(); - } - }; - - // Callback function for saving the root elements in the file. - AZ::ObjectStream::ClassReadyCB classReadyCb = - [&loadedDescriptor](void* classPtr, const AZ::Uuid& classId, AZ::SerializeContext* context) - { - // Save descriptor, delete anything else loaded from file. - if (classId == azrtti_typeid()) - { - loadedDescriptor.reset(static_cast(classPtr)); - } - else if (const AZ::SerializeContext::ClassData* classData = context->FindClassData(classId)) - { - classData->m_factory->Destroy(classPtr); - } - else - { - AZ_Error("Application", false, "Unexpected type %s found in application descriptor file. This memory will leak.", - classId.ToString().c_str()); - } - }; - - // There's other stuff in the file we may not recognize (system components), but we're not interested in that stuff. - AZ::ObjectStream::FilterDescriptor loadFilter(&AZ::Data::AssetFilterNoAssetLoading, AZ::ObjectStream::FILTERFLAG_IGNORE_UNKNOWN_CLASSES); - - if (!AZ::ObjectStream::LoadBlocking(&appDescriptorFileStream, serializeContext, classReadyCb, loadFilter, inplaceLoadCb)) - { - return AZ::Failure(AZStd::string::format("Failed to load objects from file: %s", appDescriptorFilePath)); - } - - if (!loadedDescriptor) - { - return AZ::Failure(AZStd::string::format("Failed to find descriptor object in file: %s", appDescriptorFilePath)); - } - - return AZ::Success(AZStd::move(loadedDescriptor)); - } } Application::Application() diff --git a/Code/Framework/AzFramework/AzFramework/Archive/Archive.cpp b/Code/Framework/AzFramework/AzFramework/Archive/Archive.cpp index 1891c50d10..d2a81102dc 100644 --- a/Code/Framework/AzFramework/AzFramework/Archive/Archive.cpp +++ b/Code/Framework/AzFramework/AzFramework/Archive/Archive.cpp @@ -40,8 +40,6 @@ #include -#include - namespace AZ::IO { AZ_CVAR(int, sys_PakPriority, aznumeric_cast(ArchiveVars{}.nPriority), nullptr, AZ::ConsoleFunctorFlags::Null, @@ -64,40 +62,6 @@ namespace AZ::IO::ArchiveInternal // to the actual index , this offset is added to get the valid handle static constexpr size_t PseudoFileIdxOffset = 1; - // Explanation of this function: it is like a 'find and replace' for paths - // if the source path starts with 'aliasToLookFor' it will replace it with 'aliasToReplaceWith' - // else it will leave it untouched. - // the only caveat here is that it will perform this replacement if the source path either begins - // with the literal alias to look for, or begins with the actual absolute path that the alias to - // look for represents. It is a way of redirecting all @devassets@ to @assets@ regardless of whether - // you input a string that literally starts with @devassets@ or one that starts with the absolute path to the - // folder that @devassets@ aliases. - AZStd::optional ConvertAbsolutePathToAliasedPath(AZStd::string_view sourcePath, - AZStd::string_view aliasToLookFor, AZStd::string_view aliasToReplaceWith) - { - if (auto fileIo = AZ::IO::FileIOBase::GetDirectInstance(); !aliasToLookFor.empty() && !aliasToReplaceWith.empty() && !sourcePath.empty() && fileIo) - { - auto convertedPath = fileIo->ConvertToAlias(sourcePath); - if (!convertedPath) - { - return AZStd::nullopt; - } - - if (convertedPath->Native().starts_with(aliasToLookFor)) - { - convertedPath->Native().replace(0, aliasToLookFor.size(), aliasToReplaceWith); - } - // lowercase path if it starts with either the @assets@ or @root@ alias - if (convertedPath->Native().starts_with("@assets@") || convertedPath->Native().starts_with("@root@") - || convertedPath->Native().starts_with("@projectplatformcache@")) - { - AZStd::to_lower(convertedPath->Native().begin(), convertedPath->Native().end()); - } - return convertedPath; - } - return AZStd::make_optional(sourcePath); - } - struct CCachedFileRawData { void* m_pCachedData; @@ -146,15 +110,12 @@ namespace AZ::IO::ArchiveInternal uint32_t GetFileSize() { return GetFile() ? GetFile()->GetFileEntry()->desc.lSizeUncompressed : 0; } int FSeek(uint64_t nOffset, int nMode); - size_t FRead(void* pDest, size_t nSize, size_t nCount, AZ::IO::HandleType fileHandle); - size_t FReadAll(void* pDest, size_t nFileSize, AZ::IO::HandleType fileHandle); + size_t FRead(void* pDest, size_t bytesToRead, AZ::IO::HandleType fileHandle); void* GetFileData(size_t& nFileSize, AZ::IO::HandleType fileHandle); int FEof(); - char* FGets(char* pBuf, int n); - int Getc(); uint64_t GetModificationTime() { return m_pFileData->GetFileEntry()->GetModificationTime(); } - const char* GetArchivePath() { return m_pFileData->GetZip()->GetFilePath(); } + AZ::IO::PathView GetArchivePath() { return m_pFileData->GetZip()->GetFilePath(); } protected: uint64_t m_nCurSeek; CCachedFileDataPtr m_pFileData; @@ -205,7 +166,7 @@ namespace AZ::IO::ArchiveInternal } ////////////////////////////////////////////////////////////////////////// - size_t ArchiveInternal::CZipPseudoFile::FRead(void* pDest, size_t nSize, size_t nCount, [[maybe_unused]] AZ::IO::HandleType fileHandle) + size_t ArchiveInternal::CZipPseudoFile::FRead(void* pDest, size_t bytesToRead, [[maybe_unused]] AZ::IO::HandleType fileHandle) { AZ_PROFILE_FUNCTION(AzCore); @@ -214,21 +175,13 @@ namespace AZ::IO::ArchiveInternal return 0; } - size_t nTotal = nSize * nCount; + size_t nTotal = bytesToRead; if (!nTotal || (uint32_t)m_nCurSeek >= GetFileSize()) { return 0; } - if (nTotal > GetFileSize() - m_nCurSeek) - { - nTotal = GetFileSize() - m_nCurSeek; - if (nTotal < nSize) - { - return 0; - } - nTotal -= nTotal % nSize; - } + nTotal = AZStd::min(nTotal, GetFileSize() - m_nCurSeek); int64_t nReadBytes = GetFile()->ReadData(pDest, m_nCurSeek, nTotal); if (nReadBytes == -1) @@ -242,32 +195,9 @@ namespace AZ::IO::ArchiveInternal nTotal = (size_t)nReadBytes; } m_nCurSeek += nTotal; - return nTotal / nSize; + return nTotal; } - ////////////////////////////////////////////////////////////////////////// - size_t ArchiveInternal::CZipPseudoFile::FReadAll(void* pDest, size_t nFileSize, [[maybe_unused]] AZ::IO::HandleType fileHandle) - { - if (!GetFile()) - { - return 0; - } - - if (nFileSize != GetFileSize()) - { - AZ_Assert(false, "File size parameter of nFileSize does not match the file size of the zip file"); // Bad call - return 0; - } - - if (!GetFile()->ReadData(pDest, 0, nFileSize)) - { - return 0; - } - - m_nCurSeek = nFileSize; - - return nFileSize; - } ////////////////////////////////////////////////////////////////////////// void* ArchiveInternal::CZipPseudoFile::GetFileData(size_t& nFileSize, [[maybe_unused]] AZ::IO::HandleType fileHandle) @@ -292,70 +222,6 @@ namespace AZ::IO::ArchiveInternal return (uint32_t)m_nCurSeek >= GetFileSize(); } - char* ArchiveInternal::CZipPseudoFile::FGets(char* pBuf, int n) - { - if (!GetFile()) - { - return nullptr; - } - - char* pData = (char*)GetFile()->GetData(); - if (!pData) - { - return nullptr; - } - int nn = 0; - int i; - for (i = 0; i < n; i++) - { - if (i + m_nCurSeek == GetFileSize()) - { - break; - } - char c = pData[i + m_nCurSeek]; - if (c == 0xa || c == 0) - { - pBuf[nn++] = c; - i++; - break; - } - else - if (c == 0xd) - { - continue; - } - pBuf[nn++] = c; - } - pBuf[nn] = 0; - m_nCurSeek += i; - - if (m_nCurSeek == GetFileSize()) - { - return nullptr; - } - return pBuf; - } - - int ArchiveInternal::CZipPseudoFile::Getc() - { - if (!GetFile()) - { - return EOF; - } - char* pData = (char*)GetFile()->GetData(); - if (!pData) - { - return EOF; - } - int c = EOF; - if (m_nCurSeek == GetFileSize()) - { - return c; - } - c = pData[m_nCurSeek]; - m_nCurSeek += 1; - return c; - } } namespace AZ::IO @@ -379,16 +245,17 @@ namespace AZ::IO void Add(AZStd::string_view sResourceFile) override { - auto filename = ArchiveInternal::ConvertAbsolutePathToAliasedPath(sResourceFile); - if (!filename) + if (sResourceFile.empty()) { - AZ_Error("Archive", false, "Path %s cannot be converted to @alias@ form. It is longer than MaxPathLength %zu", aznumeric_cast(sResourceFile.size()), - sResourceFile.data(), AZ::IO::MaxPathLength); return; } - AZ::IO::FixedMaxPathString& convertedFilename = filename->Native(); - AZStd::replace(convertedFilename.begin(), convertedFilename.end(), AZ_WRONG_DATABASE_SEPARATOR, AZ_CORRECT_DATABASE_SEPARATOR); - AZStd::to_lower(convertedFilename.begin(), convertedFilename.end()); + AZ::IO::FixedMaxPath convertedFilename; + if (!AZ::IO::FileIOBase::GetDirectInstance()->ResolvePath(convertedFilename, sResourceFile)) + { + AZ_Error("Archive", false, "Path %.*s cannot be resolved. It is longer than MaxPathLength %zu", + AZ_STRING_ARG(sResourceFile), AZ::IO::MaxPathLength); + return; + } AZStd::scoped_lock lock(m_lock); m_set.emplace(convertedFilename); @@ -397,23 +264,20 @@ namespace AZ::IO { AZStd::scoped_lock lock(m_lock); m_set.clear(); - m_iter = m_set.begin(); + m_iter = m_set.end(); } bool IsExist(AZStd::string_view sResourceFile) override { - auto filename = ArchiveInternal::ConvertAbsolutePathToAliasedPath(sResourceFile); - if (!filename) + AZ::IO::FixedMaxPath convertedFilename; + if (!AZ::IO::FileIOBase::GetDirectInstance()->ResolvePath(convertedFilename, sResourceFile)) { - AZ_Error("Archive", false, "Path %.*s cannot be converted to @alias@ form. It is longer than MaxPathLength %zu", aznumeric_cast(sResourceFile.size()), - sResourceFile.data(), AZ::IO::MaxPathLength); + AZ_Error("Archive", false, "Path %.*s cannot be resolved. It is longer than MaxPathLength %zu", + AZ_STRING_ARG(sResourceFile), AZ::IO::MaxPathLength); return false; } - AZ::IO::FixedMaxPathString& convertedFilename = filename->Native(); - AZStd::replace(convertedFilename.begin(), convertedFilename.end(), AZ_WRONG_DATABASE_SEPARATOR, AZ_CORRECT_DATABASE_SEPARATOR); - AZStd::to_lower(convertedFilename.begin(), convertedFilename.end()); AZStd::scoped_lock lock(m_lock); - return m_set.contains(AZStd::string_view{ convertedFilename }); + return m_set.contains(AZ::IO::PathView{ convertedFilename }); } bool Load(AZStd::string_view sResourceListFilename) override { @@ -425,9 +289,8 @@ namespace AZ::IO AZ::IO::SizeType nLen = file.Length(); AZStd::string pMemBlock; - pMemBlock.resize_no_construct(nLen); - char* buf = pMemBlock.data(); - file.Read(nLen, buf); + pMemBlock.resize_no_construct(nLen);; + file.Read(pMemBlock.size(), pMemBlock.data()); // Parse file, every line in a file represents a resource filename. AZ::StringFunc::TokenizeVisitor(pMemBlock, @@ -464,7 +327,7 @@ namespace AZ::IO } private: - using ResourceSet = AZStd::set; + using ResourceSet = AZStd::set>; AZStd::recursive_mutex m_lock; ResourceSet m_set; ResourceSet::iterator m_iter; @@ -499,12 +362,13 @@ namespace AZ::IO , m_pNextLevelResourceList{ new CResourceList{} } , m_mainThreadId{ AZStd::this_thread::get_id() } { + CompressionBus::Handler::BusConnect(); } ////////////////////////////////////////////////////////////////////////// Archive::~Archive() { - Release(); + CompressionBus::Handler::BusDisconnect(); m_arrZips = {}; @@ -530,51 +394,13 @@ namespace AZ::IO AZ_Assert(m_cachedFileRawDataSet.empty(), "All Archive file cached raw data instances not closed"); } - bool Archive::CheckFileAccessDisabled([[maybe_unused]] AZStd::string_view name, [[maybe_unused]] const char* mode) - { - return false; - } - void Archive::LogFileAccessCallStack([[maybe_unused]] AZStd::string_view name, [[maybe_unused]] AZStd::string_view nameFull, [[maybe_unused]] const char* mode) { // Print call stack for each find. - AZ_TracePrintf("Archive", "LogFileAccessCallStack() - name=%.*s; nameFull=%.*s; mode=%s\n", aznumeric_cast(name.size()), name.data(), aznumeric_cast(nameFull.size()), nameFull.data(), mode); + AZ_TracePrintf("Archive", "LogFileAccessCallStack() - name=%.*s; nameFull=%.*s; mode=%s\n", AZ_STRING_ARG(name), AZ_STRING_ARG(nameFull), mode); AZ::Debug::Trace::PrintCallstack("Archive", 32); } - ////////////////////////////////////////////////////////////////////////// - - bool Archive::IsInstalledToHDD(AZStd::string_view) const - { - return true; - } - - ////////////////////////////////////////////////////////////////////////// - void Archive::ParseAliases(AZStd::string_view szCommandLine) - { - // this is a list of pairs separated by commas, i.e. Folder1,FolderNew,Textures,TestBuildTextures etc. - AZStd::optional aliasKey = AZ::StringFunc::TokenizeNext(szCommandLine, ','); - AZStd::optional aliasPath = AZ::StringFunc::TokenizeNext(szCommandLine, ','); - for ( ;aliasKey && aliasPath; aliasKey = AZ::StringFunc::TokenizeNext(szCommandLine,','), AZ::StringFunc::TokenizeNext(szCommandLine,',')) - { - // inform the Archive system - SetAlias(*aliasKey, *aliasPath, true); - AZ_TracePrintf("Archive", "Archive ALIAS:%.*s = %.*s\n", aznumeric_cast(aliasKey->size()), aliasKey->data(), - aznumeric_cast(aliasPath->size()), aliasPath->data()); - - } - } - - ////////////////////////////////////////////////////////////////////////// - //! if bReturnSame==true, it will return the input name if an alias doesn't exist. Otherwise returns nullptr - const char* Archive::GetAlias(AZStd::string_view szName, bool bReturnSame) - { - constexpr size_t MaxAliasLength = 32; - AZStd::fixed_string aliasKey{ szName }; - const char* dest = AZ::IO::FileIOBase::GetDirectInstance()->GetAlias(aliasKey.c_str()); - return (bReturnSame && !dest) ? szName.data() : dest; - } - ////////////////////////////////////////////////////////////////////////// void Archive::SetLocalizationFolder(AZStd::string_view sLocalizationFolder) { @@ -591,28 +417,6 @@ namespace AZ::IO m_sLocalizationFolder += AZ_CORRECT_FILESYSTEM_SEPARATOR_STRING; } - ////////////////////////////////////////////////////////////////////////// - void Archive::SetAlias(AZStd::string_view szName, AZStd::string_view szAlias, bool bAdd) - { - constexpr size_t MaxAliasLength = 32; - AZStd::fixed_string aliasKey{ szName }; - if (bAdd) - { - AZ::IO::PathString aliasPath{ szAlias }; - AZ::IO::FileIOBase::GetDirectInstance()->SetAlias(aliasKey.c_str(), aliasPath.c_str()); - } - else - { - AZ::IO::FileIOBase::GetDirectInstance()->ClearAlias(aliasKey.c_str()); - } - } - - - const char* Archive::AdjustFileName(AZStd::string_view src, char* dst, size_t dstSize, uint32_t, bool) - { - AZ::IO::FixedMaxPathString srcPath{ src }; - return AZ::IO::FileIOBase::GetDirectInstance()->ResolvePath(srcPath.c_str(), dst, dstSize) ? dst : nullptr; - } ////////////////////////////////////////////////////////////////////////// bool Archive::IsFileExist(AZStd::string_view sFilename, EFileSearchLocation fileLocation) @@ -679,52 +483,50 @@ namespace AZ::IO } ////////////////////////////////////////////////////////////////////////// - AZ::IO::HandleType Archive::FOpen(AZStd::string_view pName, const char* szMode, uint32_t nInputFlags) + AZ::IO::HandleType Archive::FOpen(AZStd::string_view pName, const char* szMode) { AZ_PROFILE_FUNCTION(AzCore); const size_t pathLen = pName.size(); - if (pathLen == 0 || pathLen >= MaxPath) + if (pathLen == 0 || pathLen >= AZ::IO::MaxPathLength) { return AZ::IO::InvalidHandle; } SAutoCollectFileAccessTime accessTime(this); - AZ::IO::HandleType fileHandle = AZ::IO::InvalidHandle; - - const bool bFileCanBeOnDisk = 0 != (nInputFlags & FOPEN_ONDISK); - // get the priority into local variable to avoid it changing in the course of // this function execution (?) const ArchiveLocationPriority nVarPakPriority = GetPakPriority(); AZ::IO::OpenMode nOSFlags = AZ::IO::GetOpenModeFromStringMode(szMode); - auto szFullPath = AZ::IO::FileIOBase::GetDirectInstance()->ResolvePath(pName); - if (!szFullPath) + AZ::IO::FixedMaxPath szFullPath; + if (!AZ::IO::FileIOBase::GetDirectInstance()->ResolvePath(szFullPath, pName)) { - AZ_Assert(szFullPath, "Unable to resolve path for filepath %.*s", aznumeric_cast(pName.size()), pName.data()); + AZ_Assert(false, "Unable to resolve path for filepath %.*s", aznumeric_cast(pName.size()), pName.data()); return false; } const bool fileWritable = (nOSFlags & (AZ::IO::OpenMode::ModeWrite | AZ::IO::OpenMode::ModeAppend | AZ::IO::OpenMode::ModeUpdate)) != AZ::IO::OpenMode::Invalid; - AZ_PROFILE_SCOPE(Game, "File: %s Archive: %p", szFullPath->c_str(), this); + AZ_PROFILE_SCOPE(Game, "File: %s Archive: %p", szFullPath.c_str(), this); if (fileWritable) { // we need to open the file for writing, but we failed to do so. // the only reason that can be is that there are no directories for that file. // now create those dirs - if (!MakeDir(szFullPath->ParentPath().Native())) + if (AZ::IO::FixedMaxPath parentPath = szFullPath.ParentPath(); + !AZ::IO::FileIOBase::GetDirectInstance()->CreatePath(parentPath.c_str())) { return AZ::IO::InvalidHandle; } - if (AZ::IO::FileIOBase::GetDirectInstance()->Open(szFullPath->c_str(), nOSFlags, fileHandle)) + if (AZ::IO::HandleType fileHandle = AZ::IO::InvalidHandle; + AZ::IO::FileIOBase::GetDirectInstance()->Open(szFullPath.c_str(), nOSFlags, fileHandle)) { if (az_archive_verbosity) { - AZ_TracePrintf("Archive", " Archive::FOpen() has directly opened requested file %s for writing", szFullPath->c_str()); + AZ_TracePrintf("Archive", " Archive::FOpen() has directly opened requested file %s for writing", szFullPath.c_str()); } return fileHandle; } @@ -732,35 +534,41 @@ namespace AZ::IO return AZ::IO::InvalidHandle; } - if (nVarPakPriority == ArchiveLocationPriority::ePakPriorityFileFirst) // if the file system files have priority now.. + auto OpenFromFileSystem = [this, &szFullPath, pName, nOSFlags]() -> HandleType { - if (AZ::IO::FileIOBase::GetDirectInstance()->Open(szFullPath->c_str(), nOSFlags, fileHandle)) + if (AZ::IO::HandleType fileHandle = AZ::IO::InvalidHandle; + AZ::IO::FileIOBase::GetDirectInstance()->Open(szFullPath.c_str(), nOSFlags, fileHandle)) { if (az_archive_verbosity) { - AZ_TracePrintf("Archive", " Archive::FOpen() has directly opened requested file %s with FileFirst priority", szFullPath->c_str()); + AZ_TracePrintf("Archive", " Archive::FOpen() has directly opened requested file %s on for reading", szFullPath.c_str()); } RecordFile(fileHandle, pName); return fileHandle; } - } - uint32_t archiveFlags = 0; - CCachedFileDataPtr pFileData = GetFileData(szFullPath->Native(), archiveFlags); - if (pFileData) + return AZ::IO::InvalidHandle; + }; + auto OpenFromArchive = [this, &szFullPath, pName]() -> HandleType { - bool logged = false; - ZipDir::Cache* pZip = pFileData->GetZip(); - if (pZip) + uint32_t archiveFlags = 0; + CCachedFileDataPtr pFileData = GetFileData(szFullPath.Native(), archiveFlags); + if (pFileData == nullptr) { - const char* pZipFilePath = pZip->GetFilePath(); - if (pZipFilePath && pZipFilePath[0]) + return AZ::IO::InvalidHandle; + } + + bool logged = false; + if (ZipDir::Cache* pZip = pFileData->GetZip(); pZip != nullptr) + { + AZ::IO::PathView pZipFilePath = pZip->GetFilePath(); + if (!pZipFilePath.empty()) { if (az_archive_verbosity) { - AZ_TracePrintf("Archive", " Archive::FOpen() has opened requested file %s from archive %s, disk offset %u", - szFullPath->c_str(), pZipFilePath, pFileData->GetFileEntry()->nFileDataOffset); + AZ_TracePrintf("Archive", " Archive::FOpen() has opened requested file %s from archive %.*s, disk offset %u", + szFullPath.c_str(), AZ_STRING_ARG(pZipFilePath.Native()), pFileData->GetFileEntry()->nFileDataOffset); logged = true; } } @@ -771,57 +579,54 @@ namespace AZ::IO if (az_archive_verbosity) { AZ_TracePrintf("Archive", " Archive::FOpen() has opened requested file %s from an archive file who's path isn't known", - szFullPath->c_str()); + szFullPath.c_str()); } } - } - else - { - if (nVarPakPriority != ArchiveLocationPriority::ePakPriorityPakOnly || bFileCanBeOnDisk) // if the archive files had more priority, we didn't attempt fopen before- try it now + + size_t nFile; + // find the empty slot and open the file there; return the handle { - if (AZ::IO::FileIOBase::GetDirectInstance()->Open(szFullPath->c_str(), nOSFlags, fileHandle)) + // try to open the pseudofile from one of the zips, make sure there is no user alias + AZStd::unique_lock lock(m_csOpenFiles); + for (nFile = 0; nFile < m_arrOpenFiles.size() && m_arrOpenFiles[nFile]->GetFile(); ++nFile) { - if (az_archive_verbosity) - { - AZ_TracePrintf("Archive", " Archive::FOpen() has directly opened requested file %s after failing to open from archives", - szFullPath->c_str()); - } - - RecordFile(fileHandle, pName); - return fileHandle; + continue; } + if (nFile == m_arrOpenFiles.size()) + { + m_arrOpenFiles.emplace_back(AZStd::make_unique()); + } + AZStd::unique_ptr& rZipFile = m_arrOpenFiles[nFile]; + rZipFile->Construct(pFileData.get()); } - return AZ::IO::InvalidHandle; // we can't find such file in the pack files - } - // try to open the pseudofile from one of the zips, make sure there is no user alias - AZStd::unique_lock lock(m_csOpenFiles); + AZ::IO::HandleType handle = (AZ::IO::HandleType)(nFile + ArchiveInternal::PseudoFileIdxOffset); - size_t nFile; - // find the empty slot and open the file there; return the handle + RecordFile(handle, pName); + + return handle; // the handle to the file + }; + + switch (nVarPakPriority) { - for (nFile = 0; nFile < m_arrOpenFiles.size() && m_arrOpenFiles[nFile]->GetFile(); ++nFile) - { - continue; - } - if (nFile == m_arrOpenFiles.size()) - { - m_arrOpenFiles.emplace_back(AZStd::make_unique()); - } - AZStd::unique_ptr& rZipFile = m_arrOpenFiles[nFile]; - rZipFile->Construct(pFileData.get()); - } - - AZ::IO::HandleType ret = (AZ::IO::HandleType)(nFile + ArchiveInternal::PseudoFileIdxOffset); - - if (az_archive_verbosity) + case ArchiveLocationPriority::ePakPriorityFileFirst: { - AZ_TracePrintf("Archive", " Archive::FOpen() has opened psuedo zip file %.*s", aznumeric_cast(pName.size()), pName.data()); + AZ::IO::HandleType fileHandle = OpenFromFileSystem(); + return fileHandle != AZ::IO::InvalidHandle ? fileHandle : OpenFromArchive(); + } + case ArchiveLocationPriority::ePakPriorityPakFirst: + { + AZ::IO::HandleType fileHandle = OpenFromArchive(); + return fileHandle != AZ::IO::InvalidHandle ? fileHandle : OpenFromFileSystem(); + } + case ArchiveLocationPriority::ePakPriorityPakOnly: + { + return OpenFromArchive(); + } + default: + return AZ::IO::InvalidHandle; } - RecordFile(ret, pName); - - return ret; // the handle to the file } ////////////////////////////////////////////////////////////////////////// @@ -872,19 +677,14 @@ namespace AZ::IO ////////////////////////////////////////////////////////////////////////// // tests if the given file path refers to an existing file inside registered (opened) packs // the path must be absolute normalized lower-case with forward-slashes - ZipDir::FileEntry* Archive::FindPakFileEntry(AZStd::string_view szPath, uint32_t& nArchiveFlags, ZipDir::CachePtr* pZip, bool bSkipInMemoryArchives) const + ZipDir::FileEntry* Archive::FindPakFileEntry(AZStd::string_view szPath, uint32_t& nArchiveFlags, ZipDir::CachePtr* pZip) const { - AZ::IO::FixedMaxPath unaliasedPath; + AZ::IO::FixedMaxPath resolvedPath; + if (!AZ::IO::FileIOBase::GetDirectInstance()->ResolvePath(resolvedPath, szPath)) { - auto convertedPath = ArchiveInternal::ConvertAbsolutePathToAliasedPath(szPath); - - if (!convertedPath) - { - AZ_Error("Archive", false, "Path %s cannot be converted to @alias@ form. It is longer than MaxPathLength %zu", aznumeric_cast(szPath.size()), - szPath.data(), AZ::IO::MaxPathLength); - return nullptr; - } - unaliasedPath = AZStd::move(*convertedPath); + AZ_Error("Archive", false, "Path %s cannot be converted to @alias@ form. It is longer than MaxPathLength %zu", aznumeric_cast(szPath.size()), + szPath.data(), AZ::IO::MaxPathLength); + return nullptr; } @@ -892,28 +692,17 @@ namespace AZ::IO // scan through registered archive files and try to find this file for (auto itZip = m_arrZips.rbegin(); itZip != m_arrZips.rend(); ++itZip) { - if (bSkipInMemoryArchives && itZip->pArchive->GetFlags() & INestedArchive::FLAGS_IN_MEMORY_MASK) - { - continue; - } - if (itZip->pArchive->GetFlags() & INestedArchive::FLAGS_DISABLE_PAK) { continue; } - auto [bindRootIter, unaliasedIter] = AZStd::mismatch(itZip->m_pathBindRoot.begin(), itZip->m_pathBindRoot.end(), - unaliasedPath.begin(), unaliasedPath.end()); // If the bindRootIter is at the end then it is a prefix of the source path - if (bindRootIter == itZip->m_pathBindRoot.end()) + if (resolvedPath.IsRelativeTo(itZip->m_pathBindRoot)) { // unaliasedIter is past the bind root, so append the rest of it to a new relative path object - AZ::IO::FixedMaxPath relativePathInZip; - for (; unaliasedIter != unaliasedPath.end(); ++unaliasedIter) - { - relativePathInZip /= *unaliasedIter; - } + AZ::IO::FixedMaxPath relativePathInZip = resolvedPath.LexicallyRelative(itZip->m_pathBindRoot); ZipDir::FileEntry* pFileEntry = itZip->pZip->FindFile(relativePathInZip.Native()); if (pFileEntry) @@ -955,7 +744,7 @@ namespace AZ::IO } // returns the path to the archive in which the file was opened - const char* Archive::GetFileArchivePath(AZ::IO::HandleType fileHandle) + AZ::IO::PathView Archive::GetFileArchivePath(AZ::IO::HandleType fileHandle) { ArchiveInternal::CZipPseudoFile* pseudoFile = GetPseudoFile(fileHandle); if (pseudoFile) @@ -964,7 +753,7 @@ namespace AZ::IO } else { - return nullptr; + return {}; } } @@ -1066,7 +855,7 @@ namespace AZ::IO return 1; } - size_t Archive::FWrite(const void* data, size_t length, size_t elems, AZ::IO::HandleType fileHandle) + size_t Archive::FWrite(const void* data, size_t bytesToWrite, AZ::IO::HandleType fileHandle) { SAutoCollectFileAccessTime accessTime(this); @@ -1077,47 +866,28 @@ namespace AZ::IO } AZ_Assert(fileHandle != AZ::IO::InvalidHandle, "Invalid file has been passed to FWrite"); - if (AZ::IO::FileIOBase::GetDirectInstance()->Write(fileHandle, data, length * elems)) + if (AZ::u64 bytesWritten{}; AZ::IO::FileIOBase::GetDirectInstance()->Write(fileHandle, data, bytesToWrite, &bytesWritten)) { - return elems; + return bytesWritten; } return 0; } ////////////////////////////////////////////////////////////////////////// - size_t Archive::FReadRaw(void* pData, size_t nSize, size_t nCount, AZ::IO::HandleType fileHandle) + size_t Archive::FRead(void* pData, size_t bytesToRead, AZ::IO::HandleType fileHandle) { AZ_PROFILE_FUNCTION(AzCore); - AZ_PROFILE_SCOPE(Game, "Size: %d Archive: %p", nSize, this); SAutoCollectFileAccessTime accessTime(this); ArchiveInternal::CZipPseudoFile* pseudoFile = GetPseudoFile(fileHandle); if (pseudoFile) { - return pseudoFile->FRead(pData, nSize, nCount, fileHandle); + return pseudoFile->FRead(pData, bytesToRead, fileHandle); } AZ::u64 bytesRead = 0; - AZ::IO::FileIOBase::GetDirectInstance()->Read(fileHandle, pData, nSize * nCount, false, &bytesRead); - return static_cast(bytesRead / nSize); - } - - ////////////////////////////////////////////////////////////////////////// - size_t Archive::FReadRawAll(void* pData, size_t nFileSize, AZ::IO::HandleType fileHandle) - { - AZ_PROFILE_FUNCTION(AzCore); - - SAutoCollectFileAccessTime accessTime(this); - ArchiveInternal::CZipPseudoFile* pseudoFile = GetPseudoFile(fileHandle); - if (pseudoFile) - { - return pseudoFile->FReadAll(pData, nFileSize, fileHandle); - } - - AZ::IO::FileIOBase::GetDirectInstance()->Seek(fileHandle, 0, AZ::IO::SeekType::SeekFromStart); - AZ::u64 bytesRead = 0; - AZ::IO::FileIOBase::GetDirectInstance()->Read(fileHandle, pData, nFileSize, false, &bytesRead); - return static_cast(bytesRead); + AZ::IO::FileIOBase::GetDirectInstance()->Read(fileHandle, pData, bytesToRead, false, &bytesRead); + return bytesRead; } ////////////////////////////////////////////////////////////////////////// @@ -1234,48 +1004,6 @@ namespace AZ::IO } - int Archive::FPrintf(AZ::IO::HandleType fileHandle, const char* szFormat, ...) - { - SAutoCollectFileAccessTime accessTime(this); - ArchiveInternal::CZipPseudoFile* pseudoFile = GetPseudoFile(fileHandle); - if (pseudoFile) - { - return 0; // we don't support it now - } - - va_list arglist; - int rv; - va_start(arglist, szFormat); - rv = static_cast(AZ::IO::PrintV(fileHandle, szFormat, arglist)); - va_end(arglist); - return rv; - } - - char* Archive::FGets(char* str, int n, AZ::IO::HandleType fileHandle) - { - SAutoCollectFileAccessTime accessTime(this); - ArchiveInternal::CZipPseudoFile* pseudoFile = GetPseudoFile(fileHandle); - if (pseudoFile) - { - return pseudoFile->FGets(str, n); - } - - return AZ::IO::FGetS(str, n, fileHandle); - } - - int Archive::Getc(AZ::IO::HandleType fileHandle) - { - SAutoCollectFileAccessTime accessTime(this); - ArchiveInternal::CZipPseudoFile* pseudoFile = GetPseudoFile(fileHandle); - if (pseudoFile) - { - return pseudoFile->Getc(); - } - - return AZ::IO::GetC(fileHandle); - } - - ////////////////////////////////////////////////////////////////////////// AZ::IO::ArchiveFileIterator Archive::FindFirst(AZStd::string_view pDir, EFileSearchType searchType) { @@ -1304,7 +1032,7 @@ namespace AZ::IO break; } - AZStd::intrusive_ptr pFindData = new AZ::IO::FindData(); + AZStd::intrusive_ptr pFindData = aznew AZ::IO::FindData(); pFindData->Scan(this, szFullPath->Native(), bAllowUseFileSystem, bScanZips); return pFindData->Fetch(); @@ -1322,18 +1050,6 @@ namespace AZ::IO return true; } - ////////////////////////////////////////////////////////////////////////// - bool Archive::LoadPakToMemory([[maybe_unused]] AZStd::string_view pName, [[maybe_unused]] IArchive::EInMemoryArchiveLocation nLoadPakToMemory, - [[maybe_unused]] AZStd::intrusive_ptr pMemoryBlock) - { - return true; - } - - ////////////////////////////////////////////////////////////////////////// - void Archive::LoadPaksToMemory([[maybe_unused]] int nMaxArchiveSize, [[maybe_unused]] bool bLoadToMemory) - { - } - auto Archive::GetLevelPackOpenEvent() -> LevelPackOpenEvent* { return &m_levelOpenEvent; @@ -1344,7 +1060,7 @@ namespace AZ::IO return &m_levelCloseEvent; } //====================================================================== - bool Archive::OpenPack(AZStd::string_view szBindRootIn, AZStd::string_view szPath, uint32_t nFlags, + bool Archive::OpenPack(AZStd::string_view szBindRootIn, AZStd::string_view szPath, AZStd::intrusive_ptr pData, AZ::IO::FixedMaxPathString* pFullPath, bool addLevels) { AZ_Assert(!szBindRootIn.empty(), "Bind Root should not be empty"); @@ -1363,7 +1079,7 @@ namespace AZ::IO return false; } - bool result = OpenPackCommon(szBindRoot->Native(), szFullPath->Native(), nFlags, pData, addLevels); + bool result = OpenPackCommon(szBindRoot->Native(), szFullPath->Native(), pData, addLevels); if (pFullPath) { @@ -1373,7 +1089,7 @@ namespace AZ::IO return result; } - bool Archive::OpenPack(AZStd::string_view szPath, uint32_t nFlags, AZStd::intrusive_ptr pData, + bool Archive::OpenPack(AZStd::string_view szPath, AZStd::intrusive_ptr pData, AZ::IO::FixedMaxPathString* pFullPath, bool addLevels) { auto szFullPath = AZ::IO::FileIOBase::GetDirectInstance()->ResolvePath(szPath); @@ -1385,7 +1101,7 @@ namespace AZ::IO AZStd::string_view bindRoot = szFullPath->ParentPath().Native(); - bool result = OpenPackCommon(bindRoot, szFullPath->Native(), nFlags, pData, addLevels); + bool result = OpenPackCommon(bindRoot, szFullPath->Native(), pData, addLevels); if (pFullPath) { @@ -1396,34 +1112,22 @@ namespace AZ::IO } - bool Archive::OpenPackCommon(AZStd::string_view szBindRoot, AZStd::string_view szFullPath, uint32_t nArchiveFlags, + bool Archive::OpenPackCommon(AZStd::string_view szBindRoot, AZStd::string_view szFullPath, AZStd::intrusive_ptr pData, bool addLevels) { - // Note this will replace @devassets@ with @assets@ to provide a proper bind root for the archives - auto conversionResult = ArchiveInternal::ConvertAbsolutePathToAliasedPath(szBindRoot); - if (!conversionResult) - { - AZ_Error("Archive", false, "Path %.*s cannot be converted to @alias@ form. It is longer than MaxPathLength %zu", - aznumeric_cast(szBindRoot.size()), szBindRoot.data(), AZ::IO::MaxPathLength); - return false; - } - // setup PackDesc before the duplicate test PackDesc desc; - desc.strFileName = szFullPath; + desc.m_strFileName = szFullPath; - if (!conversionResult || conversionResult->empty()) + if (AZ::IO::FixedMaxPath pathBindRoot; !AZ::IO::FileIOBase::GetDirectInstance()->ResolvePath(pathBindRoot, szBindRoot)) { - desc.m_pathBindRoot = "@assets@"; + AZ::IO::FileIOBase::GetDirectInstance()->ResolvePath(pathBindRoot, "@assets@"); + desc.m_pathBindRoot = pathBindRoot.LexicallyNormal().String(); } else { - // Create a bind root without any trailing slashes - desc.m_pathBindRoot = AZStd::move(*conversionResult); - if (desc.m_pathBindRoot.HasRelativePath() && !desc.m_pathBindRoot.HasFilename()) - { - desc.m_pathBindRoot = desc.m_pathBindRoot.ParentPath(); - } + // Create a bind root + desc.m_pathBindRoot = pathBindRoot.LexicallyNormal().String(); } // hold the lock from the point we query the zip array, @@ -1433,56 +1137,23 @@ namespace AZ::IO // try to find this - maybe the pack has already been opened for (auto it = m_arrZips.begin(); it != m_arrZips.end(); ++it) { - const char* pFilePath = it->pZip->GetFilePath(); - if (pFilePath == desc.strFileName && it->m_pathBindRoot == desc.m_pathBindRoot) + if (AZ::IO::PathView archiveFilePath = it->pZip->GetFilePath(); + archiveFilePath == desc.m_strFileName && it->m_pathBindRoot == desc.m_pathBindRoot) { return true; // already opened } } } - int flags = INestedArchive::FLAGS_OPTIMIZED_READ_ONLY | INestedArchive::FLAGS_ABSOLUTE_PATHS; - if ((nArchiveFlags & FLAGS_PAK_IN_MEMORY) != 0) - { - flags |= INestedArchive::FLAGS_IN_MEMORY; - } - if ((nArchiveFlags & FLAGS_PAK_IN_MEMORY_CPU) != 0) - { - flags |= INestedArchive::FLAGS_IN_MEMORY_CPU; - } - if ((nArchiveFlags & FLAGS_FILENAMES_AS_CRC32) != 0) - { - flags |= INestedArchive::FLAGS_FILENAMES_AS_CRC32; - } - if ((nArchiveFlags & FLAGS_REDIRECT_TO_DISC) != 0) - { - flags |= FLAGS_REDIRECT_TO_DISC; - } - if ((nArchiveFlags & INestedArchive::FLAGS_OVERRIDE_PAK) != 0) - { - flags |= INestedArchive::FLAGS_OVERRIDE_PAK; - } - if ((nArchiveFlags & FLAGS_LEVEL_PAK_INSIDE_PAK) != 0) - { - flags |= INestedArchive::FLAGS_INSIDE_PAK; - } + const int flags = INestedArchive::FLAGS_OPTIMIZED_READ_ONLY | INestedArchive::FLAGS_ABSOLUTE_PATHS; desc.pArchive = OpenArchive(szFullPath, szBindRoot, flags, pData); if (!desc.pArchive) { return false; // couldn't open the archive } - if (m_filesCachedOnHDD.size()) - { - uint32_t crc = AZ::Crc32(szFullPath); - if (m_filesCachedOnHDD.find(crc) != m_filesCachedOnHDD.end()) - { - uint32_t eFlags = desc.pArchive->GetFlags(); - desc.pArchive->SetFlags(eFlags | INestedArchive::FLAGS_ON_HDD); - } - } - AZ_TracePrintf("Archive", "Opening archive file %.*s\n", aznumeric_cast(szFullPath.size()), szFullPath.data()); + AZ_TracePrintf("Archive", "Opening archive file %.*s\n", AZ_STRING_ARG(szFullPath)); desc.pZip = static_cast(desc.pArchive.get())->GetCache(); AZStd::unique_lock lock(m_csZips); @@ -1493,20 +1164,14 @@ namespace AZ::IO // All we have to do is name the archive appropriately to make // sure later archives added to the current set of archives sort higher // and therefore get used instead of lower sorted archives - AZStd::string_view nextBundle; + AZ::IO::PathView nextBundle; ZipArray::reverse_iterator revItZip = m_arrZips.rbegin(); - if ((nArchiveFlags & INestedArchive::FLAGS_OVERRIDE_PAK) == 0) + for (; revItZip != m_arrZips.rend(); ++revItZip) { - for (; revItZip != m_arrZips.rend(); ++revItZip) + nextBundle = revItZip->GetFullPath(); + if (desc.GetFullPath() > revItZip->GetFullPath()) { - if ((revItZip->pArchive->GetFlags() & INestedArchive::FLAGS_OVERRIDE_PAK) == 0) - { - nextBundle = revItZip->GetFullPath(); - if (azstricmp(desc.GetFullPath(), revItZip->GetFullPath()) > 0) - { - break; - } - } + break; } } @@ -1555,17 +1220,17 @@ namespace AZ::IO } AZ::IO::ArchiveNotificationBus::Broadcast([](AZ::IO::ArchiveNotifications* archiveNotifications, const char* bundleName, - AZStd::shared_ptr bundleManifest, const char* nextBundle, AZStd::shared_ptr bundleCatalog) + AZStd::shared_ptr bundleManifest, const AZ::IO::FixedMaxPath& nextBundle, AZStd::shared_ptr bundleCatalog) { - archiveNotifications->BundleOpened(bundleName, bundleManifest, nextBundle, bundleCatalog); - }, desc.strFileName.c_str(), bundleManifest, nextBundle.data(), bundleCatalog); + archiveNotifications->BundleOpened(bundleName, bundleManifest, nextBundle.c_str(), bundleCatalog); + }, desc.m_strFileName.c_str(), bundleManifest, nextBundle, bundleCatalog); return true; } // after this call, the file will be unlocked and closed, and its contents won't be used to search for files - bool Archive::ClosePack(AZStd::string_view pName, [[maybe_unused]] uint32_t nFlags) + bool Archive::ClosePack(AZStd::string_view pName) { auto szZipPath = AZ::IO::FileIOBase::GetDirectInstance()->ResolvePath(pName); if (!szZipPath) @@ -1581,16 +1246,16 @@ namespace AZ::IO AZStd::unique_lock lock(m_csZips); for (auto it = m_arrZips.begin(); it != m_arrZips.end();) { - if (azstricmp(szZipPath->c_str(), it->GetFullPath()) == 0) + if (szZipPath == it->GetFullPath()) { // this is the pack with the given name - remove it, and if possible it will be deleted // the zip is referenced from the archive and *it; the archive is referenced only from *it // // the pZip (cache) can be referenced from stream engine and pseudo-files. // the archive can be referenced from outside - AZ::IO::ArchiveNotificationBus::Broadcast([](AZ::IO::ArchiveNotifications* archiveNotifications, const char* bundleName) + AZ::IO::ArchiveNotificationBus::Broadcast([](AZ::IO::ArchiveNotifications* archiveNotifications, const AZ::IO::FixedMaxPath& bundleName) { - archiveNotifications->BundleClosed(bundleName); + archiveNotifications->BundleClosed(bundleName.c_str()); }, it->GetFullPath()); if (usePrefabSystemForLevels) @@ -1643,7 +1308,7 @@ namespace AZ::IO return foundMatchingPackFile; } - bool Archive::OpenPacks(AZStd::string_view pWildcardIn, uint32_t nFlags, AZStd::vector* pFullPaths) + bool Archive::OpenPacks(AZStd::string_view pWildcardIn, AZStd::vector* pFullPaths) { auto strBindRoot{ AZ::IO::PathView(pWildcardIn).ParentPath() }; AZ::IO::FixedMaxPath bindRoot; @@ -1651,10 +1316,10 @@ namespace AZ::IO { bindRoot = strBindRoot; } - return OpenPacksCommon(bindRoot.Native(), pWildcardIn, nFlags, pFullPaths); + return OpenPacksCommon(bindRoot.Native(), pWildcardIn, pFullPaths); } - bool Archive::OpenPacks(AZStd::string_view szBindRoot, AZStd::string_view pWildcardIn, uint32_t nFlags, AZStd::vector* pFullPaths) + bool Archive::OpenPacks(AZStd::string_view szBindRoot, AZStd::string_view pWildcardIn, AZStd::vector* pFullPaths) { auto bindRoot = AZ::IO::FileIOBase::GetDirectInstance()->ResolvePath(szBindRoot); if (!bindRoot) @@ -1662,16 +1327,16 @@ namespace AZ::IO AZ_Assert(false, "Unable to resolve path for filepath %.*s", aznumeric_cast(szBindRoot.size()), szBindRoot.data()); return false; } - return OpenPacksCommon(bindRoot->Native(), pWildcardIn, nFlags, pFullPaths); + return OpenPacksCommon(bindRoot->Native(), pWildcardIn, pFullPaths); } - bool Archive::OpenPacksCommon(AZStd::string_view szDir, AZStd::string_view pWildcardIn, uint32_t nArchiveFlags, AZStd::vector* pFullPaths, bool addLevels) + bool Archive::OpenPacksCommon(AZStd::string_view szDir, AZStd::string_view pWildcardIn, AZStd::vector* pFullPaths, bool addLevels) { constexpr AZStd::string_view wildcards{ "*?" }; if (wildcards.find_first_of(pWildcardIn) == AZStd::string_view::npos) { // No wildcards, just open pack - if (OpenPackCommon(szDir, pWildcardIn, nArchiveFlags, nullptr, addLevels)) + if (OpenPackCommon(szDir, pWildcardIn, nullptr, addLevels)) { if (pFullPaths) { @@ -1683,25 +1348,24 @@ namespace AZ::IO if (AZ::IO::ArchiveFileIterator fileIterator = FindFirst(pWildcardIn, IArchive::eFileSearchType_AllowOnDiskOnly); fileIterator) { - AZStd::vector files; + AZStd::vector files; do { - AZStd::string foundFilename{ fileIterator.m_filename }; - AZStd::to_lower(foundFilename.begin(), foundFilename.end()); - files.emplace_back(AZStd::move(foundFilename)); + auto& foundFilename = files.emplace_back(fileIterator.m_filename); + AZStd::to_lower(foundFilename.Native().begin(), foundFilename.Native().end()); } while (fileIterator = FindNext(fileIterator)); - // Open files in alphabet order. + // Open files in alphabetical order. AZStd::sort(files.begin(), files.end()); bool bAllOk = true; - for (const AZStd::string& file : files) + for (const AZ::IO::FixedMaxPath& file : files) { - bAllOk = OpenPackCommon(szDir, file, nArchiveFlags, nullptr, addLevels) && bAllOk; + bAllOk = OpenPackCommon(szDir, file.Native(), nullptr, addLevels) && bAllOk; if (pFullPaths) { - pFullPaths->emplace_back(file.begin(), file.end()); + pFullPaths->emplace_back(AZStd::move(file.Native())); } } @@ -1713,7 +1377,7 @@ namespace AZ::IO } - bool Archive::ClosePacks(AZStd::string_view pWildcardIn, uint32_t nFlags) + bool Archive::ClosePacks(AZStd::string_view pWildcardIn) { auto path = AZ::IO::FileIOBase::GetDirectInstance()->ResolvePath(pWildcardIn); if (!path) @@ -1723,26 +1387,13 @@ namespace AZ::IO } return AZ::IO::FileIOBase::GetDirectInstance()->FindFiles(AZ::IO::FixedMaxPath(path->ParentPath()).c_str(), - AZ::IO::FixedMaxPath(path->Filename()).c_str(), [&](const char* filePath) -> bool + AZ::IO::FixedMaxPath(path->Filename()).c_str(), [this](const char* filePath) -> bool { - ClosePack(filePath, nFlags); + ClosePack(filePath); return true; }); } - - ///////////////////////////////////////////////////// - bool Archive::Init([[maybe_unused]] AZStd::string_view szBasePath) - { - BusConnect(); - return true; - } - - void Archive::Release() - { - BusDisconnect(); - } - ////////////////////////////////////////////////////////////////////////// ArchiveInternal::CZipPseudoFile* Archive::GetPseudoFile(AZ::IO::HandleType fileHandle) const { @@ -1912,36 +1563,6 @@ namespace AZ::IO return m_pFileEntry->nFileDataOffset; } - bool Archive::MakeDir(AZStd::string_view szPathIn) - { - AZ::IO::StackString pathStr{ szPathIn }; - // Determine if there is a period ('.') after the last slash to determine if the path contains a file. - // This used to be a strchr on the whole path which could contain a period in a path, such as network domain paths (domain.user). - size_t findDotFromPos = pathStr.rfind(AZ_CORRECT_FILESYSTEM_SEPARATOR); - if (findDotFromPos == AZ::IO::StackString::npos) - { - findDotFromPos = pathStr.rfind(AZ_WRONG_FILESYSTEM_SEPARATOR); - if (findDotFromPos == AZ::IO::StackString::npos) - { - findDotFromPos = 0; - } - } - size_t dotPos = pathStr.find('.', findDotFromPos); - if (dotPos != AZ::IO::StackString::npos) - { - AZStd::string fullPath; - AZ::StringFunc::Path::GetFullPath(pathStr.c_str(), fullPath); - pathStr = fullPath; - } - - if (pathStr.empty()) - { - return true; - } - - return AZ::IO::FileIOBase::GetDirectInstance()->CreatePath(pathStr.c_str()); - } - ////////////////////////////////////////////////////////////////////////// // open the physical archive file - creates if it doesn't exist // returns nullptr if it's invalid or can't open the file @@ -1962,15 +1583,6 @@ namespace AZ::IO uint32_t nFactoryFlags = 0; - if (nFlags & INestedArchive::FLAGS_IN_MEMORY) - { - nFactoryFlags |= ZipDir::CacheFactory::FLAGS_IN_MEMORY; - } - - if (nFlags & INestedArchive::FLAGS_IN_MEMORY_CPU) - { - nFactoryFlags |= ZipDir::CacheFactory::FLAGS_IN_MEMORY_CPU; - } if (nFlags & INestedArchive::FLAGS_DONT_COMPACT) { @@ -1982,10 +1594,6 @@ namespace AZ::IO nFactoryFlags |= ZipDir::CacheFactory::FLAGS_READ_ONLY; } - if (nFlags & INestedArchive::FLAGS_INSIDE_PAK) - { - nFactoryFlags |= ZipDir::CacheFactory::FLAGS_READ_INSIDE_PAK; - } INestedArchive* pArchive = FindArchive(szFullPath->Native()); if (pArchive) @@ -2016,7 +1624,10 @@ namespace AZ::IO if (!pakOnDisk && (nFactoryFlags & ZipDir::CacheFactory::FLAGS_READ_ONLY)) { // Archive file not found. - AZ_TracePrintf("Archive", "Archive file %s does not exist\n", szFullPath->c_str()); + if (az_archive_verbosity) + { + AZ_TracePrintf("Archive", "Archive file %s does not exist\n", szFullPath->c_str()); + } return nullptr; } @@ -2031,148 +1642,6 @@ namespace AZ::IO return nullptr; } - uint32_t Archive::ComputeCRC(AZStd::string_view szPath, [[maybe_unused]] uint32_t nFileOpenFlags) - { - AZ_Assert(!szPath.empty(), "Path to compute Crc cannot be empty"); - - AZ::Crc32 dwCRC = 0; - - // generate crc32 - { - // avoid heap allocation by working in 8k chunks - const uint32_t dwChunkSize = 1024 * 8; - - // note that the actual CRC algorithm can work on various sized words but operates on individual words - // so there's little difference between feeding it 8k and 8mb, except you might save yourself some io calls. - - uint8_t pMem[dwChunkSize]; - - - AZ::IO::FileIOBase* fileIO = AZ::IO::FileIOBase::GetInstance(); - if (!fileIO) - { - return ZipDir::ZD_ERROR_INVALID_CALL; - } - - AZ::IO::HandleType fileHandle = AZ::IO::InvalidHandle; - - if (AZ::IO::PathString filepath{ szPath }; !fileIO->Open(filepath.c_str(), AZ::IO::OpenMode::ModeRead | AZ::IO::OpenMode::ModeBinary, fileHandle)) - { - return ZipDir::ZD_ERROR_INVALID_PATH; - } - // load whole file in chunks and compute CRC - while (true) - { - AZ::u64 bytesRead = 0; - fileIO->Read(fileHandle, pMem, dwChunkSize, false, &bytesRead); // read up to ChunkSize bytes and put the actual number of bytes read into bytesRead. - - if (bytesRead) - { - dwCRC.Add(pMem, aznumeric_caster(bytesRead)); - } - else - { - break; - } - } - - FClose(fileHandle); - } - - return dwCRC; - } - - bool Archive::ComputeMD5(AZStd::string_view szPath, uint8_t* md5, uint32_t nFileOpenFlags, bool useDirectFileAccess) - { - if (szPath.empty() || !md5) - { - return false; - } - - MD5Context context; - MD5Init(&context); - - // generate checksum - { - const AZ::u64 dwChunkSize = 1024 * 1024; // 1MB chunks - AZStd::unique_ptr pMem{ reinterpret_cast(AZ::AllocatorInstance::Get().Allocate(dwChunkSize, alignof(uint8_t))), - [](uint8_t* ptr) { AZ::AllocatorInstance::Get().DeAllocate(ptr); } - }; - - if (!pMem) - { - return false; - } - - AZ::u64 dwSize = 0; - - AZ::IO::PathString filepath{ szPath }; - if (useDirectFileAccess) - { - - AZ::IO::FileIOBase::GetDirectInstance()->Size(filepath.c_str(), dwSize); - } - else - { - AZ::IO::HandleType fileHandle = FOpen(filepath, "rb", nFileOpenFlags); - - if (fileHandle != AZ::IO::InvalidHandle) - { - dwSize = FGetSize(fileHandle); - FClose(fileHandle); - } - } - - // rbx open flags, x is a hint to not cache whole file in memory. - AZ::IO::HandleType fileHandle = AZ::IO::InvalidHandle; - if (useDirectFileAccess) - { - AZ::IO::FileIOBase::GetDirectInstance()->Open(filepath.c_str(), AZ::IO::OpenMode::ModeRead | AZ::IO::OpenMode::ModeBinary, fileHandle); - } - else - { - fileHandle = FOpen(filepath, "rbx", nFileOpenFlags); - } - - if (fileHandle == AZ::IO::InvalidHandle) - { - return false; - } - - // load whole file in chunks and compute Md5 - while (dwSize > 0) - { - uint64_t dwLocalSize = AZStd::min(dwSize, dwChunkSize); - - AZ::u64 read{ 0 }; - if (useDirectFileAccess) - { - AZ::IO::FileIOBase::GetDirectInstance()->Read(fileHandle, pMem.get(), dwLocalSize, false, &read); - } - else - { - read = FReadRaw(pMem.get(), 1, dwLocalSize, fileHandle); - } - AZ_Assert(read == dwLocalSize, "Failed to read dwLocalSize %" PRIu32 " bytes from file", dwLocalSize); - - MD5Update(&context, pMem.get(), aznumeric_cast(dwLocalSize)); - dwSize -= dwLocalSize; - } - - if (useDirectFileAccess) - { - AZ::IO::FileIOBase::GetDirectInstance()->Close(fileHandle); - } - else - { - FClose(fileHandle); - } - } - - MD5Final(md5, &context); - return true; - } - void Archive::Register(INestedArchive* pArchive) { AZStd::unique_lock lock(m_archiveMutex); @@ -2185,7 +1654,7 @@ namespace AZ::IO AZStd::unique_lock lock(m_archiveMutex); if (pArchive) { - AZ_TracePrintf("Archive", "Closing Archive file: %s\n", pArchive->GetFullPath()); + AZ_TracePrintf("Archive", "Closing Archive file: %.*s\n", AZ_STRING_ARG(pArchive->GetFullPath().Native())); } ArchiveArray::iterator it; if (m_arrArchives.size() < 16) @@ -2212,7 +1681,7 @@ namespace AZ::IO { AZStd::shared_lock lock(m_archiveMutex); auto it = AZStd::lower_bound(m_arrArchives.begin(), m_arrArchives.end(), szFullPath, NestedArchiveSortByName()); - if (it != m_arrArchives.end() && !azstrnicmp(szFullPath.data(), (*it)->GetFullPath(), szFullPath.size())) + if (it != m_arrArchives.end() && szFullPath == (*it)->GetFullPath()) { return *it; } @@ -2280,7 +1749,7 @@ namespace AZ::IO case RFOM_Disabled: default: - AZ_Assert(false, "File record option %d", aznumeric_cast(eList));; + AZ_Assert(false, "File record option %d", aznumeric_cast(eList)); } return nullptr; } @@ -2325,11 +1794,14 @@ namespace AZ::IO if (m_eRecordFileOpenList != IArchive::RFOM_Disabled) { // we only want to record ASSET access - // assets are identified as things which start with no alias, or with the @assets@ alias - auto assetPath = AZ::IO::FileIOBase::GetInstance()->ConvertToAlias(szFilename); - if (assetPath && (assetPath->Native().starts_with("@assets@") - || assetPath->Native().starts_with("@root@") - || assetPath->Native().starts_with("@projectplatformcache@"))) + // assets are identified as files that are relative to the resolved @assets@ alias path + auto fileIoBase = AZ::IO::FileIOBase::GetInstance(); + const char* aliasValue = fileIoBase->GetAlias("@assets@"); + + if (AZ::IO::FixedMaxPath resolvedFilePath; + fileIoBase->ResolvePath(resolvedFilePath, szFilename) + && aliasValue != nullptr + && resolvedFilePath.IsRelativeTo(aliasValue)) { IResourceList* pList = GetResourceList(m_eRecordFileOpenList); @@ -2360,13 +1832,8 @@ namespace AZ::IO bool prev = false; if (threadId == m_mainThreadId) { - prev = m_disableRuntimeFileAccess[0]; - m_disableRuntimeFileAccess[0] = status; - } - else if (threadId == m_renderThreadId) - { - prev = m_disableRuntimeFileAccess[1]; - m_disableRuntimeFileAccess[1] = status; + prev = m_disableRuntimeFileAccess; + m_disableRuntimeFileAccess = status; } return prev; } @@ -2440,16 +1907,6 @@ namespace AZ::IO return AZ::AllocatorInstance::Get().DeAllocate(p); } - void Archive::Lock() - { - m_csMain.lock(); - } - - void Archive::Unlock() - { - m_csMain.unlock(); - } - // gets the current archive priority ArchiveLocationPriority Archive::GetPakPriority() const { @@ -2519,7 +1976,7 @@ namespace AZ::IO { found = true; - info.m_archiveFilename.InitFromRelativePath(archive->GetFilePath()); + info.m_archiveFilename.InitFromRelativePath(archive->GetFilePath().Native()); info.m_offset = pFileData->GetFileDataOffset(); info.m_compressedSize = entry->desc.lSizeCompressed; info.m_uncompressedSize = entry->desc.lSizeUncompressed; @@ -2561,7 +2018,7 @@ namespace AZ::IO ZipDir::CachePtr pZip; uint32_t nArchiveFlags; - ZipDir::FileEntry* pFileEntry = FindPakFileEntry(szFullPath->Native(), nArchiveFlags, &pZip, false); + ZipDir::FileEntry* pFileEntry = FindPakFileEntry(szFullPath->Native(), nArchiveFlags, &pZip); if (!pFileEntry) { return 0; @@ -2589,7 +2046,7 @@ namespace AZ::IO return static_cast(StreamMediaType::TypeHDD); } - bool Archive::SetPacksAccessible(bool bAccessible, AZStd::string_view pWildcard, uint32_t nFlags) + bool Archive::SetPacksAccessible(bool bAccessible, AZStd::string_view pWildcard) { auto filePath = AZ::IO::FileIOBase::GetDirectInstance()->ResolvePath(pWildcard); if (!filePath) @@ -2601,24 +2058,24 @@ namespace AZ::IO return AZ::IO::FileIOBase::GetDirectInstance()->FindFiles(AZ::IO::FixedMaxPath(filePath->ParentPath()).c_str(), AZ::IO::FixedMaxPath(filePath->Filename()).c_str(), [&](const char* filePath) -> bool { - SetPackAccessible(bAccessible, filePath, nFlags); + SetPackAccessible(bAccessible, filePath); return true; }); } - bool Archive::SetPackAccessible(bool bAccessible, AZStd::string_view pName, [[maybe_unused]] uint32_t nFlags) + bool Archive::SetPackAccessible(bool bAccessible, AZStd::string_view pName) { auto szZipPath = AZ::IO::FileIOBase::GetDirectInstance()->ResolvePath(pName); if (!szZipPath) { - AZ_Assert(false, "Unable to resolve path for filepath %.*s", aznumeric_cast(pName.size()), pName.data()); + AZ_Assert(false, "Unable to resolve path for filepath %.*s", AZ_STRING_ARG(pName)); return false; } AZStd::unique_lock lock(m_csZips); for (auto it = m_arrZips.begin(); it != m_arrZips.end(); ++it) { - if (!azstricmp(szZipPath->c_str(), it->GetFullPath())) + if (szZipPath == it->GetFullPath()) { return it->pArchive->SetPackAccessible(bAccessible); } diff --git a/Code/Framework/AzFramework/AzFramework/Archive/Archive.h b/Code/Framework/AzFramework/AzFramework/Archive/Archive.h index ec964f7fa3..f08d90a66e 100644 --- a/Code/Framework/AzFramework/AzFramework/Archive/Archive.h +++ b/Code/Framework/AzFramework/AzFramework/Archive/Archive.h @@ -19,6 +19,7 @@ #include #include #include +#include #include #include #include @@ -26,7 +27,6 @@ #include #include #include -#include #include #include @@ -115,12 +115,12 @@ namespace AZ::IO struct PackDesc { AZ::IO::Path m_pathBindRoot; // the zip binding root - AZStd::string strFileName; // the zip file name (with path) - very useful for debugging so please don't remove + AZ::IO::Path m_strFileName; // the zip file name (with path) - very useful for debugging so please don't remove // [LYN-2376] Remove once legacy slice support is removed bool m_containsLevelPak = false; // indicates whether this archive has level.pak inside it or not - const char* GetFullPath() const { return pZip->GetFilePath(); } + AZ::IO::PathView GetFullPath() const { return pZip->GetFilePath(); } AZStd::intrusive_ptr pArchive; ZipDir::CachePtr pZip; @@ -129,10 +129,7 @@ namespace AZ::IO // ArchiveFindDataSet entire purpose is to keep a reference to the intrusive_ptr of ArchiveFindData // so that it doesn't go out of scope - using ArchiveFindDataSet = AZStd::set, AZ::OSStdAllocator>; - - // given the source relative path, constructs the full path to the file according to the flags - const char* AdjustFileName(AZStd::string_view src, char* dst, size_t dstSize, uint32_t nFlags, bool skipMods = false) override; + using ArchiveFindDataSet = AZStd::set>; /** @@ -154,29 +151,17 @@ namespace AZ::IO //! CompressionBus Handler implementation. void FindCompressionInfo(bool& found, AZ::IO::CompressionInfo& info, const AZStd::string_view filename) override; - //! Processes an alias command line containing multiple aliases. - void ParseAliases(AZStd::string_view szCommandLine) override; - //! adds or removes an alias from the list - if bAdd set to false will remove it - void SetAlias(AZStd::string_view szName, AZStd::string_view szAlias, bool bAdd) override; - //! gets an alias from the list, if any exist. - //! if bReturnSame==true, it will return the input name if an alias doesn't exist. Otherwise returns nullptr - const char* GetAlias(AZStd::string_view szName, bool bReturnSame = true) override; - // Set the localization folder void SetLocalizationFolder(AZStd::string_view sLocalizationFolder) override; const char* GetLocalizationFolder() const override { return m_sLocalizationFolder.c_str(); } const char* GetLocalizationRoot() const override { return m_sLocalizationRoot.c_str(); } - // lock all the operations - void Lock() override; - void Unlock() override; - // open the physical archive file - creates if it doesn't exist // returns nullptr if it's invalid or can't open the file - AZStd::intrusive_ptr OpenArchive(AZStd::string_view szPath, AZStd::string_view bindRoot = {}, uint32_t nFlags = 0, AZStd::intrusive_ptr pData = nullptr) override; + AZStd::intrusive_ptr OpenArchive(AZStd::string_view szPath, AZStd::string_view bindRoot = {}, uint32_t nArchiveFlags = 0, AZStd::intrusive_ptr pData = nullptr) override; // returns the path to the archive in which the file was opened - const char* GetFileArchivePath(AZ::IO::HandleType fileHandle) override; + AZ::IO::PathView GetFileArchivePath(AZ::IO::HandleType fileHandle) override; ////////////////////////////////////////////////////////////////////////// @@ -192,40 +177,31 @@ namespace AZ::IO void RegisterFileAccessSink(IArchiveFileAccessSink* pSink) override; void UnregisterFileAccessSink(IArchiveFileAccessSink* pSink) override; - bool Init(AZStd::string_view szBasePath) override; - void Release() override; - - bool IsInstalledToHDD(AZStd::string_view acFilePath = 0) const override; - // [LYN-2376] Remove 'addLevels' parameter once legacy slice support is removed - bool OpenPack(AZStd::string_view pName, uint32_t nFlags = 0, AZStd::intrusive_ptr pData = nullptr, AZ::IO::FixedMaxPathString* pFullPath = nullptr, bool addLevels = true) override; - bool OpenPack(AZStd::string_view szBindRoot, AZStd::string_view pName, uint32_t nFlags = 0, AZStd::intrusive_ptr pData = nullptr, AZ::IO::FixedMaxPathString* pFullPath = nullptr, bool addLevels = true) override; + bool OpenPack(AZStd::string_view pName, AZStd::intrusive_ptr pData = nullptr, AZ::IO::FixedMaxPathString* pFullPath = nullptr, bool addLevels = true) override; + bool OpenPack(AZStd::string_view szBindRoot, AZStd::string_view pName, AZStd::intrusive_ptr pData = nullptr, AZ::IO::FixedMaxPathString* pFullPath = nullptr, bool addLevels = true) override; // after this call, the file will be unlocked and closed, and its contents won't be used to search for files - bool ClosePack(AZStd::string_view pName, uint32_t nFlags = 0) override; - bool OpenPacks(AZStd::string_view pWildcard, uint32_t nFlags = 0, AZStd::vector* pFullPaths = nullptr) override; - bool OpenPacks(AZStd::string_view szBindRoot, AZStd::string_view pWildcard, uint32_t nFlags = 0, AZStd::vector* pFullPaths = nullptr) override; + bool ClosePack(AZStd::string_view pName) override; + bool OpenPacks(AZStd::string_view pWildcard, AZStd::vector* pFullPaths = nullptr) override; + bool OpenPacks(AZStd::string_view szBindRoot, AZStd::string_view pWildcard, AZStd::vector* pFullPaths = nullptr) override; // closes pack files by the path and wildcard - bool ClosePacks(AZStd::string_view pWildcard, uint32_t nFlags = 0) override; + bool ClosePacks(AZStd::string_view pWildcard) override; //returns if a archive exists matching the wildcard bool FindPacks(AZStd::string_view pWildcardIn) override; // prevent access to specific archive files - bool SetPacksAccessible(bool bAccessible, AZStd::string_view pWildcard, uint32_t nFlags = 0) override; - bool SetPackAccessible(bool bAccessible, AZStd::string_view pName, uint32_t nFlags = 0) override; + bool SetPacksAccessible(bool bAccessible, AZStd::string_view pWildcard) override; + bool SetPackAccessible(bool bAccessible, AZStd::string_view pName) override; // returns the file modification time uint64_t GetModificationTime(AZ::IO::HandleType fileHandle) override; - bool LoadPakToMemory(AZStd::string_view pName, EInMemoryArchiveLocation nLoadArchiveToMemory, AZStd::intrusive_ptr pMemoryBlock = nullptr) override; - void LoadPaksToMemory(int nMaxArchiveSize, bool bLoadToMemory) override; - - AZ::IO::HandleType FOpen(AZStd::string_view pName, const char* mode, uint32_t nPathFlags = 0) override; - size_t FReadRaw(void* data, size_t length, size_t elems, AZ::IO::HandleType handle) override; - size_t FReadRawAll(void* data, size_t nFileSize, AZ::IO::HandleType handle) override; + AZ::IO::HandleType FOpen(AZStd::string_view pName, const char* mode) override; + size_t FRead(void* data, size_t bytesToRead, AZ::IO::HandleType handle) override; void* FGetCachedFileData(AZ::IO::HandleType handle, size_t& nFileSize) override; - size_t FWrite(const void* data, size_t length, size_t elems, AZ::IO::HandleType handle) override; + size_t FWrite(const void* data, size_t bytesToWrite, AZ::IO::HandleType handle) override; size_t FSeek(AZ::IO::HandleType handle, uint64_t seek, int mode) override; uint64_t FTell(AZ::IO::HandleType handle) override; int FFlush(AZ::IO::HandleType handle) override; @@ -234,9 +210,7 @@ namespace AZ::IO AZ::IO::ArchiveFileIterator FindNext(AZ::IO::ArchiveFileIterator fileIterator) override; bool FindClose(AZ::IO::ArchiveFileIterator fileIterator) override; int FEof(AZ::IO::HandleType handle) override; - char* FGets(char*, int, AZ::IO::HandleType) override; - int Getc(AZ::IO::HandleType) override; - int FPrintf(AZ::IO::HandleType handle, const char* format, ...) override; + size_t FGetSize(AZ::IO::HandleType fileHandle) override; size_t FGetSize(AZStd::string_view sFilename, bool bAllowUseFileSystem = false) override; bool IsInPak(AZ::IO::HandleType handle) override; @@ -248,9 +222,6 @@ namespace AZ::IO bool IsFolder(AZStd::string_view sPath) override; IArchive::SignedFileSize GetFileSizeOnDisk(AZStd::string_view filename) override; - // creates a directory - bool MakeDir(AZStd::string_view szPath) override; - // compresses the raw data into raw data. The buffer for compressed data itself with the heap passed. Uses method 8 (deflate) // returns one of the Z_* errors (Z_OK upon success) // MT-safe @@ -275,22 +246,12 @@ namespace AZ::IO IResourceList* GetResourceList(ERecordFileOpenList eList) override; void SetResourceList(ERecordFileOpenList eList, IResourceList* pResourceList) override; - uint32_t ComputeCRC(AZStd::string_view szPath, uint32_t nFileOpenFlags = 0) override; - bool ComputeMD5(AZStd::string_view szPath, uint8_t* md5, uint32_t nFileOpenFlags = 0, bool useDirectFileAccess = false) override; - void DisableRuntimeFileAccess(bool status) override { - m_disableRuntimeFileAccess[0] = status; - m_disableRuntimeFileAccess[1] = status; + m_disableRuntimeFileAccess = status; } bool DisableRuntimeFileAccess(bool status, AZStd::thread_id threadId) override; - bool CheckFileAccessDisabled(AZStd::string_view name, const char* mode) override; - - void SetRenderThreadId(AZStd::thread_id renderThreadId) override - { - m_renderThreadId = renderThreadId; - } // gets the current archive priority ArchiveLocationPriority GetPakPriority() const override; @@ -307,11 +268,11 @@ namespace AZ::IO // Return cached file data for entries inside archive file. CCachedFileDataPtr GetOpenedFileDataInZip(AZ::IO::HandleType file); ZipDir::FileEntry* FindPakFileEntry(AZStd::string_view szPath, uint32_t& nArchiveFlags, - ZipDir::CachePtr* pZip = {}, bool bSkipInMemoryArchives = {}) const; + ZipDir::CachePtr* pZip = {}) const; private: - bool OpenPackCommon(AZStd::string_view szBindRoot, AZStd::string_view pName, uint32_t nArchiveFlags, AZStd::intrusive_ptr pData = nullptr, bool addLevels = true); - bool OpenPacksCommon(AZStd::string_view szDir, AZStd::string_view pWildcardIn, uint32_t nArchiveFlags, AZStd::vector* pFullPaths = nullptr, bool addLevels = true); + bool OpenPackCommon(AZStd::string_view szBindRoot, AZStd::string_view pName, AZStd::intrusive_ptr pData = nullptr, bool addLevels = true); + bool OpenPacksCommon(AZStd::string_view szDir, AZStd::string_view pWildcardIn, AZStd::vector* pFullPaths = nullptr, bool addLevels = true); ZipDir::FileEntry* FindPakFileEntry(AZStd::string_view szPath) const; @@ -346,9 +307,6 @@ namespace AZ::IO AZStd::mutex m_cachedFileRawDataMutex; // For m_pCachedFileRawDataSet using RawDataCacheLockGuard = AZStd::scoped_lock; - // The F* emulation functions critical section: protects all F* functions - // that don't have a chance to be called recursively (to avoid deadlocks) - AZStd::mutex m_csMain; mutable AZStd::shared_mutex m_archiveMutex; ArchiveArray m_arrArchives; @@ -360,8 +318,6 @@ namespace AZ::IO ////////////////////////////////////////////////////////////////////////// IArchive::ERecordFileOpenList m_eRecordFileOpenList = RFOM_Disabled; - using RecordedFilesSet = AZStd::set; - RecordedFilesSet m_recordedFilesSet; AZStd::intrusive_ptr m_pEngineStartupResourceList; @@ -372,28 +328,16 @@ namespace AZ::IO float m_fFileAccessTime{}; // Time used to perform file operations AZStd::vector m_FileAccessSinks; // useful for gathering file access statistics - bool m_disableRuntimeFileAccess[2]{}; + bool m_disableRuntimeFileAccess{}; //threads which we don't want to access files from during the game AZStd::thread_id m_mainThreadId{}; - AZStd::thread_id m_renderThreadId{}; AZStd::fixed_string<128> m_sLocalizationFolder; AZStd::fixed_string<128> m_sLocalizationRoot; - AZStd::set, AZ::OSStdAllocator> m_filesCachedOnHDD; - // [LYN-2376] Remove once legacy slice support is removed LevelPackOpenEvent m_levelOpenEvent; LevelPackCloseEvent m_levelCloseEvent; }; } - -namespace AZ::IO::ArchiveInternal -{ - // Utility function to de-alias archive file opening and file-within-archive opening - // if the file specified was an absolute path but it points at one of the aliases, de-alias it and replace it with that alias. - // this works around problems where the level editor is in control but still mounts asset packs (ie, level.pak mounted as @assets@) - AZStd::optional ConvertAbsolutePathToAliasedPath(AZStd::string_view sourcePath, - AZStd::string_view aliasToLookFor = "@devassets@", AZStd::string_view aliasToReplaceWith = "@assets@"); -} diff --git a/Code/Framework/AzFramework/AzFramework/Archive/ArchiveFileIO.cpp b/Code/Framework/AzFramework/AzFramework/Archive/ArchiveFileIO.cpp index 55f7640785..85ce0b6f9a 100644 --- a/Code/Framework/AzFramework/AzFramework/Archive/ArchiveFileIO.cpp +++ b/Code/Framework/AzFramework/AzFramework/Archive/ArchiveFileIO.cpp @@ -5,10 +5,9 @@ * SPDX-License-Identifier: Apache-2.0 OR MIT * */ -#include +#include #include #include // for function<> in the find files callback. -#include #include #include @@ -188,7 +187,7 @@ namespace AZ::IO return IO::ResultCode::Error; } - size_t result = m_archive->FReadRaw(buffer, 1, size, fileHandle); + size_t result = m_archive->FRead(buffer, size, fileHandle); if (bytesRead) { *bytesRead = static_cast(result); @@ -213,7 +212,7 @@ namespace AZ::IO return IO::ResultCode::Error; } - size_t result = m_archive->FWrite(buffer, 1, size, fileHandle); + size_t result = m_archive->FWrite(buffer, size, fileHandle); if (bytesWritten) { *bytesWritten = static_cast(result); @@ -357,14 +356,8 @@ namespace AZ::IO return IO::ResultCode::Error; } - // avoid using AZStd::string if possible - use OSString instead of StringFunc - AZ::OSString destPath(destinationFilePath); + IO::Path destPath(IO::PathView(destinationFilePath).ParentPath()); - AZ::OSString::size_type pos = destPath.find_last_of(AZ_CORRECT_AND_WRONG_FILESYSTEM_SEPARATOR); - if (pos != AZ::OSString::npos) - { - destPath.resize(pos); - } CreatePath(destPath.c_str()); if (!Open(destinationFilePath, IO::OpenMode::ModeWrite | IO::OpenMode::ModeBinary, destinationFile)) @@ -466,31 +459,25 @@ namespace AZ::IO return IO::ResultCode::Error; } - AZStd::fixed_string total = filePath; + AZ::IO::FixedMaxPath total = filePath; if (total.empty()) { return IO::ResultCode::Error; } - if (!total.ends_with(AZ_CORRECT_FILESYSTEM_SEPARATOR) && !total.ends_with(AZ_WRONG_FILESYSTEM_SEPARATOR)) - { - total.append(AZ_CORRECT_FILESYSTEM_SEPARATOR_STRING); - } - - total.append(filter); + total /= filter; AZ::IO::ArchiveFileIterator fileIterator = m_archive->FindFirst(total.c_str()); if (!fileIterator) { return IO::ResultCode::Success; // its not an actual fatal error to not find anything. } - for (;fileIterator; fileIterator = m_archive->FindNext(fileIterator)) + for (; fileIterator; fileIterator = m_archive->FindNext(fileIterator)) { - total = AZStd::fixed_string::format("%s/%.*s", filePath, aznumeric_cast(fileIterator.m_filename.size()), fileIterator.m_filename.data()); - AZStd::optional resolvedAliasLength = ConvertToAlias(total.data(), total.capacity()); - if (resolvedAliasLength) + total = filePath; + total /= fileIterator.m_filename; + if (ConvertToAlias(total, total)) { - total.resize_no_construct(*resolvedAliasLength); if (!callback(total.c_str())) { break; @@ -510,8 +497,13 @@ namespace AZ::IO const auto fileIt = m_trackedFiles.find(fileHandle); if (fileIt != m_trackedFiles.end()) { - AZ_Assert(filenameSize >= fileIt->second.length(), "Filename size %" PRIu64 " is larger than the size of the tracked file %s:%zu", fileIt->second.c_str(), fileIt->second.size()); - azstrncpy(filename, filenameSize, fileIt->second.c_str(), fileIt->second.length()); + const AZStd::string_view trackedFileView = fileIt->second.Native(); + if (filenameSize <= trackedFileView.size()) + { + return false; + } + size_t trackedFileViewLength = trackedFileView.copy(filename, trackedFileView.size()); + filename[trackedFileViewLength] = '\0'; return true; } diff --git a/Code/Framework/AzFramework/AzFramework/Archive/ArchiveFileIO.h b/Code/Framework/AzFramework/AzFramework/Archive/ArchiveFileIO.h index c99fbb14c5..21cef18a7a 100644 --- a/Code/Framework/AzFramework/AzFramework/Archive/ArchiveFileIO.h +++ b/Code/Framework/AzFramework/AzFramework/Archive/ArchiveFileIO.h @@ -13,7 +13,6 @@ #include #include #include -#include namespace AZ::IO @@ -78,7 +77,7 @@ namespace AZ::IO protected: // we keep a list of file names ever opened so that we can easily return it. mutable AZStd::recursive_mutex m_operationGuard; - AZStd::unordered_map, AZStd::equal_to, AZ::OSStdAllocator> m_trackedFiles; + AZStd::unordered_map m_trackedFiles; AZStd::fixed_vector m_copyBuffer; IArchive* m_archive; }; diff --git a/Code/Framework/AzFramework/AzFramework/Archive/ArchiveFindData.cpp b/Code/Framework/AzFramework/AzFramework/Archive/ArchiveFindData.cpp index c4c845a832..d7a92efbf6 100644 --- a/Code/Framework/AzFramework/AzFramework/Archive/ArchiveFindData.cpp +++ b/Code/Framework/AzFramework/AzFramework/Archive/ArchiveFindData.cpp @@ -15,34 +15,6 @@ namespace AZ::IO { - size_t ArchiveFileIteratorHash::operator()(const AZ::IO::ArchiveFileIterator& iter) const - { - return iter.GetHash(); - } - - bool AZStdStringLessCaseInsensitive::operator()(AZStd::string_view left, AZStd::string_view right) const - { - // If one or both strings are 0-length, return true if the left side is smaller, false if they're equal or left is larger. - size_t compareLength = (AZStd::min)(left.size(), right.size()); - if (compareLength == 0) - { - return left.size() < right.size(); - } - - // They're both non-zero, so compare the strings up until the length of the shorter string. - int compareResult = azstrnicmp(left.data(), right.data(), compareLength); - - // If both strings are equal for the number of characters compared, return true if the left side is shorter, false if - // they're equal or left is longer. - if (compareResult == 0) - { - return left.size() < right.size(); - } - - // Return true if the left side should come first alphabetically, false if the right side should. - return compareResult < 0; - } - FileDesc::FileDesc(Attribute fileAttribute, uint64_t fileSize, time_t accessTime, time_t creationTime, time_t writeTime) : nAttrib{ fileAttribute } , nSize{ fileSize } @@ -52,10 +24,9 @@ namespace AZ::IO { } - ArchiveFileIterator::ArchiveFileIterator(FindData* findData, AZStd::string_view filename, const FileDesc& fileDesc) + // ArchiveFileIterator + ArchiveFileIterator::ArchiveFileIterator(FindData* findData) : m_findData{ findData } - , m_filename{ filename } - , m_fileDesc{ fileDesc } { } @@ -73,21 +44,36 @@ namespace AZ::IO return operator++(); } - bool ArchiveFileIterator::operator==(const AZ::IO::ArchiveFileIterator& rhs) const - { - return GetHash() == rhs.GetHash(); - } ArchiveFileIterator::operator bool() const { return m_findData && m_lastFetchValid; } - size_t ArchiveFileIterator::GetHash() const + // FindData::ArchiveFile + FindData::ArchiveFile::ArchiveFile() = default; + FindData::ArchiveFile::ArchiveFile(AZStd::string_view filename, const FileDesc& fileDesc) + : m_filename(filename) + , m_fileDesc(fileDesc) + { + } + size_t FindData::ArchiveFile::GetHash() const { return AZStd::hash{}(m_filename.c_str()); } + bool FindData::ArchiveFile::operator==(const ArchiveFile& rhs) const + { + return GetHash() == rhs.GetHash(); + } + + // FindData::ArchiveFilehash + size_t FindData::ArchiveFileHash::operator()(const ArchiveFile& archiveFile) const + { + return archiveFile.GetHash(); + } + + // FindData void FindData::Scan(IArchive* archive, AZStd::string_view szDir, bool bAllowUseFS, bool bScanZips) { // get the priority into local variable to avoid it changing in the course of @@ -119,40 +105,37 @@ namespace AZ::IO void FindData::ScanFS([[maybe_unused]] IArchive* archive, AZStd::string_view szDirIn) { - AZStd::string searchDirectory; - AZStd::string pattern; + AZ::IO::PathView directory{ szDirIn }; + AZ::IO::FixedMaxPath searchDirectory = directory.ParentPath(); + AZ::IO::FixedMaxPath pattern = directory.Filename(); + auto ScanFileSystem = [this](const char* filePath) -> bool { - AZ::IO::PathString directory{ szDirIn }; - AZ::StringFunc::Path::GetFullPath(directory.c_str(), searchDirectory); - AZ::StringFunc::Path::GetFullFileName(directory.c_str(), pattern); - } - AZ::IO::FileIOBase::GetDirectInstance()->FindFiles(searchDirectory.c_str(), pattern.c_str(), [&](const char* filePath) -> bool - { - AZ::IO::ArchiveFileIterator fileIterator{ nullptr, AZ::IO::PathView(filePath).Filename().Native(), {} }; + ArchiveFile archiveFile{ AZ::IO::PathView(filePath).Filename().Native(), {} }; if (AZ::IO::FileIOBase::GetDirectInstance()->IsDirectory(filePath)) { - fileIterator.m_fileDesc.nAttrib = fileIterator.m_fileDesc.nAttrib | AZ::IO::FileDesc::Attribute::Subdirectory; - m_fileSet.emplace(AZStd::move(fileIterator)); + archiveFile.m_fileDesc.nAttrib = archiveFile.m_fileDesc.nAttrib | AZ::IO::FileDesc::Attribute::Subdirectory; + m_fileSet.emplace(AZStd::move(archiveFile)); } else { if (AZ::IO::FileIOBase::GetDirectInstance()->IsReadOnly(filePath)) { - fileIterator.m_fileDesc.nAttrib = fileIterator.m_fileDesc.nAttrib | AZ::IO::FileDesc::Attribute::ReadOnly; + archiveFile.m_fileDesc.nAttrib = archiveFile.m_fileDesc.nAttrib | AZ::IO::FileDesc::Attribute::ReadOnly; } AZ::u64 fileSize = 0; AZ::IO::FileIOBase::GetDirectInstance()->Size(filePath, fileSize); - fileIterator.m_fileDesc.nSize = fileSize; - fileIterator.m_fileDesc.tWrite = AZ::IO::FileIOBase::GetDirectInstance()->ModificationTime(filePath); + archiveFile.m_fileDesc.nSize = fileSize; + archiveFile.m_fileDesc.tWrite = AZ::IO::FileIOBase::GetDirectInstance()->ModificationTime(filePath); // These times are not supported by our file interface - fileIterator.m_fileDesc.tAccess = fileIterator.m_fileDesc.tWrite; - fileIterator.m_fileDesc.tCreate = fileIterator.m_fileDesc.tWrite; - m_fileSet.emplace(AZStd::move(fileIterator)); + archiveFile.m_fileDesc.tAccess = archiveFile.m_fileDesc.tWrite; + archiveFile.m_fileDesc.tCreate = archiveFile.m_fileDesc.tWrite; + m_fileSet.emplace(AZStd::move(archiveFile)); } return true; - }); + }; + AZ::IO::FileIOBase::GetDirectInstance()->FindFiles(searchDirectory.c_str(), pattern.c_str(), ScanFileSystem); } ////////////////////////////////////////////////////////////////////////// @@ -180,7 +163,7 @@ namespace AZ::IO fileDesc.nAttrib = AZ::IO::FileDesc::Attribute::ReadOnly | AZ::IO::FileDesc::Attribute::Archive; fileDesc.nSize = fileEntry->desc.lSizeUncompressed; fileDesc.tWrite = fileEntry->GetModificationTime(); - m_fileSet.emplace(AZ::IO::ArchiveFileIterator{ this, fname, fileDesc }); + m_fileSet.emplace(fname, fileDesc); } ZipDir::FindDir findDirectoryEntry(zipCache); @@ -193,7 +176,7 @@ namespace AZ::IO } AZ::IO::FileDesc fileDesc; fileDesc.nAttrib = AZ::IO::FileDesc::Attribute::ReadOnly | AZ::IO::FileDesc::Attribute::Archive | AZ::IO::FileDesc::Attribute::Subdirectory; - m_fileSet.emplace(AZ::IO::ArchiveFileIterator{ this, fname, fileDesc }); + m_fileSet.emplace(fname, fileDesc); } }; @@ -208,30 +191,16 @@ namespace AZ::IO // so there's really no way to filter out opening the pack and looking at the files inside. // however, the bind root is not part of the inner zip entry name either // and the ZipDir::FindFile actually expects just the chopped off piece. - // we have to find whats in common between them and check that: + // we have to find the common path segments between them and check that: - auto resolvedBindRoot = AZ::IO::FileIOBase::GetDirectInstance()->ResolvePath(it->m_pathBindRoot); - if (!resolvedBindRoot) + AZ::IO::FixedMaxPath bindRoot; + if (!AZ::IO::FileIOBase::GetDirectInstance()->ResolvePath(bindRoot, it->m_pathBindRoot)) { AZ_Assert(false, "Unable to resolve Path for archive %s bind root %s", it->GetFullPath(), it->m_pathBindRoot.c_str()); return; } - AZ::IO::FixedMaxPath bindRoot{ *resolvedBindRoot }; - auto [bindRootIter, sourcePathIter] = AZStd::mismatch(AZStd::begin(bindRoot), AZStd::end(bindRoot), - AZStd::begin(sourcePath), AZStd::end(sourcePath)); - if (sourcePathIter == AZStd::begin(sourcePath)) - { - // The path has no characters in common , early out the search as filepath is not part of the iterated zip - continue; - } - - AZ::IO::FixedMaxPath sourcePathRemainder; - for (; sourcePathIter != AZStd::end(sourcePath); ++sourcePathIter) - { - sourcePathRemainder /= *sourcePathIter; - } // Example: // "@assets@\\levels\\*" <--- szDir // "@assets@\\" <--- mount point @@ -256,18 +225,26 @@ namespace AZ::IO // then it means that the pack's mount point itself might be a return value, not the files inside the pack // in that case, we compare the mount point remainder itself with the search filter + auto [bindRootIter, sourcePathIter] = AZStd::mismatch(bindRoot.begin(), bindRoot.end(), + sourcePath.begin(), sourcePath.end()); if (bindRootIter != bindRoot.end()) { + AZ::IO::FixedMaxPath sourcePathRemainder; + for (; sourcePathIter != sourcePath.end(); ++sourcePathIter) + { + sourcePathRemainder /= *sourcePathIter; + } + // Retrieve next path component of the mount point remainder - if (!bindRootIter->empty() && AZStd::wildcard_match(sourcePathRemainder.Native(), bindRootIter->Native())) + if (!bindRootIter->empty() && bindRootIter->Match(sourcePathRemainder.Native())) { AZ::IO::FileDesc fileDesc{ AZ::IO::FileDesc::Attribute::ReadOnly | AZ::IO::FileDesc::Attribute::Archive | AZ::IO::FileDesc::Attribute::Subdirectory }; - m_fileSet.emplace(AZ::IO::ArchiveFileIterator{ this, bindRootIter->Native(), fileDesc }); + m_fileSet.emplace(AZStd::move(bindRootIter->Native()), fileDesc); } } else { - + AZ::IO::FixedMaxPath sourcePathRemainder = sourcePath.LexicallyRelative(bindRoot); // if we get here, it means that the search pattern's root and the mount point for this pack are identical // which means we may search inside the pack. ScanInZip(it->pZip.get(), sourcePathRemainder.Native()); @@ -280,17 +257,17 @@ namespace AZ::IO { if (m_fileSet.empty()) { - AZ::IO::ArchiveFileIterator emptyFileIterator; - emptyFileIterator.m_lastFetchValid = false; - emptyFileIterator.m_findData = this; - return emptyFileIterator; + return {}; } // Remove Fetched item from the FindData map so that the iteration continues - AZ::IO::ArchiveFileIterator fileIterator{ *m_fileSet.begin() }; + AZ::IO::ArchiveFileIterator fileIterator; + auto archiveFileIt = m_fileSet.begin(); + fileIterator.m_filename = archiveFileIt->m_filename; + fileIterator.m_fileDesc = archiveFileIt->m_fileDesc; fileIterator.m_lastFetchValid = true; fileIterator.m_findData = this; - m_fileSet.erase(m_fileSet.begin()); + m_fileSet.erase(archiveFileIt); return fileIterator; } } diff --git a/Code/Framework/AzFramework/AzFramework/Archive/ArchiveFindData.h b/Code/Framework/AzFramework/AzFramework/Archive/ArchiveFindData.h index 12544d124d..ebdbf45626 100644 --- a/Code/Framework/AzFramework/AzFramework/Archive/ArchiveFindData.h +++ b/Code/Framework/AzFramework/AzFramework/Archive/ArchiveFindData.h @@ -36,56 +36,72 @@ namespace AZ::IO AZ_DEFINE_ENUM_BITWISE_OPERATORS(AZ::IO::FileDesc::Attribute); + inline constexpr size_t ArchiveFilenameMaxLength = 256; + using ArchiveFileString = AZStd::fixed_string; + class FindData; + //! This is not really an iterator, but a handle + //! that extends ownership of any found filenames from an archive file or the file system struct ArchiveFileIterator { ArchiveFileIterator() = default; - ArchiveFileIterator(FindData* findData, AZStd::string_view filename, const FileDesc& fileDesc); + explicit ArchiveFileIterator(FindData* findData); ArchiveFileIterator operator++(); ArchiveFileIterator operator++(int); - bool operator==(const AZ::IO::ArchiveFileIterator& rhs) const; - explicit operator bool() const; - size_t GetHash() const; - - inline static constexpr size_t FilenameMaxLength = 256; - AZStd::fixed_string m_filename; + ArchiveFileString m_filename; FileDesc m_fileDesc; - AZStd::intrusive_ptr m_findData{}; private: friend class FindData; + friend class Archive; + AZStd::intrusive_ptr m_findData; bool m_lastFetchValid{}; }; - struct ArchiveFileIteratorHash - { - size_t operator()(const AZ::IO::ArchiveFileIterator& iter) const; - }; - struct AZStdStringLessCaseInsensitive - { - bool operator()(AZStd::string_view left, AZStd::string_view right) const; - - using is_transparent = void; - }; class FindData : public AZStd::intrusive_base { public: AZ_CLASS_ALLOCATOR(FindData, AZ::SystemAllocator, 0); FindData() = default; - AZ::IO::ArchiveFileIterator Fetch(); + ArchiveFileIterator Fetch(); void Scan(IArchive* archive, AZStd::string_view path, bool bAllowUseFS = false, bool bScanZips = true); protected: void ScanFS(IArchive* archive, AZStd::string_view path); + // Populates the FileSet with files within the that match the path pattern that is + // if it refers to a file within a bound archive root or returns the archive root + // path if the path pattern matches it. void ScanZips(IArchive* archive, AZStd::string_view path); - using FileSet = AZStd::unordered_set; + class ArchiveFile + { + public: + friend class FindData; + + ArchiveFile(); + ArchiveFile(AZStd::string_view filename, const FileDesc& fileDesc); + + size_t GetHash() const; + bool operator==(const ArchiveFile& rhs) const; + + private: + ArchiveFileString m_filename; + FileDesc m_fileDesc; + }; + + struct ArchiveFileHash + { + size_t operator()(const ArchiveFile& archiveFile) const; + }; + + using FileSet = AZStd::unordered_set; FileSet m_fileSet; }; + } diff --git a/Code/Framework/AzFramework/AzFramework/Archive/IArchive.h b/Code/Framework/AzFramework/AzFramework/Archive/IArchive.h index 5ac417564a..bd9615110a 100644 --- a/Code/Framework/AzFramework/AzFramework/Archive/IArchive.h +++ b/Code/Framework/AzFramework/AzFramework/Archive/IArchive.h @@ -12,12 +12,10 @@ #include #include #include -#include #include #include #include #include -#include #include @@ -106,66 +104,6 @@ namespace AZ::IO { AZ_RTTI(IArchive, "{764A2260-FF8A-4C86-B958-EBB0B69D9DFA}"); using FileTime = uint64_t; - // Flags used in file path resolution rules - enum EPathResolutionRules - { - // If used, the source path will be treated as the destination path - // and no transformations will be done. Pass this flag when the path is to be the actual - // path on the disk/in the packs and doesn't need adjustment (or after it has come through adjustments already) - // if this is set, AdjustFileName will not map the input path into the folder (Ex: Shaders will not be converted to Game\Shaders) - FLAGS_PATH_REAL = 1 << 16, - - // AdjustFileName will always copy the file path to the destination path: - // regardless of the returned value, szDestpath can be used - FLAGS_COPY_DEST_ALWAYS = 1 << 17, - - // Adds trailing slash to the path - FLAGS_ADD_TRAILING_SLASH = 1L << 18, - - // if this is set, AdjustFileName will not make relative paths into full paths - FLAGS_NO_FULL_PATH = 1 << 21, - - // if this is set, AdjustFileName will redirect path to disc - FLAGS_REDIRECT_TO_DISC = 1 << 22, - - // if this is set, AdjustFileName will not adjust path for writing files - FLAGS_FOR_WRITING = 1 << 23, - - // if this is set, the archive would be stored in memory (gpu) - FLAGS_PAK_IN_MEMORY = 1 << 25, - - // Store all file names as crc32 in a flat directory structure. - FLAGS_FILENAMES_AS_CRC32 = 1 << 26, - - // if this is set, AdjustFileName will try to find the file under any mod paths we know about - FLAGS_CHECK_MOD_PATHS = 1 << 27, - - // if this is set, AdjustFileName will always check the filesystem/disk and not check inside open archives - FLAGS_NEVER_IN_PAK = 1 << 28, - - // returns existing file name from the local data or existing cache file name - // used by the resource compiler to pass the real file name - FLAGS_RESOLVE_TO_CACHE = 1 << 29, - - // if this is set, the archive would be stored in memory (cpu) - FLAGS_PAK_IN_MEMORY_CPU = 1 << 30, - - // if this is set, the level pak is inside another archive - FLAGS_LEVEL_PAK_INSIDE_PAK = 1 << 31, - }; - - // Used for widening FOpen functionality. They're ignored for the regular File System files. - enum EFOpenFlags - { - // If possible, will prevent the file from being read from memory. - FOPEN_HINT_DIRECT_OPERATION = 1, - // Will prevent a "missing file" warnings to be created. - FOPEN_HINT_QUIET = 1 << 1, - // File should be on disk - FOPEN_ONDISK = 1 << 2, - // Open is done by the streaming thread. - FOPEN_FORSTREAMING = 1 << 3, - }; // enum ERecordFileOpenList @@ -175,8 +113,6 @@ namespace AZ::IO RFOM_Level, // during level loading till export2game -> resourcelist.txt, used to generate the list for level2level loading RFOM_NextLevel // used for level2level loading }; - // the size of the buffer that receives the full path to the file - inline static constexpr size_t MaxPath = 1024; //file location enum used in isFileExist to control where the archive system looks for the file. enum EFileSearchLocation @@ -205,63 +141,31 @@ namespace AZ::IO virtual ~IArchive() = default; - /** - * Deprecated: Use the AZ::IO::FileIOBase::ResolvePath function below that doesn't accept the nFlags or skipMods parameters - * given the source relative path, constructs the full path to the file according to the flags - * returns the pointer to the constructed path (can be either szSourcePath, or szDestPath, or NULL in case of error - */ - // - virtual const char* AdjustFileName(AZStd::string_view src, char* dst, size_t dstSize, uint32_t nFlags, bool skipMods = false) = 0; - - virtual bool Init(AZStd::string_view szBasePath) = 0; - virtual void Release() = 0; - - // Summary: - // Returns true if given archivepath is installed to HDD - // If no file path is given it will return true if whole application is installed to HDD - virtual bool IsInstalledToHDD(AZStd::string_view acFilePath = 0) const = 0; - // after this call, the archive file will be searched for files when they aren't on the OS file system // Arguments: // pName - must not be 0 - virtual bool OpenPack(AZStd::string_view pName, uint32_t nFlags = FLAGS_PATH_REAL, AZStd::intrusive_ptr pData = {}, + virtual bool OpenPack(AZStd::string_view pName, AZStd::intrusive_ptr pData = {}, AZ::IO::FixedMaxPathString* pFullPath = nullptr, bool addLevels = true) = 0; // after this call, the archive file will be searched for files when they aren't on the OS file system - virtual bool OpenPack(AZStd::string_view pBindingRoot, AZStd::string_view pName, uint32_t nFlags = FLAGS_PATH_REAL, + virtual bool OpenPack(AZStd::string_view pBindingRoot, AZStd::string_view pName, AZStd::intrusive_ptr pData = {}, AZ::IO::FixedMaxPathString* pFullPath = nullptr, bool addLevels = true) = 0; // after this call, the file will be unlocked and closed, and its contents won't be used to search for files - virtual bool ClosePack(AZStd::string_view pName, uint32_t nFlags = FLAGS_PATH_REAL) = 0; + virtual bool ClosePack(AZStd::string_view pName) = 0; // opens pack files by the path and wildcard - virtual bool OpenPacks(AZStd::string_view pWildcard, uint32_t nFlags = FLAGS_PATH_REAL, AZStd::vector* pFullPaths = nullptr) = 0; + virtual bool OpenPacks(AZStd::string_view pWildcard, AZStd::vector* pFullPaths = nullptr) = 0; // opens pack files by the path and wildcard - virtual bool OpenPacks(AZStd::string_view pBindingRoot, AZStd::string_view pWildcard, uint32_t nFlags = FLAGS_PATH_REAL, + virtual bool OpenPacks(AZStd::string_view pBindingRoot, AZStd::string_view pWildcard, AZStd::vector* pFullPaths = nullptr) = 0; // closes pack files by the path and wildcard - virtual bool ClosePacks(AZStd::string_view pWildcard, uint32_t nFlags = FLAGS_PATH_REAL) = 0; + virtual bool ClosePacks(AZStd::string_view pWildcard) = 0; //returns if a archive exists matching the wildcard virtual bool FindPacks(AZStd::string_view pWildcardIn) = 0; // Set access status of a archive files with a wildcard - virtual bool SetPacksAccessible(bool bAccessible, AZStd::string_view pWildcard, uint32_t nFlags = FLAGS_PATH_REAL) = 0; + virtual bool SetPacksAccessible(bool bAccessible, AZStd::string_view pWildcard) = 0; // Set access status of a pack file - virtual bool SetPackAccessible(bool bAccessible, AZStd::string_view pName, uint32_t nFlags = FLAGS_PATH_REAL) = 0; - - // Load or unload archive file completely to memory. - virtual bool LoadPakToMemory(AZStd::string_view pName, EInMemoryArchiveLocation eLoadToMemory, AZStd::intrusive_ptr pMemoryBlock = nullptr) = 0; - virtual void LoadPaksToMemory(int nMaxArchiveSize, bool bLoadToMemory) = 0; - - // Processes an alias command line containing multiple aliases. - virtual void ParseAliases(AZStd::string_view szCommandLine) = 0; - // adds or removes an alias from the list - virtual void SetAlias(AZStd::string_view szName, AZStd::string_view szAlias, bool bAdd) = 0; - // gets an alias from the list, if any exist. - // if bReturnSame==true, it will return the input name if an alias doesn't exist. Otherwise returns NULL - virtual const char* GetAlias(AZStd::string_view szName, bool bReturnSame = true) = 0; - - // lock all the operations - virtual void Lock() = 0; - virtual void Unlock() = 0; + virtual bool SetPackAccessible(bool bAccessible, AZStd::string_view pName) = 0; // Set and Get the localization folder name (Languages, Localization, ...) virtual void SetLocalizationFolder(AZStd::string_view sLocalizationFolder) = 0; @@ -273,28 +177,19 @@ namespace AZ::IO // ex: AZ::IO::HandleType fileHandle = FOpen( "test.txt","rbx" ); // mode x is a direct access mode, when used file reads will go directly into the low level file system without any internal data caching. // Text mode is not supported for files in Archives. - // for nFlags @see IArchive::EFOpenFlags - virtual AZ::IO::HandleType FOpen(AZStd::string_view pName, const char* mode, uint32_t nFlags = 0) = 0; - - // Read raw data from file, no endian conversion. - virtual size_t FReadRaw(void* data, size_t length, size_t elems, AZ::IO::HandleType fileHandle) = 0; - - // Read all file contents into the provided memory, nSizeOfFile must be the same as returned by GetFileSize(handle) - // Current seek pointer is ignored and reseted to 0. - // no endian conversion. - virtual size_t FReadRawAll(void* data, size_t nFileSize, AZ::IO::HandleType fileHandle) = 0; + virtual AZ::IO::HandleType FOpen(AZStd::string_view pName, const char* mode) = 0; // Get pointer to the internally cached, loaded data of the file. // WARNING! The returned pointer is only valid while the fileHandle has not been closed. virtual void* FGetCachedFileData(AZ::IO::HandleType fileHandle, size_t& nFileSize) = 0; - // Write file data, cannot be used for writing into the Archive. - // Use INestedArchive interface for writing into the archivefiles. - virtual size_t FWrite(const void* data, size_t length, size_t elems, AZ::IO::HandleType fileHandle) = 0; + // Read raw data from file, no endian conversion. + virtual size_t FRead(void* data, size_t bytesToRead, AZ::IO::HandleType fileHandle) = 0; + + // Write file data, cannot be used for writing into the Archive. + // Use INestedArchive interface for writing into the archive files. + virtual size_t FWrite(const void* data, size_t bytesToWrite, AZ::IO::HandleType fileHandle) = 0; - virtual int FPrintf(AZ::IO::HandleType fileHandle, const char* format, ...) = 0; - virtual char* FGets(char*, int, AZ::IO::HandleType) = 0; - virtual int Getc(AZ::IO::HandleType) = 0; virtual size_t FGetSize(AZ::IO::HandleType fileHandle) = 0; virtual size_t FGetSize(AZStd::string_view pName, bool bAllowUseFileSystem = false) = 0; virtual bool IsInPak(AZ::IO::HandleType fileHandle) = 0; @@ -318,7 +213,6 @@ namespace AZ::IO virtual AZStd::intrusive_ptr PoolAllocMemoryBlock(size_t nSize, const char* sUsage, size_t nAlign = 1) = 0; // Arguments: - // nFlags is a combination of EPathResolutionRules flags. virtual ArchiveFileIterator FindFirst(AZStd::string_view pDir, EFileSearchType searchType = eFileSearchType_AllowInZipsOnly) = 0; virtual ArchiveFileIterator FindNext(AZ::IO::ArchiveFileIterator handle) = 0; virtual bool FindClose(AZ::IO::ArchiveFileIterator handle) = 0; @@ -334,9 +228,6 @@ namespace AZ::IO virtual IArchive::SignedFileSize GetFileSizeOnDisk(AZStd::string_view filename) = 0; - // creates a directory - virtual bool MakeDir(AZStd::string_view szPath) = 0; - // open the physical archive file - creates if it doesn't exist // returns NULL if it's invalid or can't open the file // nFlags is a combination of flags from EArchiveFlags enum. @@ -344,8 +235,8 @@ namespace AZ::IO AZStd::intrusive_ptr pData = nullptr) = 0; // returns the path to the archive in which the file was opened - // returns NULL if the file is a physical file, and "" if the path to archive is unknown (shouldn't ever happen) - virtual const char* GetFileArchivePath(AZ::IO::HandleType fileHandle) = 0; + // returns empty path view if the file is a physical file + virtual AZ::IO::PathView GetFileArchivePath(AZ::IO::HandleType fileHandle) = 0; // compresses the raw data into raw data. The buffer for compressed data itself with the heap passed. Uses method 8 (deflate) // returns one of the Z_* errors (Z_OK upon success) @@ -378,25 +269,7 @@ namespace AZ::IO // get the current mode, can be set by RecordFileOpen() virtual IArchive::ERecordFileOpenList GetRecordFileOpenList() = 0; - // computes CRC (zip compatible) for a file - // useful if a huge uncompressed file is generation in non continuous way - // good for big files - low memory overhead (1MB) - // Arguments: - // szPath - must not be 0 - // Returns: - // error code - virtual uint32_t ComputeCRC(AZStd::string_view szPath, uint32_t nFileOpenFlags = 0) = 0; - - // computes MD5 checksum for a file - // good for big files - low memory overhead (1MB) - // Arguments: - // szPath - must not be 0 - // md5 - destination array of uint8_t [16] - // Returns: - // true if success, false on failure - virtual bool ComputeMD5(AZStd::string_view szPath, uint8_t* md5, uint32_t nFileOpenFlags = 0, bool useDirectFileAccess = false) = 0; - - // useful for gathering file access statistics, assert if it was inserted already but then it does not become insersted + // useful for gathering file access statistics, assert if it was inserted already but then it does not become inserted // Arguments: // pSink - must not be 0 virtual void RegisterFileAccessSink(IArchiveFileAccessSink* pSink) = 0; @@ -408,8 +281,6 @@ namespace AZ::IO // When enabled, files accessed at runtime will be tracked virtual void DisableRuntimeFileAccess(bool status) = 0; virtual bool DisableRuntimeFileAccess(bool status, AZStd::thread_id threadId) = 0; - virtual bool CheckFileAccessDisabled(AZStd::string_view name, const char* mode) = 0; - virtual void SetRenderThreadId(AZStd::thread_id renderThreadId) = 0; // gets the current pak priority virtual ArchiveLocationPriority GetPakPriority() const = 0; @@ -431,21 +302,6 @@ namespace AZ::IO using LevelPackCloseEvent = AZ::Event; virtual auto GetLevelPackCloseEvent()->LevelPackCloseEvent* = 0; - // Type-safe endian conversion read. - template - size_t FRead(T* data, size_t elems, AZ::IO::HandleType fileHandle, bool bSwapEndian = false) - { - size_t count = FReadRaw(data, sizeof(T), elems, fileHandle); - SwapEndian(data, count, bSwapEndian); - return count; - } - // Type-independent Write. - template - void FWrite(T* data, size_t elems, AZ::IO::HandleType fileHandle) - { - FWrite((void*)data, sizeof(T), elems, fileHandle); - } - inline static constexpr IArchive::SignedFileSize FILE_NOT_PRESENT = -1; }; diff --git a/Code/Framework/AzFramework/AzFramework/Archive/INestedArchive.h b/Code/Framework/AzFramework/AzFramework/Archive/INestedArchive.h index b45d705259..f85fd273ce 100644 --- a/Code/Framework/AzFramework/AzFramework/Archive/INestedArchive.h +++ b/Code/Framework/AzFramework/AzFramework/Archive/INestedArchive.h @@ -9,9 +9,9 @@ #pragma once +#include #include #include -#include #include namespace AZ::IO @@ -71,28 +71,10 @@ namespace AZ::IO // multiple times FLAGS_DONT_COMPACT = 1 << 5, - // flag is set when complete pak has been loaded into memory - FLAGS_IN_MEMORY = 1 << 6, - FLAGS_IN_MEMORY_CPU = 1 << 7, - FLAGS_IN_MEMORY_MASK = FLAGS_IN_MEMORY | FLAGS_IN_MEMORY_CPU, - - // Store all file names as crc32 in a flat directory structure. - FLAGS_FILENAMES_AS_CRC32 = 1 << 8, - - // flag is set when pak is stored on HDD - FLAGS_ON_HDD = 1 << 9, - - //Override pak - paks opened with this flag go at the end of the list and contents will be found before other paks - //Used for patching - FLAGS_OVERRIDE_PAK = 1 << 10, - // Disable a pak file without unloading it, this flag is used in combination with patches and multiplayer - // to ensure that specific paks stay in the position(to keep the same priority) but beeing disabled + // to ensure that specific paks stay in the position(to keep the same priority) but being disabled // when running multiplayer FLAGS_DISABLE_PAK = 1 << 11, - - // flag is set when pak is inside another pak - FLAGS_INSIDE_PAK = 1 << 12, }; using Handle = void*; @@ -122,7 +104,7 @@ namespace AZ::IO virtual int StartContinuousFileUpdate(AZStd::string_view szRelativePath, uint64_t nSize) = 0; // Summary: - // Adds a new file to the zip or update an existing's segment if it is not compressed - just stored + // Adds a new file to the zip or update an existing segment if it is not compressed - just stored // adds a directory (creates several nested directories if needed) // ( name might be misleading as if nOverwriteSeekPos is used the update is not continuous ) // Arguments: @@ -164,7 +146,7 @@ namespace AZ::IO // Summary: // Get the full path to the archive file. - virtual const char* GetFullPath() const = 0; + virtual AZ::IO::PathView GetFullPath() const = 0; // Summary: // Get the flags of this object. diff --git a/Code/Framework/AzFramework/AzFramework/Archive/NestedArchive.cpp b/Code/Framework/AzFramework/AzFramework/Archive/NestedArchive.cpp index dc1d4aa864..1e0f237df5 100644 --- a/Code/Framework/AzFramework/AzFramework/Archive/NestedArchive.cpp +++ b/Code/Framework/AzFramework/AzFramework/Archive/NestedArchive.cpp @@ -174,7 +174,7 @@ namespace AZ::IO return m_pCache->ReadFile(reinterpret_cast(fileHandle), nullptr, pBuffer); } - const char* NestedArchive::GetFullPath() const + AZ::IO::PathView NestedArchive::GetFullPath() const { return m_pCache->GetFilePath(); } @@ -193,19 +193,9 @@ namespace AZ::IO if (nFlagsToSet & FLAGS_RELATIVE_PATHS_ONLY) { m_nFlags |= FLAGS_RELATIVE_PATHS_ONLY; - } - - if (nFlagsToSet & FLAGS_ON_HDD) - { - m_nFlags |= FLAGS_ON_HDD; - } - - if (nFlagsToSet & FLAGS_RELATIVE_PATHS_ONLY || - nFlagsToSet & FLAGS_ON_HDD) - { - // we don't support changing of any other flags return true; } + return false; } @@ -252,20 +242,12 @@ namespace AZ::IO return AZ::IO::FixedMaxPathString{ szRelativePath }; } - if ((szRelativePath.size() > 1 && szRelativePath[1] == ':') || (m_nFlags & FLAGS_ABSOLUTE_PATHS)) + if ((m_nFlags & FLAGS_ABSOLUTE_PATHS) == FLAGS_ABSOLUTE_PATHS) { // make the normalized full path and try to match it against the binding root of this object - auto resolvedPath = AZ::IO::FileIOBase::GetDirectInstance()->ResolvePath(szRelativePath); - - // Make sure the resolve path is longer than the bind root and that it starts with the bind root - if (!resolvedPath || resolvedPath->Native().size() <= m_strBindRoot.size() || azstrnicmp(resolvedPath->c_str(), m_strBindRoot.c_str(), m_strBindRoot.size()) != 0) - { - return {}; - } - - // Remove the bind root prefix from the resolved path - resolvedPath->Native().erase(0, m_strBindRoot.size() + 1); - return resolvedPath->Native(); + AZ::IO::FixedMaxPath resolvedPath; + AZ::IO::FileIOBase::GetDirectInstance()->ResolvePath(resolvedPath, szRelativePath); + return resolvedPath.LexicallyProximate(m_strBindRoot).Native(); } return AZ::IO::FixedMaxPathString{ szRelativePath }; diff --git a/Code/Framework/AzFramework/AzFramework/Archive/NestedArchive.h b/Code/Framework/AzFramework/AzFramework/Archive/NestedArchive.h index eac98b2f07..34bbcdc201 100644 --- a/Code/Framework/AzFramework/AzFramework/Archive/NestedArchive.h +++ b/Code/Framework/AzFramework/AzFramework/Archive/NestedArchive.h @@ -19,15 +19,15 @@ namespace AZ::IO { bool operator()(const INestedArchive* left, const INestedArchive* right) const { - return azstricmp(left->GetFullPath(), right->GetFullPath()) < 0; + return left->GetFullPath() < right->GetFullPath(); } bool operator()(AZStd::string_view left, const INestedArchive* right) const { - return azstrnicmp(left.data(), right->GetFullPath(), left.size()) < 0; + return AZ::IO::PathView(left) < right->GetFullPath(); } bool operator()(const INestedArchive* left, AZStd::string_view right) const { - return azstrnicmp(left->GetFullPath(), right.data(), right.size()) < 0; + return left->GetFullPath() < AZ::IO::PathView(right); } }; @@ -78,7 +78,7 @@ namespace AZ::IO int ReadFile(Handle fileHandle, void* pBuffer) override; // returns the full path to the archive file - const char* GetFullPath() const override; + AZ::IO::PathView GetFullPath() const override; ZipDir::Cache* GetCache(); uint32_t GetFlags() const override; @@ -95,7 +95,7 @@ namespace AZ::IO ZipDir::CachePtr m_pCache; // the binding root may be empty string - in this case, the absolute path binding won't work - AZStd::string m_strBindRoot; + AZ::IO::Path m_strBindRoot; IArchive* m_archive{}; uint32_t m_nFlags{}; }; diff --git a/Code/Framework/AzFramework/AzFramework/Archive/ZipDirCache.cpp b/Code/Framework/AzFramework/AzFramework/Archive/ZipDirCache.cpp index 81f26d78b8..d17dbd0837 100644 --- a/Code/Framework/AzFramework/AzFramework/Archive/ZipDirCache.cpp +++ b/Code/Framework/AzFramework/AzFramework/Archive/ZipDirCache.cpp @@ -9,7 +9,6 @@ #include #include -#include #include #include @@ -104,24 +103,21 @@ namespace AZ::IO::ZipDir : m_pCache(pCache) , m_bCommitted(false) { - AZ::IO::PathString normalizedPath{ szRelativePath }; - AZ::StringFunc::Path::Normalize(normalizedPath); - AZStd::to_lower(AZStd::begin(normalizedPath), AZStd::end(normalizedPath)); // Update the cache string pool with the relative path to the file - auto pathIt = m_pCache->m_relativePathPool.emplace(normalizedPath); + auto pathIt = m_pCache->m_relativePathPool.emplace(AZ::IO::PathView(szRelativePath).LexicallyNormal()); m_szRelativePath = *pathIt.first; // this is the name of the directory - create it or find it - m_pFileEntry = m_pCache->GetRoot()->Add(m_szRelativePath); + m_pFileEntry = m_pCache->GetRoot()->Add(m_szRelativePath.Native()); if (m_pFileEntry && az_archive_zip_directory_cache_verbosity) { - AZ_TracePrintf("Archive", R"(File "%s" has been added to archive at root "%s")", normalizedPath.c_str(), pCache->GetFilePath()); + AZ_TracePrintf("Archive", R"(File "%s" has been added to archive at root "%s")", pathIt.first->c_str(), pCache->GetFilePath()); } } ~FileEntryTransactionAdd() { if (m_pFileEntry && !m_bCommitted) { - m_pCache->RemoveFile(m_szRelativePath); + m_pCache->RemoveFile(m_szRelativePath.Native()); m_pCache->m_relativePathPool.erase(m_szRelativePath); } } @@ -131,11 +127,11 @@ namespace AZ::IO::ZipDir } AZStd::string_view GetRelativePath() const { - return m_szRelativePath; + return m_szRelativePath.Native(); } private: Cache* m_pCache; - AZStd::string_view m_szRelativePath; + AZ::IO::PathView m_szRelativePath; FileEntry* m_pFileEntry; bool m_bCommitted; }; @@ -587,34 +583,27 @@ namespace AZ::IO::ZipDir // deletes the file from the archive ErrorEnum Cache::RemoveFile(AZStd::string_view szRelativePathSrc) { - // Normalize and lower case the relative path - AZ::IO::PathString szRelativePath{ szRelativePathSrc }; - AZ::StringFunc::Path::Normalize(szRelativePath); - AZStd::to_lower(AZStd::begin(szRelativePath), AZStd::end(szRelativePath)); - AZStd::string_view normalizedRelativePath = szRelativePath; - - // find the last slash in the path - size_t slashOffset = normalizedRelativePath.find_last_of(AZ_CORRECT_AND_WRONG_FILESYSTEM_SEPARATOR); + AZ::IO::PathView szRelativePath{ szRelativePathSrc }; AZStd::string_view fileName; // the name of the file to delete FileEntryTree* pDir; // the dir from which the subdir will be deleted - if (slashOffset != AZStd::string_view::npos) + if (szRelativePath.HasParentPath()) { FindDir fd(GetRoot()); // the directory to remove - pDir = fd.FindExact(normalizedRelativePath.substr(0, slashOffset)); + pDir = fd.FindExact(szRelativePath.ParentPath()); if (!pDir) { return ZD_ERROR_DIR_NOT_FOUND;// there is no such directory } - fileName = normalizedRelativePath.substr(slashOffset + 1); + fileName = szRelativePath.Filename().Native(); } else { pDir = GetRoot(); - fileName = normalizedRelativePath; + fileName = szRelativePath.Native(); } ErrorEnum e = pDir->RemoveFile(fileName); @@ -625,7 +614,7 @@ namespace AZ::IO::ZipDir if (az_archive_zip_directory_cache_verbosity) { AZ_TracePrintf("Archive", R"(File "%.*s" has been remove from archive at root "%s")", - aznumeric_cast(fileName.size()), fileName.data(), GetFilePath()); + AZ_STRING_ARG(szRelativePath.Native()), GetFilePath()); } } return e; @@ -635,45 +624,38 @@ namespace AZ::IO::ZipDir // deletes the directory, with all its descendants (files and subdirs) ErrorEnum Cache::RemoveDir(AZStd::string_view szRelativePathSrc) { - // Normalize and lower case the relative path - AZ::IO::PathString szRelativePath{ szRelativePathSrc }; - AZ::StringFunc::Path::Normalize(szRelativePath); - AZStd::to_lower(AZStd::begin(szRelativePath), AZStd::end(szRelativePath)); - AZStd::string_view normalizedRelativePath = szRelativePath; - - // find the last slash in the path - size_t slashOffset = normalizedRelativePath.find_last_of(AZ_CORRECT_AND_WRONG_FILESYSTEM_SEPARATOR); + AZ::IO::PathView szRelativePath{ szRelativePathSrc }; AZStd::string_view dirName; // the name of the dir to delete FileEntryTree* pDir; // the dir from which the subdir will be deleted - if (slashOffset != AZStd::string_view::npos) + if (szRelativePath.HasParentPath()) { FindDir fd(GetRoot()); // the directory to remove - pDir = fd.FindExact(normalizedRelativePath.substr(0, slashOffset)); + pDir = fd.FindExact(szRelativePath.ParentPath()); if (!pDir) { return ZD_ERROR_DIR_NOT_FOUND;// there is no such directory } - dirName = normalizedRelativePath.substr(slashOffset + 1); + dirName = szRelativePath.Filename().Native(); } else { pDir = GetRoot(); - dirName = normalizedRelativePath; + dirName = szRelativePath.Native(); } - ErrorEnum e = pDir->RemoveDir(normalizedRelativePath); + ErrorEnum e = pDir->RemoveDir(dirName); if (e == ZD_ERROR_SUCCESS) { m_nFlags |= FLAGS_UNCOMPACTED | FLAGS_CDR_DIRTY; if (az_archive_zip_directory_cache_verbosity) { - AZ_TracePrintf("Archive", R"(File "%.*s" has been remove from archive at root "%s")", - aznumeric_cast(normalizedRelativePath.size()), normalizedRelativePath.data(), GetFilePath()); + AZ_TracePrintf("Archive", R"(Directory "%.*s" has been remove from archive at root "%s")", + AZ_STRING_ARG(szRelativePath.Native()), GetFilePath()); } } return e; @@ -769,9 +751,7 @@ namespace AZ::IO::ZipDir // finds the file by exact path FileEntry* Cache::FindFile(AZStd::string_view szPathSrc, [[maybe_unused]] bool bFullInfo) { - AZ::IO::PathString szPath{ szPathSrc }; - AZ::StringFunc::Path::Normalize(szPath); - AZStd::to_lower(AZStd::begin(szPath), AZStd::end(szPath)); + AZ::IO::PathView szPath{ szPathSrc }; ZipDir::FindFile fd(GetRoot()); FileEntry* fileEntry = fd.FindExact(szPath); @@ -779,19 +759,13 @@ namespace AZ::IO::ZipDir { if (az_archive_zip_directory_cache_verbosity) { - AZ_TracePrintf("Archive", "FindExact failed to find file %s at root %s", szPath.c_str(), GetFilePath()); + AZ_TracePrintf("Archive", "FindExact failed to find file %.*s at root %s", AZ_STRING_ARG(szPath.Native()), GetFilePath()); } return {}; } return fileEntry; } - // returns the size of memory occupied by the instance referred to by this cache - size_t Cache::GetSize() const - { - return sizeof(*this) + m_strFilePath.capacity() + m_treeDir.GetSize() - sizeof(m_treeDir); - } - // refreshes information about the given file entry into this file entry ErrorEnum Cache::Refresh(FileEntryBase* pFileEntry) { @@ -800,7 +774,7 @@ namespace AZ::IO::ZipDir return ZD_ERROR_INVALID_CALL; } - if (pFileEntry->nFileDataOffset != pFileEntry->INVALID_DATA_OFFSET) + if (pFileEntry->nFileDataOffset != FileEntryBase::INVALID_DATA_OFFSET) { return ZD_ERROR_SUCCESS; // the data offset has been successfully read.. } diff --git a/Code/Framework/AzFramework/AzFramework/Archive/ZipDirCache.h b/Code/Framework/AzFramework/AzFramework/Archive/ZipDirCache.h index 35bf0ae251..646410f8db 100644 --- a/Code/Framework/AzFramework/AzFramework/Archive/ZipDirCache.h +++ b/Code/Framework/AzFramework/AzFramework/Archive/ZipDirCache.h @@ -16,6 +16,7 @@ #pragma once #include +#include #include #include #include @@ -89,9 +90,6 @@ namespace AZ::IO::ZipDir // refreshes information about the given file entry into this file entry ErrorEnum Refresh(FileEntryBase* pFileEntry); - // returns the size of memory occupied by the instance of this cache - size_t GetSize() const; - // QUICK check to determine whether the file entry belongs to this object bool IsOwnerOf(const FileEntry* pFileEntry) const { @@ -100,9 +98,9 @@ namespace AZ::IO::ZipDir // returns the string - path to the zip file from which this object was constructed. // this will be "" if the object was constructed with a factory that wasn't created with FLAGS_MEMORIZE_ZIP_PATH - const char* GetFilePath() const + AZ::IO::PathView GetFilePath() const { - return m_strFilePath.c_str(); + return m_strFilePath; } FileEntryTree* GetRoot() @@ -135,10 +133,10 @@ namespace AZ::IO::ZipDir FileEntryTree m_treeDir; AZ::IO::HandleType m_fileHandle; AZ::IAllocatorAllocate* m_allocator; - AZStd::string m_strFilePath; + AZ::IO::Path m_strFilePath; // String Pool for persistently storing paths as long as they reside in the cache - AZStd::unordered_set m_relativePathPool; + AZStd::unordered_set m_relativePathPool; // offset to the start of CDR in the file,even if there's no CDR there currently // when a new file is added, it can start from here, but this value will need to be updated then diff --git a/Code/Framework/AzFramework/AzFramework/Archive/ZipDirCacheFactory.cpp b/Code/Framework/AzFramework/AzFramework/Archive/ZipDirCacheFactory.cpp index 0092c7c8f8..5c5e93d441 100644 --- a/Code/Framework/AzFramework/AzFramework/Archive/ZipDirCacheFactory.cpp +++ b/Code/Framework/AzFramework/AzFramework/Archive/ZipDirCacheFactory.cpp @@ -41,13 +41,6 @@ namespace AZ::IO::ZipDir m_encryptedHeaders = ZipFile::HEADERS_NOT_ENCRYPTED; m_signedHeaders = ZipFile::HEADERS_NOT_SIGNED; - if (m_nFlags & FLAGS_FILENAMES_AS_CRC32) - { - m_bBuildFileEntryMap = false; - m_bBuildFileEntryTree = false; - m_bBuildOptimizedFileEntry = true; - } - if (m_nFlags & FLAGS_READ_INSIDE_PAK) { m_fileExt.m_fileIOBase = AZ::IO::FileIOBase::GetInstance(); @@ -88,12 +81,12 @@ namespace AZ::IO::ZipDir if (m_fileExt.m_fileHandle == AZ::IO::InvalidHandle) { - THROW_ZIPDIR_ERROR(ZD_ERROR_IO_FAILED, "Could not open file in binary mode for reading"); + AZ_Warning("Archive", false, R"(ZD_ERROR_IO_FAILED: Could not open file "%s" in binary mode for reading)", szFileName); return {}; } if (!ReadCache(*pCache)) { - THROW_ZIPDIR_ERROR(ZD_ERROR_IO_FAILED, "Could not read the CDR of the pack file."); + AZ_Warning("Archive", false, R"(ZD_ERROR_IO_FAILED: Could not read the CDR of the pack file "%s".)", pCache->m_strFilePath.c_str()); return {}; } } @@ -113,12 +106,12 @@ namespace AZ::IO::ZipDir size_t nFileSize = (size_t)Tell(); Seek(0, SEEK_SET); - AZ_Assert(nFileSize != 0, "File of size 0 will not be open for reading"); + AZ_Warning("Archive", nFileSize != 0, R"(ZD_ERROR_IO_FAILED: File "%s" with size 0 will not be open for reading)", szFileName); if (nFileSize) { if (!ReadCache(*pCache)) { - THROW_ZIPDIR_ERROR(ZD_ERROR_IO_FAILED, "Could not open file in binary mode for reading"); + AZ_Warning("Archive", false, R"(ZD_ERROR_IO_FAILED: Could not open file "%s" in binary mode for reading)", szFileName); return {}; } bOpenForWriting = false; @@ -143,7 +136,7 @@ namespace AZ::IO::ZipDir if (m_fileExt.m_fileHandle == AZ::IO::InvalidHandle) { - THROW_ZIPDIR_ERROR(ZD_ERROR_IO_FAILED, "Could not open file in binary mode for appending (read/write)"); + AZ_Warning("Archive", false, R"(ZD_ERROR_IO_FAILED: Could not open file "%s" in binary mode for appending (read/write))", szFileName); return {}; } } @@ -211,7 +204,7 @@ namespace AZ::IO::ZipDir if (m_headerExtended.nHeaderSize != sizeof(m_headerExtended)) { // Extended Header is not valid - THROW_ZIPDIR_ERROR(ZD_ERROR_DATA_IS_CORRUPT, "Bad extended header"); + AZ_Warning("Archive", false, "ZD_ERROR_DATA_IS_CORRUPT: Bad extended header"); return false; } //We have the header, so read the encryption and signing techniques @@ -224,7 +217,7 @@ namespace AZ::IO::ZipDir if (m_headerExtended.nEncryption != ZipFile::HEADERS_NOT_ENCRYPTED && m_encryptedHeaders != ZipFile::HEADERS_NOT_ENCRYPTED) { //Encryption technique has been specified in both the disk number (old technique) and the custom header (new technique). - THROW_ZIPDIR_ERROR(ZD_ERROR_DATA_IS_CORRUPT, "Unexpected encryption technique in header"); + AZ_Warning("Archive", false, "ZD_ERROR_DATA_IS_CORRUPT: Unexpected encryption technique in header"); return false; } else @@ -240,7 +233,7 @@ namespace AZ::IO::ZipDir break; default: // Unexpected technique - THROW_ZIPDIR_ERROR(ZD_ERROR_DATA_IS_CORRUPT, "Bad encryption technique in header"); + AZ_Warning("Archive", false, "ZD_ERROR_DATA_IS_CORRUPT: Bad encryption technique in header"); return false; } } @@ -255,7 +248,7 @@ namespace AZ::IO::ZipDir break; default: // Unexpected technique - THROW_ZIPDIR_ERROR(ZD_ERROR_DATA_IS_CORRUPT, "Bad signing technique in header"); + AZ_Warning("Archive", false, "ZD_ERROR_DATA_IS_CORRUPT: Bad signing technique in header"); return false; } @@ -266,7 +259,7 @@ namespace AZ::IO::ZipDir Read(&m_headerSignature, sizeof(m_headerSignature)); if (m_headerSignature.nHeaderSize != sizeof(m_headerSignature)) { - THROW_ZIPDIR_ERROR(ZD_ERROR_DATA_IS_CORRUPT, "Bad signature header"); + AZ_Warning("Archive", false, "ZD_ERROR_DATA_IS_CORRUPT: Bad signature header"); return false; } } @@ -274,7 +267,7 @@ namespace AZ::IO::ZipDir else { // Unexpected technique - THROW_ZIPDIR_ERROR(ZD_ERROR_DATA_IS_CORRUPT, "Comment field is the wrong length"); + AZ_Warning("Archive", false, "ZD_ERROR_DATA_IS_CORRUPT: Comment field is the wrong length"); return false; } } @@ -285,7 +278,7 @@ namespace AZ::IO::ZipDir || m_CDREnd.nCDRStartDisk != 0 || m_CDREnd.numEntriesOnDisk != m_CDREnd.numEntriesTotal) { - THROW_ZIPDIR_ERROR(ZD_ERROR_UNSUPPORTED, "Multivolume archive detected. Current version of ZipDir does not support multivolume archives"); + AZ_Warning("Archive", false, "ZD_ERROR_UNSUPPORTED: Multivolume archive detected.Current version of ZipDir does not support multivolume archives"); return false; } @@ -295,7 +288,7 @@ namespace AZ::IO::ZipDir || m_CDREnd.lCDRSize > m_nCDREndPos || m_CDREnd.lCDROffset + m_CDREnd.lCDRSize > m_nCDREndPos) { - THROW_ZIPDIR_ERROR(ZD_ERROR_DATA_IS_CORRUPT, "The central directory offset or size are out of range, the pak is probably corrupt, try to repare or delete the file"); + AZ_Warning("Archive", false, "ZD_ERROR_DATA_IS_CORRUPT: The central directory offset or size are out of range, the pak is probably corrupt, try to repare or delete the file"); return false; } @@ -394,7 +387,12 @@ namespace AZ::IO::ZipDir // if there's nothing to search if (nNewBufPos >= nOldBufPos) { - THROW_ZIPDIR_ERROR(ZD_ERROR_NO_CDR, "Cannot find Central Directory Record in pak. This is either not a pak file, or a pak file without Central Directory. It does not mean that the data is permanently lost, but it may be severely damaged. Please repair the file with external tools, there may be enough information left to recover the file completely."); // we didn't find anything + AZ_Warning("Archive", false, "ZD_ERROR_NO_CDR: Cannot find Central Directory Record in pak." + " This is either not a pak file, or a pak file without Central Directory." + " It does not mean that the data is permanently lost," + " but it may be severely damaged." + " Please repair the file with external tools," + " there may be enough information left to recover the file completely."); // we didn't find anything return false; } @@ -418,7 +416,11 @@ namespace AZ::IO::ZipDir } else { - THROW_ZIPDIR_ERROR(ZD_ERROR_DATA_IS_CORRUPT, "Central Directory Record is followed by a comment of inconsistent length. This might be a minor misconsistency, please try to repair the file. However, it is dangerous to open the file because I will have to guess some structure offsets, which can lead to permanent unrecoverable damage of the archive content"); + AZ_Warning("Archive", false, "ZD_ERROR_DATA_IS_CORRUPT:" + " Central Directory Record is followed by a comment of inconsistent length." + " This might be a minor misconsistency, please try to repair the file.However," + " it is dangerous to open the file because I will have to guess some structure offsets," + " which can lead to permanent unrecoverable damage of the archive content"); return false; } } @@ -436,7 +438,7 @@ namespace AZ::IO::ZipDir nOldBufPos = nNewBufPos; memmove(&pReservedBuffer[CDRSearchWindowSize], pWindow, sizeof(ZipFile::CDREnd) - 1); } - THROW_ZIPDIR_ERROR(ZD_ERROR_UNEXPECTED, "The program flow may not have possibly lead here. This error is unexplainable"); // we shouldn't be here + AZ_Assert(false, "ZD_ERROR_UNEXPECTED: The program flow may not have possibly lead here. This error is unexplainable"); // we shouldn't be here return false; } @@ -460,13 +462,13 @@ namespace AZ::IO::ZipDir if (pBuffer.empty()) // couldn't allocate enough memory for temporary copy of CDR { - THROW_ZIPDIR_ERROR(ZD_ERROR_NO_MEMORY, "Not enough memory to cache Central Directory record for fast initialization. This error may not happen on non-console systems"); + AZ_Warning("Archive", false, "ZD_ERROR_NO_MEMORY: Not enough memory to cache Central Directory record for fast initialization. This error may not happen on non-console systems"); return false; } if (!ReadHeaderData(&pBuffer[0], m_CDREnd.lCDRSize)) { - THROW_ZIPDIR_ERROR(ZD_ERROR_CORRUPTED_DATA, "Archive contains corrupted CDR."); + AZ_Warning("Archive", false, "ZD_ERROR_CORRUPTED_DATA: Archive contains corrupted CDR."); return false; } @@ -482,7 +484,7 @@ namespace AZ::IO::ZipDir if ((pFile->nVersionNeeded & 0xFF) > 20) { - THROW_ZIPDIR_ERROR(ZD_ERROR_UNSUPPORTED, "Cannot read the archive file (nVersionNeeded > 20)."); + AZ_Warning("Archive", false, "ZD_ERROR_UNSUPPORTED: Cannot read the archive file (nVersionNeeded > 20)."); return false; } //if (pFile->lSignature != pFile->SIGNATURE) // Timur, Dont compare signatures as signatue in memory can be overwritten by the code below @@ -492,7 +494,8 @@ namespace AZ::IO::ZipDir // if the record overlaps with the End Of CDR structure, something is wrong if (pEndOfRecord > pEndOfData) { - THROW_ZIPDIR_ERROR(ZD_ERROR_CDR_IS_CORRUPT, "Central Directory record is either corrupt, or truncated, or missing. Cannot read the archive directory"); + AZ_Warning("Archive", false, "ZD_ERROR_CDR_IS_CORRUPT: Central Directory record is either corrupt, or truncated, or missing." + " Cannot read the archive directory"); return false; } @@ -550,18 +553,22 @@ namespace AZ::IO::ZipDir ////////////////////////////////////////////////////////////////////////// // give the CDR File Header entry, reads the local file header to validate - // and determine where the actual file lies + // and determine where the actual file resides void CacheFactory::AddFileEntry(char* strFilePath, const ZipFile::CDRFileHeader* pFileHeader, const SExtraZipFileData& extra) { if (pFileHeader->lLocalHeaderOffset > m_CDREnd.lCDROffset) { - THROW_ZIPDIR_ERROR(ZD_ERROR_CDR_IS_CORRUPT, "Central Directory contains file descriptors pointing outside the archive file boundaries. The archive file is either truncated or damaged. Please try to repair the file"); // the file offset is beyond the CDR: impossible + AZ_Warning("Archive", false, "ZD_ERROR_CDR_IS_CORRUPT:" + " Central Directory contains file descriptors pointing outside the archive file boundaries." + " The archive file is either truncated or damaged.Please try to repair the file"); // the file offset is beyond the CDR: impossible return; } if ((pFileHeader->nMethod == ZipFile::METHOD_STORE || pFileHeader->nMethod == ZipFile::METHOD_STORE_AND_STREAMCIPHER_KEYTABLE) && pFileHeader->desc.lSizeUncompressed != pFileHeader->desc.lSizeCompressed) { - THROW_ZIPDIR_ERROR(ZD_ERROR_VALIDATION_FAILED, "File with STORE compression method declares its compressed size not matching its uncompressed size. File descriptor is inconsistent, archive content may be damaged, please try to repair the archive"); + AZ_Warning("Archive", false, "ZD_ERROR_VALIDATION_FAILED:" + " File with STORE compression method declares its compressed size not matching its uncompressed size." + " File descriptor is inconsistent, archive content may be damaged, please try to repair the archive"); return; } @@ -593,8 +600,7 @@ namespace AZ::IO::ZipDir if (m_encryptedHeaders != ZipFile::HEADERS_NOT_ENCRYPTED) { // use CDR instead of local header - // The pak encryption tool asserts that there is no extra data at the end of the local file header, so don't add any extra data from the CDR header. - fileEntry.nFileDataOffset = pFileHeader->lLocalHeaderOffset + sizeof(ZipFile::LocalFileHeader) + pFileHeader->nFileNameLength; + fileEntry.nFileDataOffset = pFileHeader->lLocalHeaderOffset + sizeof(ZipFile::LocalFileHeader) + pFileHeader->nFileNameLength + pFileHeader->nExtraFieldLength; } else { @@ -617,7 +623,9 @@ namespace AZ::IO::ZipDir //|| pFileHeader->nLastModTime != pLocalFileHeader->nLastModTime ) { - THROW_ZIPDIR_ERROR(ZD_ERROR_VALIDATION_FAILED, "The local file header descriptor doesn't match the basic parameters declared in the global file header in the file. The archive content is misconsistent and may be damaged. Please try to repair the archive"); + AZ_Warning("Archive", false, "ZD_ERROR_VALIDATION_FAILED:" + " The local file header descriptor doesn't match the basic parameters declared in the global file header in the file." + " The archive content is misconsistent and may be damaged. Please try to repair the archive"); return; } @@ -628,7 +636,9 @@ namespace AZ::IO::ZipDir if (!AZStd::equal(zipFileDataBegin, zipFileDataEnd, reinterpret_cast(pFileHeader + 1), CompareNoCase)) { // either file name, or the extra field do not match - THROW_ZIPDIR_ERROR(ZD_ERROR_VALIDATION_FAILED, "The local file header contains file name which does not match the file name of the global file header. The archive content is misconsistent with its directory. Please repair the archive"); + AZ_Warning("Archive", false, "ZD_ERROR_VALIDATION_FAILED:" + " The local file header contains file name which does not match the file name of the global file header." + " The archive content is misconsistent with its directory. Please repair the archive"); return; } @@ -642,7 +652,9 @@ namespace AZ::IO::ZipDir if (fileEntry.nFileDataOffset >= m_nCDREndPos) { - THROW_ZIPDIR_ERROR(ZD_ERROR_VALIDATION_FAILED, "The global file header declares the file which crosses the boundaries of the archive. The archive is either corrupted or truncated, please try to repair it"); + AZ_Warning("Archive", false, "ZD_ERROR_VALIDATION_FAILED:" + " The global file header declares the file which crosses the boundaries of the archive." + " The archive is either corrupted or truncated, please try to repair it"); return; } @@ -686,29 +698,29 @@ namespace AZ::IO::ZipDir case Z_OK: break; case Z_MEM_ERROR: - THROW_ZIPDIR_ERROR(ZD_ERROR_ZLIB_NO_MEMORY, "ZLib reported out-of-memory error"); + AZ_Warning("Archive", false, "ZD_ERROR_ZLIB_NO_MEMORY: ZLib reported out-of-memory error"); return; case Z_BUF_ERROR: - THROW_ZIPDIR_ERROR(ZD_ERROR_ZLIB_CORRUPTED_DATA, "ZLib reported compressed stream buffer error"); + AZ_Warning("Archive", false, "ZD_ERROR_ZLIB_CORRUPTED_DATA: ZLib reported compressed stream buffer error"); return; case Z_DATA_ERROR: - THROW_ZIPDIR_ERROR(ZD_ERROR_ZLIB_CORRUPTED_DATA, "ZLib reported compressed stream data error"); + AZ_Warning("Archive", false, "ZD_ERROR_ZLIB_CORRUPTED_DATA: ZLib reported compressed stream data error"); return; default: - THROW_ZIPDIR_ERROR(ZD_ERROR_ZLIB_FAILED, "ZLib reported an unexpected unknown error"); + AZ_Warning("Archive", false, "ZD_ERROR_ZLIB_FAILED: ZLib reported an unexpected unknown error"); return; } if (nDestSize != fileEntry.desc.lSizeUncompressed) { - THROW_ZIPDIR_ERROR(ZD_ERROR_CORRUPTED_DATA, "Uncompressed stream doesn't match the size of uncompressed file stored in the archive file headers"); + AZ_Warning("Archive", false, "ZD_ERROR_CORRUPTED_DATA: Uncompressed stream doesn't match the size of uncompressed file stored in the archive file headers"); return; } uLong uCRC32 = AZ::Crc32((Bytef*)pUncompressed, nDestSize); if (uCRC32 != fileEntry.desc.lCRC32) { - THROW_ZIPDIR_ERROR(ZD_ERROR_CRC32_CHECK, "Uncompressed stream CRC32 check failed"); + AZ_Warning("Archive", false, "ZD_ERROR_CRC32_CHECK: Uncompressed stream CRC32 check failed"); return; } } @@ -737,7 +749,7 @@ namespace AZ::IO::ZipDir { if (FSeek(&m_fileExt, nPos, nOrigin)) { - THROW_ZIPDIR_ERROR(ZD_ERROR_IO_FAILED, "Cannot fseek() to the new position in the file. This is unexpected error and should not happen under any circumstances. Perhaps some network or disk failure error has caused this"); + AZ_Warning("Archive", false, "ZD_ERROR_IO_FAILED: Cannot fseek() to the new position in the file. This is unexpected error and should not happen under any circumstances. Perhaps some network or disk failure error has caused this"); return; } } @@ -747,7 +759,7 @@ namespace AZ::IO::ZipDir int64_t nPos = FTell(&m_fileExt); if (nPos == -1) { - THROW_ZIPDIR_ERROR(ZD_ERROR_IO_FAILED, "Cannot ftell() position in the archive. This is unexpected error and should not happen under any circumstances. Perhaps some network or disk failure error has caused this"); + AZ_Warning("Archive", false, "ZD_ERROR_IO_FAILED: Cannot ftell() position in the archive. This is unexpected error and should not happen under any circumstances. Perhaps some network or disk failure error has caused this"); return 0; } return nPos; @@ -757,7 +769,7 @@ namespace AZ::IO::ZipDir { if (FRead(&m_fileExt, pDest, nSize, 1) != 1) { - THROW_ZIPDIR_ERROR(ZD_ERROR_IO_FAILED, "Cannot fread() a portion of data from archive"); + AZ_Warning("Archive", false, "ZD_ERROR_IO_FAILED: Cannot fread() a portion of data from archive"); return false; } return true; diff --git a/Code/Framework/AzFramework/AzFramework/Archive/ZipDirCacheFactory.h b/Code/Framework/AzFramework/AzFramework/Archive/ZipDirCacheFactory.h index 1f27cb5504..c31d4d7dfd 100644 --- a/Code/Framework/AzFramework/AzFramework/Archive/ZipDirCacheFactory.h +++ b/Code/Framework/AzFramework/AzFramework/Archive/ZipDirCacheFactory.h @@ -33,20 +33,13 @@ namespace AZ::IO::ZipDir // if this is set, the archive will be created anew (the existing file will be overwritten) FLAGS_CREATE_NEW = 1 << 3, - // Cache will be loaded completely into the memory. - FLAGS_IN_MEMORY = 1 << 4, - FLAGS_IN_MEMORY_CPU = 1 << 5, - - // Store all file names as crc32 in a flat directory structure. - FLAGS_FILENAMES_AS_CRC32 = 1 << 6, - // if this is set, zip path will be searched inside other zips FLAGS_READ_INSIDE_PAK = 1 << 7, }; // initializes the internal structures // nFlags can have FLAGS_READ_ONLY flag, in this case the object will be opened only for reading - CacheFactory (InitMethodEnum nInitMethod, uint32_t nFlags = 0); + CacheFactory(InitMethodEnum nInitMethod, uint32_t nFlags = 0); ~CacheFactory(); // the new function creates a new cache diff --git a/Code/Framework/AzFramework/AzFramework/Archive/ZipDirFind.cpp b/Code/Framework/AzFramework/AzFramework/Archive/ZipDirFind.cpp index 30c8676f75..4fb1a54ded 100644 --- a/Code/Framework/AzFramework/AzFramework/Archive/ZipDirFind.cpp +++ b/Code/Framework/AzFramework/AzFramework/Archive/ZipDirFind.cpp @@ -17,7 +17,7 @@ namespace AZ::IO::ZipDir { - bool FindFile::FindFirst(AZStd::string_view szWildcard) + bool FindFile::FindFirst(AZ::IO::PathView szWildcard) { if (!PreFind(szWildcard)) { @@ -29,7 +29,7 @@ namespace AZ::IO::ZipDir return SkipNonMatchingFiles(); } - bool FindDir::FindFirst(AZStd::string_view szWildcard) + bool FindDir::FindFirst(AZ::IO::PathView szWildcard) { if (!PreFind(szWildcard)) { @@ -42,37 +42,20 @@ namespace AZ::IO::ZipDir } // matches the file wildcard in the m_szWildcard to the given file/dir name - // this takes into account the fact that xxx. is the alias name for xxx - bool FindData::MatchWildcard(AZStd::string_view szName) + bool FindData::MatchWildcard(AZ::IO::PathView szName) { - if (AZStd::wildcard_match(m_szWildcard, szName)) - { - return true; - } - - // check if the file object name contains extension sign (.) - size_t extensionOffset = szName.find('.'); - if (extensionOffset != AZStd::string_view::npos) - { - return false; - } - - // no extension sign - add it - AZStd::fixed_string szAlias{ szName }; - szAlias.push_back('.'); - - return AZStd::wildcard_match(m_szWildcard, szAlias); + return szName.Match(m_szWildcard.Native()); } - FileEntry* FindFile::FindExact(AZStd::string_view szPath) + FileEntry* FindFile::FindExact(AZ::IO::PathView szPath) { if (!PreFind(szPath)) { return nullptr; } - FileEntryTree::FileMap::iterator itFile = m_pDirHeader->FindFile(m_szWildcard.c_str()); + FileEntryTree::FileMap::iterator itFile = m_pDirHeader->FindFile(m_szWildcard); if (itFile == m_pDirHeader->GetFileEnd()) { m_pDirHeader = nullptr; // we didn't find it, fail the search @@ -84,7 +67,7 @@ namespace AZ::IO::ZipDir return m_pDirHeader->GetFileEntry(m_itFile); } - FileEntryTree* FindDir::FindExact(AZStd::string_view szPath) + FileEntryTree* FindDir::FindExact(AZ::IO::PathView szPath) { if (!PreFind(szPath)) { @@ -97,40 +80,50 @@ namespace AZ::IO::ZipDir ////////////////////////////////////////////////////////////////////////// // after this call returns successfully (with true returned), the m_szWildcard - // contains the file name/wildcard and m_pDirHeader contains the directory where + // contains the file name/glob and m_pDirHeader contains the directory where // the file (s) are to be found - bool FindData::PreFind(AZStd::string_view szWildcard) + bool FindData::PreFind(AZ::IO::PathView pathGlob) { if (!m_pRoot) { return false; } - // start the search from the root - m_pDirHeader = m_pRoot; - m_szWildcard = szWildcard; - - // for each path directory, copy it into the wildcard buffer and try to find the subdirectory - for (AZStd::optional pathEntry = AZ::StringFunc::TokenizeNext(szWildcard, AZ_CORRECT_AND_WRONG_FILESYSTEM_SEPARATOR); pathEntry; - pathEntry = AZ::StringFunc::TokenizeNext(szWildcard, AZ_CORRECT_AND_WRONG_FILESYSTEM_SEPARATOR)) + FileEntryTree* entryTreeHeader = m_pRoot; + // If there is a root path in the glob path, attempt to locate it from the root + if (AZ::IO::PathView rootPath = m_szWildcard.RootPath(); !rootPath.empty()) { - // Update wildcard to new path entry - m_szWildcard = *pathEntry; - - // If the wildcard parameter that has been passed to TokenizeNext is empty - // Then pathEntry is the final portion of the path - if (!szWildcard.empty()) + FileEntryTree* dirEntry = entryTreeHeader->FindDir(rootPath); + if (dirEntry == nullptr) { - FileEntryTree* dirEntry = m_pDirHeader->FindDir(*pathEntry); - if (!dirEntry) - { - m_pDirHeader = nullptr; // an intermediate directory has not been found continue the search - return false; - } - m_pDirHeader = dirEntry->GetDirectory(); + return false; } + + entryTreeHeader = dirEntry->GetDirectory(); + pathGlob = pathGlob.RelativePath(); + } + + + AZ::IO::PathView filenameSegment = pathGlob; + // Recurse through the directories within the file tree for each remaining parent path segment + // of pathGlob parameter + auto parentPathIter = pathGlob.begin(); + for (auto filenamePathIter = parentPathIter == pathGlob.end() ? pathGlob.end() : AZStd::next(parentPathIter, 1); + filenamePathIter != pathGlob.end(); ++parentPathIter, ++filenamePathIter) + { + FileEntryTree* dirEntry = entryTreeHeader->FindDir(*parentPathIter); + if (dirEntry == nullptr) + { + return false; + } + entryTreeHeader = dirEntry->GetDirectory(); + filenameSegment = *filenamePathIter; } + // At this point the all the intermediate directories have been found + // so update the directory header to point at the last file entry tree + m_pDirHeader = entryTreeHeader; + m_szWildcard = filenameSegment; return true; } diff --git a/Code/Framework/AzFramework/AzFramework/Archive/ZipDirFind.h b/Code/Framework/AzFramework/AzFramework/Archive/ZipDirFind.h index 2bb3932aa9..f9b773a42d 100644 --- a/Code/Framework/AzFramework/AzFramework/Archive/ZipDirFind.h +++ b/Code/Framework/AzFramework/AzFramework/Archive/ZipDirFind.h @@ -38,11 +38,10 @@ namespace AZ::IO::ZipDir // after this call returns successfully (with true returned), the m_szWildcard // contains the file name/wildcard and m_pDirHeader contains the directory where // the file (s) are to be found - bool PreFind(AZStd::string_view szWildcard); + bool PreFind(AZ::IO::PathView szWildcard); // matches the file wildcard in the m_szWildcard to the given file/dir name - // this takes into account the fact that xxx. is the alias name for xxx - bool MatchWildcard(AZStd::string_view szName); + bool MatchWildcard(AZ::IO::PathView szName); // the directory inside which the current object (file or directory) is being searched FileEntryTree* m_pDirHeader{}; @@ -50,7 +49,7 @@ namespace AZ::IO::ZipDir FileEntryTree* m_pRoot{}; // the root of the zip file in which to search // the actual wildcard being used in the current scan - the file name wildcard only! - AZStd::fixed_string m_szWildcard; + AZ::IO::FixedMaxPath m_szWildcard; }; class FindFile @@ -66,9 +65,9 @@ namespace AZ::IO::ZipDir { } // if bExactFile is passed, only the file is searched, and besides with the exact name as passed (no wildcards) - bool FindFirst(AZStd::string_view szWildcard); + bool FindFirst(AZ::IO::PathView szWildcard); - FileEntry* FindExact(AZStd::string_view szPath); + FileEntry* FindExact(AZ::IO::PathView szPath); // goes on to the next file entry bool FindNext(); @@ -94,9 +93,9 @@ namespace AZ::IO::ZipDir { } // if bExactFile is passed, only the file is searched, and besides with the exact name as passed (no wildcards) - bool FindFirst(AZStd::string_view szWildcard); + bool FindFirst(AZ::IO::PathView szWildcard); - FileEntryTree* FindExact(AZStd::string_view szPath); + FileEntryTree* FindExact(AZ::IO::PathView szPath); // goes on to the next file entry bool FindNext(); diff --git a/Code/Framework/AzFramework/AzFramework/Archive/ZipDirList.cpp b/Code/Framework/AzFramework/AzFramework/Archive/ZipDirList.cpp index 2f96a93a82..729f394b9d 100644 --- a/Code/Framework/AzFramework/AzFramework/Archive/ZipDirList.cpp +++ b/Code/Framework/AzFramework/AzFramework/Archive/ZipDirList.cpp @@ -68,14 +68,14 @@ namespace AZ::IO::ZipDir { for (FileEntryTree::SubdirMap::iterator it = pTree->GetDirBegin(); it != pTree->GetDirEnd(); ++it) { - AddAllFiles(it->second.get(), AZStd::string::format("%.*s%.*s/", aznumeric_cast(strRoot.size()), strRoot.data(), aznumeric_cast(it->first.size()), it->first.data())); + AddAllFiles(it->second.get(), (AZ::IO::Path(strRoot) / it->first).Native()); } for (FileEntryTree::FileMap::iterator it = pTree->GetFileBegin(); it != pTree->GetFileEnd(); ++it) { FileRecord rec; rec.pFileEntryBase = pTree->GetFileEntry(it); - rec.strPath = AZStd::string::format("%.*s%.*s", aznumeric_cast(strRoot.size()), strRoot.data(), aznumeric_cast(it->first.size()), it->first.data()); + rec.strPath = (AZ::IO::Path(strRoot) / it->first).Native(); push_back(rec); } } diff --git a/Code/Framework/AzFramework/AzFramework/Archive/ZipDirStructures.cpp b/Code/Framework/AzFramework/AzFramework/Archive/ZipDirStructures.cpp index 1d09705900..cea517decd 100644 --- a/Code/Framework/AzFramework/AzFramework/Archive/ZipDirStructures.cpp +++ b/Code/Framework/AzFramework/AzFramework/Archive/ZipDirStructures.cpp @@ -187,8 +187,7 @@ namespace AZ::IO::ZipDir::ZipDirStructuresInternal // If src/dst overlap (in place decompress), then inflate in chunks, copying src locally to ensure // pointers don't foul each other. - bool bIndependantBlocks = ((pInput + nInputLen) <= pOutput) || (pInput >= (pOutput + nOutputLen)); - if (bIndependantBlocks) + if ((pInput + nInputLen) <= pOutput || pInput >= (pOutput + nOutputLen)) { pZStream->next_in = (Bytef*)pInput; pZStream->avail_in = aznumeric_cast(nInputLen); @@ -260,8 +259,7 @@ namespace AZ::IO::ZipDir::ZipDirStructuresInternal // If src/dst overlap (in place decompress), then inflate in chunks, copying src locally to ensure // pointers don't foul each other. - bool bIndependantBlocks = ((pIn + nIn) <= stream.next_out) || (pIn >= (stream.next_out + stream.avail_out)); - if (bIndependantBlocks) + if ((pIn + nIn) <= stream.next_out || pIn >= (stream.next_out + stream.avail_out)) { stream.next_in = pIn; stream.avail_in = nIn; @@ -432,18 +430,18 @@ namespace AZ::IO::ZipDir bool CZipFile::EvaluateSectorSize(const char* filename) { - char volume[AZ_MAX_PATH_LEN]; + AZ::IO::FixedMaxPath volume; - if (AZ::StringFunc::Path::IsRelative(filename)) + if (AZ::IO::PathView(filename).IsRelative()) { - AZ::IO::FileIOBase::GetDirectInstance()->ResolvePath(filename, volume, AZ_ARRAY_SIZE(volume)); + AZ::IO::FileIOBase::GetDirectInstance()->ResolvePath(volume, filename); } else { - azstrcpy(volume, AZ_ARRAY_SIZE(volume), filename); + volume = filename; } - AZ::IO::FixedMaxPathString drive{ AZ::IO::PathView(volume).RootName().Native() }; + AZ::IO::FixedMaxPath drive = volume.RootName(); if (drive.empty()) { return false; @@ -498,18 +496,18 @@ namespace AZ::IO::ZipDir ////////////////////////////////////////////////////////////////////////// FileEntryBase::FileEntryBase(const ZipFile::CDRFileHeader& header, const SExtraZipFileData& extra) { - this->desc = header.desc; - this->nFileHeaderOffset = header.lLocalHeaderOffset; - //this->nFileDataOffset = INVALID_DATA_OFFSET; // we don't know yet - this->nMethod = header.nMethod; - this->nNameOffset = 0; // we don't know yet - this->nLastModTime = header.nLastModTime; - this->nLastModDate = header.nLastModDate; - this->nNTFS_LastModifyTime = extra.nLastModifyTime; + desc = header.desc; + nFileHeaderOffset = header.lLocalHeaderOffset; + + nMethod = header.nMethod; + nNameOffset = 0; // we don't know yet + nLastModTime = header.nLastModTime; + nLastModDate = header.nLastModDate; + nNTFS_LastModifyTime = extra.nLastModifyTime; // make an estimation (at least this offset should be there), but we don't actually know yet - this->nFileDataOffset = header.lLocalHeaderOffset + sizeof(ZipFile::LocalFileHeader) + header.nFileNameLength; - this->nEOFOffset = header.lLocalHeaderOffset + sizeof(ZipFile::LocalFileHeader) + header.nFileNameLength + header.desc.lSizeCompressed; + nFileDataOffset = header.lLocalHeaderOffset + sizeof(ZipFile::LocalFileHeader) + header.nFileNameLength + header.nExtraFieldLength; + nEOFOffset = nFileDataOffset + header.desc.lSizeCompressed; } // Uncompresses raw (without wrapping) data that is compressed with method 8 (deflated) in the Zip file @@ -666,7 +664,9 @@ namespace AZ::IO::ZipDir DirEntry* pEnd = pBegin + this->numDirs; DirEntry* pEntry = AZStd::lower_bound(pBegin, pEnd, szName, pred); #if AZ_TRAIT_LEGACY_CRYPAK_UNIX_LIKE_FILE_SYSTEM - if (pEntry != pEnd && !azstrnicmp(szName.data(), pEntry->GetName(pNamePool), szName.size())) + AZ::IO::PathView searchPath(szName, AZ::IO::WindowsPathSeparator); + AZ::IO::PathView entryPath(pEntry->GetName(pNamePool), AZ::IO::WindowsPathSeparator); + if (pEntry != pEnd && searchPath == entryPath) #else if (pEntry != pEnd && szName == pEntry->GetName(pNamePool)) #endif @@ -690,7 +690,9 @@ namespace AZ::IO::ZipDir FileEntry* pEnd = pBegin + this->numFiles; FileEntry* pEntry = AZStd::lower_bound(pBegin, pEnd, szName, pred); #if AZ_TRAIT_LEGACY_CRYPAK_UNIX_LIKE_FILE_SYSTEM - if (pEntry != pEnd && !azstrnicmp(szName.data(), pEntry->GetName(pNamePool), szName.size())) + AZ::IO::PathView searchPath(szName, AZ::IO::WindowsPathSeparator); + AZ::IO::PathView entryPath(pEntry->GetName(pNamePool), AZ::IO::WindowsPathSeparator); + if (pEntry != pEnd && searchPath == entryPath) #else if (pEntry != pEnd && szName == pEntry->GetName(pNamePool)) #endif @@ -813,8 +815,6 @@ namespace AZ::IO::ZipDir header.nFileNameLength = aznumeric_cast(nFileNameLength); header.nExtraFieldLength = 0; - pFileEntry->nFileDataOffset = pFileEntry->nFileHeaderOffset + sizeof(header) + header.nFileNameLength; - pFileEntry->nEOFOffset = pFileEntry->nFileDataOffset + pFileEntry->desc.lSizeCompressed; if (!AZ::IO::FileIOBase::GetDirectInstance()->Write(fileHandle, &header, sizeof(header))) { return ZD_ERROR_IO_FAILED; @@ -990,13 +990,6 @@ namespace AZ::IO::ZipDir } ////////////////////////////////////////////////////////////////////////// - uint32_t FileNameHash(AZStd::string_view filename) - { - AZ::IO::StackString pathname{ filename }; - AZStd::replace(AZStd::begin(pathname), AZStd::end(pathname), AZ_WRONG_DATABASE_SEPARATOR, AZ_CORRECT_DATABASE_SEPARATOR); - - return AZ::Crc32(pathname); - } int64_t FSeek(CZipFile* file, int64_t origin, int command) { diff --git a/Code/Framework/AzFramework/AzFramework/Archive/ZipDirStructures.h b/Code/Framework/AzFramework/AzFramework/Archive/ZipDirStructures.h index 2f9046f53e..9295a7dd95 100644 --- a/Code/Framework/AzFramework/AzFramework/Archive/ZipDirStructures.h +++ b/Code/Framework/AzFramework/AzFramework/Archive/ZipDirStructures.h @@ -119,8 +119,6 @@ namespace AZ::IO::ZipDir const char* m_szDescription; }; -#define THROW_ZIPDIR_ERROR(ZD_ERR, DESC) AZ_Warning("Archive", false, DESC) - // possible initialization methods enum InitMethodEnum { @@ -157,8 +155,6 @@ namespace AZ::IO::ZipDir int FEof(CZipFile* zipFile); - uint32_t FileNameHash(AZStd::string_view filename); - ////////////////////////////////////////////////////////////////////////// struct SExtraZipFileData @@ -173,7 +169,7 @@ namespace AZ::IO::ZipDir inline static constexpr uint32_t INVALID_DATA_OFFSET = 0xFFFFFFFF; ZipFile::DataDescriptor desc{}; - uint32_t nFileDataOffset{}; // offset of the packed info inside the file; NOTE: this can be INVALID_DATA_OFFSET, if not calculated yet! + uint32_t nFileDataOffset{ INVALID_DATA_OFFSET }; // offset of the packed info inside the file; NOTE: this can be INVALID_DATA_OFFSET, if not calculated yet! uint32_t nFileHeaderOffset{ INVALID_DATA_OFFSET }; // offset of the local file header uint32_t nNameOffset{}; // offset of the file name in the name pool for the directory diff --git a/Code/Framework/AzFramework/AzFramework/Archive/ZipDirTree.cpp b/Code/Framework/AzFramework/AzFramework/Archive/ZipDirTree.cpp index 213287ef74..e772cb596a 100644 --- a/Code/Framework/AzFramework/AzFramework/Archive/ZipDirTree.cpp +++ b/Code/Framework/AzFramework/AzFramework/Archive/ZipDirTree.cpp @@ -9,7 +9,6 @@ #include #include -#include #include #include #include @@ -18,37 +17,42 @@ namespace AZ::IO::ZipDir { // Adds or finds the file. Returns non-initialized structure if it was added, // or an IsInitialized() structure if it was found - FileEntry* FileEntryTree::Add(AZStd::string_view szPath) + FileEntry* FileEntryTree::Add(AZ::IO::PathView inputPathView) { - AZStd::optional pathEntry = AZ::StringFunc::TokenizeNext(szPath, AZ_CORRECT_AND_WRONG_FILESYSTEM_SEPARATOR); - if (!pathEntry) + if (inputPathView.empty()) { AZ_Assert(false, "An empty file path cannot be added to the zip file entry tree"); return nullptr; } // If a path separator was found, add a subdirectory - if (!szPath.empty()) + auto inputPathIter = inputPathView.begin(); + AZ::IO::PathView firstPathSegment(*inputPathIter); + auto inputPathNextIter = inputPathIter == inputPathView.end() ? inputPathView.end() : AZStd::next(inputPathIter, 1); + AZ::IO::PathView remainingPath = inputPathNextIter != inputPathView.end() ? + AZStd::string_view(inputPathNextIter->Native().begin(), inputPathView.Native().end()) + : AZStd::string_view{}; + if (!remainingPath.empty()) { - auto dirEntryIter = m_mapDirs.find(*pathEntry); + auto dirEntryIter = m_mapDirs.find(firstPathSegment); // we have a subdirectory here - create the file in it if (dirEntryIter == m_mapDirs.end()) { - dirEntryIter = m_mapDirs.emplace(*pathEntry, AZStd::make_unique()).first; + dirEntryIter = m_mapDirs.emplace(firstPathSegment, AZStd::make_unique()).first; } - return dirEntryIter->second->Add(szPath); + return dirEntryIter->second->Add(remainingPath); } // Add the filename - auto fileEntryIter = m_mapFiles.find(*pathEntry); + auto fileEntryIter = m_mapFiles.find(firstPathSegment); if (fileEntryIter == m_mapFiles.end()) { - fileEntryIter = m_mapFiles.emplace(*pathEntry, AZStd::make_unique()).first; + fileEntryIter = m_mapFiles.emplace(firstPathSegment, AZStd::make_unique()).first; } return fileEntryIter->second.get(); } // adds a file to this directory - ErrorEnum FileEntryTree::Add(AZStd::string_view szPath, const FileEntryBase& file) + ErrorEnum FileEntryTree::Add(AZ::IO::PathView szPath, const FileEntryBase& file) { FileEntry* pFile = Add(szPath); if (!pFile) @@ -63,7 +67,7 @@ namespace AZ::IO::ZipDir return ZD_ERROR_SUCCESS; } - // returns the number of files in this tree, including this and sublevels + // returns the number of files in this tree, including this and subdirectories uint32_t FileEntryTree::NumFilesTotal() const { uint32_t numFiles = aznumeric_cast(m_mapFiles.size()); @@ -91,21 +95,6 @@ namespace AZ::IO::ZipDir m_mapFiles.clear(); } - size_t FileEntryTree::GetSize() const - { - size_t nSize = sizeof(*this); - for (const auto& [dirname, dirEntry] : m_mapDirs) - { - nSize += dirname.size() + sizeof(decltype(m_mapDirs)::value_type) + dirEntry->GetSize(); - } - - for (const auto& [filename, fileEntry] : m_mapFiles) - { - nSize += filename.size() + sizeof(decltype(m_mapFiles)::value_type); - } - return nSize; - } - bool FileEntryTree::IsOwnerOf(const FileEntry* pFileEntry) const { for (const auto& [path, fileEntry] : m_mapFiles) @@ -127,7 +116,7 @@ namespace AZ::IO::ZipDir return false; } - FileEntryTree* FileEntryTree::FindDir(AZStd::string_view szDirName) + FileEntryTree* FileEntryTree::FindDir(AZ::IO::PathView szDirName) { if (auto it = m_mapDirs.find(szDirName); it != m_mapDirs.end()) { @@ -137,7 +126,7 @@ namespace AZ::IO::ZipDir return nullptr; } - FileEntryTree::FileMap::iterator FileEntryTree::FindFile(AZStd::string_view szFileName) + FileEntryTree::FileMap::iterator FileEntryTree::FindFile(AZ::IO::PathView szFileName) { return m_mapFiles.find(szFileName); } @@ -152,7 +141,7 @@ namespace AZ::IO::ZipDir return it == GetDirEnd() ? nullptr : it->second.get(); } - ErrorEnum FileEntryTree::RemoveDir(AZStd::string_view szDirName) + ErrorEnum FileEntryTree::RemoveDir(AZ::IO::PathView szDirName) { SubdirMap::iterator itRemove = m_mapDirs.find(szDirName); if (itRemove == m_mapDirs.end()) @@ -164,7 +153,13 @@ namespace AZ::IO::ZipDir return ZD_ERROR_SUCCESS; } - ErrorEnum FileEntryTree::RemoveFile(AZStd::string_view szFileName) + ErrorEnum FileEntryTree::RemoveAll() + { + Clear(); + return ZD_ERROR_SUCCESS; + } + + ErrorEnum FileEntryTree::RemoveFile(AZ::IO::PathView szFileName) { FileMap::iterator itRemove = m_mapFiles.find(szFileName); if (itRemove == m_mapFiles.end()) diff --git a/Code/Framework/AzFramework/AzFramework/Archive/ZipDirTree.h b/Code/Framework/AzFramework/AzFramework/Archive/ZipDirTree.h index cfe539e896..9bdc047a7a 100644 --- a/Code/Framework/AzFramework/AzFramework/Archive/ZipDirTree.h +++ b/Code/Framework/AzFramework/AzFramework/Archive/ZipDirTree.h @@ -10,6 +10,7 @@ #pragma once #include +#include #include #include #include @@ -24,12 +25,12 @@ namespace AZ::IO::ZipDir // adds a file to this directory // Function can modify szPath input - ErrorEnum Add(AZStd::string_view szPath, const FileEntryBase& file); + ErrorEnum Add(AZ::IO::PathView szPath, const FileEntryBase& file); // Adds or finds the file. Returns non-initialized structure if it was added, // or an IsInitialized() structure if it was found // Function can modify szPath input - FileEntry* Add(AZStd::string_view szPath); + FileEntry* Add(AZ::IO::PathView szPath); // returns the number of files in this tree, including this and sublevels uint32_t NumFilesTotal() const; @@ -45,24 +46,18 @@ namespace AZ::IO::ZipDir m_mapFiles.swap(rThat.m_mapFiles); } - size_t GetSize() const; - bool IsOwnerOf(const FileEntry* pFileEntry) const; // subdirectories - using SubdirMap = AZStd::map>; + using SubdirMap = AZStd::map>; // file entries - using FileMap = AZStd::map>; + using FileMap = AZStd::map>; - FileEntryTree* FindDir(AZStd::string_view szDirName); - ErrorEnum RemoveDir (AZStd::string_view szDirName); - ErrorEnum RemoveAll () - { - Clear(); - return ZD_ERROR_SUCCESS; - } - FileMap::iterator FindFile(AZStd::string_view szFileName); - ErrorEnum RemoveFile(AZStd::string_view szFileName); + FileEntryTree* FindDir(AZ::IO::PathView szDirName); + ErrorEnum RemoveDir(AZ::IO::PathView szDirName); + ErrorEnum RemoveAll(); + FileMap::iterator FindFile(AZ::IO::PathView szFileName); + ErrorEnum RemoveFile(AZ::IO::PathView szFileName); // the FileEntryTree is simultaneously an entry in the dir list AND the directory header FileEntryTree* GetDirectory() { @@ -75,8 +70,8 @@ namespace AZ::IO::ZipDir SubdirMap::iterator GetDirBegin() { return m_mapDirs.begin(); } SubdirMap::iterator GetDirEnd() { return m_mapDirs.end(); } uint32_t NumDirs() const { return aznumeric_cast(m_mapDirs.size()); } - AZStd::string_view GetFileName(FileMap::iterator it) { return it->first; } - AZStd::string_view GetDirName(SubdirMap::iterator it) { return it->first; } + AZStd::string_view GetFileName(FileMap::iterator it) { return it->first.Native(); } + AZStd::string_view GetDirName(SubdirMap::iterator it) { return it->first.Native(); } FileEntry* GetFileEntry(FileMap::iterator it); FileEntryTree* GetDirEntry(SubdirMap::iterator it); diff --git a/Code/Framework/AzFramework/AzFramework/AzFrameworkModule.cpp b/Code/Framework/AzFramework/AzFramework/AzFrameworkModule.cpp index c5fee7ec9a..83f1954e11 100644 --- a/Code/Framework/AzFramework/AzFramework/AzFrameworkModule.cpp +++ b/Code/Framework/AzFramework/AzFramework/AzFrameworkModule.cpp @@ -16,6 +16,7 @@ #include #include #include +#include #include #include #include @@ -47,6 +48,7 @@ namespace AzFramework AzFramework::CreateScriptDebugAgentFactory(), AzFramework::AssetSystem::AssetSystemComponent::CreateDescriptor(), AzFramework::InputSystemComponent::CreateDescriptor(), + AzFramework::InputContextComponent::CreateDescriptor(), #if !defined(AZCORE_EXCLUDE_LUA) AzFramework::ScriptComponent::CreateDescriptor(), diff --git a/Code/Framework/AzFramework/AzFramework/IO/LocalFileIO.cpp b/Code/Framework/AzFramework/AzFramework/IO/LocalFileIO.cpp index 50190ac7d5..4072c17ea0 100644 --- a/Code/Framework/AzFramework/AzFramework/IO/LocalFileIO.cpp +++ b/Code/Framework/AzFramework/AzFramework/IO/LocalFileIO.cpp @@ -734,7 +734,7 @@ namespace AZ { if (AZ::StringFunc::StartsWith(pathStrView, aliasKey)) { - // Reduce of the size result result path by the size of the and add the resolved alias size + // Add to the size of result path by the resolved alias length - the alias key length AZStd::string_view postAliasView = pathStrView.substr(aliasKey.size()); size_t requiredFixedMaxPathSize = postAliasView.size(); requiredFixedMaxPathSize += aliasValue.size(); diff --git a/Code/Framework/AzFramework/AzFramework/Input/Contexts/InputContext.h b/Code/Framework/AzFramework/AzFramework/Input/Contexts/InputContext.h index 7220b8b8d5..e7143a25b9 100644 --- a/Code/Framework/AzFramework/AzFramework/Input/Contexts/InputContext.h +++ b/Code/Framework/AzFramework/AzFramework/Input/Contexts/InputContext.h @@ -55,6 +55,10 @@ namespace AzFramework // Allocator AZ_CLASS_ALLOCATOR(InputContext, AZ::SystemAllocator, 0); + //////////////////////////////////////////////////////////////////////////////////////////// + // Type Info + AZ_RTTI(InputContext, "{D17A85B2-405F-40AB-BBA7-F118256D39AB}", InputDevice); + //////////////////////////////////////////////////////////////////////////////////////////// //! Constructor //! \param[in] name Unique, will be truncated if exceeds InputDeviceId::MAX_NAME_LENGTH = 64 diff --git a/Code/Framework/AzFramework/AzFramework/Input/Contexts/InputContextComponent.cpp b/Code/Framework/AzFramework/AzFramework/Input/Contexts/InputContextComponent.cpp new file mode 100644 index 0000000000..ff147bd9d8 --- /dev/null +++ b/Code/Framework/AzFramework/AzFramework/Input/Contexts/InputContextComponent.cpp @@ -0,0 +1,172 @@ +/* + * Copyright (c) Contributors to the Open 3D Engine Project. + * For complete copyright and license terms please see the LICENSE at the root of this distribution. + * + * SPDX-License-Identifier: Apache-2.0 OR MIT + * + */ + +#include +#include +#include + +#include +#include +#include + +//////////////////////////////////////////////////////////////////////////////////////////////////// +namespace AzFramework +{ + //////////////////////////////////////////////////////////////////////////////////////////////// + void InputContextComponent::GetProvidedServices(AZ::ComponentDescriptor::DependencyArrayType& provided) + { + provided.push_back(AZ_CRC("InputContextService", 0xa2734425)); + } + + //////////////////////////////////////////////////////////////////////////////////////////////// + void InputContextComponent::Reflect(AZ::ReflectContext* context) + { + if (AZ::SerializeContext* serializeContext = azrtti_cast(context)) + { + serializeContext->Class() + ->Version(0) + ->Field("Unique Name", &InputContextComponent::m_uniqueName) + ->Field("Input Mappings", &InputContextComponent::m_inputMappings) + ->Field("Local Player Index", &InputContextComponent::m_localPlayerIndex) + ->Field("Input Listener Priority", &InputContextComponent::m_inputListenerPriority) + ->Field("Consumes Processed Input", &InputContextComponent::m_consumesProcessedInput) + ; + + if (AZ::EditContext* editContext = serializeContext->GetEditContext()) + { + editContext->Class("Input Context", + "An input context is a collection of input mappings, which map 'raw' input to custom input channels (ie. events).") + ->ClassElement(AZ::Edit::ClassElements::EditorData, "") + ->Attribute(AZ::Edit::Attributes::AutoExpand, true) + ->Attribute(AZ::Edit::Attributes::Category, "Input") + ->Attribute(AZ::Edit::Attributes::AppearsInAddComponentMenu, AZ_CRC("Game", 0x232b318c)) + ->DataElement(AZ::Edit::UIHandlers::Default, &InputContextComponent::m_uniqueName, "Unique Name", + "The name of the input context, unique among all active input contexts and input devices.\n" + "This will be truncated if its length exceeds that of InputDeviceId::MAX_NAME_LENGTH = 64") + ->DataElement(AZ::Edit::UIHandlers::Default, &InputContextComponent::m_inputMappings, "Input Mappings", + "The list of all input mappings that will be created when the input context is activated.") + ->Attribute(AZ::Edit::Attributes::AutoExpand, true) + ->DataElement(AZ::Edit::UIHandlers::SpinBox, &InputContextComponent::m_localPlayerIndex, "Local Player Index", + "The local player index that this context will receive input from (0 based, -1 means all controllers).\n" + "Will only work on platforms such as PC where the local user id corresponds to the local player index.\n" + "For other platforms, SetLocalUserId must be called at runtime with the id of a logged in user.") + ->Attribute(AZ::Edit::Attributes::Min, -1) + ->Attribute(AZ::Edit::Attributes::Max, 3) + ->DataElement(AZ::Edit::UIHandlers::SpinBox, &InputContextComponent::m_inputListenerPriority, "Input Listener Priority", + "The priority used to sort the input context relative to all other input event listeners.\n" + "Higher numbers indicate greater priority.") + ->Attribute(AZ::Edit::Attributes::Min, InputChannelEventListener::GetPriorityLast()) + ->Attribute(AZ::Edit::Attributes::Max, InputChannelEventListener::GetPriorityFirst()) + ->DataElement(AZ::Edit::UIHandlers::CheckBox, &InputContextComponent::m_consumesProcessedInput, "Consumes Processed Input", + "Should the input context consume input that is processed by any of its input mappings?") + ; + } + } + + InputMapping::ConfigBase::Reflect(context); + InputMappingAnd::Config::Reflect(context); + InputMappingOr::Config::Reflect(context); + } + + //////////////////////////////////////////////////////////////////////////////////////////////// + InputContextComponent::~InputContextComponent() + { + Deactivate(); + } + + //////////////////////////////////////////////////////////////////////////////////////////////// + void InputContextComponent::Init() + { + // The local player index that this component will receive input from (0 base, -1 wildcard) + // can be set from data, but will only work on platforms where the local user id corresponds + // to a local player index. For other platforms SetLocalUserId must be called at runtime with + // the id of a logged in local user, which will overwrite anything that is set here from data. + const LocalUserId localUserId = (m_localPlayerIndex == -1) ? LocalUserIdAny : aznumeric_cast(m_localPlayerIndex); + SetLocalUserId(localUserId); + } + + //////////////////////////////////////////////////////////////////////////////////////////////// + void InputContextComponent::Activate() + { + InputContextComponentRequestBus::Handler::BusConnect(GetEntityId()); + CreateInputContext(); + } + + //////////////////////////////////////////////////////////////////////////////////////////////// + void InputContextComponent::Deactivate() + { + ResetInputContext(); + InputContextComponentRequestBus::Handler::BusDisconnect(GetEntityId()); + } + + //////////////////////////////////////////////////////////////////////////////////////////////// + void InputContextComponent::SetLocalUserId(LocalUserId localUserId) + { + // Create a new filter, or reset any existing one if we have been passed LocalUserIdAny. + if (localUserId != LocalUserIdAny) + { + m_localUserIdFilter = AZStd::make_shared(InputChannelEventFilter::AnyChannelNameCrc32, + InputChannelEventFilter::AnyDeviceNameCrc32, + aznumeric_cast(m_localPlayerIndex)); + } + else + { + m_localUserIdFilter.reset(); + } + + // Set the filter if the input context has already been created. + if (m_inputContext) + { + m_inputContext->SetFilter(m_localUserIdFilter); + } + } + + //////////////////////////////////////////////////////////////////////////////////////////////// + void InputContextComponent::CreateInputContext() + { + if (m_uniqueName.empty()) + { + AZ_Error("InputContextComponent", false, "Cannot create input context with empty name."); + return; + } + + if (InputDeviceRequests::FindInputDevice(InputDeviceId(m_uniqueName.c_str()))) + { + AZ_Error("InputContextComponent", false, + "Cannot create input context '%s' with non-unique name.", m_uniqueName.c_str()); + return; + } + + if (m_inputMappings.empty()) + { + AZ_Error("InputContextComponent", false, + "Cannot create input context '%s' with no input mappings.", m_uniqueName.c_str()); + return; + } + + // Create the input context. + InputContext::InitData initData; + initData.autoActivate = true; + initData.filter = m_localUserIdFilter; + initData.priority = m_inputListenerPriority; + initData.consumesProcessedInput = m_consumesProcessedInput; + m_inputContext = AZStd::make_unique(m_uniqueName.c_str(), initData); + + // Create and add all input mappings. + for (const InputMapping::ConfigBase* inputMapping : m_inputMappings) + { + inputMapping->CreateInputMappingAndAddToContext(*m_inputContext); + } + } + + //////////////////////////////////////////////////////////////////////////////////////////////// + void InputContextComponent::ResetInputContext() + { + m_inputContext.reset(); + } +} // namespace AzFramework diff --git a/Code/Framework/AzFramework/AzFramework/Input/Contexts/InputContextComponent.h b/Code/Framework/AzFramework/AzFramework/Input/Contexts/InputContextComponent.h new file mode 100644 index 0000000000..1b9286bd4c --- /dev/null +++ b/Code/Framework/AzFramework/AzFramework/Input/Contexts/InputContextComponent.h @@ -0,0 +1,129 @@ +/* + * Copyright (c) Contributors to the Open 3D Engine Project. + * For complete copyright and license terms please see the LICENSE at the root of this distribution. + * + * SPDX-License-Identifier: Apache-2.0 OR MIT + * + */ + +#pragma once + +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include + +//////////////////////////////////////////////////////////////////////////////////////////////////// +namespace AzFramework +{ + //////////////////////////////////////////////////////////////////////////////////////////////// + class InputContextComponentRequests : public AZ::ComponentBus + { + public: + //////////////////////////////////////////////////////////////////////////////////////////// + //! Set the local user id that the InputContextComponent should process input from + //! \param[in] localUserId Local user id the InputContextComponent should process input from + virtual void SetLocalUserId(LocalUserId localUserId) = 0; + }; + using InputContextComponentRequestBus = AZ::EBus; + + //////////////////////////////////////////////////////////////////////////////////////////////// + //! An InputContextComponent is used to configure (at edit time) the data necessary to create an + //! InputContext (at run time). The life cycle of any InputContextComponent is controlled by the + //! AZ::Entity it is attached to, adhering to the same rules as any other AZ::Component, and the + //! InputContext which it owns is created/destroyed when the component is activated/deactivated. + class InputContextComponent : public AZ::Component + , public InputContextComponentRequestBus::Handler + { + public: + //////////////////////////////////////////////////////////////////////////////////////////// + // AZ::Component Setup + AZ_COMPONENT(InputContextComponent, "{321689F8-A572-47D7-9D1C-EF9E0D2CD472}"); + + //////////////////////////////////////////////////////////////////////////////////////////// + //! \ref AZ::ComponentDescriptor::GetProvidedServices + static void GetProvidedServices(AZ::ComponentDescriptor::DependencyArrayType& provided); + + //////////////////////////////////////////////////////////////////////////////////////////// + //! \ref AZ::ComponentDescriptor::Reflect + static void Reflect(AZ::ReflectContext* context); + + //////////////////////////////////////////////////////////////////////////////////////////// + //! Default Constructor + InputContextComponent() = default; + + //////////////////////////////////////////////////////////////////////////////////////////// + //! Destructor + ~InputContextComponent() override; + + protected: + //////////////////////////////////////////////////////////////////////////////////////////// + //! \ref AZ::Component::Init + void Init() override; + + //////////////////////////////////////////////////////////////////////////////////////////// + //! \ref AZ::Component::Activate + void Activate() override; + + //////////////////////////////////////////////////////////////////////////////////////////// + //! \ref AZ::Component::Deactivate + void Deactivate() override; + + //////////////////////////////////////////////////////////////////////////////////////////// + // \ref AzFramework::InputContextComponentRequests::SetLocalUserId + void SetLocalUserId(LocalUserId localUserId) override; + + private: + //////////////////////////////////////////////////////////////////////////////////////////// + //! Create the input context. + void CreateInputContext(); + + //////////////////////////////////////////////////////////////////////////////////////////// + //! Reset the input context. + void ResetInputContext(); + + //////////////////////////////////////////////////////////////////////////////////////////// + //! The list of all input mappings that will be created when the input context is activated. + //! Reflected to EditContext, then used to create and add input mapping classes in Activate. + AZStd::vector m_inputMappings; + + //////////////////////////////////////////////////////////////////////////////////////////// + //! The name of the input context, unique among all active input contexts and input devices. + //! This will be truncated if its length exceeds that of InputDeviceId::MAX_NAME_LENGTH = 64 + //! Reflected to EditContext, then used to create the unique input context class in Activate. + AZStd::string m_uniqueName; + + //////////////////////////////////////////////////////////////////////////////////////////// + //! Input context that is created and owned by this component. Not reflected to EditContext. + AZStd::unique_ptr m_inputContext; + + //////////////////////////////////////////////////////////////////////////////////////////// + //! Filter used to determine whether an input event should be handled by this input context. + //! Not reflected, but created inside SetLocalUserId if needed to fliter by a local user id. + AZStd::shared_ptr m_localUserIdFilter; + + //////////////////////////////////////////////////////////////////////////////////////////// + //! The local player index that this component will receive input from (0 base, -1 wildcard). + //! Will only work on platforms where the local user id corresponds to the local player index. + //! For other platforms, SetLocalUserId must be called at runtime with id of a logged in user. + //! Reflected to EditContext, then used if needed to create the local user id filter in Init. + AZ::s32 m_localPlayerIndex = -1; + + //////////////////////////////////////////////////////////////////////////////////////////// + //! The priority used to sort the input context relative to all other input event listeners. + //! Reflected to EditContext, then used to create the unique input context class in Activate. + AZ::s32 m_inputListenerPriority = InputChannelEventListener::GetPriorityDefault(); + + //////////////////////////////////////////////////////////////////////////////////////////// + //! Should the input context consume input that is processed by any of its input mappings? + //! Reflected to EditContext, then used to create the unique input context class in Activate. + bool m_consumesProcessedInput = false; + }; +} // namespace AzFramework diff --git a/Code/Framework/AzFramework/AzFramework/Input/Mappings/InputMapping.cpp b/Code/Framework/AzFramework/AzFramework/Input/Mappings/InputMapping.cpp index 2f848368ca..b8a261677f 100644 --- a/Code/Framework/AzFramework/AzFramework/Input/Mappings/InputMapping.cpp +++ b/Code/Framework/AzFramework/AzFramework/Input/Mappings/InputMapping.cpp @@ -9,9 +9,156 @@ #include #include +#include +#include +#include + //////////////////////////////////////////////////////////////////////////////////////////////////// namespace AzFramework { + //////////////////////////////////////////////////////////////////////////////////////////////// + void InputMapping::InputChannelNameFilteredByDeviceType::Reflect(AZ::ReflectContext* context) + { + if (AZ::SerializeContext* serializeContext = azrtti_cast(context)) + { + serializeContext->Class() + ->Version(0) + ->Field("Input Device Type", &InputChannelNameFilteredByDeviceType::m_inputDeviceType) + ->Field("Input Channel Name", &InputChannelNameFilteredByDeviceType::m_inputChannelName) + ; + + if (AZ::EditContext* editContext = serializeContext->GetEditContext()) + { + editContext->Class("InputChannelNameFilteredByDeviceType", + "An input channel name (filtered by an input device type) to add to the input mapping.") + ->ClassElement(AZ::Edit::ClassElements::EditorData, "") + ->Attribute(AZ::Edit::Attributes::AutoExpand, true) + ->Attribute(AZ::Edit::Attributes::ChangeNotify, AZ::Edit::PropertyRefreshLevels::AttributesAndValues) + ->Attribute(AZ::Edit::Attributes::NameLabelOverride, &InputChannelNameFilteredByDeviceType::GetNameLabelOverride) + ->DataElement(AZ::Edit::UIHandlers::ComboBox, &InputChannelNameFilteredByDeviceType::m_inputDeviceType, "Input Device Type", + "The type of input device by which to filter input channel names.") + ->Attribute(AZ::Edit::Attributes::StringList, &InputChannelNameFilteredByDeviceType::GetValidInputDeviceTypes) + ->Attribute(AZ::Edit::Attributes::ChangeNotify, &InputChannelNameFilteredByDeviceType::OnInputDeviceTypeSelected) + ->DataElement(AZ::Edit::UIHandlers::ComboBox, &InputChannelNameFilteredByDeviceType::m_inputChannelName, "Input Channel Name", + "The input channel name to add to the input mapping.") + ->Attribute(AZ::Edit::Attributes::StringList, &InputChannelNameFilteredByDeviceType::GetValidInputChannelNamesBySelectedDevice) + ->Attribute(AZ::Edit::Attributes::ChangeNotify, AZ::Edit::PropertyRefreshLevels::AttributesAndValues) + ; + } + } + } + + //////////////////////////////////////////////////////////////////////////////////////////////// + InputMapping::InputChannelNameFilteredByDeviceType::InputChannelNameFilteredByDeviceType() + { + // Try initialize the selected input device type and input channel name to something valid. + if (m_inputDeviceType.empty()) + { + const AZStd::vector validInputDeviceTypes = GetValidInputDeviceTypes(); + if (!validInputDeviceTypes.empty()) + { + m_inputDeviceType = validInputDeviceTypes[0]; + OnInputDeviceTypeSelected(); + } + } + } + + //////////////////////////////////////////////////////////////////////////////////////////////// + AZ::Crc32 InputMapping::InputChannelNameFilteredByDeviceType::OnInputDeviceTypeSelected() + { + const AZStd::vector validInputNames = GetValidInputChannelNamesBySelectedDevice(); + if (!validInputNames.empty()) + { + m_inputChannelName = validInputNames[0]; + } + return AZ::Edit::PropertyRefreshLevels::AttributesAndValues; + } + + //////////////////////////////////////////////////////////////////////////////////////////////// + AZStd::string InputMapping::InputChannelNameFilteredByDeviceType::GetNameLabelOverride() const + { + return m_inputChannelName.empty() ? "" : m_outputInputChannelName; + } + //////////////////////////////////////////////////////////////////////////////////////////////// InputMapping::InputMapping(const InputChannelId& inputChannelId, const InputContext& inputContext) : InputChannel(inputChannelId, inputContext) diff --git a/Code/Framework/AzFramework/AzFramework/Input/Mappings/InputMapping.h b/Code/Framework/AzFramework/AzFramework/Input/Mappings/InputMapping.h index 93ca96eded..c2f82fb7f8 100644 --- a/Code/Framework/AzFramework/AzFramework/Input/Mappings/InputMapping.h +++ b/Code/Framework/AzFramework/AzFramework/Input/Mappings/InputMapping.h @@ -12,6 +12,7 @@ #include #include +#include //////////////////////////////////////////////////////////////////////////////////////////////////// namespace AzFramework @@ -26,6 +27,111 @@ namespace AzFramework class InputMapping : public InputChannel { public: + //////////////////////////////////////////////////////////////////////////////////////////// + //! Convenience class that allows for selection of an input channel name filtered by device. + struct InputChannelNameFilteredByDeviceType + { + public: + //////////////////////////////////////////////////////////////////////////////////////// + // Allocator + AZ_CLASS_ALLOCATOR(InputChannelNameFilteredByDeviceType, AZ::SystemAllocator, 0); + + //////////////////////////////////////////////////////////////////////////////////////// + // Type Info + AZ_RTTI(InputChannelNameFilteredByDeviceType, "{68CC4865-1C0E-4E2E-BDAE-AF42EA30DBE8}"); + + //////////////////////////////////////////////////////////////////////////////////////// + // Reflection + static void Reflect(AZ::ReflectContext* context); + + //////////////////////////////////////////////////////////////////////////////////////////// + //! Constructor + InputChannelNameFilteredByDeviceType(); + + //////////////////////////////////////////////////////////////////////////////////////////// + //! Destructor + virtual ~InputChannelNameFilteredByDeviceType() = default; + + //////////////////////////////////////////////////////////////////////////////////////////// + //! Get the currently selected input device type. + //! \return Currently selected input device type. + inline const AZStd::string& GetInputDeviceType() const { return m_inputDeviceType; } + + //////////////////////////////////////////////////////////////////////////////////////////// + //! Get the currently selected input channel name. + //! \return Currently selected input channel name. + inline const AZStd::string& GetInputChannelName() const { return m_inputChannelName; } + + protected: + //////////////////////////////////////////////////////////////////////////////////////////// + //! Called when an input device type is selected. + //! \return The AZ::Edit::PropertyRefreshLevels to apply to the property tree view. + virtual AZ::Crc32 OnInputDeviceTypeSelected(); + + //////////////////////////////////////////////////////////////////////////////////////////// + //! Get the name label override to display. + //! \return Name label override to display. + virtual AZStd::string GetNameLabelOverride() const; + + //////////////////////////////////////////////////////////////////////////////////////////// + //! Get the valid input device types for this input mapping. + //! \return Valid input device types for this input mapping. + virtual AZStd::vector GetValidInputDeviceTypes() const; + + //////////////////////////////////////////////////////////////////////////////////////////// + //! Get the valid input channel names for this input mapping given the selected device type. + //! \return Valid input channel names for this input mapping given the selected device type. + virtual AZStd::vector GetValidInputChannelNamesBySelectedDevice() const; + + private: + //////////////////////////////////////////////////////////////////////////////////////////// + // Variables + AZStd::string m_inputDeviceType; //!< The currently selected input device type. + AZStd::string m_inputChannelName; //!< The currently selected input channel name. + }; + + //////////////////////////////////////////////////////////////////////////////////////////// + //! Base class for input mapping configuration values that are exposed to the editor. + class ConfigBase + { + public: + //////////////////////////////////////////////////////////////////////////////////////// + // Allocator + AZ_CLASS_ALLOCATOR(ConfigBase, AZ::SystemAllocator, 0); + + //////////////////////////////////////////////////////////////////////////////////////// + // Type Info + AZ_RTTI(ConfigBase, "{72EBBBCC-D57E-4085-AFD9-4910506010B6}"); + + //////////////////////////////////////////////////////////////////////////////////////// + // Reflection + static void Reflect(AZ::ReflectContext* context); + + //////////////////////////////////////////////////////////////////////////////////////////// + //! Destructor + virtual ~ConfigBase() = default; + + //////////////////////////////////////////////////////////////////////////////////////// + //! Create an input mapping and add it to the input context. + //! \param[in] inputContext Input context that the input mapping will be added to. + AZStd::shared_ptr CreateInputMappingAndAddToContext(InputContext& inputContext) const; + + //////////////////////////////////////////////////////////////////////////////////////// + //! Override to create the relevant input mapping. + //! \param[in] inputContext Input context that owns the input mapping. + virtual AZStd::shared_ptr CreateInputMapping(const InputContext& inputContext) const = 0; + + //////////////////////////////////////////////////////////////////////////////////////////// + //! Get the name label override to display. + //! \return Name label override to display. + virtual AZStd::string GetNameLabelOverride() const; + + protected: + //////////////////////////////////////////////////////////////////////////////////////// + //! The unique input channel name (event) output by the input mapping. + AZStd::string m_outputInputChannelName; + }; + //////////////////////////////////////////////////////////////////////////////////////////// // Allocator AZ_CLASS_ALLOCATOR(InputMapping, AZ::SystemAllocator, 0); diff --git a/Code/Framework/AzFramework/AzFramework/Input/Mappings/InputMappingAnd.cpp b/Code/Framework/AzFramework/AzFramework/Input/Mappings/InputMappingAnd.cpp index 5d371888da..6837807f4e 100644 --- a/Code/Framework/AzFramework/AzFramework/Input/Mappings/InputMappingAnd.cpp +++ b/Code/Framework/AzFramework/AzFramework/Input/Mappings/InputMappingAnd.cpp @@ -8,9 +8,72 @@ #include +#include +#include +#include + //////////////////////////////////////////////////////////////////////////////////////////////////// namespace AzFramework { + //////////////////////////////////////////////////////////////////////////////////////////////// + void InputMappingAnd::Config::Reflect(AZ::ReflectContext* context) + { + if (AZ::SerializeContext* serializeContext = azrtti_cast(context)) + { + serializeContext->Class() + ->Version(0) + ->Field("Source Input Channel Names", &Config::m_sourceInputChannelNames) + ; + + if (AZ::EditContext* editContext = serializeContext->GetEditContext()) + { + editContext->Class("Input Mapping: And", + "Maps multiple different input sources to a single output using 'AND' logic.") + ->ClassElement(AZ::Edit::ClassElements::EditorData, "") + ->Attribute(AZ::Edit::Attributes::AutoExpand, true) + ->Attribute(AZ::Edit::Attributes::ChangeNotify, AZ::Edit::PropertyRefreshLevels::AttributesAndValues) + ->Attribute(AZ::Edit::Attributes::NameLabelOverride, &InputMappingAnd::Config::GetNameLabelOverride) + ->DataElement(AZ::Edit::UIHandlers::Default, &Config::m_sourceInputChannelNames, "Source Input Channel Names", + "The source input channel names that will be mapped to the output input channel name.") + ; + } + } + } + + //////////////////////////////////////////////////////////////////////////////////////////////// + AZStd::shared_ptr InputMappingAnd::Config::CreateInputMapping(const InputContext& inputContext) const + { + if (m_outputInputChannelName.empty()) + { + AZ_Error("InputMappingAnd::Config", false, "Cannot create input mapping with empty name."); + return nullptr; + } + + if (InputChannelRequests::FindInputChannel(InputChannelId(m_outputInputChannelName.c_str()))) + { + AZ_Error("InputMappingAnd::Config", false, + "Cannot create input mapping '%s' with non-unique name.", m_outputInputChannelName.c_str()); + return nullptr; + } + + if (m_sourceInputChannelNames.empty()) + { + AZ_Error("InputMappingAnd::Config", false, + "Cannot create input mapping '%s' with no source inputs.", m_outputInputChannelName.c_str()); + return nullptr; + } + + const InputChannelId outputInputChannelId(m_outputInputChannelName.c_str()); + AZStd::shared_ptr inputMapping = AZStd::make_shared(outputInputChannelId, + inputContext); + for (const InputChannelNameFilteredByDeviceType& sourceInputChannelName : m_sourceInputChannelNames) + { + const InputChannelId sourceInputChannelId(sourceInputChannelName.GetInputChannelName().c_str()); + inputMapping->AddSourceInput(sourceInputChannelId); + } + return inputMapping; + } + //////////////////////////////////////////////////////////////////////////////////////////////// InputMappingAnd::InputMappingAnd(const InputChannelId& inputChannelId, const InputContext& inputContext) : InputMapping(inputChannelId, inputContext) diff --git a/Code/Framework/AzFramework/AzFramework/Input/Mappings/InputMappingAnd.h b/Code/Framework/AzFramework/AzFramework/Input/Mappings/InputMappingAnd.h index d7a767e3a5..61e54497db 100644 --- a/Code/Framework/AzFramework/AzFramework/Input/Mappings/InputMappingAnd.h +++ b/Code/Framework/AzFramework/AzFramework/Input/Mappings/InputMappingAnd.h @@ -19,6 +19,38 @@ namespace AzFramework class InputMappingAnd : public InputMapping { public: + //////////////////////////////////////////////////////////////////////////////////////////// + //! The input mapping configuration values that are exposed to the editor. + class Config : public InputMapping::ConfigBase + { + public: + //////////////////////////////////////////////////////////////////////////////////////// + // Allocator + AZ_CLASS_ALLOCATOR(Config, AZ::SystemAllocator, 0); + + //////////////////////////////////////////////////////////////////////////////////////// + // Type Info + AZ_RTTI(Config, "{54E972F3-0477-4E2E-93F5-4E06ED755DF6}", InputMapping::ConfigBase); + + //////////////////////////////////////////////////////////////////////////////////////// + // Reflection + static void Reflect(AZ::ReflectContext* context); + + //////////////////////////////////////////////////////////////////////////////////////////// + //! Destructor + ~Config() override = default; + + protected: + //////////////////////////////////////////////////////////////////////////////////////// + //! \ref AzFramework::InputMapping::Type::CreateInputMapping + AZStd::shared_ptr CreateInputMapping(const InputContext& inputContext) const override; + + private: + //////////////////////////////////////////////////////////////////////////////////////// + //! The source input channel names that will be mapped to the output input channel name. + AZStd::vector m_sourceInputChannelNames; + }; + //////////////////////////////////////////////////////////////////////////////////////////// // Allocator AZ_CLASS_ALLOCATOR(InputMappingAnd, AZ::SystemAllocator, 0); diff --git a/Code/Framework/AzFramework/AzFramework/Input/Mappings/InputMappingOr.cpp b/Code/Framework/AzFramework/AzFramework/Input/Mappings/InputMappingOr.cpp index 459d32dc68..bc47065c05 100644 --- a/Code/Framework/AzFramework/AzFramework/Input/Mappings/InputMappingOr.cpp +++ b/Code/Framework/AzFramework/AzFramework/Input/Mappings/InputMappingOr.cpp @@ -8,9 +8,72 @@ #include +#include +#include +#include + //////////////////////////////////////////////////////////////////////////////////////////////////// namespace AzFramework { + //////////////////////////////////////////////////////////////////////////////////////////////// + void InputMappingOr::Config::Reflect(AZ::ReflectContext* context) + { + if (AZ::SerializeContext* serializeContext = azrtti_cast(context)) + { + serializeContext->Class() + ->Version(0) + ->Field("Source Input Channel Names", &Config::m_sourceInputChannelNames) + ; + + if (AZ::EditContext* editContext = serializeContext->GetEditContext()) + { + editContext->Class("Input Mapping: Or", + "Maps multiple different input sources to a single output using 'OR' logic.") + ->ClassElement(AZ::Edit::ClassElements::EditorData, "") + ->Attribute(AZ::Edit::Attributes::AutoExpand, true) + ->Attribute(AZ::Edit::Attributes::ChangeNotify, AZ::Edit::PropertyRefreshLevels::AttributesAndValues) + ->Attribute(AZ::Edit::Attributes::NameLabelOverride, &InputMappingOr::Config::GetNameLabelOverride) + ->DataElement(AZ::Edit::UIHandlers::Default, &Config::m_sourceInputChannelNames, "Source Input Channel Names", + "The source input channel names that will be mapped to the output input channel name.") + ; + } + } + } + + //////////////////////////////////////////////////////////////////////////////////////////////// + AZStd::shared_ptr InputMappingOr::Config::CreateInputMapping(const InputContext& inputContext) const + { + if (m_outputInputChannelName.empty()) + { + AZ_Error("InputMappingOr::Config", false, "Cannot create input mapping with empty name."); + return nullptr; + } + + if (InputChannelRequests::FindInputChannel(InputChannelId(m_outputInputChannelName.c_str()))) + { + AZ_Error("InputMappingOr::Config", false, + "Cannot create input mapping '%s' with non-unique name.", m_outputInputChannelName.c_str()); + return nullptr; + } + + if (m_sourceInputChannelNames.empty()) + { + AZ_Error("InputMappingOr::Config", false, + "Cannot create input mapping '%s' with no source inputs.", m_outputInputChannelName.c_str()); + return nullptr; + } + + const InputChannelId outputInputChannelId(m_outputInputChannelName.c_str()); + AZStd::shared_ptr inputMapping = AZStd::make_shared(outputInputChannelId, + inputContext); + for (const InputChannelNameFilteredByDeviceType& sourceInputChannelName : m_sourceInputChannelNames) + { + const InputChannelId sourceInputChannelId(sourceInputChannelName.GetInputChannelName().c_str()); + inputMapping->AddSourceInput(sourceInputChannelId); + } + return inputMapping; + } + //////////////////////////////////////////////////////////////////////////////////////////////// InputMappingOr::InputMappingOr(const InputChannelId& inputChannelId, const InputContext& inputContext) : InputMapping(inputChannelId, inputContext) diff --git a/Code/Framework/AzFramework/AzFramework/Input/Mappings/InputMappingOr.h b/Code/Framework/AzFramework/AzFramework/Input/Mappings/InputMappingOr.h index b8359f828e..a0440d1855 100644 --- a/Code/Framework/AzFramework/AzFramework/Input/Mappings/InputMappingOr.h +++ b/Code/Framework/AzFramework/AzFramework/Input/Mappings/InputMappingOr.h @@ -19,6 +19,38 @@ namespace AzFramework class InputMappingOr : public InputMapping { public: + //////////////////////////////////////////////////////////////////////////////////////////// + //! The input mapping configuration values that are exposed to the editor. + class Config : public InputMapping::ConfigBase + { + public: + //////////////////////////////////////////////////////////////////////////////////////// + // Allocator + AZ_CLASS_ALLOCATOR(Config, AZ::SystemAllocator, 0); + + //////////////////////////////////////////////////////////////////////////////////////// + // Type Info + AZ_RTTI(Config, "{428AFDD4-D353-494A-BBAC-37E00F82CFFD}", InputMapping::ConfigBase); + + //////////////////////////////////////////////////////////////////////////////////////// + // Reflection + static void Reflect(AZ::ReflectContext* context); + + //////////////////////////////////////////////////////////////////////////////////////////// + //! Destructor + ~Config() override = default; + + protected: + //////////////////////////////////////////////////////////////////////////////////////// + //! \ref AzFramework::InputMapping::Type::CreateInputMapping + AZStd::shared_ptr CreateInputMapping(const InputContext& inputContext) const override; + + private: + //////////////////////////////////////////////////////////////////////////////////////// + //! The source input channel names that will be mapped to the output input channel name. + AZStd::vector m_sourceInputChannelNames; + }; + //////////////////////////////////////////////////////////////////////////////////////////// // Allocator AZ_CLASS_ALLOCATOR(InputMappingOr, AZ::SystemAllocator, 0); diff --git a/Code/Framework/AzFramework/AzFramework/Spawnable/SpawnableEntitiesInterface.cpp b/Code/Framework/AzFramework/AzFramework/Spawnable/SpawnableEntitiesInterface.cpp index 617eb3a0b9..75fca39574 100644 --- a/Code/Framework/AzFramework/AzFramework/Spawnable/SpawnableEntitiesInterface.cpp +++ b/Code/Framework/AzFramework/AzFramework/Spawnable/SpawnableEntitiesInterface.cpp @@ -36,6 +36,16 @@ namespace AzFramework return m_end; } + const AZ::Entity* const* SpawnableEntityContainerView::begin() const + { + return m_begin; + } + + const AZ::Entity* const* SpawnableEntityContainerView::end() const + { + return m_end; + } + const AZ::Entity* const* SpawnableEntityContainerView::cbegin() { return m_begin; @@ -46,11 +56,28 @@ namespace AzFramework return m_end; } - size_t SpawnableEntityContainerView::size() + AZ::Entity* SpawnableEntityContainerView::operator[](size_t n) + { + AZ_Assert(n < size(), "Index %zu is out of bounds (size: %llu) for Spawnable Entity Container View", n, size()); + return *(m_begin + n); + } + + const AZ::Entity* SpawnableEntityContainerView::operator[](size_t n) const + { + AZ_Assert(n < size(), "Index %zu is out of bounds (size: %llu) for Spawnable Entity Container View", n, size()); + return *(m_begin + n); + } + + size_t SpawnableEntityContainerView::size() const { return AZStd::distance(m_begin, m_end); } + bool SpawnableEntityContainerView::empty() const + { + return m_begin == m_end; + } + // // SpawnableConstEntityContainerView @@ -78,6 +105,16 @@ namespace AzFramework return m_end; } + const AZ::Entity* const* SpawnableConstEntityContainerView::begin() const + { + return m_begin; + } + + const AZ::Entity* const* SpawnableConstEntityContainerView::end() const + { + return m_end; + } + const AZ::Entity* const* SpawnableConstEntityContainerView::cbegin() { return m_begin; @@ -88,11 +125,28 @@ namespace AzFramework return m_end; } - size_t SpawnableConstEntityContainerView::size() + const AZ::Entity* SpawnableConstEntityContainerView::operator[](size_t n) + { + AZ_Assert(n < size(), "Index %zu is out of bounds (size: %llu) for Spawnable Const Entity Container View", n, size()); + return *(m_begin + n); + } + + const AZ::Entity* SpawnableConstEntityContainerView::operator[](size_t n) const + { + AZ_Assert(n < size(), "Index %zu is out of bounds (size: %llu) for Spawnable Entity Container View", n, size()); + return *(m_begin + n); + } + + size_t SpawnableConstEntityContainerView::size() const { return AZStd::distance(m_begin, m_end); } + bool SpawnableConstEntityContainerView::empty() const + { + return m_begin == m_end; + } + // // SpawnableIndexEntityPair diff --git a/Code/Framework/AzFramework/AzFramework/Spawnable/SpawnableEntitiesInterface.h b/Code/Framework/AzFramework/AzFramework/Spawnable/SpawnableEntitiesInterface.h index 4b09dcbc75..6901fc7116 100644 --- a/Code/Framework/AzFramework/AzFramework/Spawnable/SpawnableEntitiesInterface.h +++ b/Code/Framework/AzFramework/AzFramework/Spawnable/SpawnableEntitiesInterface.h @@ -36,11 +36,18 @@ namespace AzFramework SpawnableEntityContainerView(AZ::Entity** begin, size_t length); SpawnableEntityContainerView(AZ::Entity** begin, AZ::Entity** end); - AZ::Entity** begin(); - AZ::Entity** end(); - const AZ::Entity* const* cbegin(); - const AZ::Entity* const* cend(); - size_t size(); + [[nodiscard]] AZ::Entity** begin(); + [[nodiscard]] AZ::Entity** end(); + [[nodiscard]] const AZ::Entity* const* begin() const; + [[nodiscard]] const AZ::Entity* const* end() const; + [[nodiscard]] const AZ::Entity* const* cbegin(); + [[nodiscard]] const AZ::Entity* const* cend(); + + [[nodiscard]] AZ::Entity* operator[](size_t n); + [[nodiscard]] const AZ::Entity* operator[](size_t n) const; + + [[nodiscard]] size_t size() const; + [[nodiscard]] bool empty() const; private: AZ::Entity** m_begin; @@ -53,11 +60,18 @@ namespace AzFramework SpawnableConstEntityContainerView(AZ::Entity** begin, size_t length); SpawnableConstEntityContainerView(AZ::Entity** begin, AZ::Entity** end); - const AZ::Entity* const* begin(); - const AZ::Entity* const* end(); - const AZ::Entity* const* cbegin(); - const AZ::Entity* const* cend(); - size_t size(); + [[nodiscard]] const AZ::Entity* const* begin(); + [[nodiscard]] const AZ::Entity* const* end(); + [[nodiscard]] const AZ::Entity* const* begin() const; + [[nodiscard]] const AZ::Entity* const* end() const; + [[nodiscard]] const AZ::Entity* const* cbegin(); + [[nodiscard]] const AZ::Entity* const* cend(); + + [[nodiscard]] const AZ::Entity* operator[](size_t n); + [[nodiscard]] const AZ::Entity* operator[](size_t n) const; + + [[nodiscard]] size_t size() const; + [[nodiscard]] bool empty() const; private: AZ::Entity** m_begin; diff --git a/Code/Framework/AzFramework/AzFramework/Viewport/ClickDetector.cpp b/Code/Framework/AzFramework/AzFramework/Viewport/ClickDetector.cpp index b909689c22..1b3645630e 100644 --- a/Code/Framework/AzFramework/AzFramework/Viewport/ClickDetector.cpp +++ b/Code/Framework/AzFramework/AzFramework/Viewport/ClickDetector.cpp @@ -9,8 +9,19 @@ #include #include +#include + namespace AzFramework { + ClickDetector::ClickDetector() + { + m_timeNowFn = [] + { + const auto now = AZStd::chrono::high_resolution_clock::now(); + return AZStd::chrono::time_point_cast(now).time_since_epoch(); + }; + } + ClickDetector::ClickOutcome ClickDetector::DetectClick(const ClickEvent clickEvent, const ScreenVector& cursorDelta) { const auto previousDetectionState = m_detectionState; @@ -26,11 +37,13 @@ namespace AzFramework if (clickEvent == ClickEvent::Down) { - const auto now = std::chrono::steady_clock::now(); + const auto now = m_timeNowFn(); if (m_tryBeginTime) { - const std::chrono::duration diff = now - m_tryBeginTime.value(); - if (diff.count() < m_doubleClickInterval) + using FloatingPointSeconds = AZStd::chrono::duration; + + const auto diff = now - m_tryBeginTime.value(); + if (FloatingPointSeconds(diff).count() < m_doubleClickInterval) { return ClickOutcome::Nil; } @@ -43,7 +56,8 @@ namespace AzFramework } else if (clickEvent == ClickEvent::Up) { - const auto clickOutcome = [detectionState = m_detectionState] { + const auto clickOutcome = [detectionState = m_detectionState] + { if (detectionState == DetectionState::WaitingForMove) { return ClickOutcome::Click; @@ -66,4 +80,9 @@ namespace AzFramework return ClickOutcome::Nil; } + + void ClickDetector::OverrideTimeNowFn(AZStd::function timeNowFn) + { + m_timeNowFn = AZStd::move(timeNowFn); + } } // namespace AzFramework diff --git a/Code/Framework/AzFramework/AzFramework/Viewport/ClickDetector.h b/Code/Framework/AzFramework/AzFramework/Viewport/ClickDetector.h index f95924550a..70bdeb4619 100644 --- a/Code/Framework/AzFramework/AzFramework/Viewport/ClickDetector.h +++ b/Code/Framework/AzFramework/AzFramework/Viewport/ClickDetector.h @@ -8,6 +8,7 @@ #pragma once +#include #include #include @@ -21,10 +22,9 @@ namespace AzFramework //! (mouse down with movement and then mouse up). class ClickDetector { - //! Alias for recording time of mouse down events - using Time = std::chrono::time_point; - public: + ClickDetector(); + //! Internal representation of click event (map from external event for this when //! calling DetectClick). enum class ClickEvent @@ -51,6 +51,10 @@ namespace AzFramework void SetDoubleClickInterval(float doubleClickInterval); //! Override the dead zone before a 'move' outcome will be triggered. void SetDeadZone(float deadZone); + //! Override how the current time is retrieved. + //! This is helpful to override when it comes to simulating different passages of + //! time to avoid double click issues in tests for example. + void OverrideTimeNowFn(AZStd::function timeNowFn); private: //! Internal state of ClickDetector based on incoming events. @@ -65,7 +69,9 @@ namespace AzFramework float m_deadZone = 2.0f; //!< How far to move before a click is cancelled (when Move will fire). float m_doubleClickInterval = 0.4f; //!< Default double click interval, can be overridden. DetectionState m_detectionState; //!< Internal state of ClickDetector. - AZStd::optional diff --git a/Code/Tools/AssetProcessor/Platform/Mac/main_dummy.cpp b/Code/Tools/AssetProcessor/Platform/Mac/main_dummy.cpp deleted file mode 100644 index 3eed37e555..0000000000 --- a/Code/Tools/AssetProcessor/Platform/Mac/main_dummy.cpp +++ /dev/null @@ -1,75 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project. - * For complete copyright and license terms please see the LICENSE at the root of this distribution. - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ - -#include -#include -#include -#include -#include - -#include - -int main(int argc, char* argv[]) -{ - // Create a ComponentApplication to initialize the AZ::SystemAllocator and initialize the SettingsRegistry - AZ::ComponentApplication::Descriptor desc; - AZ::ComponentApplication application; - application.Create(desc); - - AZStd::vector envVars; - - const char* homePath = std::getenv("HOME"); - envVars.push_back(AZStd::string::format("HOME=%s", homePath)); - - if (auto settingsRegistry = AZ::SettingsRegistry::Get(); settingsRegistry != nullptr) - { - const char* dyldLibPathOrig = std::getenv("DYLD_LIBRARY_PATH"); - AZStd::string dyldSearchPath = AZStd::string::format("DYLD_LIBRARY_PATH=%s", dyldLibPathOrig); - if (AZ::IO::FixedMaxPath projectModulePath; - settingsRegistry->Get(projectModulePath.Native(), AZ::SettingsRegistryMergeUtils::FilePathKey_ProjectConfigurationBinPath)) - { - dyldSearchPath.append(":"); - dyldSearchPath.append(projectModulePath.c_str()); - } - - if (AZ::IO::FixedMaxPath installedBinariesFolder; - settingsRegistry->Get(installedBinariesFolder.Native(), AZ::SettingsRegistryMergeUtils::FilePathKey_InstalledBinaryFolder)) - { - if (AZ::IO::FixedMaxPath engineRootFolder; - settingsRegistry->Get(engineRootFolder.Native(), AZ::SettingsRegistryMergeUtils::FilePathKey_EngineRootFolder)) - { - installedBinariesFolder = engineRootFolder / installedBinariesFolder; - dyldSearchPath.append(":"); - dyldSearchPath.append(installedBinariesFolder.c_str()); - } - } - envVars.push_back(dyldSearchPath); - } - - AZStd::string commandArgs; - for (int i = 1; i < argc; i++) - { - commandArgs.append(argv[i]); - commandArgs.append(" "); - } - - AzFramework::ProcessLauncher::ProcessLaunchInfo processLaunchInfo; - AZ::IO::Path processPath{ AZ::IO::PathView(AZ::Utils::GetExecutableDirectory()) }; - processPath /= "AssetProcessor"; - processLaunchInfo.m_processExecutableString = AZStd::move(processPath.Native()); - processLaunchInfo.m_commandlineParameters = commandArgs; - processLaunchInfo.m_environmentVariables = &envVars; - processLaunchInfo.m_showWindow = true; - - AzFramework::ProcessLauncher::LaunchUnwatchedProcess(processLaunchInfo); - - application.Destroy(); - - return 0; -} - diff --git a/Code/Tools/AssetProcessor/native/InternalBuilders/SettingsRegistryBuilder.cpp b/Code/Tools/AssetProcessor/native/InternalBuilders/SettingsRegistryBuilder.cpp index 7c88c4324c..e6d9894116 100644 --- a/Code/Tools/AssetProcessor/native/InternalBuilders/SettingsRegistryBuilder.cpp +++ b/Code/Tools/AssetProcessor/native/InternalBuilders/SettingsRegistryBuilder.cpp @@ -191,10 +191,51 @@ namespace AssetProcessor response.m_createJobOutputs.push_back(AZStd::move(job)); } - AZ::IO::Path settingsRegistryWildcard = AZ::SettingsRegistryInterface::RegistryFolder; + AZ::IO::Path settingsRegistryWildcard = AZStd::string_view(AZ::Utils::GetEnginePath()); + settingsRegistryWildcard /= AZ::SettingsRegistryInterface::RegistryFolder; settingsRegistryWildcard /= "*.setreg"; response.m_sourceFileDependencyList.emplace_back(AZStd::move(settingsRegistryWildcard.Native()), AZ::Uuid::CreateNull(), AssetBuilderSDK::SourceFileDependency::SourceFileDependencyType::Wildcards); + + auto projectPath = AZ::IO::Path(AZStd::string_view(AZ::Utils::GetProjectPath())); + response.m_sourceFileDependencyList.emplace_back( + AZStd::move((projectPath / AZ::SettingsRegistryInterface::RegistryFolder / "*.setreg").Native()), + AZ::Uuid::CreateNull(), + AssetBuilderSDK::SourceFileDependency::SourceFileDependencyType::Wildcards); + response.m_sourceFileDependencyList.emplace_back( + AZStd::move((projectPath / AZ::SettingsRegistryInterface::DevUserRegistryFolder / "*.setreg").Native()), + AZ::Uuid::CreateNull(), + AssetBuilderSDK::SourceFileDependency::SourceFileDependencyType::Wildcards); + + if (auto settingsRegistry = AZ::Interface::Get(); settingsRegistry != nullptr) + { + AZStd::vector gemInfos; + if (AzFramework::GetGemsInfo(gemInfos, *settingsRegistry)) + { + // Gather unique list of Settings Registry wildcard directories + AZStd::vector gemSettingsRegistryWildcards; + for (const AzFramework::GemInfo& gemInfo : gemInfos) + { + for (const AZ::IO::Path& absoluteSourcePath : gemInfo.m_absoluteSourcePaths) + { + auto gemSettingsRegistryWildcard = absoluteSourcePath / AZ::SettingsRegistryInterface::RegistryFolder / "*.setreg"; + if (auto foundIt = AZStd::find(gemSettingsRegistryWildcards.begin(), gemSettingsRegistryWildcards.end(), gemSettingsRegistryWildcard); + foundIt == gemSettingsRegistryWildcards.end()) + { + gemSettingsRegistryWildcards.emplace_back(gemSettingsRegistryWildcard); + } + } + } + + // Add to the Source File Dependency list + for (AZ::IO::Path& gemSettingsRegistryWildcard : gemSettingsRegistryWildcards) + { + response.m_sourceFileDependencyList.emplace_back( + AZStd::move(gemSettingsRegistryWildcard.Native()), AZ::Uuid::CreateNull(), + AssetBuilderSDK::SourceFileDependency::SourceFileDependencyType::Wildcards); + } + } + } response.m_result = AssetBuilderSDK::CreateJobsResultCode::Success; } diff --git a/Code/Tools/BundleLauncher/CMakeLists.txt b/Code/Tools/BundleLauncher/CMakeLists.txt new file mode 100644 index 0000000000..812cb21099 --- /dev/null +++ b/Code/Tools/BundleLauncher/CMakeLists.txt @@ -0,0 +1,24 @@ +# +# Copyright (c) Contributors to the Open 3D Engine Project. +# For complete copyright and license terms please see the LICENSE at the root of this distribution. +# +# SPDX-License-Identifier: Apache-2.0 OR MIT +# +# + +# This is the launcher that will be used by the O3DE_SDK.app bundle +# generated by the cmake install process for Mac. +if(NOT ${PAL_PLATFORM_NAME} STREQUAL Mac) + return() +endif() + +ly_add_target( + NAME O3DE_SDK EXECUTABLE + NAMESPACE AZ + FILES_CMAKE + O3DE_SDK_files.cmake + BUILD_DEPENDENCIES + PRIVATE + AZ::AzCore + AZ::AzFramework +) diff --git a/Code/Tools/BundleLauncher/O3DE_SDK_Launcher.cpp b/Code/Tools/BundleLauncher/O3DE_SDK_Launcher.cpp new file mode 100644 index 0000000000..0c362ac829 --- /dev/null +++ b/Code/Tools/BundleLauncher/O3DE_SDK_Launcher.cpp @@ -0,0 +1,63 @@ +/* + * Copyright (c) Contributors to the Open 3D Engine Project. + * For complete copyright and license terms please see the LICENSE at the root of this distribution. + * + * SPDX-License-Identifier: Apache-2.0 OR MIT + * + */ + +#include +#include +#include +#include +#include + +#include +#include + +int main(int argc, char* argv[]) +{ + // We need to pass in the engine path since we won't be able to find it by searching upwards. + // We can't use any containers that use our custom allocator till after the call to ComponentApplication::Create() + AZ::IO::FixedMaxPath processPath = AZ::Utils::GetExecutableDirectory(); + AZ::IO::FixedMaxPath enginePath = (processPath / "../Engine").LexicallyNormal(); + auto enginePathParam = AZ::SettingsRegistryInterface::FixedValueString::format(R"(--engine-path="%s")", enginePath.c_str()); + // Uses the fixed_vector deduction guide to determine the type is AZStd::fixed_vector + AZStd::fixed_vector commandLineParams{ processPath.Native().data(), enginePathParam.data() }; + + + // Create a ComponentApplication to initialize the AZ::SystemAllocator and initialize the SettingsRegistry + AZ::ComponentApplication application(static_cast(commandLineParams.size()), commandLineParams.data()); + application.Create(AZ::ComponentApplication::Descriptor()); + + AZ::IO::FixedMaxPath installedBinariesFolder; + if (auto settingsRegistry = AZ::SettingsRegistry::Get(); settingsRegistry != nullptr) + { + if (settingsRegistry->Get(installedBinariesFolder.Native(), AZ::SettingsRegistryMergeUtils::FilePathKey_InstalledBinaryFolder)) + { + installedBinariesFolder = enginePath / installedBinariesFolder; + } + } + + AZ::IO::FixedMaxPath shellPath = "/bin/sh"; + AZStd::string parameters = AZStd::string::format("-c \"export LY_CMAKE_PATH=/usr/local/bin && \"%s/python/get_python.sh\"\"", enginePath.c_str()); + AzFramework::ProcessLauncher::ProcessLaunchInfo shellProcessLaunch; + shellProcessLaunch.m_processExecutableString = AZStd::move(shellPath.Native()); + shellProcessLaunch.m_commandlineParameters = parameters; + shellProcessLaunch.m_showWindow = true; + shellProcessLaunch.m_workingDirectory = enginePath.String(); + AZStd::unique_ptr shellProcess(AzFramework::ProcessWatcher::LaunchProcess(shellProcessLaunch, AzFramework::ProcessCommunicationType::COMMUNICATOR_TYPE_NONE)); + shellProcess->WaitForProcessToExit(120); + shellProcess.reset(); + + AZ::IO::FixedMaxPath projectManagerPath = installedBinariesFolder/"o3de.app"/"Contents"/"MacOS"/"o3de"; + AzFramework::ProcessLauncher::ProcessLaunchInfo processLaunchInfo; + processLaunchInfo.m_processExecutableString = AZStd::move(projectManagerPath.Native()); + processLaunchInfo.m_showWindow = true; + AzFramework::ProcessLauncher::LaunchUnwatchedProcess(processLaunchInfo); + + application.Destroy(); + + return 0; +} + diff --git a/Code/Tools/BundleLauncher/O3DE_SDK_files.cmake b/Code/Tools/BundleLauncher/O3DE_SDK_files.cmake new file mode 100644 index 0000000000..04989c9df2 --- /dev/null +++ b/Code/Tools/BundleLauncher/O3DE_SDK_files.cmake @@ -0,0 +1,11 @@ +# +# Copyright (c) Contributors to the Open 3D Engine Project. +# For complete copyright and license terms please see the LICENSE at the root of this distribution. +# +# SPDX-License-Identifier: Apache-2.0 OR MIT +# +# + +set(FILES + O3DE_SDK_Launcher.cpp +) diff --git a/Code/Tools/BundleLauncher/info.plist b/Code/Tools/BundleLauncher/info.plist new file mode 100644 index 0000000000..5b3dd43b37 --- /dev/null +++ b/Code/Tools/BundleLauncher/info.plist @@ -0,0 +1,18 @@ + + + + + CFBundleExecutable + O3DE_SDK + CFBundleIdentifier + org.O3DE.O3DE_SDK + CFBundlePackageType + APPL + CFBundleSignature + ???? + NSHumanReadableCopyright + Copyright (c) Contributors to the Open 3D Engine Project. + NSPrincipalClass + NSApplication + + diff --git a/Code/Tools/CMakeLists.txt b/Code/Tools/CMakeLists.txt index 66c43e53e5..8107089433 100644 --- a/Code/Tools/CMakeLists.txt +++ b/Code/Tools/CMakeLists.txt @@ -20,3 +20,4 @@ add_subdirectory(GridHub) add_subdirectory(Standalone) add_subdirectory(TestImpactFramework) add_subdirectory(ProjectManager) +add_subdirectory(BundleLauncher) diff --git a/Code/Tools/ProjectManager/Platform/Mac/PAL_mac.cmake b/Code/Tools/ProjectManager/Platform/Mac/PAL_mac.cmake index 7a325ca97e..5cd1fb5a22 100644 --- a/Code/Tools/ProjectManager/Platform/Mac/PAL_mac.cmake +++ b/Code/Tools/ProjectManager/Platform/Mac/PAL_mac.cmake @@ -5,3 +5,4 @@ # SPDX-License-Identifier: Apache-2.0 OR MIT # # + diff --git a/Code/Tools/ProjectManager/Resources/Delete.svg b/Code/Tools/ProjectManager/Resources/Delete.svg new file mode 100644 index 0000000000..f932c71544 --- /dev/null +++ b/Code/Tools/ProjectManager/Resources/Delete.svg @@ -0,0 +1,4 @@ + + + + diff --git a/Code/Tools/ProjectManager/Resources/Edit.svg b/Code/Tools/ProjectManager/Resources/Edit.svg new file mode 100644 index 0000000000..3ee9bbbfae --- /dev/null +++ b/Code/Tools/ProjectManager/Resources/Edit.svg @@ -0,0 +1,7 @@ + + + + + + + diff --git a/Code/Tools/ProjectManager/Resources/ProjectManager.qrc b/Code/Tools/ProjectManager/Resources/ProjectManager.qrc index 2e93e9eca9..30bcc1ace5 100644 --- a/Code/Tools/ProjectManager/Resources/ProjectManager.qrc +++ b/Code/Tools/ProjectManager/Resources/ProjectManager.qrc @@ -35,5 +35,8 @@ Backgrounds/DefaultBackground.jpg Backgrounds/FtueBackground.jpg FeatureTagClose.svg + Refresh.svg + Edit.svg + Delete.svg diff --git a/Code/Tools/ProjectManager/Resources/ProjectManager.qss b/Code/Tools/ProjectManager/Resources/ProjectManager.qss index 17c5077d83..30117d6636 100644 --- a/Code/Tools/ProjectManager/Resources/ProjectManager.qss +++ b/Code/Tools/ProjectManager/Resources/ProjectManager.qss @@ -518,3 +518,82 @@ QProgressBar::chunk { font-size: 12px; font-weight: 600; } + +/************** Engine **************/ + +#engineTab::tab-bar { + left: 60px; +} + +#engineTabBar::tab { + height: 50px; + background-color: transparent; + font-weight: 400; + font-size: 18px; + min-width: 160px; +} + +#engineTabBar::tab:selected { + border-bottom: 3px solid #94D2FF; + color: #94D2FF; + font-weight: 600; +} +#engineTabBar::tab:hover { + color: #94D2FF; + font-weight: 600; +} +#engineTabBar::tab:pressed { + color: #66bcfa; +} + +#engineTopFrame { + background-color:#1E252F; +} + +/************** Gem Repo **************/ + +#gemRepoHeaderLabel { + font-size: 12px; +} + +#gemRepoHeaderRefreshButton { + background-color: transparent; + qproperty-flat: true; + qproperty-iconSize: 14px; +} + +#gemRepoHeaderAddButton { + background: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1, + stop: 0 #888888, stop: 1.0 #555555); + qproperty-flat: true; + margin-right:30px; + min-width:120px; + max-width:120px; + min-height:24px; + max-height:24px; + border-radius: 3px; + text-align:center; + font-size:12px; + font-weight:600; +} +#gemRepoHeaderAddButton:hover { + background: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1, + stop: 0 #999999, stop: 1.0 #666666); +} +#gemRepoHeaderAddButton:pressed { + background: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1, + stop: 0 #555555, stop: 1.0 #777777); +} + +#gemRepoHeaderTable { + background-color: transparent; + max-height: 30px; +} + +#gemRepoListHeader { + background-color: transparent; +} + +#gemRepoInspector { + background: #444444; +} diff --git a/Code/Tools/ProjectManager/Resources/Refresh.svg b/Code/Tools/ProjectManager/Resources/Refresh.svg new file mode 100644 index 0000000000..80cc892c68 --- /dev/null +++ b/Code/Tools/ProjectManager/Resources/Refresh.svg @@ -0,0 +1,4 @@ + + + + diff --git a/Code/Tools/ProjectManager/Source/EngineScreenCtrl.cpp b/Code/Tools/ProjectManager/Source/EngineScreenCtrl.cpp new file mode 100644 index 0000000000..c78a9426db --- /dev/null +++ b/Code/Tools/ProjectManager/Source/EngineScreenCtrl.cpp @@ -0,0 +1,64 @@ +/* + * Copyright (c) Contributors to the Open 3D Engine Project. + * For complete copyright and license terms please see the LICENSE at the root of this distribution. + * + * SPDX-License-Identifier: Apache-2.0 OR MIT + * + */ + +#include +#include +#include + +#include +#include +#include + +namespace O3DE::ProjectManager +{ + EngineScreenCtrl::EngineScreenCtrl(QWidget* parent) + : ScreenWidget(parent) + { + QVBoxLayout* vLayout = new QVBoxLayout(); + vLayout->setContentsMargins(0, 0, 0, 0); + + QFrame* topBarFrameWidget = new QFrame(this); + topBarFrameWidget->setObjectName("engineTopFrame"); + QHBoxLayout* topBarHLayout = new QHBoxLayout(); + topBarHLayout->setContentsMargins(0, 0, 0, 0); + + topBarFrameWidget->setLayout(topBarHLayout); + + QTabWidget* tabWidget = new QTabWidget(); + tabWidget->setObjectName("engineTab"); + tabWidget->tabBar()->setObjectName("engineTabBar"); + tabWidget->tabBar()->setFocusPolicy(Qt::TabFocus); + + m_engineSettingsScreen = new EngineSettingsScreen(); + m_gemRepoScreen = new GemRepoScreen(); + + tabWidget->addTab(m_engineSettingsScreen, tr("General")); + tabWidget->addTab(m_gemRepoScreen, tr("Gem Repositories")); + topBarHLayout->addWidget(tabWidget); + + vLayout->addWidget(topBarFrameWidget); + + setLayout(vLayout); + } + + ProjectManagerScreen EngineScreenCtrl::GetScreenEnum() + { + return ProjectManagerScreen::UpdateProject; + } + + QString EngineScreenCtrl::GetTabText() + { + return tr("Engine"); + } + + bool EngineScreenCtrl::IsTab() + { + return true; + } + +} // namespace O3DE::ProjectManager diff --git a/Code/Tools/ProjectManager/Source/EngineScreenCtrl.h b/Code/Tools/ProjectManager/Source/EngineScreenCtrl.h new file mode 100644 index 0000000000..9e799f13e7 --- /dev/null +++ b/Code/Tools/ProjectManager/Source/EngineScreenCtrl.h @@ -0,0 +1,34 @@ +/* + * Copyright (c) Contributors to the Open 3D Engine Project. + * For complete copyright and license terms please see the LICENSE at the root of this distribution. + * + * SPDX-License-Identifier: Apache-2.0 OR MIT + * + */ +#pragma once + +#if !defined(Q_MOC_RUN) +#include +#endif + +namespace O3DE::ProjectManager +{ + QT_FORWARD_DECLARE_CLASS(EngineSettingsScreen) + QT_FORWARD_DECLARE_CLASS(GemRepoScreen) + + class EngineScreenCtrl + : public ScreenWidget + { + public: + explicit EngineScreenCtrl(QWidget* parent = nullptr); + ~EngineScreenCtrl() = default; + ProjectManagerScreen GetScreenEnum() override; + + QString GetTabText() override; + bool IsTab() override; + + EngineSettingsScreen* m_engineSettingsScreen = nullptr; + GemRepoScreen* m_gemRepoScreen = nullptr; + }; + +} // namespace O3DE::ProjectManager diff --git a/Code/Tools/ProjectManager/Source/EngineSettingsScreen.cpp b/Code/Tools/ProjectManager/Source/EngineSettingsScreen.cpp index 0c24aac9f1..dec1c9a257 100644 --- a/Code/Tools/ProjectManager/Source/EngineSettingsScreen.cpp +++ b/Code/Tools/ProjectManager/Source/EngineSettingsScreen.cpp @@ -7,15 +7,16 @@ */ #include -#include -#include -#include -#include #include #include #include #include +#include +#include +#include +#include + namespace O3DE::ProjectManager { EngineSettingsScreen::EngineSettingsScreen(QWidget* parent) @@ -78,16 +79,6 @@ namespace O3DE::ProjectManager return ProjectManagerScreen::EngineSettings; } - QString EngineSettingsScreen::GetTabText() - { - return tr("Engine"); - } - - bool EngineSettingsScreen::IsTab() - { - return true; - } - void EngineSettingsScreen::OnTextChanged() { // save engine settings diff --git a/Code/Tools/ProjectManager/Source/EngineSettingsScreen.h b/Code/Tools/ProjectManager/Source/EngineSettingsScreen.h index 9d212c44b1..2f16400405 100644 --- a/Code/Tools/ProjectManager/Source/EngineSettingsScreen.h +++ b/Code/Tools/ProjectManager/Source/EngineSettingsScreen.h @@ -24,8 +24,6 @@ namespace O3DE::ProjectManager ~EngineSettingsScreen() = default; ProjectManagerScreen GetScreenEnum() override; - QString GetTabText() override; - bool IsTab() override; protected slots: void OnTextChanged(); diff --git a/Code/Tools/ProjectManager/Source/GemRepo/GemRepoInfo.cpp b/Code/Tools/ProjectManager/Source/GemRepo/GemRepoInfo.cpp new file mode 100644 index 0000000000..3e524d8ec8 --- /dev/null +++ b/Code/Tools/ProjectManager/Source/GemRepo/GemRepoInfo.cpp @@ -0,0 +1,32 @@ +/* + * Copyright (c) Contributors to the Open 3D Engine Project. + * For complete copyright and license terms please see the LICENSE at the root of this distribution. + * + * SPDX-License-Identifier: Apache-2.0 OR MIT + * + */ + +#include + +namespace O3DE::ProjectManager +{ + GemRepoInfo::GemRepoInfo( + const QString& name, const QString& creator, const QString& summary, const QDateTime& lastUpdated, bool isEnabled = true) + : m_name(name) + , m_creator(creator) + , m_summary(summary) + , m_lastUpdated(lastUpdated) + , m_isEnabled(isEnabled) + { + } + + bool GemRepoInfo::IsValid() const + { + return !m_name.isEmpty(); + } + + bool GemRepoInfo::operator<(const GemRepoInfo& gemRepoInfo) const + { + return (m_lastUpdated < gemRepoInfo.m_lastUpdated); + } +} // namespace O3DE::ProjectManager diff --git a/Code/Tools/ProjectManager/Source/GemRepo/GemRepoInfo.h b/Code/Tools/ProjectManager/Source/GemRepo/GemRepoInfo.h new file mode 100644 index 0000000000..6f4f828951 --- /dev/null +++ b/Code/Tools/ProjectManager/Source/GemRepo/GemRepoInfo.h @@ -0,0 +1,37 @@ +/* + * Copyright (c) Contributors to the Open 3D Engine Project. + * For complete copyright and license terms please see the LICENSE at the root of this distribution. + * + * SPDX-License-Identifier: Apache-2.0 OR MIT + * + */ + +#pragma once + +#if !defined(Q_MOC_RUN) +#include +#include +#endif + +namespace O3DE::ProjectManager +{ + class GemRepoInfo + { + public: + GemRepoInfo() = default; + GemRepoInfo(const QString& name, const QString& creator, const QString& summary, const QDateTime& lastUpdated, bool isEnabled); + + bool IsValid() const; + + bool operator<(const GemRepoInfo& gemRepoInfo) const; + + QString m_path; + QString m_name = "Unknown Gem Repo Name"; + QString m_creator = "Unknown Creator"; + bool m_isEnabled = false; //! Is the repo currently enabled for this engine? + QString m_summary = "No summary provided."; + QString m_directoryLink; + QString m_repoLink; + QDateTime m_lastUpdated; + }; +} // namespace O3DE::ProjectManager diff --git a/Code/Tools/ProjectManager/Source/GemRepo/GemRepoItemDelegate.cpp b/Code/Tools/ProjectManager/Source/GemRepo/GemRepoItemDelegate.cpp new file mode 100644 index 0000000000..88ccee2636 --- /dev/null +++ b/Code/Tools/ProjectManager/Source/GemRepo/GemRepoItemDelegate.cpp @@ -0,0 +1,222 @@ +/* + * Copyright (c) Contributors to the Open 3D Engine Project. + * For complete copyright and license terms please see the LICENSE at the root of this distribution. + * + * SPDX-License-Identifier: Apache-2.0 OR MIT + * + */ + +#include +#include + +#include +#include +#include + +namespace O3DE::ProjectManager +{ + GemRepoItemDelegate::GemRepoItemDelegate(QAbstractItemModel* model, QObject* parent) + : QStyledItemDelegate(parent) + , m_model(model) + { + m_refreshIcon = QIcon(":/Refresh.svg").pixmap(s_refreshIconSize, s_refreshIconSize); + m_editIcon = QIcon(":/Edit.svg").pixmap(s_iconSize, s_iconSize); + m_deleteIcon = QIcon(":/Delete.svg").pixmap(s_iconSize, s_iconSize); + } + + void GemRepoItemDelegate::paint(QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& modelIndex) const + { + if (!modelIndex.isValid()) + { + return; + } + + QStyleOptionViewItem options(option); + initStyleOption(&options, modelIndex); + + painter->setRenderHint(QPainter::Antialiasing); + + QRect fullRect, itemRect, contentRect; + CalcRects(options, fullRect, itemRect, contentRect); + QRect buttonRect = CalcButtonRect(contentRect); + + QFont standardFont(options.font); + standardFont.setPixelSize(static_cast(s_fontSize)); + QFontMetrics standardFontMetrics(standardFont); + + painter->save(); + painter->setClipping(true); + painter->setClipRect(fullRect); + painter->setFont(standardFont); + painter->setPen(m_textColor); + + // Draw background + painter->fillRect(fullRect, m_backgroundColor); + + // Draw item background + const QColor itemBackgroundColor = options.state & QStyle::State_MouseOver ? m_itemBackgroundColor.lighter(120) : m_itemBackgroundColor; + painter->fillRect(itemRect, itemBackgroundColor); + + // Draw border + if (options.state & QStyle::State_Selected) + { + painter->save(); + QPen borderPen(m_borderColor); + borderPen.setWidth(s_borderWidth); + painter->setPen(borderPen); + painter->drawRect(itemRect); + + painter->restore(); + } + + // Repo enabled + DrawButton(painter, buttonRect, modelIndex); + + // Repo name + QString repoName = GemRepoModel::GetName(modelIndex); + repoName = QFontMetrics(standardFont).elidedText(repoName, Qt::TextElideMode::ElideRight, s_nameMaxWidth); + + QRect repoNameRect = GetTextRect(standardFont, repoName, s_fontSize); + int currentHorizontalOffset = buttonRect.left() + s_buttonWidth + s_buttonSpacing; + repoNameRect.moveTo(currentHorizontalOffset, contentRect.center().y() - repoNameRect.height() / 2); + repoNameRect = painter->boundingRect(repoNameRect, Qt::TextSingleLine, repoName); + + painter->drawText(repoNameRect, Qt::TextSingleLine, repoName); + + // Rem repo creator + QString repoCreator = GemRepoModel::GetCreator(modelIndex); + repoCreator = standardFontMetrics.elidedText(repoCreator, Qt::TextElideMode::ElideRight, s_creatorMaxWidth); + + QRect repoCreatorRect = GetTextRect(standardFont, repoCreator, s_fontSize); + currentHorizontalOffset += s_nameMaxWidth + s_contentSpacing; + repoCreatorRect.moveTo(currentHorizontalOffset, contentRect.center().y() - repoCreatorRect.height() / 2); + repoCreatorRect = painter->boundingRect(repoCreatorRect, Qt::TextSingleLine, repoCreator); + + painter->drawText(repoCreatorRect, Qt::TextSingleLine, repoCreator); + + // Repo update + QString repoUpdatedDate = GemRepoModel::GetLastUpdated(modelIndex).toString("dd/MM/yyyy hh:mmap"); + repoUpdatedDate = standardFontMetrics.elidedText(repoUpdatedDate, Qt::TextElideMode::ElideRight, s_updatedMaxWidth); + + QRect repoUpdatedDateRect = GetTextRect(standardFont, repoUpdatedDate, s_fontSize); + currentHorizontalOffset += s_creatorMaxWidth + s_contentSpacing; + repoUpdatedDateRect.moveTo(currentHorizontalOffset, contentRect.center().y() - repoUpdatedDateRect.height() / 2); + repoUpdatedDateRect = painter->boundingRect(repoUpdatedDateRect, Qt::TextSingleLine, repoUpdatedDate); + + painter->drawText(repoUpdatedDateRect, Qt::TextSingleLine, repoUpdatedDate); + + // Draw refresh button + painter->drawPixmap( + repoUpdatedDateRect.left() + repoUpdatedDateRect.width() + s_refreshIconSpacing, + contentRect.center().y() - s_refreshIconSize / 3, // Dividing size by 3 centers much better + m_refreshIcon); + + if (options.state & QStyle::State_MouseOver) + { + DrawEditButtons(painter, contentRect); + } + + painter->restore(); + } + + QSize GemRepoItemDelegate::sizeHint(const QStyleOptionViewItem& option, const QModelIndex& modelIndex) const + { + QStyleOptionViewItem options(option); + initStyleOption(&options, modelIndex); + + int marginsHorizontal = s_itemMargins.left() + s_itemMargins.right() + s_contentMargins.left() + s_contentMargins.right(); + return QSize(marginsHorizontal + s_buttonWidth + s_buttonSpacing + s_nameMaxWidth + s_creatorMaxWidth + s_updatedMaxWidth + s_contentSpacing * 3, s_height); + } + + bool GemRepoItemDelegate::editorEvent(QEvent* event, QAbstractItemModel* model, const QStyleOptionViewItem& option, const QModelIndex& modelIndex) + { + if (!modelIndex.isValid()) + { + return false; + } + + if (event->type() == QEvent::KeyPress) + { + auto keyEvent = static_cast(event); + if (keyEvent->key() == Qt::Key_Space) + { + const bool isAdded = GemRepoModel::IsEnabled(modelIndex); + GemRepoModel::SetEnabled(*model, modelIndex, !isAdded); + return true; + } + } + + if (event->type() == QEvent::MouseButtonPress) + { + QMouseEvent* mouseEvent = static_cast(event); + + QRect fullRect, itemRect, contentRect; + CalcRects(option, fullRect, itemRect, contentRect); + const QRect buttonRect = CalcButtonRect(contentRect); + + if (buttonRect.contains(mouseEvent->pos())) + { + const bool isAdded = GemRepoModel::IsEnabled(modelIndex); + GemRepoModel::SetEnabled(*model, modelIndex, !isAdded); + return true; + } + } + + return QStyledItemDelegate::editorEvent(event, model, option, modelIndex); + } + + void GemRepoItemDelegate::CalcRects(const QStyleOptionViewItem& option, QRect& outFullRect, QRect& outItemRect, QRect& outContentRect) const + { + outFullRect = QRect(option.rect); + outItemRect = QRect(outFullRect.adjusted(s_itemMargins.left(), s_itemMargins.top(), -s_itemMargins.right(), -s_itemMargins.bottom())); + outContentRect = QRect(outItemRect.adjusted(s_contentMargins.left(), s_contentMargins.top(), -s_contentMargins.right(), -s_contentMargins.bottom())); + } + + QRect GemRepoItemDelegate::GetTextRect(QFont& font, const QString& text, qreal fontSize) const + { + font.setPixelSize(static_cast(fontSize)); + return QFontMetrics(font).boundingRect(text); + } + + QRect GemRepoItemDelegate::CalcButtonRect(const QRect& contentRect) const + { + const QPoint topLeft = QPoint(contentRect.left(), contentRect.top() + contentRect.height() / 2 - s_buttonHeight / 2); + const QSize size = QSize(s_buttonWidth, s_buttonHeight); + return QRect(topLeft, size); + } + + void GemRepoItemDelegate::DrawButton(QPainter* painter, const QRect& buttonRect, const QModelIndex& modelIndex) const + { + painter->save(); + QPoint circleCenter; + + const bool isEnabled = GemRepoModel::IsEnabled(modelIndex); + if (isEnabled) + { + painter->setBrush(m_buttonEnabledColor); + painter->setPen(m_buttonEnabledColor); + + circleCenter = buttonRect.center() + QPoint(buttonRect.width() / 2 - s_buttonBorderRadius + 1, 1); + } + else + { + circleCenter = buttonRect.center() + QPoint(-buttonRect.width() / 2 + s_buttonBorderRadius + 1, 1); + } + + // Rounded rect + painter->drawRoundedRect(buttonRect, s_buttonBorderRadius, s_buttonBorderRadius); + + // Circle + painter->setBrush(m_textColor); + painter->drawEllipse(circleCenter, s_buttonCircleRadius, s_buttonCircleRadius); + + painter->restore(); + } + + void GemRepoItemDelegate::DrawEditButtons(QPainter* painter, const QRect& contentRect) const + { + painter->drawPixmap(contentRect.right() - s_iconSize * 2 - s_iconSpacing, contentRect.center().y() - s_iconSize / 2, m_editIcon); + painter->drawPixmap(contentRect.right() - s_iconSize, contentRect.center().y() - s_iconSize / 2, m_deleteIcon); + } + +} // namespace O3DE::ProjectManager diff --git a/Code/Tools/ProjectManager/Source/GemRepo/GemRepoItemDelegate.h b/Code/Tools/ProjectManager/Source/GemRepo/GemRepoItemDelegate.h new file mode 100644 index 0000000000..08d1fdffae --- /dev/null +++ b/Code/Tools/ProjectManager/Source/GemRepo/GemRepoItemDelegate.h @@ -0,0 +1,82 @@ +/* + * Copyright (c) Contributors to the Open 3D Engine Project. + * For complete copyright and license terms please see the LICENSE at the root of this distribution. + * + * SPDX-License-Identifier: Apache-2.0 OR MIT + * + */ + +#pragma once + +#if !defined(Q_MOC_RUN) +#include +#include +#endif + +QT_FORWARD_DECLARE_CLASS(QAbstractItemModel) +QT_FORWARD_DECLARE_CLASS(QEvent) + +namespace O3DE::ProjectManager +{ + class GemRepoItemDelegate + : public QStyledItemDelegate + { + Q_OBJECT // AUTOMOC + + public: + explicit GemRepoItemDelegate(QAbstractItemModel* model, QObject* parent = nullptr); + ~GemRepoItemDelegate() = default; + + void paint(QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& modelIndex) const override; + bool editorEvent(QEvent* event, QAbstractItemModel* model, const QStyleOptionViewItem& option, const QModelIndex& modelIndex) override; + QSize sizeHint(const QStyleOptionViewItem& option, const QModelIndex& modelIndex) const override; + + // Colors + const QColor m_textColor = QColor("#FFFFFF"); + const QColor m_backgroundColor = QColor("#333333"); // Outside of the actual repo item + const QColor m_itemBackgroundColor = QColor("#404040"); // Background color of the repo item + const QColor m_borderColor = QColor("#1E70EB"); + const QColor m_buttonEnabledColor = QColor("#1E70EB"); + + // Item + inline constexpr static int s_height = 72; // Repo item total height + inline constexpr static qreal s_fontSize = 12.0; + + // Margin and borders + inline constexpr static QMargins s_itemMargins = QMargins(/*left=*/0, /*top=*/8, /*right=*/60, /*bottom=*/8); // Item border distances + inline constexpr static QMargins s_contentMargins = QMargins(/*left=*/20, /*top=*/20, /*right=*/20, /*bottom=*/20); // Distances of the elements within an item to the item borders + inline constexpr static int s_borderWidth = 4; + + // Content + inline constexpr static int s_contentSpacing = 5; + inline constexpr static int s_nameMaxWidth = 145; + inline constexpr static int s_creatorMaxWidth = 115; + inline constexpr static int s_updatedMaxWidth = 125; + + // Button + inline constexpr static int s_buttonWidth = 32; + inline constexpr static int s_buttonHeight = 16; + inline constexpr static int s_buttonBorderRadius = 8; + inline constexpr static int s_buttonCircleRadius = s_buttonBorderRadius - 2; + inline constexpr static int s_buttonSpacing = 20; + + // Icon + inline constexpr static int s_iconSize = 24; + inline constexpr static int s_iconSpacing = 16; + inline constexpr static int s_refreshIconSize = 14; + inline constexpr static int s_refreshIconSpacing = 10; + + protected: + void CalcRects(const QStyleOptionViewItem& option, QRect& outFullRect, QRect& outItemRect, QRect& outContentRect) const; + QRect GetTextRect(QFont& font, const QString& text, qreal fontSize) const; + QRect CalcButtonRect(const QRect& contentRect) const; + void DrawButton(QPainter* painter, const QRect& contentRect, const QModelIndex& modelIndex) const; + void DrawEditButtons(QPainter* painter, const QRect& contentRect) const; + + QAbstractItemModel* m_model = nullptr; + + QPixmap m_refreshIcon; + QPixmap m_editIcon; + QPixmap m_deleteIcon; + }; +} // namespace O3DE::ProjectManager diff --git a/Code/Tools/ProjectManager/Source/GemRepo/GemRepoListView.cpp b/Code/Tools/ProjectManager/Source/GemRepo/GemRepoListView.cpp new file mode 100644 index 0000000000..519d52cb35 --- /dev/null +++ b/Code/Tools/ProjectManager/Source/GemRepo/GemRepoListView.cpp @@ -0,0 +1,23 @@ +/* + * Copyright (c) Contributors to the Open 3D Engine Project. + * For complete copyright and license terms please see the LICENSE at the root of this distribution. + * + * SPDX-License-Identifier: Apache-2.0 OR MIT + * + */ + +#include +#include + +namespace O3DE::ProjectManager +{ + GemRepoListView::GemRepoListView(QAbstractItemModel* model, QWidget* parent) + : QListView(parent) + { + setObjectName("gemRepoListView"); + setVerticalScrollMode(QAbstractItemView::ScrollPerPixel); + + setModel(model); + setItemDelegate(new GemRepoItemDelegate(model, this)); + } +} // namespace O3DE::ProjectManager diff --git a/Code/Tools/ProjectManager/Source/GemRepo/GemRepoListView.h b/Code/Tools/ProjectManager/Source/GemRepo/GemRepoListView.h new file mode 100644 index 0000000000..0fd5d5c180 --- /dev/null +++ b/Code/Tools/ProjectManager/Source/GemRepo/GemRepoListView.h @@ -0,0 +1,28 @@ +/* + * Copyright (c) Contributors to the Open 3D Engine Project. + * For complete copyright and license terms please see the LICENSE at the root of this distribution. + * + * SPDX-License-Identifier: Apache-2.0 OR MIT + * + */ + +#pragma once + +#if !defined(Q_MOC_RUN) +#include +#endif + +QT_FORWARD_DECLARE_CLASS(QAbstractItemModel) + +namespace O3DE::ProjectManager +{ + class GemRepoListView + : public QListView + { + Q_OBJECT // AUTOMOC + + public: + explicit GemRepoListView(QAbstractItemModel* model, QWidget* parent = nullptr); + ~GemRepoListView() = default; + }; +} // namespace O3DE::ProjectManager diff --git a/Code/Tools/ProjectManager/Source/GemRepo/GemRepoModel.cpp b/Code/Tools/ProjectManager/Source/GemRepo/GemRepoModel.cpp new file mode 100644 index 0000000000..7a42c135e9 --- /dev/null +++ b/Code/Tools/ProjectManager/Source/GemRepo/GemRepoModel.cpp @@ -0,0 +1,94 @@ +/* + * Copyright (c) Contributors to the Open 3D Engine Project. + * For complete copyright and license terms please see the LICENSE at the root of this distribution. + * + * SPDX-License-Identifier: Apache-2.0 OR MIT + * + */ + +#include + +#include + +namespace O3DE::ProjectManager +{ + GemRepoModel::GemRepoModel(QObject* parent) + : QStandardItemModel(parent) + { + m_selectionModel = new QItemSelectionModel(this, parent); + } + + QItemSelectionModel* GemRepoModel::GetSelectionModel() const + { + return m_selectionModel; + } + + void GemRepoModel::AddGemRepo(const GemRepoInfo& gemRepoInfo) + { + QStandardItem* item = new QStandardItem(); + + item->setFlags(Qt::ItemIsEnabled | Qt::ItemIsSelectable); + + item->setData(gemRepoInfo.m_name, RoleName); + item->setData(gemRepoInfo.m_creator, RoleCreator); + item->setData(gemRepoInfo.m_summary, RoleSummary); + item->setData(gemRepoInfo.m_isEnabled, RoleIsEnabled); + item->setData(gemRepoInfo.m_directoryLink, RoleDirectoryLink); + item->setData(gemRepoInfo.m_repoLink, RoleRepoLink); + item->setData(gemRepoInfo.m_lastUpdated, RoleLastUpdated); + item->setData(gemRepoInfo.m_path, RolePath); + + appendRow(item); + } + + void GemRepoModel::Clear() + { + clear(); + } + + QString GemRepoModel::GetName(const QModelIndex& modelIndex) + { + return modelIndex.data(RoleName).toString(); + } + + QString GemRepoModel::GetCreator(const QModelIndex& modelIndex) + { + return modelIndex.data(RoleCreator).toString(); + } + + QString GemRepoModel::GetSummary(const QModelIndex& modelIndex) + { + return modelIndex.data(RoleSummary).toString(); + } + + QString GemRepoModel::GetDirectoryLink(const QModelIndex& modelIndex) + { + return modelIndex.data(RoleDirectoryLink).toString(); + } + + QString GemRepoModel::GetRepoLink(const QModelIndex& modelIndex) + { + return modelIndex.data(RoleRepoLink).toString(); + } + + QDateTime GemRepoModel::GetLastUpdated(const QModelIndex& modelIndex) + { + return modelIndex.data(RoleLastUpdated).toDateTime(); + } + + QString GemRepoModel::GetPath(const QModelIndex& modelIndex) + { + return modelIndex.data(RolePath).toString(); + } + + bool GemRepoModel::IsEnabled(const QModelIndex& modelIndex) + { + return modelIndex.data(RoleIsEnabled).toBool(); + } + + void GemRepoModel::SetEnabled(QAbstractItemModel& model, const QModelIndex& modelIndex, bool isEnabled) + { + model.setData(modelIndex, isEnabled, RoleIsEnabled); + } + +} // namespace O3DE::ProjectManager diff --git a/Code/Tools/ProjectManager/Source/GemRepo/GemRepoModel.h b/Code/Tools/ProjectManager/Source/GemRepo/GemRepoModel.h new file mode 100644 index 0000000000..2f1537d339 --- /dev/null +++ b/Code/Tools/ProjectManager/Source/GemRepo/GemRepoModel.h @@ -0,0 +1,58 @@ +/* + * Copyright (c) Contributors to the Open 3D Engine Project. + * For complete copyright and license terms please see the LICENSE at the root of this distribution. + * + * SPDX-License-Identifier: Apache-2.0 OR MIT + * + */ + +#pragma once + +#if !defined(Q_MOC_RUN) +#include +#include +#endif + +QT_FORWARD_DECLARE_CLASS(QItemSelectionModel) + +namespace O3DE::ProjectManager +{ + class GemRepoModel + : public QStandardItemModel + { + Q_OBJECT // AUTOMOC + + public: + explicit GemRepoModel(QObject* parent = nullptr); + QItemSelectionModel* GetSelectionModel() const; + + void AddGemRepo(const GemRepoInfo& gemInfo); + void Clear(); + + static QString GetName(const QModelIndex& modelIndex); + static QString GetCreator(const QModelIndex& modelIndex); + static QString GetSummary(const QModelIndex& modelIndex); + static QString GetDirectoryLink(const QModelIndex& modelIndex); + static QString GetRepoLink(const QModelIndex& modelIndex); + static QDateTime GetLastUpdated(const QModelIndex& modelIndex); + static QString GetPath(const QModelIndex& modelIndex); + + static bool IsEnabled(const QModelIndex& modelIndex); + static void SetEnabled(QAbstractItemModel& model, const QModelIndex& modelIndex, bool isEnabled); + + private: + enum UserRole + { + RoleName = Qt::UserRole, + RoleCreator, + RoleSummary, + RoleIsEnabled, + RoleDirectoryLink, + RoleRepoLink, + RoleLastUpdated, + RolePath + }; + + QItemSelectionModel* m_selectionModel = nullptr; + }; +} // namespace O3DE::ProjectManager diff --git a/Code/Tools/ProjectManager/Source/GemRepo/GemRepoScreen.cpp b/Code/Tools/ProjectManager/Source/GemRepo/GemRepoScreen.cpp new file mode 100644 index 0000000000..82de53a0d0 --- /dev/null +++ b/Code/Tools/ProjectManager/Source/GemRepo/GemRepoScreen.cpp @@ -0,0 +1,145 @@ +/* + * Copyright (c) Contributors to the Open 3D Engine Project. + * For complete copyright and license terms please see the LICENSE at the root of this distribution. + * + * SPDX-License-Identifier: Apache-2.0 OR MIT + * + */ + +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace O3DE::ProjectManager +{ + GemRepoScreen::GemRepoScreen(QWidget* parent) + : ScreenWidget(parent) + { + m_gemRepoModel = new GemRepoModel(this); + + QVBoxLayout* vLayout = new QVBoxLayout(); + vLayout->setMargin(0); + vLayout->setSpacing(0); + setLayout(vLayout); + + QHBoxLayout* hLayout = new QHBoxLayout(); + hLayout->setMargin(0); + hLayout->setSpacing(0); + vLayout->addLayout(hLayout); + + hLayout->addSpacing(60); + + m_gemRepoInspector = new QFrame(this); + m_gemRepoInspector->setObjectName(tr("gemRepoInspector")); + m_gemRepoInspector->setFixedWidth(240); + + QVBoxLayout* middleVLayout = new QVBoxLayout(); + middleVLayout->setMargin(0); + middleVLayout->setSpacing(0); + + middleVLayout->addSpacing(30); + + QHBoxLayout* topMiddleHLayout = new QHBoxLayout(); + topMiddleHLayout->setMargin(0); + topMiddleHLayout->setSpacing(0); + + m_lastAllUpdateLabel = new QLabel(tr("Last Updated: Never"), this); + m_lastAllUpdateLabel->setObjectName("gemRepoHeaderLabel"); + topMiddleHLayout->addWidget(m_lastAllUpdateLabel); + + topMiddleHLayout->addSpacing(20); + + m_AllUpdateButton = new QPushButton(QIcon(":/Refresh.svg"), tr("Update All"), this); + m_AllUpdateButton->setObjectName("gemRepoHeaderRefreshButton"); + topMiddleHLayout->addWidget(m_AllUpdateButton); + + topMiddleHLayout->addSpacerItem(new QSpacerItem(0, 0, QSizePolicy::Expanding, QSizePolicy::Minimum)); + + m_AddRepoButton = new QPushButton(tr("Add Repository"), this); + m_AddRepoButton->setObjectName("gemRepoHeaderAddButton"); + topMiddleHLayout->addWidget(m_AddRepoButton); + + middleVLayout->addLayout(topMiddleHLayout); + + middleVLayout->addSpacing(30); + + // Create a QTableWidget just for its header + // Using a seperate model allows the setup of a header exactly as needed + m_gemRepoHeaderTable = new QTableWidget(this); + m_gemRepoHeaderTable->setObjectName("gemRepoHeaderTable"); + m_gemRepoListHeader = m_gemRepoHeaderTable->horizontalHeader(); + m_gemRepoListHeader->setObjectName("gemRepoListHeader"); + m_gemRepoListHeader->setSectionResizeMode(QHeaderView::ResizeMode::Fixed); + + // Insert columns so the header labels will show up + m_gemRepoHeaderTable->insertColumn(0); + m_gemRepoHeaderTable->insertColumn(1); + m_gemRepoHeaderTable->insertColumn(2); + m_gemRepoHeaderTable->insertColumn(3); + m_gemRepoHeaderTable->setHorizontalHeaderLabels({ tr("Enabled"), tr("Repository Name"), tr("Creator"), tr("Updated") }); + + const int headerExtraMargin = 10; + m_gemRepoListHeader->resizeSection(0, GemRepoItemDelegate::s_buttonWidth + GemRepoItemDelegate::s_buttonSpacing - 3); + m_gemRepoListHeader->resizeSection(1, GemRepoItemDelegate::s_nameMaxWidth + GemRepoItemDelegate::s_contentSpacing - headerExtraMargin); + m_gemRepoListHeader->resizeSection(2, GemRepoItemDelegate::s_creatorMaxWidth + GemRepoItemDelegate::s_contentSpacing - headerExtraMargin); + m_gemRepoListHeader->resizeSection(3, GemRepoItemDelegate::s_updatedMaxWidth + GemRepoItemDelegate::s_contentSpacing - headerExtraMargin); + + // Required to set stylesheet in code as it will not be respected if set in qss + m_gemRepoHeaderTable->horizontalHeader()->setStyleSheet("QHeaderView::section { background-color:transparent; color:white; font-size:12px; text-align:left; border-style:none; }"); + middleVLayout->addWidget(m_gemRepoHeaderTable); + + m_gemRepoListView = new GemRepoListView(m_gemRepoModel, this); + middleVLayout->addWidget(m_gemRepoListView); + + hLayout->addLayout(middleVLayout); + hLayout->addWidget(m_gemRepoInspector); + + Reinit(); + } + + void GemRepoScreen::Reinit() + { + m_gemRepoModel->clear(); + FillModel(); + + // Select the first entry after everything got correctly sized + QTimer::singleShot(200, [=]{ + QModelIndex firstModelIndex = m_gemRepoListView->model()->index(0,0); + m_gemRepoListView->selectionModel()->select(firstModelIndex, QItemSelectionModel::ClearAndSelect); + }); + } + + void GemRepoScreen::FillModel() + { + AZ::Outcome, AZStd::string> allGemRepoInfosResult = PythonBindingsInterface::Get()->GetAllGemRepoInfos(); + if (allGemRepoInfosResult.IsSuccess()) + { + // Add all available repos to the model + const QVector allGemRepoInfos = allGemRepoInfosResult.GetValue(); + for (const GemRepoInfo& gemRepoInfo : allGemRepoInfos) + { + m_gemRepoModel->AddGemRepo(gemRepoInfo); + } + } + else + { + QMessageBox::critical(this, tr("Operation failed"), QString("Cannot retrieve gem repos for engine.\n\nError:\n%2").arg(allGemRepoInfosResult.GetError().c_str())); + } + } + + ProjectManagerScreen GemRepoScreen::GetScreenEnum() + { + return ProjectManagerScreen::GemRepos; + } +} // namespace O3DE::ProjectManager diff --git a/Code/Tools/ProjectManager/Source/GemRepo/GemRepoScreen.h b/Code/Tools/ProjectManager/Source/GemRepo/GemRepoScreen.h new file mode 100644 index 0000000000..b5316db84f --- /dev/null +++ b/Code/Tools/ProjectManager/Source/GemRepo/GemRepoScreen.h @@ -0,0 +1,50 @@ +/* + * Copyright (c) Contributors to the Open 3D Engine Project. + * For complete copyright and license terms please see the LICENSE at the root of this distribution. + * + * SPDX-License-Identifier: Apache-2.0 OR MIT + * + */ + +#pragma once + +#if !defined(Q_MOC_RUN) +#include +#endif + +QT_FORWARD_DECLARE_CLASS(QLabel) +QT_FORWARD_DECLARE_CLASS(QPushButton) +QT_FORWARD_DECLARE_CLASS(QHeaderView) +QT_FORWARD_DECLARE_CLASS(QTableWidget) + +namespace O3DE::ProjectManager +{ + QT_FORWARD_DECLARE_CLASS(GemRepoListView) + QT_FORWARD_DECLARE_CLASS(GemRepoModel) + + class GemRepoScreen + : public ScreenWidget + { + public: + explicit GemRepoScreen(QWidget* parent = nullptr); + ~GemRepoScreen() = default; + ProjectManagerScreen GetScreenEnum() override; + + void Reinit(); + + GemRepoModel* GetGemRepoModel() const { return m_gemRepoModel; } + + private: + void FillModel(); + + QTableWidget* m_gemRepoHeaderTable = nullptr; + QHeaderView* m_gemRepoListHeader = nullptr; + GemRepoListView* m_gemRepoListView = nullptr; + QFrame* m_gemRepoInspector = nullptr; + GemRepoModel* m_gemRepoModel = nullptr; + + QLabel* m_lastAllUpdateLabel; + QPushButton* m_AllUpdateButton; + QPushButton* m_AddRepoButton; + }; +} // namespace O3DE::ProjectManager diff --git a/Code/Tools/ProjectManager/Source/ProjectManagerWindow.cpp b/Code/Tools/ProjectManager/Source/ProjectManagerWindow.cpp index a723ccb917..d2f2d969f1 100644 --- a/Code/Tools/ProjectManager/Source/ProjectManagerWindow.cpp +++ b/Code/Tools/ProjectManager/Source/ProjectManagerWindow.cpp @@ -22,7 +22,7 @@ namespace O3DE::ProjectManager QVector screenEnums = { ProjectManagerScreen::Projects, - ProjectManagerScreen::EngineSettings, + ProjectManagerScreen::Engine, ProjectManagerScreen::CreateProject, ProjectManagerScreen::UpdateProject }; diff --git a/Code/Tools/ProjectManager/Source/PythonBindings.cpp b/Code/Tools/ProjectManager/Source/PythonBindings.cpp index 18901946f3..6f8ff9abce 100644 --- a/Code/Tools/ProjectManager/Source/PythonBindings.cpp +++ b/Code/Tools/ProjectManager/Source/PythonBindings.cpp @@ -912,4 +912,45 @@ namespace O3DE::ProjectManager return AZ::Success(AZStd::move(templates)); } } + + GemRepoInfo PythonBindings::GemRepoInfoFromPath(pybind11::handle path, pybind11::handle pyEnginePath) + { + /* Placeholder Logic */ + (void)path; + (void)pyEnginePath; + + return GemRepoInfo(); + } + +//#define MOCK_GEM_REPO_INFO true + + AZ::Outcome, AZStd::string> PythonBindings::GetAllGemRepoInfos() + { + QVector gemRepos; + +#ifndef MOCK_GEM_REPO_INFO + auto result = ExecuteWithLockErrorHandling( + [&] + { + /* Placeholder Logic, o3de scripts need method added + * + for (auto path : m_manifest.attr("get_gem_repos")()) + { + gemRepos.push_back(GemRepoInfoFromPath(path, pybind11::none())); + } + * + */ + }); + if (!result.IsSuccess()) + { + return AZ::Failure(result.GetError().c_str()); + } +#else + gemRepos.push_back(GemRepoInfo("JohnCreates", "John Smith", "", QDateTime(QDate(2021, 8, 31), QTime(11, 57)), true)); + gemRepos.push_back(GemRepoInfo("JanesGems", "Jane Doe", "", QDateTime(QDate(2021, 9, 10), QTime(18, 23)), false)); +#endif // MOCK_GEM_REPO_INFO + + std::sort(gemRepos.begin(), gemRepos.end()); + return AZ::Success(AZStd::move(gemRepos)); + } } diff --git a/Code/Tools/ProjectManager/Source/PythonBindings.h b/Code/Tools/ProjectManager/Source/PythonBindings.h index 8482ac56e7..3b766c3797 100644 --- a/Code/Tools/ProjectManager/Source/PythonBindings.h +++ b/Code/Tools/ProjectManager/Source/PythonBindings.h @@ -56,12 +56,16 @@ namespace O3DE::ProjectManager // ProjectTemplate AZ::Outcome> GetProjectTemplates(const QString& projectPath = {}) override; + // Gem Repos + AZ::Outcome, AZStd::string> GetAllGemRepoInfos() override; + private: AZ_DISABLE_COPY_MOVE(PythonBindings); AZ::Outcome ExecuteWithLockErrorHandling(AZStd::function executionCallback); bool ExecuteWithLock(AZStd::function executionCallback); GemInfo GemInfoFromPath(pybind11::handle path, pybind11::handle pyProjectPath); + GemRepoInfo GemRepoInfoFromPath(pybind11::handle path, pybind11::handle pyEnginePath); ProjectInfo ProjectInfoFromPath(pybind11::handle path); ProjectTemplateInfo ProjectTemplateInfoFromPath(pybind11::handle path, pybind11::handle pyProjectPath); bool RegisterThisEngine(); diff --git a/Code/Tools/ProjectManager/Source/PythonBindingsInterface.h b/Code/Tools/ProjectManager/Source/PythonBindingsInterface.h index ca14a54630..9fd3002f93 100644 --- a/Code/Tools/ProjectManager/Source/PythonBindingsInterface.h +++ b/Code/Tools/ProjectManager/Source/PythonBindingsInterface.h @@ -17,6 +17,7 @@ #include #include #include +#include namespace O3DE::ProjectManager { @@ -56,14 +57,14 @@ namespace O3DE::ProjectManager /** * Get info about a Gem - * @param path the absolute path to the Gem + * @param projectPath the absolute path to the Gem * @return an outcome with GemInfo on success */ virtual AZ::Outcome GetGemInfo(const QString& path, const QString& projectPath = {}) = 0; /** * Get all available gem infos. This concatenates gems registered by the engine and the project. - * @param path The absolute path to the project. + * @param projectPath The absolute path to the project. * @return A list of gem infos. */ virtual AZ::Outcome, AZStd::string> GetAllGemInfos(const QString& projectPath) = 0; @@ -155,6 +156,14 @@ namespace O3DE::ProjectManager * @return an outcome with ProjectTemplateInfos on success */ virtual AZ::Outcome> GetProjectTemplates(const QString& projectPath = {}) = 0; + + // Gem Repos + + /** + * Get all available gem repo infos. Gathers all repos registered with the engine. + * @return A list of gem repo infos. + */ + virtual AZ::Outcome, AZStd::string> GetAllGemRepoInfos() = 0; }; using PythonBindingsInterface = AZ::Interface; diff --git a/Code/Tools/ProjectManager/Source/ScreenDefs.h b/Code/Tools/ProjectManager/Source/ScreenDefs.h index 97ebe19751..2ced8c08c9 100644 --- a/Code/Tools/ProjectManager/Source/ScreenDefs.h +++ b/Code/Tools/ProjectManager/Source/ScreenDefs.h @@ -23,7 +23,9 @@ namespace O3DE::ProjectManager Projects, UpdateProject, UpdateProjectSettings, - EngineSettings + Engine, + EngineSettings, + GemRepos }; static QHash s_ProjectManagerStringNames = { @@ -34,7 +36,9 @@ namespace O3DE::ProjectManager { "Projects", ProjectManagerScreen::Projects}, { "UpdateProject", ProjectManagerScreen::UpdateProject}, { "UpdateProjectSettings", ProjectManagerScreen::UpdateProjectSettings}, - { "EngineSettings", ProjectManagerScreen::EngineSettings} + { "Engine", ProjectManagerScreen::Engine}, + { "EngineSettings", ProjectManagerScreen::EngineSettings}, + { "GemRepos", ProjectManagerScreen::GemRepos} }; // need to define qHash for ProjectManagerScreen when using scoped enums diff --git a/Code/Tools/ProjectManager/Source/ScreenFactory.cpp b/Code/Tools/ProjectManager/Source/ScreenFactory.cpp index f3bddfdd27..44aa713e6a 100644 --- a/Code/Tools/ProjectManager/Source/ScreenFactory.cpp +++ b/Code/Tools/ProjectManager/Source/ScreenFactory.cpp @@ -13,7 +13,9 @@ #include #include #include +#include #include +#include namespace O3DE::ProjectManager { @@ -41,9 +43,15 @@ namespace O3DE::ProjectManager case (ProjectManagerScreen::UpdateProjectSettings): newScreen = new UpdateProjectSettingsScreen(parent); break; + case (ProjectManagerScreen::Engine): + newScreen = new EngineScreenCtrl(parent); + break; case (ProjectManagerScreen::EngineSettings): newScreen = new EngineSettingsScreen(parent); break; + case (ProjectManagerScreen::GemRepos): + newScreen = new GemRepoScreen(parent); + break; case (ProjectManagerScreen::Empty): default: newScreen = new ScreenWidget(parent); diff --git a/Code/Tools/ProjectManager/project_manager_files.cmake b/Code/Tools/ProjectManager/project_manager_files.cmake index 6d0f392e52..7a336972e0 100644 --- a/Code/Tools/ProjectManager/project_manager_files.cmake +++ b/Code/Tools/ProjectManager/project_manager_files.cmake @@ -56,6 +56,8 @@ set(FILES Source/ProjectsScreen.cpp Source/ProjectSettingsScreen.h Source/ProjectSettingsScreen.cpp + Source/EngineScreenCtrl.h + Source/EngineScreenCtrl.cpp Source/EngineSettingsScreen.h Source/EngineSettingsScreen.cpp Source/ProjectButtonWidget.h @@ -98,4 +100,14 @@ set(FILES Source/GemCatalog/GemRequirementListView.cpp Source/GemCatalog/GemSortFilterProxyModel.h Source/GemCatalog/GemSortFilterProxyModel.cpp + Source/GemRepo/GemRepoScreen.h + Source/GemRepo/GemRepoScreen.cpp + Source/GemRepo/GemRepoInfo.h + Source/GemRepo/GemRepoInfo.cpp + Source/GemRepo/GemRepoItemDelegate.h + Source/GemRepo/GemRepoItemDelegate.cpp + Source/GemRepo/GemRepoListView.h + Source/GemRepo/GemRepoListView.cpp + Source/GemRepo/GemRepoModel.h + Source/GemRepo/GemRepoModel.cpp ) diff --git a/Code/Tools/TestImpactFramework/Runtime/Code/Include/TestImpactFramework/TestImpactClientSequenceReport.h b/Code/Tools/TestImpactFramework/Runtime/Code/Include/TestImpactFramework/TestImpactClientSequenceReport.h index b39c2c8bcb..b668bda155 100644 --- a/Code/Tools/TestImpactFramework/Runtime/Code/Include/TestImpactFramework/TestImpactClientSequenceReport.h +++ b/Code/Tools/TestImpactFramework/Runtime/Code/Include/TestImpactFramework/TestImpactClientSequenceReport.h @@ -122,12 +122,14 @@ namespace TestImpact }; //! Base class for all sequence report types. - template + template class SequenceReportBase { public: + static constexpr SequenceReportType ReportType = Type; + using PolicyState = PolicyStateType; + //! Constructs the report for a sequence of selected tests. - //! @param type The type of sequence this report is generated for. //! @param maxConcurrency The maximum number of concurrent test targets in flight at any given time. //! @param testTargetTimeout The maximum duration individual test targets may be in flight for (infinite if empty). //! @param globalTimeout The maximum duration the entire test sequence may run for (infinite if empty). @@ -136,33 +138,49 @@ namespace TestImpact //! @param selectedTestRuns The target names of the selected test runs. //! @param selectedTestRunReport The report for the set of selected test runs. SequenceReportBase( - SequenceReportType type, size_t maxConcurrency, - const AZStd::optional& testTargetTimeout, - const AZStd::optional& globalTimeout, - const PolicyStateType& policyState, + AZStd::optional testTargetTimeout, + AZStd::optional globalTimeout, + PolicyStateType policyState, SuiteType suiteType, - const TestRunSelection& selectedTestRuns, - TestRunReport&& selectedTestRunReport) - : m_type(type) - , m_maxConcurrency(maxConcurrency) - , m_testTargetTimeout(testTargetTimeout) - , m_globalTimeout(globalTimeout) - , m_policyState(policyState) + TestRunSelection selectedTestRuns, + TestRunReport selectedTestRunReport) + : m_maxConcurrency(maxConcurrency) + , m_testTargetTimeout(AZStd::move(testTargetTimeout)) + , m_globalTimeout(AZStd::move(globalTimeout)) + , m_policyState(AZStd::move(policyState)) , m_suite(suiteType) - , m_selectedTestRuns(selectedTestRuns) + , m_selectedTestRuns(AZStd::move(selectedTestRuns)) , m_selectedTestRunReport(AZStd::move(selectedTestRunReport)) { } - virtual ~SequenceReportBase() = default; - - //! Returns the identifying type for this sequence report. - SequenceReportType GetType() const + SequenceReportBase(SequenceReportBase&& report) + : SequenceReportBase( + AZStd::move(report.m_maxConcurrency), + AZStd::move(report.m_testTargetTimeout), + AZStd::move(report.m_globalTimeout), + AZStd::move(report.m_policyState), + AZStd::move(report.m_suite), + AZStd::move(report.m_selectedTestRuns), + AZStd::move(report.m_selectedTestRunReport)) { - return m_type; } + SequenceReportBase(const SequenceReportBase& report) + : SequenceReportBase( + report.m_maxConcurrency, + report.m_testTargetTimeout, + report.m_globalTimeout, + report.m_policyState, + report.m_suite, + report.m_selectedTestRuns, + report.m_selectedTestRunReport) + { + } + + virtual ~SequenceReportBase() = default; + //! Returns the maximum concurrency for this sequence. size_t GetMaxConcurrency() const { @@ -284,7 +302,6 @@ namespace TestImpact } private: - SequenceReportType m_type; size_t m_maxConcurrency = 0; AZStd::optional m_testTargetTimeout; AZStd::optional m_globalTimeout; @@ -296,58 +313,27 @@ namespace TestImpact //! Report type for regular test sequences. class RegularSequenceReport - : public SequenceReportBase + : public SequenceReportBase { public: - //! Constructs the report for a regular sequence. - //! @param maxConcurrency The maximum number of concurrent test targets in flight at any given time. - //! @param testTargetTimeout The maximum duration individual test targets may be in flight for (infinite if empty). - //! @param globalTimeout The maximum duration the entire test sequence may run for (infinite if empty). - //! @param policyState The policy state this sequence was executed under. - //! @param suiteType The suite from which the tests have been selected from. - //! @param selectedTestRuns The target names of the selected test runs. - //! @param selectedTestRunReport The report for the set of selected test runs. - RegularSequenceReport( - size_t maxConcurrency, - const AZStd::optional& testTargetTimeout, - const AZStd::optional& globalTimeout, - const SequencePolicyState& policyState, - SuiteType suiteType, - const TestRunSelection& selectedTestRuns, - TestRunReport&& selectedTestRunReport); + using SequenceReportBase::SequenceReportBase; }; //! Report type for seed test sequences. class SeedSequenceReport - : public SequenceReportBase + : public SequenceReportBase { public: - //! Constructs the report for a seed sequence. - //! @param maxConcurrency The maximum number of concurrent test targets in flight at any given time. - //! @param testTargetTimeout The maximum duration individual test targets may be in flight for (infinite if empty). - //! @param globalTimeout The maximum duration the entire test sequence may run for (infinite if empty). - //! @param policyState The policy state this sequence was executed under. - //! @param suiteType The suite from which the tests have been selected from. - //! @param selectedTestRuns The target names of the selected test runs. - //! @param selectedTestRunReport The report for the set of selected test runs. - SeedSequenceReport( - size_t maxConcurrency, - const AZStd::optional& testTargetTimeout, - const AZStd::optional& globalTimeout, - const SequencePolicyState& policyState, - SuiteType suiteType, - const TestRunSelection& selectedTestRuns, - TestRunReport&& selectedTestRunReport); + using SequenceReportBase::SequenceReportBase; }; //! Report detailing a test run sequence of selected and drafted tests. - template + template class DraftingSequenceReportBase - : public SequenceReportBase + : public SequenceReportBase { public: //! Constructs the report for sequences that draft in previously failed/newly added test targets. - //! @param type The type of sequence this report is generated for. //! @param maxConcurrency The maximum number of concurrent test targets in flight at any given time. //! @param testTargetTimeout The maximum duration individual test targets may be in flight for (infinite if empty). //! @param globalTimeout The maximum duration the entire test sequence may run for (infinite if empty). @@ -358,18 +344,16 @@ namespace TestImpact //! @param selectedTestRunReport The report for the set of selected test runs. //! @param draftedTestRunReport The report for the set of drafted test runs. DraftingSequenceReportBase( - SequenceReportType type, size_t maxConcurrency, - const AZStd::optional& testTargetTimeout, - const AZStd::optional& globalTimeout, - const PolicyStateType& policyState, + AZStd::optional testTargetTimeout, + AZStd::optional globalTimeout, + PolicyStateType policyState, SuiteType suiteType, - const TestRunSelection& selectedTestRuns, - const AZStd::vector& draftedTestRuns, + TestRunSelection selectedTestRuns, + AZStd::vector draftedTestRuns, TestRunReport&& selectedTestRunReport, TestRunReport&& draftedTestRunReport) - : SequenceReportBase ( - type, + : SequenceReportBase( maxConcurrency, testTargetTimeout, globalTimeout, @@ -377,7 +361,17 @@ namespace TestImpact suiteType, selectedTestRuns, AZStd::move(selectedTestRunReport)) - , m_draftedTestRuns(draftedTestRuns) + , m_draftedTestRuns(AZStd::move(draftedTestRuns)) + , m_draftedTestRunReport(AZStd::move(draftedTestRunReport)) + { + } + + DraftingSequenceReportBase( + SequenceReportBase&& report, + AZStd::vector draftedTestRuns, + TestRunReport&& draftedTestRunReport) + : SequenceReportBase(AZStd::move(report)) + , m_draftedTestRuns(AZStd::move(draftedTestRuns)) , m_draftedTestRunReport(AZStd::move(draftedTestRunReport)) { } @@ -456,7 +450,7 @@ namespace TestImpact //! Report detailing an impact analysis sequence of selected, discarded and drafted tests. class ImpactAnalysisSequenceReport - : public DraftingSequenceReportBase + : public DraftingSequenceReportBase { public: //! Constructs the report for an impact analysis sequence. @@ -471,16 +465,18 @@ namespace TestImpact //! @param draftedTestRunReport The report for the set of drafted test runs. ImpactAnalysisSequenceReport( size_t maxConcurrency, - const AZStd::optional& testTargetTimeout, - const AZStd::optional& globalTimeout, - const ImpactAnalysisSequencePolicyState& policyState, + AZStd::optional testTargetTimeout, + AZStd::optional globalTimeout, + ImpactAnalysisSequencePolicyState policyState, SuiteType suiteType, - const TestRunSelection& selectedTestRuns, - const AZStd::vector& discardedTestRuns, - const AZStd::vector& draftedTestRuns, + TestRunSelection selectedTestRuns, + AZStd::vector discardedTestRuns, + AZStd::vector draftedTestRuns, TestRunReport&& selectedTestRunReport, TestRunReport&& draftedTestRunReport); + ImpactAnalysisSequenceReport(DraftingSequenceReportBase&& report, AZStd::vector discardedTestRuns); + //! Returns the test runs discarded from running in the sequence. const AZStd::vector& GetDiscardedTestRuns() const; private: @@ -489,7 +485,7 @@ namespace TestImpact //! Report detailing an impact analysis sequence of selected, discarded and drafted test runs. class SafeImpactAnalysisSequenceReport - : public DraftingSequenceReportBase + : public DraftingSequenceReportBase { public: //! Constructs the report for a sequence of selected, discarded and drafted test runs. @@ -506,17 +502,20 @@ namespace TestImpact //! @param draftedTestRunReport The report for the set of drafted test runs. SafeImpactAnalysisSequenceReport( size_t maxConcurrency, - const AZStd::optional& testTargetTimeout, - const AZStd::optional& globalTimeout, - const SafeImpactAnalysisSequencePolicyState& policyState, + AZStd::optional testTargetTimeout, + AZStd::optional globalTimeout, + SafeImpactAnalysisSequencePolicyState policyState, SuiteType suiteType, - const TestRunSelection& selectedTestRuns, - const TestRunSelection& discardedTestRuns, - const AZStd::vector& draftedTestRuns, + TestRunSelection selectedTestRuns, + TestRunSelection discardedTestRuns, + AZStd::vector draftedTestRuns, TestRunReport&& selectedTestRunReport, TestRunReport&& discardedTestRunReport, TestRunReport&& draftedTestRunReport); + SafeImpactAnalysisSequenceReport( + DraftingSequenceReportBase&& report, TestRunSelection discardedTestRuns, TestRunReport&& discardedTestRunReport); + // SequenceReport overrides ... AZStd::chrono::milliseconds GetDuration() const override; TestSequenceResult GetResult() const override; diff --git a/Code/Tools/TestImpactFramework/Runtime/Code/Include/TestImpactFramework/TestImpactClientSequenceReportSerializer.h b/Code/Tools/TestImpactFramework/Runtime/Code/Include/TestImpactFramework/TestImpactClientSequenceReportSerializer.h index fc226588e7..06bb0cdaa1 100644 --- a/Code/Tools/TestImpactFramework/Runtime/Code/Include/TestImpactFramework/TestImpactClientSequenceReportSerializer.h +++ b/Code/Tools/TestImpactFramework/Runtime/Code/Include/TestImpactFramework/TestImpactClientSequenceReportSerializer.h @@ -14,15 +14,27 @@ namespace TestImpact { - //! Serializes a regular sequence report to JSON format. + //! Serializes a regular sequence report to Json format. AZStd::string SerializeSequenceReport(const Client::RegularSequenceReport& sequenceReport); - //! Serializes a seed sequence report to JSON format. + //! Serializes a seed sequence report to Json format. AZStd::string SerializeSequenceReport(const Client::SeedSequenceReport& sequenceReport); - //! Serializes an impact analysis sequence report to JSON format. + //! Serializes an impact analysis sequence report to Json format. AZStd::string SerializeSequenceReport(const Client::ImpactAnalysisSequenceReport& sequenceReport); - //! Serializes a safe impact analysis sequence report to JSON format. + //! Serializes a safe impact analysis sequence report to Json format. AZStd::string SerializeSequenceReport(const Client::SafeImpactAnalysisSequenceReport& sequenceReport); + + //! Deserialize a regular sequence report from Json format. + Client::RegularSequenceReport DeserializeRegularSequenceReport(const AZStd::string& sequenceReportJson); + + //! Deserialize a seed sequence report from Json format. + Client::SeedSequenceReport DeserializeSeedSequenceReport(const AZStd::string& sequenceReportJson); + + //! Deserialize an impact analysis sequence report from Json format. + Client::ImpactAnalysisSequenceReport DeserializeImpactAnalysisSequenceReport(const AZStd::string& sequenceReportJson); + + //! Deserialize a safe impact analysis sequence report from Json format. + Client::SafeImpactAnalysisSequenceReport DeserializeSafeImpactAnalysisSequenceReport(const AZStd::string& sequenceReportJson); } // namespace TestImpact diff --git a/Code/Tools/TestImpactFramework/Runtime/Code/Include/TestImpactFramework/TestImpactUtils.h b/Code/Tools/TestImpactFramework/Runtime/Code/Include/TestImpactFramework/TestImpactUtils.h index c4625e9d2c..f7afd49b26 100644 --- a/Code/Tools/TestImpactFramework/Runtime/Code/Include/TestImpactFramework/TestImpactUtils.h +++ b/Code/Tools/TestImpactFramework/Runtime/Code/Include/TestImpactFramework/TestImpactUtils.h @@ -103,4 +103,43 @@ namespace TestImpact //! User-friendly names for the client test result types. AZStd::string ClientTestResultAsString(Client::TestResult result); + + //! User-friendly names for the suite types. + SuiteType SuiteTypeFromString(const AZStd::string& suiteType); + + //! Returns the sequence report type for the specified string. + Client::SequenceReportType SequenceReportTypeFromString(const AZStd::string& type); + + //! Returns the test run result for the specified string. + Client::TestRunResult TestRunResultFromString(const AZStd::string& result); + + //! Returns the test result for the specified string. + Client::TestResult TestResultFromString(const AZStd::string& result); + + //! Returns the test sequence result for the specified string. + TestSequenceResult TestSequenceResultFromString(const AZStd::string& result); + + //! Returns the execution failure policy for the specified string. + Policy::ExecutionFailure ExecutionFailurePolicyFromString(const AZStd::string& executionFailurePolicy); + + //! Returns the failed test coverage policy for the specified string. + Policy::FailedTestCoverage FailedTestCoveragePolicyFromString(const AZStd::string& failedTestCoveragePolicy); + + //! Returns the test prioritization policy for the specified string. + Policy::TestPrioritization TestPrioritizationPolicyFromString(const AZStd::string& testPrioritizationPolicy); + + //! Returns the test failure policy for the specified string. + Policy::TestFailure TestFailurePolicyFromString(const AZStd::string& testFailurePolicy); + + //! Returns the integrity failure policy for the specified string. + Policy::IntegrityFailure IntegrityFailurePolicyFromString(const AZStd::string& integrityFailurePolicy); + + //! Returns the dynamic dependency map policy for the specified string. + Policy::DynamicDependencyMap DynamicDependencyMapPolicyFromString(const AZStd::string& dynamicDependencyMapPolicy); + + //! Returns the test sharding policy for the specified string. + Policy::TestSharding TestShardingPolicyFromString(const AZStd::string& testShardingPolicy); + + //! Returns the target output capture policy for the specified string. + Policy::TargetOutputCapture TargetOutputCapturePolicyFromString(const AZStd::string& targetOutputCapturePolicy); } // namespace TestImpact diff --git a/Code/Tools/TestImpactFramework/Runtime/Code/Source/TestImpactClientSequenceReport.cpp b/Code/Tools/TestImpactFramework/Runtime/Code/Source/TestImpactClientSequenceReport.cpp index 3f4656758a..17157e70fc 100644 --- a/Code/Tools/TestImpactFramework/Runtime/Code/Source/TestImpactClientSequenceReport.cpp +++ b/Code/Tools/TestImpactFramework/Runtime/Code/Source/TestImpactClientSequenceReport.cpp @@ -159,69 +159,35 @@ namespace TestImpact return m_totalNumDisabledTests; } - RegularSequenceReport::RegularSequenceReport( + ImpactAnalysisSequenceReport::ImpactAnalysisSequenceReport( size_t maxConcurrency, - const AZStd::optional& testTargetTimeout, - const AZStd::optional& globalTimeout, - const SequencePolicyState& policyState, + AZStd::optional testTargetTimeout, + AZStd::optional globalTimeout, + ImpactAnalysisSequencePolicyState policyState, SuiteType suiteType, - const TestRunSelection& selectedTestRuns, - TestRunReport&& selectedTestRunReport) - : SequenceReportBase( - SequenceReportType::RegularSequence, - maxConcurrency, - testTargetTimeout, - globalTimeout, - policyState, - suiteType, - selectedTestRuns, - AZStd::move(selectedTestRunReport)) - { - } - - SeedSequenceReport::SeedSequenceReport( - size_t maxConcurrency, - const AZStd::optional& testTargetTimeout, - const AZStd::optional& globalTimeout, - const SequencePolicyState& policyState, - SuiteType suiteType, - const TestRunSelection& selectedTestRuns, - TestRunReport&& selectedTestRunReport) - : SequenceReportBase( - SequenceReportType::SeedSequence, - maxConcurrency, - testTargetTimeout, - globalTimeout, - policyState, - suiteType, - selectedTestRuns, - AZStd::move(selectedTestRunReport)) + TestRunSelection selectedTestRuns, + AZStd::vector discardedTestRuns, + AZStd::vector draftedTestRuns, + TestRunReport&& selectedTestRunReport, + TestRunReport&& draftedTestRunReport) + : DraftingSequenceReportBase( + maxConcurrency, + AZStd::move(testTargetTimeout), + AZStd::move(globalTimeout), + AZStd::move(policyState), + suiteType, + AZStd::move(selectedTestRuns), + AZStd::move(draftedTestRuns), + AZStd::move(selectedTestRunReport), + AZStd::move(draftedTestRunReport)) + , m_discardedTestRuns(discardedTestRuns) { } ImpactAnalysisSequenceReport::ImpactAnalysisSequenceReport( - size_t maxConcurrency, - const AZStd::optional& testTargetTimeout, - const AZStd::optional& globalTimeout, - const ImpactAnalysisSequencePolicyState& policyState, - SuiteType suiteType, - const TestRunSelection& selectedTestRuns, - const AZStd::vector& discardedTestRuns, - const AZStd::vector& draftedTestRuns, - TestRunReport&& selectedTestRunReport, - TestRunReport&& draftedTestRunReport) - : DraftingSequenceReportBase( - SequenceReportType::ImpactAnalysisSequence, - maxConcurrency, - testTargetTimeout, - globalTimeout, - policyState, - suiteType, - selectedTestRuns, - draftedTestRuns, - AZStd::move(selectedTestRunReport), - AZStd::move(draftedTestRunReport)) - , m_discardedTestRuns(discardedTestRuns) + DraftingSequenceReportBase&& report, AZStd::vector discardedTestRuns) + : DraftingSequenceReportBase(AZStd::move(report)) + , m_discardedTestRuns(AZStd::move(discardedTestRuns)) { } @@ -232,25 +198,24 @@ namespace TestImpact SafeImpactAnalysisSequenceReport::SafeImpactAnalysisSequenceReport( size_t maxConcurrency, - const AZStd::optional& testTargetTimeout, - const AZStd::optional& globalTimeout, - const SafeImpactAnalysisSequencePolicyState& policyState, + AZStd::optional testTargetTimeout, + AZStd::optional globalTimeout, + SafeImpactAnalysisSequencePolicyState policyState, SuiteType suiteType, - const TestRunSelection& selectedTestRuns, - const TestRunSelection& discardedTestRuns, - const AZStd::vector& draftedTestRuns, + TestRunSelection selectedTestRuns, + TestRunSelection discardedTestRuns, + AZStd::vector draftedTestRuns, TestRunReport&& selectedTestRunReport, TestRunReport&& discardedTestRunReport, TestRunReport&& draftedTestRunReport) : DraftingSequenceReportBase( - SequenceReportType::SafeImpactAnalysisSequence, maxConcurrency, - testTargetTimeout, - globalTimeout, - policyState, + AZStd::move(testTargetTimeout), + AZStd::move(globalTimeout), + AZStd::move(policyState), suiteType, - selectedTestRuns, - draftedTestRuns, + AZStd::move(selectedTestRuns), + AZStd::move(draftedTestRuns), AZStd::move(selectedTestRunReport), AZStd::move(draftedTestRunReport)) , m_discardedTestRuns(discardedTestRuns) @@ -258,6 +223,14 @@ namespace TestImpact { } + SafeImpactAnalysisSequenceReport::SafeImpactAnalysisSequenceReport( + DraftingSequenceReportBase&& report, TestRunSelection discardedTestRuns, TestRunReport&& discardedTestRunReport) + : DraftingSequenceReportBase(AZStd::move(report)) + , m_discardedTestRuns(AZStd::move(discardedTestRuns)) + , m_discardedTestRunReport(AZStd::move(discardedTestRunReport)) + { + } + TestSequenceResult SafeImpactAnalysisSequenceReport::GetResult() const { return CalculateMultiTestSequenceResult({ DraftingSequenceReportBase::GetResult(), m_discardedTestRunReport.GetResult() }); diff --git a/Code/Tools/TestImpactFramework/Runtime/Code/Source/TestImpactClientSequenceReportSerializer.cpp b/Code/Tools/TestImpactFramework/Runtime/Code/Source/TestImpactClientSequenceReportSerializer.cpp index 99a187fe16..944fd4ac38 100644 --- a/Code/Tools/TestImpactFramework/Runtime/Code/Source/TestImpactClientSequenceReportSerializer.cpp +++ b/Code/Tools/TestImpactFramework/Runtime/Code/Source/TestImpactClientSequenceReportSerializer.cpp @@ -21,7 +21,7 @@ namespace TestImpact { namespace SequenceReportFields { - // Keys for pertinent JSON node and attribute names + // Keys for pertinent Json node and attribute names constexpr const char* Keys[] = { "name", @@ -417,13 +417,13 @@ namespace TestImpact writer.String(DynamicDependencyMapPolicyAsString(policyState.m_dynamicDependencyMap).c_str()); } - template + template void SerializeSequenceReportBaseMembers( - const Client::SequenceReportBase& sequenceReport, rapidjson::PrettyWriter& writer) + const SequenceReportBaseType& sequenceReport, rapidjson::PrettyWriter& writer) { // Type writer.Key(SequenceReportFields::Keys[SequenceReportFields::Type]); - writer.String(SequenceReportTypeAsString(sequenceReport.GetType()).c_str()); + writer.String(SequenceReportTypeAsString(sequenceReport.ReportType).c_str()); // Test target timeout writer.Key(SequenceReportFields::Keys[SequenceReportFields::TestTargetTimeout]); @@ -510,9 +510,9 @@ namespace TestImpact writer.Uint64(sequenceReport.GetTotalNumDisabledTests()); } - template + template void SerializeDraftingSequenceReportMembers( - const Client::DraftingSequenceReportBase& sequenceReport, rapidjson::PrettyWriter& writer) + const DraftingSequenceReportBaseType& sequenceReport, rapidjson::PrettyWriter& writer) { SerializeSequenceReportBaseMembers(sequenceReport, writer); @@ -603,4 +603,254 @@ namespace TestImpact return stringBuffer.GetString(); } + + AZStd::chrono::high_resolution_clock::time_point TimePointFromMsInt64(AZ::s64 ms) + { + return AZStd::chrono::high_resolution_clock::time_point(AZStd::chrono::milliseconds(ms)); + } + + AZStd::vector DeserializeTests(const rapidjson::Value& serialTests) + { + AZStd::vector tests; + tests.reserve(serialTests[SequenceReportFields::Keys[SequenceReportFields::Tests]].GetArray().Size()); + for (const auto& test : serialTests[SequenceReportFields::Keys[SequenceReportFields::Tests]].GetArray()) + { + const AZStd::string name = test[SequenceReportFields::Keys[SequenceReportFields::Name]].GetString(); + const auto result = TestResultFromString(test[SequenceReportFields::Keys[SequenceReportFields::Result]].GetString()); + tests.emplace_back(name, result); + } + + return tests; + } + + Client::TestRunBase DeserializeTestRunBase(const rapidjson::Value& serialTestRun) + { + return Client::TestRunBase( + serialTestRun[SequenceReportFields::Keys[SequenceReportFields::Name]].GetString(), + serialTestRun[SequenceReportFields::Keys[SequenceReportFields::CommandArgs]].GetString(), + TimePointFromMsInt64(serialTestRun[SequenceReportFields::Keys[SequenceReportFields::StartTime]].GetInt64()), + AZStd::chrono::milliseconds(serialTestRun[SequenceReportFields::Keys[SequenceReportFields::Duration]].GetInt64()), + TestRunResultFromString(serialTestRun[SequenceReportFields::Keys[SequenceReportFields::Result]].GetString())); + } + + template + AZStd::vector DeserializeTestRuns(const rapidjson::Value& serialTestRuns) + { + AZStd::vector testRuns; + testRuns.reserve(serialTestRuns.GetArray().Size()); + for (const auto& testRun : serialTestRuns.GetArray()) + { + testRuns.emplace_back(DeserializeTestRunBase(testRun)); + } + + return testRuns; + } + + template + AZStd::vector DeserializeCompletedTestRuns(const rapidjson::Value& serialCompletedTestRuns) + { + AZStd::vector testRuns; + testRuns.reserve(serialCompletedTestRuns.GetArray().Size()); + for (const auto& testRun : serialCompletedTestRuns.GetArray()) + { + testRuns.emplace_back( + DeserializeTestRunBase(testRun), DeserializeTests(testRun[SequenceReportFields::Keys[SequenceReportFields::Tests]])); + } + + return testRuns; + } + + Client::TestRunReport DeserializeTestRunReport(const rapidjson::Value& serialTestRunReport) + { + return Client::TestRunReport( + TestSequenceResultFromString(serialTestRunReport[SequenceReportFields::Keys[SequenceReportFields::Result]].GetString()), + TimePointFromMsInt64(serialTestRunReport[SequenceReportFields::Keys[SequenceReportFields::StartTime]].GetInt64()), + AZStd::chrono::milliseconds(serialTestRunReport[SequenceReportFields::Keys[SequenceReportFields::Duration]].GetInt64()), + DeserializeCompletedTestRuns( + serialTestRunReport[SequenceReportFields::Keys[SequenceReportFields::PassingTestRuns]]), + DeserializeCompletedTestRuns( + serialTestRunReport[SequenceReportFields::Keys[SequenceReportFields::FailingTestRuns]]), + DeserializeTestRuns( + serialTestRunReport[SequenceReportFields::Keys[SequenceReportFields::ExecutionFailureTestRuns]]), + DeserializeTestRuns( + serialTestRunReport[SequenceReportFields::Keys[SequenceReportFields::TimedOutTestRuns]]), + DeserializeTestRuns( + serialTestRunReport[SequenceReportFields::Keys[SequenceReportFields::UnexecutedTestRuns]])); + } + + Client::TestRunSelection DeserializeTestSelection(const rapidjson::Value& serialTestRunSelection) + { + const auto extractTestTargetNames = [](const rapidjson::Value& serialTestTargets) + { + AZStd::vector testTargets; + testTargets.reserve(serialTestTargets.GetArray().Size()); + for (const auto& testTarget : serialTestTargets.GetArray()) + { + testTargets.emplace_back(testTarget.GetString()); + } + + return testTargets; + }; + + return Client::TestRunSelection( + extractTestTargetNames(serialTestRunSelection[SequenceReportFields::Keys[SequenceReportFields::IncludedTestRuns]]), + extractTestTargetNames(serialTestRunSelection[SequenceReportFields::Keys[SequenceReportFields::ExcludedTestRuns]])); + } + + PolicyStateBase DeserializePolicyStateBaseMembers(const rapidjson::Value& serialPolicyState) + { + return + { + ExecutionFailurePolicyFromString(serialPolicyState[SequenceReportFields::Keys[SequenceReportFields::ExecutionFailure]].GetString()), + FailedTestCoveragePolicyFromString(serialPolicyState[SequenceReportFields::Keys[SequenceReportFields::CoverageFailure]].GetString()), + TestFailurePolicyFromString(serialPolicyState[SequenceReportFields::Keys[SequenceReportFields::TestFailure]].GetString()), + IntegrityFailurePolicyFromString(serialPolicyState[SequenceReportFields::Keys[SequenceReportFields::IntegrityFailure]].GetString()), + TestShardingPolicyFromString(serialPolicyState[SequenceReportFields::Keys[SequenceReportFields::TestSharding]].GetString()), + TargetOutputCapturePolicyFromString(serialPolicyState[SequenceReportFields::Keys[SequenceReportFields::TargetOutputCapture]].GetString()) + }; + } + + SequencePolicyState DeserializePolicyStateMembers(const rapidjson::Value& serialPolicyState) + { + return { DeserializePolicyStateBaseMembers(serialPolicyState) }; + } + + SafeImpactAnalysisSequencePolicyState DeserializeSafeImpactAnalysisPolicyStateMembers(const rapidjson::Value& serialPolicyState) + { + return + { + DeserializePolicyStateBaseMembers(serialPolicyState), + TestPrioritizationPolicyFromString(serialPolicyState[SequenceReportFields::Keys[SequenceReportFields::TestPrioritization]].GetString()) + }; + } + + ImpactAnalysisSequencePolicyState DeserializeImpactAnalysisSequencePolicyStateMembers(const rapidjson::Value& serialPolicyState) + { + return + { + DeserializePolicyStateBaseMembers(serialPolicyState), + TestPrioritizationPolicyFromString(serialPolicyState[SequenceReportFields::Keys[SequenceReportFields::TestPrioritization]].GetString()), + DynamicDependencyMapPolicyFromString( + serialPolicyState[SequenceReportFields::Keys[SequenceReportFields::DynamicDependencyMap]].GetString()) + }; + } + + template + PolicyStateType DeserializePolicyStateType(const rapidjson::Value& serialPolicyStateType) + { + if constexpr (AZStd::is_same_v) + { + return DeserializePolicyStateMembers(serialPolicyStateType); + } + else if constexpr (AZStd::is_same_v) + { + return DeserializeSafeImpactAnalysisPolicyStateMembers(serialPolicyStateType); + } + else if constexpr (AZStd::is_same_v) + { + return DeserializeImpactAnalysisSequencePolicyStateMembers(serialPolicyStateType); + } + else + { + static_assert(false, "Template paramater must be a valid policy state type"); + } + } + + template + SequenceReportBaseType DeserialiseSequenceReportBase(const rapidjson::Value& serialSequenceReportBase) + { + const auto type = SequenceReportTypeFromString(serialSequenceReportBase[SequenceReportFields::Keys[SequenceReportFields::Type]].GetString()); + AZ_TestImpact_Eval( + type == SequenceReportBaseType::ReportType, + SequenceReportException, AZStd::string::format( + "The JSON sequence report type '%s' does not match the constructed report type", + serialSequenceReportBase[SequenceReportFields::Keys[SequenceReportFields::Type]].GetString())); + + const auto testTargetTimeout = + serialSequenceReportBase[SequenceReportFields::Keys[SequenceReportFields::TestTargetTimeout]].GetUint64(); + const auto globalTimeout = + serialSequenceReportBase[SequenceReportFields::Keys[SequenceReportFields::GlobalTimeout]].GetUint64(); + + return SequenceReportBaseType( + serialSequenceReportBase[SequenceReportFields::Keys[SequenceReportFields::MaxConcurrency]].GetUint64(), + testTargetTimeout ? AZStd::optional{ testTargetTimeout } : AZStd::nullopt, + globalTimeout ? AZStd::optional{ globalTimeout } : AZStd::nullopt, + DeserializePolicyStateType(serialSequenceReportBase), + SuiteTypeFromString(serialSequenceReportBase[SequenceReportFields::Keys[SequenceReportFields::Suite]].GetString()), + DeserializeTestSelection(serialSequenceReportBase[SequenceReportFields::Keys[SequenceReportFields::SelectedTestRuns]]), + DeserializeTestRunReport(serialSequenceReportBase[SequenceReportFields::Keys[SequenceReportFields::SelectedTestRunReport]])); + } + + template + Client::DraftingSequenceReportBase + DeserializeDraftingSequenceReportBase(const rapidjson::Value& serialDraftingSequenceReportBase) + { + AZStd::vector draftingTestRuns; + draftingTestRuns.reserve( + serialDraftingSequenceReportBase[SequenceReportFields::Keys[SequenceReportFields::DraftedTestRuns]].GetArray().Size()); + for (const auto& testRun : + serialDraftingSequenceReportBase[SequenceReportFields::Keys[SequenceReportFields::DraftedTestRuns]].GetArray()) + { + draftingTestRuns.emplace_back(testRun.GetString()); + } + + using SequenceBase = + Client::SequenceReportBase; + using DraftingSequenceBase = + Client::DraftingSequenceReportBase; + + return DraftingSequenceBase( + DeserialiseSequenceReportBase(serialDraftingSequenceReportBase), + AZStd::move(draftingTestRuns), + DeserializeTestRunReport(serialDraftingSequenceReportBase[SequenceReportFields::Keys[SequenceReportFields::DraftedTestRunReport]])); + } + + rapidjson::Document OpenSequenceReportJson(const AZStd::string& sequenceReportJson) + { + rapidjson::Document doc; + + if (doc.Parse<0>(sequenceReportJson.c_str()).HasParseError()) + { + throw SequenceReportException("Could not parse sequence report data"); + } + + return doc; + } + + Client::RegularSequenceReport DeserializeRegularSequenceReport(const AZStd::string& sequenceReportJson) + { + const auto doc = OpenSequenceReportJson(sequenceReportJson); + return DeserialiseSequenceReportBase(doc); + } + + Client::SeedSequenceReport DeserializeSeedSequenceReport(const AZStd::string& sequenceReportJson) + { + const auto doc = OpenSequenceReportJson(sequenceReportJson); + return DeserialiseSequenceReportBase(doc); + } + + Client::ImpactAnalysisSequenceReport DeserializeImpactAnalysisSequenceReport(const AZStd::string& sequenceReportJson) + { + const auto doc = OpenSequenceReportJson(sequenceReportJson); + + AZStd::vector discardedTestRuns; + discardedTestRuns.reserve(doc[SequenceReportFields::Keys[SequenceReportFields::DiscardedTestRuns]].GetArray().Size()); + for (const auto& testRun : doc[SequenceReportFields::Keys[SequenceReportFields::DiscardedTestRuns]].GetArray()) + { + discardedTestRuns.emplace_back(testRun.GetString()); + } + + return Client::ImpactAnalysisSequenceReport( + DeserializeDraftingSequenceReportBase(doc), AZStd::move(discardedTestRuns)); + } + + Client::SafeImpactAnalysisSequenceReport DeserializeSafeImpactAnalysisSequenceReport(const AZStd::string& sequenceReportJson) + { + const auto doc = OpenSequenceReportJson(sequenceReportJson); + + return Client::SafeImpactAnalysisSequenceReport( + DeserializeDraftingSequenceReportBase(doc), + DeserializeTestSelection(doc[SequenceReportFields::Keys[SequenceReportFields::DiscardedTestRuns]]), + DeserializeTestRunReport(doc[SequenceReportFields::Keys[SequenceReportFields::DiscardedTestRunReport]])); + } } // namespace TestImpact diff --git a/Code/Tools/TestImpactFramework/Runtime/Code/Source/TestImpactUtils.cpp b/Code/Tools/TestImpactFramework/Runtime/Code/Source/TestImpactUtils.cpp index 3f6c9dafd4..ecfdec287b 100644 --- a/Code/Tools/TestImpactFramework/Runtime/Code/Source/TestImpactUtils.cpp +++ b/Code/Tools/TestImpactFramework/Runtime/Code/Source/TestImpactUtils.cpp @@ -243,4 +243,256 @@ namespace TestImpact throw(Exception(AZStd::string::format("Unexpected client test case result: %u", aznumeric_cast(result)))); } } + + SuiteType SuiteTypeFromString(const AZStd::string& suiteType) + { + if (suiteType == SuiteTypeAsString(SuiteType::Main)) + { + return SuiteType::Main; + } + else if (suiteType == SuiteTypeAsString(SuiteType::Periodic)) + { + return SuiteType::Periodic; + } + else if (suiteType == SuiteTypeAsString(SuiteType::Sandbox)) + { + return SuiteType::Sandbox; + } + else + { + throw Exception(AZStd::string::format("Unexpected suite type: '%s'", suiteType.c_str())); + } + } + + Client::SequenceReportType SequenceReportTypeFromString(const AZStd::string& type) + { + if (type == SequenceReportTypeAsString(Client::SequenceReportType::ImpactAnalysisSequence)) + { + return Client::SequenceReportType::ImpactAnalysisSequence; + } + else if (type == SequenceReportTypeAsString(Client::SequenceReportType::RegularSequence)) + { + return Client::SequenceReportType::RegularSequence; + } + else if (type == SequenceReportTypeAsString(Client::SequenceReportType::SafeImpactAnalysisSequence)) + { + return Client::SequenceReportType::SafeImpactAnalysisSequence; + } + else if (type == SequenceReportTypeAsString(Client::SequenceReportType::SeedSequence)) + { + return Client::SequenceReportType::SeedSequence; + } + else + { + throw Exception(AZStd::string::format("Unexpected sequence report type: '%s'", type.c_str())); + } + } + + Client::TestRunResult TestRunResultFromString(const AZStd::string& result) + { + if (result == TestRunResultAsString(Client::TestRunResult::AllTestsPass)) + { + return Client::TestRunResult::AllTestsPass; + } + else if (result == TestRunResultAsString(Client::TestRunResult::FailedToExecute)) + { + return Client::TestRunResult::FailedToExecute; + } + else if (result == TestRunResultAsString(Client::TestRunResult::NotRun)) + { + return Client::TestRunResult::NotRun; + } + else if (result == TestRunResultAsString(Client::TestRunResult::TestFailures)) + { + return Client::TestRunResult::TestFailures; + } + else if (result == TestRunResultAsString(Client::TestRunResult::Timeout)) + { + return Client::TestRunResult::Timeout; + } + else + { + throw Exception(AZStd::string::format("Unexpected client test run result: '%s'", result.c_str())); + } + } + + Client::TestResult TestResultFromString(const AZStd::string& result) + { + if (result == ClientTestResultAsString(Client::TestResult::Failed)) + { + return Client::TestResult::Failed; + } + else if (result == ClientTestResultAsString(Client::TestResult::NotRun)) + { + return Client::TestResult::NotRun; + } + else if (result == ClientTestResultAsString(Client::TestResult::Passed)) + { + return Client::TestResult::Passed; + } + else + { + throw Exception(AZStd::string::format("Unexpected client test result: '%s'", result.c_str())); + } + } + + TestSequenceResult TestSequenceResultFromString(const AZStd::string& result) + { + if (result == TestSequenceResultAsString(TestSequenceResult::Failure)) + { + return TestSequenceResult::Failure; + } + else if (result == TestSequenceResultAsString(TestSequenceResult::Success)) + { + return TestSequenceResult::Success; + } + else if (result == TestSequenceResultAsString(TestSequenceResult::Timeout)) + { + return TestSequenceResult::Timeout; + } + else + { + throw Exception(AZStd::string::format("Unexpected test sequence result: '%s'", result.c_str())); + } + } + + Policy::ExecutionFailure ExecutionFailurePolicyFromString(const AZStd::string& executionFailurePolicy) + { + if (executionFailurePolicy == ExecutionFailurePolicyAsString(Policy::ExecutionFailure::Abort)) + { + return Policy::ExecutionFailure::Abort; + } + else if (executionFailurePolicy == ExecutionFailurePolicyAsString(Policy::ExecutionFailure::Continue)) + { + return Policy::ExecutionFailure::Continue; + } + else if (executionFailurePolicy == ExecutionFailurePolicyAsString(Policy::ExecutionFailure::Ignore)) + { + return Policy::ExecutionFailure::Ignore; + } + else + { + throw Exception(AZStd::string::format("Unexpected execution failure policy: '%s'", executionFailurePolicy.c_str())); + } + } + + Policy::FailedTestCoverage FailedTestCoveragePolicyFromString(const AZStd::string& failedTestCoveragePolicy) + { + if (failedTestCoveragePolicy == FailedTestCoveragePolicyAsString(Policy::FailedTestCoverage::Discard)) + { + return Policy::FailedTestCoverage::Discard; + } + else if (failedTestCoveragePolicy == FailedTestCoveragePolicyAsString(Policy::FailedTestCoverage::Keep)) + { + return Policy::FailedTestCoverage::Keep; + } + else + { + throw Exception(AZStd::string::format("Unexpected failed test coverage policy: '%s'", failedTestCoveragePolicy.c_str())); + } + } + + Policy::TestPrioritization TestPrioritizationPolicyFromString(const AZStd::string& testPrioritizationPolicy) + { + if (testPrioritizationPolicy == TestPrioritizationPolicyAsString(Policy::TestPrioritization::DependencyLocality)) + { + return Policy::TestPrioritization::DependencyLocality; + } + else if (testPrioritizationPolicy == TestPrioritizationPolicyAsString(Policy::TestPrioritization::None)) + { + return Policy::TestPrioritization::None; + } + else + { + throw Exception(AZStd::string::format("Unexpected test prioritization policy: '%s'", testPrioritizationPolicy.c_str())); + } + } + + Policy::TestFailure TestFailurePolicyFromString(const AZStd::string& testFailurePolicy) + { + if (testFailurePolicy == TestFailurePolicyAsString(Policy::TestFailure::Abort)) + { + return Policy::TestFailure::Abort; + } + else if (testFailurePolicy == TestFailurePolicyAsString(Policy::TestFailure::Continue)) + { + return Policy::TestFailure::Continue; + } + else + { + throw Exception(AZStd::string::format("Unexpected test failure policy: '%s'", testFailurePolicy.c_str())); + } + } + + Policy::IntegrityFailure IntegrityFailurePolicyFromString(const AZStd::string& integrityFailurePolicy) + { + if (integrityFailurePolicy == IntegrityFailurePolicyAsString(Policy::IntegrityFailure::Abort)) + { + return Policy::IntegrityFailure::Abort; + } + else if (integrityFailurePolicy == IntegrityFailurePolicyAsString(Policy::IntegrityFailure::Continue)) + { + return Policy::IntegrityFailure::Continue; + } + else + { + throw Exception(AZStd::string::format("Unexpected integration failure policy: '%s'", integrityFailurePolicy.c_str())); + } + } + + Policy::DynamicDependencyMap DynamicDependencyMapPolicyFromString(const AZStd::string& dynamicDependencyMapPolicy) + { + if (dynamicDependencyMapPolicy == DynamicDependencyMapPolicyAsString(Policy::DynamicDependencyMap::Discard)) + { + return Policy::DynamicDependencyMap::Discard; + } + else if (dynamicDependencyMapPolicy == DynamicDependencyMapPolicyAsString(Policy::DynamicDependencyMap::Update)) + { + return Policy::DynamicDependencyMap::Update; + } + else + { + throw Exception(AZStd::string::format("Unexpected dynamic dependency map policy: '%s'", dynamicDependencyMapPolicy.c_str())); + } + } + + Policy::TestSharding TestShardingPolicyFromString(const AZStd::string& testShardingPolicy) + { + if (testShardingPolicy == TestShardingPolicyAsString(Policy::TestSharding::Always)) + { + return Policy::TestSharding::Always; + } + else if (testShardingPolicy == TestShardingPolicyAsString(Policy::TestSharding::Never)) + { + return Policy::TestSharding::Never; + } + else + { + throw Exception(AZStd::string::format("Unexpected test sharding policy: '%s'", testShardingPolicy.c_str())); + } + } + + Policy::TargetOutputCapture TargetOutputCapturePolicyFromString(const AZStd::string& targetOutputCapturePolicy) + { + if (targetOutputCapturePolicy == TargetOutputCapturePolicyAsString(Policy::TargetOutputCapture::File)) + { + return Policy::TargetOutputCapture::File; + } + else if (targetOutputCapturePolicy == TargetOutputCapturePolicyAsString(Policy::TargetOutputCapture::None)) + { + return Policy::TargetOutputCapture::None; + } + else if (targetOutputCapturePolicy == TargetOutputCapturePolicyAsString(Policy::TargetOutputCapture::StdOut)) + { + return Policy::TargetOutputCapture::StdOut; + } + else if (targetOutputCapturePolicy == TargetOutputCapturePolicyAsString(Policy::TargetOutputCapture::StdOutAndFile)) + { + return Policy::TargetOutputCapture::StdOutAndFile; + } + else + { + throw Exception(AZStd::string::format("Unexpected target output capture policy: '%s'", targetOutputCapturePolicy.c_str())); + } + } } // namespace TestImpact diff --git a/Gems/AWSClientAuth/cdk/utils/name_utils.py b/Gems/AWSClientAuth/cdk/utils/name_utils.py index 4921b735eb..ea9dd68060 100755 --- a/Gems/AWSClientAuth/cdk/utils/name_utils.py +++ b/Gems/AWSClientAuth/cdk/utils/name_utils.py @@ -6,10 +6,11 @@ SPDX-License-Identifier: Apache-2.0 OR MIT """ import re from aws_cdk import core +from .resource_name_sanitizer import sanitize_resource_name def format_aws_resource_name(feature_name: str, project_name: str, env: core.Environment, resource_type: str): - return f'{project_name}-{feature_name}-{resource_type}-{env.region}' + return sanitize_resource_name(f'{project_name}-{feature_name}-{resource_type}-{env.region}', resource_type) def format_aws_resource_id(feature_name: str, project_name: str, env: core.Environment, resource_type: str): @@ -31,4 +32,5 @@ def format_aws_resource_authenticated_id(feature_name: str, project_name: str, e def format_aws_resource_authenticated_name(feature_name: str, project_name: str, env: core.Environment, resource_type: str, authenticated: bool): authenticated_string = 'Authenticated' if authenticated else 'Unauthenticated' - return f'{project_name}{feature_name}{resource_type}{authenticated_string}-{env.region}' + return sanitize_resource_name( + f'{project_name}{feature_name}{resource_type}{authenticated_string}-{env.region}', resource_type) diff --git a/Gems/AWSClientAuth/cdk/utils/resource_name_sanitizer.py b/Gems/AWSClientAuth/cdk/utils/resource_name_sanitizer.py new file mode 100644 index 0000000000..d4a2d77f44 --- /dev/null +++ b/Gems/AWSClientAuth/cdk/utils/resource_name_sanitizer.py @@ -0,0 +1,45 @@ +""" +Copyright (c) Contributors to the Open 3D Engine Project. +For complete copyright and license terms please see the LICENSE at the root of this distribution. + +SPDX-License-Identifier: Apache-2.0 OR MIT +""" + +import hashlib +from aws_cdk import ( + core, + aws_cognito as cognito, + aws_iam as iam +) + +MAX_RESOURCE_NAME_LENGTH_MAPPING = { + core.Stack.__name__: 128, + iam.Role.__name__: 64, + iam.ManagedPolicy.__name__: 144, + cognito.CfnUserPoolClient.__name__: 128, + cognito.CfnUserPool.__name__: 128, + cognito.CfnIdentityPool.__name__: 128 + +} + + +def sanitize_resource_name(resource_name: str, resource_type: str) -> str: + """ + Truncate the resource name if its length exceeds the limit. + This is the best effort for sanitizing resource names based on the AWS documents since each AWS service + has its unique restrictions. Customers can extend this function for validation or sanitization. + + :param resource_name: Original name of the resource. + :param resource_type: Type of the resource. + :return Sanitized resource name that can be deployed with AWS. + """ + result = resource_name + if not MAX_RESOURCE_NAME_LENGTH_MAPPING.get(resource_type): + return result + + if len(resource_name) > MAX_RESOURCE_NAME_LENGTH_MAPPING[resource_type]: + # PYTHONHASHSEED is set to "random" by default in Python 3.3 and up. Cannot use + # the built-in hash function here since it will give a different return value in each session + digest = "-%x" % (int(hashlib.md5(resource_name.encode('ascii', 'ignore')).hexdigest(), 16) & 0xffffffff) + result = resource_name[:MAX_RESOURCE_NAME_LENGTH_MAPPING[resource_type] - len(digest)] + digest + return result diff --git a/Gems/AWSMetrics/cdk/aws_metrics/aws_metrics_stack.py b/Gems/AWSMetrics/cdk/aws_metrics/aws_metrics_stack.py index 337a14a301..41d70f83ec 100755 --- a/Gems/AWSMetrics/cdk/aws_metrics/aws_metrics_stack.py +++ b/Gems/AWSMetrics/cdk/aws_metrics/aws_metrics_stack.py @@ -53,6 +53,7 @@ class AWSMetricsStack(core.Stack): self._batch_processing = BatchProcessing( self, input_stream_arn=self._data_ingestion.input_stream_arn, + application_name=application_name, analytics_bucket_arn=self._data_lake_integration.analytics_bucket_arn, events_database_name=self._data_lake_integration.events_database_name, events_table_name=self._data_lake_integration.events_table_name @@ -60,6 +61,7 @@ class AWSMetricsStack(core.Stack): self._batch_analytics = BatchAnalytics( self, + application_name=application_name, analytics_bucket_name=self._data_lake_integration.analytics_bucket_name, events_database_name=self._data_lake_integration.events_database_name, events_table_name=self._data_lake_integration.events_table_name diff --git a/Gems/AWSMetrics/cdk/aws_metrics/batch_analytics.py b/Gems/AWSMetrics/cdk/aws_metrics/batch_analytics.py index 8398113bc4..eb36d8a5da 100755 --- a/Gems/AWSMetrics/cdk/aws_metrics/batch_analytics.py +++ b/Gems/AWSMetrics/cdk/aws_metrics/batch_analytics.py @@ -20,10 +20,12 @@ class BatchAnalytics: """ def __init__(self, stack: core.Construct, + application_name: str, analytics_bucket_name: str, events_database_name: str, events_table_name) -> None: self._stack = stack + self._application_name = application_name self._analytics_bucket_name = analytics_bucket_name self._events_database_name = events_database_name self._events_table_name = events_table_name @@ -58,6 +60,12 @@ class BatchAnalytics: ) ) ) + core.CfnOutput( + self._stack, + id='AthenaWorkGroupName', + description='Name of the Athena work group that contains sample queries', + export_name=f"{self._application_name}:AthenaWorkGroup", + value=self._athena_work_group.name) def _create_athena_queries(self) -> None: """ diff --git a/Gems/AWSMetrics/cdk/aws_metrics/batch_processing.py b/Gems/AWSMetrics/cdk/aws_metrics/batch_processing.py index 4dbb3b2120..803f6076c8 100755 --- a/Gems/AWSMetrics/cdk/aws_metrics/batch_processing.py +++ b/Gems/AWSMetrics/cdk/aws_metrics/batch_processing.py @@ -26,11 +26,13 @@ class BatchProcessing: """ def __init__(self, stack: core.Construct, + application_name: str, input_stream_arn: str, analytics_bucket_arn: str, events_database_name: str, events_table_name) -> None: self._stack = stack + self._application_name = application_name self._input_stream_arn = input_stream_arn self._analytics_bucket_arn = analytics_bucket_arn self._events_database_name = events_database_name @@ -60,6 +62,12 @@ class BatchProcessing: os.path.join(os.path.dirname(__file__), 'lambdas', 'events_processing_lambda')), role=self._events_processing_lambda_role ) + core.CfnOutput( + self._stack, + id='EventProcessingLambdaName', + description='Lambda function for processing metrics events data.', + export_name=f"{self._application_name}:EventProcessingLambda", + value=self._events_processing_lambda.function_name) def _create_events_processing_lambda_role(self, function_name: str) -> None: """ diff --git a/Gems/AWSMetrics/cdk/aws_metrics/dashboard.py b/Gems/AWSMetrics/cdk/aws_metrics/dashboard.py index 32ff0d9c84..616643ebb1 100755 --- a/Gems/AWSMetrics/cdk/aws_metrics/dashboard.py +++ b/Gems/AWSMetrics/cdk/aws_metrics/dashboard.py @@ -52,7 +52,7 @@ class Dashboard: max_width=aws_metrics_constants.DASHBOARD_MAX_WIDGET_WIDTH) ) - dashboard_output = core.CfnOutput( + core.CfnOutput( stack, id='DashboardName', description='CloudWatch dashboard to monitor the operational health and real-time metrics', diff --git a/Gems/AWSMetrics/cdk/aws_metrics/data_ingestion.py b/Gems/AWSMetrics/cdk/aws_metrics/data_ingestion.py index a21e629c38..cc11796ee9 100755 --- a/Gems/AWSMetrics/cdk/aws_metrics/data_ingestion.py +++ b/Gems/AWSMetrics/cdk/aws_metrics/data_ingestion.py @@ -69,14 +69,14 @@ class DataIngestion: cfn_rest_api.add_property_deletion_override("BodyS3Location") cfn_rest_api.add_property_override("FailOnWarnings", True) - api_id_output = core.CfnOutput( + core.CfnOutput( self._stack, id='RESTApiId', description='Service API Id for the analytics pipeline', export_name=f"{application_name}:RestApiId", value=self._rest_api.rest_api_id) - stage_output = core.CfnOutput( + core.CfnOutput( self._stack, id='RESTApiStage', description='Stage for the REST API deployment', diff --git a/Gems/AWSMetrics/cdk/aws_metrics/data_lake_integration.py b/Gems/AWSMetrics/cdk/aws_metrics/data_lake_integration.py index e47b1a95c2..a0b93eb212 100755 --- a/Gems/AWSMetrics/cdk/aws_metrics/data_lake_integration.py +++ b/Gems/AWSMetrics/cdk/aws_metrics/data_lake_integration.py @@ -67,7 +67,7 @@ class DataLakeIntegration: cfn_bucket = self._analytics_bucket.node.find_child('Resource') cfn_bucket.apply_removal_policy(core.RemovalPolicy.DESTROY) - analytics_bucket_output = core.CfnOutput( + core.CfnOutput( self._stack, id='AnalyticsBucketName', description='Name of the S3 bucket for storing metrics event data', @@ -89,6 +89,12 @@ class DataLakeIntegration: name=f'{self._stack.stack_name}-EventsDatabase'.lower() ) ) + core.CfnOutput( + self._stack, + id='EventDatabaseName', + description='Glue database for metrics events.', + export_name=f"{self._application_name}:EventsDatabase", + value=self._events_database.ref) def _create_events_table(self) -> None: """ @@ -199,7 +205,7 @@ class DataLakeIntegration: configuration=aws_metrics_constants.CRAWLER_CONFIGURATION ) - events_crawler_output = core.CfnOutput( + core.CfnOutput( self._stack, id='EventsCrawlerName', description='Glue Crawler to populate the AWS Glue Data Catalog with metrics events tables', diff --git a/Gems/AWSMetrics/cdk/aws_metrics/real_time_data_processing.py b/Gems/AWSMetrics/cdk/aws_metrics/real_time_data_processing.py index 4ef9caa022..ffd74a51a9 100755 --- a/Gems/AWSMetrics/cdk/aws_metrics/real_time_data_processing.py +++ b/Gems/AWSMetrics/cdk/aws_metrics/real_time_data_processing.py @@ -113,7 +113,7 @@ class RealTimeDataProcessing: ), ) - analytics_application_output = core.CfnOutput( + core.CfnOutput( self._stack, id='AnalyticsApplicationName', description='Kinesis Data Analytics application to process the real-time metrics data', @@ -199,6 +199,12 @@ class RealTimeDataProcessing: os.path.join(os.path.dirname(__file__), 'lambdas', 'analytics_processing_lambda')), role=self._analytics_processing_lambda_role ) + core.CfnOutput( + self._stack, + id='AnalyticsProcessingLambdaName', + description='Lambda function for sending processed data to CloudWatch.', + export_name=f"{self._application_name}:AnalyticsProcessingLambda", + value=self._analytics_processing_lambda.function_name) def _create_analytics_processing_lambda_role(self, function_name: str) -> iam.Role: """ diff --git a/Gems/Atom/Asset/ImageProcessingAtom/Code/CMakeLists.txt b/Gems/Atom/Asset/ImageProcessingAtom/Code/CMakeLists.txt index dfeee011cc..1463124e27 100644 --- a/Gems/Atom/Asset/ImageProcessingAtom/Code/CMakeLists.txt +++ b/Gems/Atom/Asset/ImageProcessingAtom/Code/CMakeLists.txt @@ -62,6 +62,7 @@ ly_add_target( 3rdParty::Qt::Core 3rdParty::Qt::Widgets 3rdParty::Qt::Gui + 3rdParty::astc-encoder 3rdParty::etc2comp 3rdParty::PVRTexTool 3rdParty::squish-ccr @@ -77,8 +78,6 @@ ly_add_target( Gem::Atom_RPI.Public Gem::Atom_RHI.Reflect Gem::Atom_Utils.Static - RUNTIME_DEPENDENCIES - 3rdParty::ASTCEncoder ) ly_add_source_properties( diff --git a/Gems/Atom/Asset/ImageProcessingAtom/Code/Source/Compressors/ASTCCompressor.cpp b/Gems/Atom/Asset/ImageProcessingAtom/Code/Source/Compressors/ASTCCompressor.cpp new file mode 100644 index 0000000000..4ef47c043d --- /dev/null +++ b/Gems/Atom/Asset/ImageProcessingAtom/Code/Source/Compressors/ASTCCompressor.cpp @@ -0,0 +1,322 @@ +/* + * Copyright (c) Contributors to the Open 3D Engine Project. + * For complete copyright and license terms please see the LICENSE at the root of this distribution. + * + * SPDX-License-Identifier: Apache-2.0 OR MIT + * + */ + +#include + +#include +#include +#include + +#include +#include +#include +#include +#include + + +namespace ImageProcessingAtom +{ + bool ASTCCompressor::IsCompressedPixelFormatSupported(EPixelFormat fmt) + { + return IsASTCFormat(fmt); + } + + bool ASTCCompressor::IsUncompressedPixelFormatSupported(EPixelFormat fmt) + { + // astc encoder requires the compress input image or decompress output image to have four channels + switch (fmt) + { + // uint 8 + case ePixelFormat_R8G8B8A8: + case ePixelFormat_R8G8B8X8: + // fp16 + case ePixelFormat_R16G16B16A16F: + // fp32 + case ePixelFormat_R32G32B32A32F: + return true; + default: + return false; + } + } + + EPixelFormat ASTCCompressor::GetSuggestedUncompressedFormat([[maybe_unused]] EPixelFormat compressedfmt, EPixelFormat uncompressedfmt) const + { + if (IsUncompressedPixelFormatSupported(uncompressedfmt)) + { + return uncompressedfmt; + } + + auto formatInfo = CPixelFormats::GetInstance().GetPixelFormatInfo(uncompressedfmt); + switch (formatInfo->eSampleType) + { + case ESampleType::eSampleType_Half: + return ePixelFormat_R16G16B16A16F; + case ESampleType::eSampleType_Float: + return ePixelFormat_R32G32B32A32F; + } + + return ePixelFormat_R8G8B8A8; + } + + ColorSpace ASTCCompressor::GetSupportedColorSpace([[maybe_unused]] EPixelFormat compressFormat) const + { + return ColorSpace::autoSelect; + } + + const char* ASTCCompressor::GetName() const + { + return "ASTCCompressor"; + } + + bool ASTCCompressor::DoesSupportDecompress([[maybe_unused]] EPixelFormat fmtDst) + { + return true; + } + + astcenc_profile GetAstcProfile(bool isSrgb, EPixelFormat pixelFormat) + { + // select profile depends on LDR or HDR, SRGB or Linear + // ASTCENC_PRF_LDR + // ASTCENC_PRF_LDR_SRGB + // ASTCENC_PRF_HDR_RGB_LDR_A + // ASTCENC_PRF_HDR + + auto formatInfo = CPixelFormats::GetInstance().GetPixelFormatInfo(pixelFormat); + bool isHDR = formatInfo->eSampleType == ESampleType::eSampleType_Half || formatInfo->eSampleType == ESampleType::eSampleType_Float; + astcenc_profile profile; + if (isHDR) + { + // HDR is not support in core vulkan 1.1 for android. + // https://arm-software.github.io/vulkan-sdk/_a_s_t_c.html + profile = isSrgb?ASTCENC_PRF_HDR_RGB_LDR_A:ASTCENC_PRF_HDR; + } + else + { + + profile = isSrgb?ASTCENC_PRF_LDR_SRGB:ASTCENC_PRF_LDR; + } + return profile; + } + + astcenc_type GetAstcDataType(EPixelFormat pixelFormat) + { + auto formatInfo = CPixelFormats::GetInstance().GetPixelFormatInfo(pixelFormat); + astcenc_type dataType = ASTCENC_TYPE_U8; + + switch (formatInfo->eSampleType) + { + case ESampleType::eSampleType_Uint8: + dataType = ASTCENC_TYPE_U8; + break; + case ESampleType::eSampleType_Half: + dataType = ASTCENC_TYPE_F16; + break; + case ESampleType::eSampleType_Float: + dataType = ASTCENC_TYPE_F32; + break; + default: + dataType = ASTCENC_TYPE_U8; + AZ_Assert(false, "Unsupport uncompressed format %s", formatInfo->szName); + break; + } + + return dataType; + } + + float GetAstcCompressQuality(ICompressor::EQuality quality) + { + switch (quality) + { + case ICompressor::EQuality::eQuality_Fast: + return ASTCENC_PRE_FAST; + case ICompressor::EQuality::eQuality_Slow: + return ASTCENC_PRE_THOROUGH; + case ICompressor::EQuality::eQuality_Preview: + case ICompressor::EQuality::eQuality_Normal: + default: + return ASTCENC_PRE_MEDIUM; + } + } + + IImageObjectPtr ASTCCompressor::CompressImage(IImageObjectPtr srcImage, EPixelFormat fmtDst, const CompressOption* compressOption) const + { + //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; + } + + astcenc_swizzle swizzle {ASTCENC_SWZ_R, ASTCENC_SWZ_G, ASTCENC_SWZ_B, compressOption->discardAlpha? ASTCENC_SWZ_1:ASTCENC_SWZ_A}; + AZ::u32 flags = 0; + if (srcImage->HasImageFlags(EIF_RenormalizedTexture)) + { + ImageToProcess imageToProcess(srcImage); + imageToProcess.ConvertFormatUncompressed(ePixelFormat_R8G8B8X8); + srcImage = imageToProcess.Get(); + fmtSrc = srcImage->GetPixelFormat(); + + flags = ASTCENC_FLG_MAP_NORMAL; + swizzle = astcenc_swizzle{ ASTCENC_SWZ_R, ASTCENC_SWZ_R, ASTCENC_SWZ_R, ASTCENC_SWZ_G }; + } + + auto dstFormatInfo = CPixelFormats::GetInstance().GetPixelFormatInfo(fmtDst); + + const float quality = GetAstcCompressQuality(compressOption->compressQuality); + const astcenc_profile profile = GetAstcProfile(srcImage->HasImageFlags(EIF_SRGBRead), fmtSrc); + + astcenc_config config; + astcenc_error status; + status = astcenc_config_init(profile, dstFormatInfo->blockWidth, dstFormatInfo->blockHeight, 1, quality, flags, &config); + + //ASTCENC_FLG_MAP_NORMAL + AZ_Assert( status == ASTCENC_SUCCESS, "ERROR: Codec config init failed: %s\n", astcenc_get_error_string(status)); + + // Create a context based on the configuration + astcenc_context* context; + AZ::u32 blockCount = ((srcImage->GetWidth(0)+ dstFormatInfo->blockWidth-1)/dstFormatInfo->blockWidth) * ((srcImage->GetHeight(0) + dstFormatInfo->blockHeight-1)/dstFormatInfo->blockHeight); + AZ::u32 threadCount = AZStd::min(AZStd::thread::hardware_concurrency(), blockCount); + status = astcenc_context_alloc(&config, threadCount, &context); + AZ_Assert( status == ASTCENC_SUCCESS, "ERROR: Codec context alloc failed: %s\n", astcenc_get_error_string(status)); + + const astcenc_type dataType =GetAstcDataType(fmtSrc); + + // Compress the image for each mips + IImageObjectPtr dstImage(srcImage->AllocateImage(fmtDst)); + const AZ::u32 dstMips = dstImage->GetMipCount(); + for (AZ::u32 mip = 0; mip < dstMips; ++mip) + { + astcenc_image image; + image.dim_x = srcImage->GetWidth(mip); + image.dim_y = srcImage->GetHeight(mip); + image.dim_z = 1; + image.data_type = dataType; + + AZ::u8* srcMem; + AZ::u32 srcPitch; + srcImage->GetImagePointer(mip, srcMem, srcPitch); + image.data = reinterpret_cast(&srcMem); + + AZ::u8* dstMem; + AZ::u32 dstPitch; + dstImage->GetImagePointer(mip, dstMem, dstPitch); + AZ::u32 dataSize = dstImage->GetMipBufSize(mip); + + // Create jobs for each compression thread + auto completionJob = aznew AZ::JobCompletion(); + for (AZ::u32 threadIdx = 0; threadIdx < threadCount; threadIdx++) + { + const auto jobLambda = [&status, context, &image, &swizzle, dstMem, dataSize, threadIdx]() + { + astcenc_error error = astcenc_compress_image(context, &image, &swizzle, dstMem, dataSize, threadIdx); + if (error != ASTCENC_SUCCESS) + { + status = error; + } + }; + + AZ::Job* simulationJob = AZ::CreateJobFunction(AZStd::move(jobLambda), true, nullptr); //auto-deletes + simulationJob->SetDependent(completionJob); + simulationJob->Start(); + } + + if (completionJob) + { + completionJob->StartAndWaitForCompletion(); + delete completionJob; + completionJob = nullptr; + } + + if (status != ASTCENC_SUCCESS) + { + AZ_Error("Image Processing", false, "ASTCCompressor::CompressImage failed: %s\n", astcenc_get_error_string(status)); + astcenc_context_free(context); + return nullptr; + } + + // Need to reset to compress next mip + astcenc_compress_reset(context); + } + astcenc_context_free(context); + + return dstImage; + } + + IImageObjectPtr ASTCCompressor::DecompressImage(IImageObjectPtr srcImage, EPixelFormat fmtDst) const + { + //validate input + EPixelFormat fmtSrc = srcImage->GetPixelFormat(); //compressed + auto srcFormatInfo = CPixelFormats::GetInstance().GetPixelFormatInfo(fmtSrc); + + if (!IsCompressedPixelFormatSupported(fmtSrc) || !IsUncompressedPixelFormatSupported(fmtDst)) + { + return nullptr; + } + + const float quality = ASTCENC_PRE_MEDIUM; + astcenc_swizzle swizzle {ASTCENC_SWZ_R, ASTCENC_SWZ_G, ASTCENC_SWZ_B, ASTCENC_SWZ_A}; + if (srcImage->HasImageFlags(EIF_RenormalizedTexture)) + { + swizzle = astcenc_swizzle{ASTCENC_SWZ_R, ASTCENC_SWZ_A, ASTCENC_SWZ_Z, ASTCENC_SWZ_1}; + } + + astcenc_config config; + astcenc_error status; + astcenc_profile profile = GetAstcProfile(srcImage->HasImageFlags(EIF_SRGBRead), fmtDst); + AZ::u32 flags = ASTCENC_FLG_DECOMPRESS_ONLY; + status = astcenc_config_init(profile, srcFormatInfo->blockWidth, srcFormatInfo->blockHeight, 1, quality, flags, &config); + + //ASTCENC_FLG_MAP_NORMAL + AZ_Assert( status == ASTCENC_SUCCESS, "astcenc_config_init failed: %s\n", astcenc_get_error_string(status)); + + // Create a context based on the configuration + const AZ::u32 threadCount = 1; // Decompress function doesn't support multiple threads + astcenc_context* context; + status = astcenc_context_alloc(&config, threadCount, &context); + AZ_Assert( status == ASTCENC_SUCCESS, "astcenc_context_alloc failed: %s\n", astcenc_get_error_string(status)); + + astcenc_type dataType =GetAstcDataType(fmtDst); + + // Decompress the image for each mips + IImageObjectPtr dstImage(srcImage->AllocateImage(fmtDst)); + const AZ::u32 dstMips = dstImage->GetMipCount(); + for (AZ::u32 mip = 0; mip < dstMips; ++mip) + { + astcenc_image image; + image.dim_x = srcImage->GetWidth(mip); + image.dim_y = srcImage->GetHeight(mip); + image.dim_z = 1; + image.data_type = dataType; + + AZ::u8* srcMem; + AZ::u32 srcPitch; + srcImage->GetImagePointer(mip, srcMem, srcPitch); + AZ::u32 srcDataSize = srcImage->GetMipBufSize(mip); + + AZ::u8* dstMem; + AZ::u32 dstPitch; + dstImage->GetImagePointer(mip, dstMem, dstPitch); + image.data = reinterpret_cast(&dstMem); + + status = astcenc_decompress_image(context, srcMem, srcDataSize, &image, &swizzle, 0); + + if (status != ASTCENC_SUCCESS) + { + AZ_Error("Image Processing", false, "ASTCCompressor::DecompressImage failed: %s\n", astcenc_get_error_string(status)); + astcenc_context_free(context); + return nullptr; + } + } + + astcenc_context_free(context); + + return dstImage; + } +} //namespace ImageProcessingAtom diff --git a/Gems/Atom/Asset/ImageProcessingAtom/Code/Source/Compressors/ASTCCompressor.h b/Gems/Atom/Asset/ImageProcessingAtom/Code/Source/Compressors/ASTCCompressor.h new file mode 100644 index 0000000000..cf191c7072 --- /dev/null +++ b/Gems/Atom/Asset/ImageProcessingAtom/Code/Source/Compressors/ASTCCompressor.h @@ -0,0 +1,30 @@ +/* + * Copyright (c) Contributors to the Open 3D Engine Project. + * For complete copyright and license terms please see the LICENSE at the root of this distribution. + * + * SPDX-License-Identifier: Apache-2.0 OR MIT + * + */ + +#pragma once + +#include + +namespace ImageProcessingAtom +{ + class ASTCCompressor + : 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) const override; + IImageObjectPtr DecompressImage(IImageObjectPtr srcImage, EPixelFormat fmtDst) const override; + + EPixelFormat GetSuggestedUncompressedFormat(EPixelFormat compressedfmt, EPixelFormat uncompressedfmt) const override; + ColorSpace GetSupportedColorSpace(EPixelFormat compressFormat) const final; + const char* GetName() const final; + }; +} // namespace ImageProcessingAtom diff --git a/Gems/Atom/Asset/ImageProcessingAtom/Code/Source/Compressors/Compressor.cpp b/Gems/Atom/Asset/ImageProcessingAtom/Code/Source/Compressors/Compressor.cpp index 9013bff1db..1dd18faaf3 100644 --- a/Gems/Atom/Asset/ImageProcessingAtom/Code/Source/Compressors/Compressor.cpp +++ b/Gems/Atom/Asset/ImageProcessingAtom/Code/Source/Compressors/Compressor.cpp @@ -8,6 +8,7 @@ #include +#include #include #include #include @@ -15,11 +16,8 @@ namespace ImageProcessingAtom { - ICompressorPtr ICompressor::FindCompressor(EPixelFormat fmt, [[maybe_unused]] ColorSpace colorSpace, bool isCompressing) + ICompressorPtr ICompressor::FindCompressor(EPixelFormat fmt, ColorSpace colorSpace, bool isCompressing) { - // The ISPC texture compressor is able to compress BC1, BC3, BC6H and BC7 formats, and all of the ASTC formats. - // Note: The ISPC texture compressor is only able to compress images that are a multiple of the compressed format's blocksize. - // Another limitation is that the compressor requires LDR source images to be in sRGB colorspace. if (ISPCCompressor::IsCompressedPixelFormatSupported(fmt)) { if ((isCompressing && ISPCCompressor::IsSourceColorSpaceSupported(colorSpace, fmt)) || (!isCompressing && ISPCCompressor::DoesSupportDecompress(fmt))) @@ -35,6 +33,14 @@ namespace ImageProcessingAtom return ICompressorPtr(new CTSquisher()); } } + + if (ASTCCompressor::IsCompressedPixelFormatSupported(fmt)) + { + if (isCompressing || (!isCompressing && ASTCCompressor::DoesSupportDecompress(fmt))) + { + return ICompressorPtr(new ASTCCompressor()); + } + } // Both ETC2Compressor and PVRTCCompressor can process ETC formats // According to Mobile team, Etc2Com is faster than PVRTexLib, so we check with ETC2Compressor before PVRTCCompressor diff --git a/Gems/Atom/Asset/ImageProcessingAtom/Code/Source/Compressors/Compressor.h b/Gems/Atom/Asset/ImageProcessingAtom/Code/Source/Compressors/Compressor.h index dff71e59db..6920ae0cc1 100644 --- a/Gems/Atom/Asset/ImageProcessingAtom/Code/Source/Compressors/Compressor.h +++ b/Gems/Atom/Asset/ImageProcessingAtom/Code/Source/Compressors/Compressor.h @@ -38,8 +38,7 @@ namespace ImageProcessingAtom EQuality compressQuality = eQuality_Normal; //required for CTSquisher AZ::Vector3 rgbWeight = AZ::Vector3(0.3333f, 0.3334f, 0.3333f); - //required for ISPC texture compressor - bool ispcDiscardAlpha = false; + bool discardAlpha = false; }; public: diff --git a/Gems/Atom/Asset/ImageProcessingAtom/Code/Source/Compressors/ISPCTextureCompressor.cpp b/Gems/Atom/Asset/ImageProcessingAtom/Code/Source/Compressors/ISPCTextureCompressor.cpp index 5e96c7274d..b1b41d98bc 100644 --- a/Gems/Atom/Asset/ImageProcessingAtom/Code/Source/Compressors/ISPCTextureCompressor.cpp +++ b/Gems/Atom/Asset/ImageProcessingAtom/Code/Source/Compressors/ISPCTextureCompressor.cpp @@ -57,6 +57,12 @@ namespace ImageProcessingAtom bool ISPCCompressor::IsCompressedPixelFormatSupported(EPixelFormat fmt) { + // Even though the ISPC compressor support ASTC formats. But it has restrictions + // 1. Only supports LDR color profile + // 2. Only supports a subset of 2D block sizes + // Also it has overall lower quality compare to astc-encoder + // So we won't add ASTC as part of supported formats here + // Ref: https://solidpixel.github.io/2020/03/02/astc-compared.html switch (fmt) { case ePixelFormat_BC3: @@ -152,7 +158,7 @@ namespace ImageProcessingAtom if (compressOption) { quality = compressOption->compressQuality; - discardAlpha = compressOption->ispcDiscardAlpha; + discardAlpha = compressOption->discardAlpha; } // Get the compression profile @@ -230,24 +236,12 @@ namespace ImageProcessingAtom } break; default: - if (IsASTCFormat(destinationFormat)) - { - const PixelFormatInfo* info = CPixelFormats::GetInstance().GetPixelFormatInfo(destinationFormat); - astc_enc_settings settings = {}; - - const auto setProfile = compressionProfile->GetASTC(discardAlpha); - setProfile(&settings, info->blockWidth, info->blockHeight); - - // Compress with ASTC - CompressBlocksASTC(&sourceSurface, destinationImageData, &settings); - } - else - { - // No valid pixel format - AZ_Assert(false, "Unhandled pixel format %d", destinationFormat); - return nullptr; - } - break; + { + // No valid pixel format + AZ_Assert(false, "Unhandled pixel format %d", destinationFormat); + return nullptr; + } + break; } } diff --git a/Gems/Atom/Asset/ImageProcessingAtom/Code/Source/Compressors/PVRTC.cpp b/Gems/Atom/Asset/ImageProcessingAtom/Code/Source/Compressors/PVRTC.cpp index 7c899e4ad2..f3a630e8c1 100644 --- a/Gems/Atom/Asset/ImageProcessingAtom/Code/Source/Compressors/PVRTC.cpp +++ b/Gems/Atom/Asset/ImageProcessingAtom/Code/Source/Compressors/PVRTC.cpp @@ -19,7 +19,7 @@ namespace ImageProcessingAtom { - // Note: PVRTexLib supports ASTC formats, ETC formats, PVRTC formats and BC formats + // Note: PVRTexLib supports 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. @@ -27,34 +27,6 @@ namespace ImageProcessingAtom { 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: @@ -156,26 +128,7 @@ namespace ImageProcessingAtom 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 + else { if (quality == eQuality_Preview) { @@ -252,7 +205,7 @@ namespace ImageProcessingAtom if (!isSuccess) { - AZ_Error("Image Processing", false, "Failed to compress image with PVRTexLib. You may not have astcenc.exe for compressing ASTC formates"); + AZ_Error("Image Processing", false, "Failed to compress image with PVRTexLib."); return nullptr; } diff --git a/Gems/Atom/Asset/ImageProcessingAtom/Code/Source/Processing/ImageConvert.cpp b/Gems/Atom/Asset/ImageProcessingAtom/Code/Source/Processing/ImageConvert.cpp index 9b41645280..5995146c59 100644 --- a/Gems/Atom/Asset/ImageProcessingAtom/Code/Source/Processing/ImageConvert.cpp +++ b/Gems/Atom/Asset/ImageProcessingAtom/Code/Source/Processing/ImageConvert.cpp @@ -117,6 +117,11 @@ namespace ImageProcessingAtom } } + const ImageConvertProcessDescriptor* ImageConvertProcess::GetInputDesc() const + { + return m_input.get(); + } + ImageConvertProcess::ImageConvertProcess(AZStd::unique_ptr&& descriptor) : m_image(nullptr) , m_progressStep(0) @@ -554,12 +559,6 @@ namespace ImageProcessingAtom // pixel format conversion bool ImageConvertProcess::ConvertPixelformat() { - //For ASTC compression we need to clear out the alpha to get accurate rgb compression. - if(m_alphaImage && IsASTCFormat(m_input->m_presetSetting.m_pixelFormat)) - { - m_image->Get()->Swizzle("rgb1"); - } - //set up compress option ICompressor::EQuality quality; if (m_input->m_isPreview) @@ -574,7 +573,14 @@ namespace ImageProcessingAtom // set the compression options m_image->GetCompressOption().compressQuality = quality; m_image->GetCompressOption().rgbWeight = m_input->m_presetSetting.GetColorWeight(); - m_image->GetCompressOption().ispcDiscardAlpha = m_input->m_presetSetting.m_discardAlpha; + m_image->GetCompressOption().discardAlpha = m_input->m_presetSetting.m_discardAlpha; + + //For ASTC compression we need to clear out the alpha to get accurate rgb compression. + if(m_alphaImage && IsASTCFormat(m_input->m_presetSetting.m_pixelFormat)) + { + m_image->GetCompressOption().discardAlpha = true; + } + m_image->ConvertFormat(m_input->m_presetSetting.m_pixelFormat); return true; diff --git a/Gems/Atom/Asset/ImageProcessingAtom/Code/Source/Processing/ImageConvert.h b/Gems/Atom/Asset/ImageProcessingAtom/Code/Source/Processing/ImageConvert.h index 190e68ca31..6ab866ee09 100644 --- a/Gems/Atom/Asset/ImageProcessingAtom/Code/Source/Processing/ImageConvert.h +++ b/Gems/Atom/Asset/ImageProcessingAtom/Code/Source/Processing/ImageConvert.h @@ -122,6 +122,8 @@ namespace ImageProcessingAtom // Get output JobProducts and append them to the outProducts vector. void GetAppendOutputProducts(AZStd::vector& outProducts); + const ImageConvertProcessDescriptor* GetInputDesc() const; + private: //input image and settings AZStd::shared_ptr m_input; diff --git a/Gems/Atom/Asset/ImageProcessingAtom/Code/Tests/ImageProcessing_Test.cpp b/Gems/Atom/Asset/ImageProcessingAtom/Code/Tests/ImageProcessing_Test.cpp index 0656fb4e46..c4240306c4 100644 --- a/Gems/Atom/Asset/ImageProcessingAtom/Code/Tests/ImageProcessing_Test.cpp +++ b/Gems/Atom/Asset/ImageProcessingAtom/Code/Tests/ImageProcessing_Test.cpp @@ -12,8 +12,12 @@ #include +#include + #include #include +#include +#include #include #include #include @@ -123,6 +127,9 @@ namespace UnitTest AZStd::string m_outputRootFolder; AZStd::string m_outputFolder; + AZStd::unique_ptr m_jobManager; + AZStd::unique_ptr m_jobContext; + void SetUp() override { AllocatorsBase::SetupAllocator(); @@ -159,6 +166,27 @@ namespace UnitTest m_jsonSystemComponent->Reflect(m_jsonRegistrationContext.get()); BuilderPluginComponent::Reflect(m_jsonRegistrationContext.get()); + // Setup job context for job system + JobManagerDesc jobManagerDesc; + JobManagerThreadDesc threadDesc; +#if AZ_TRAIT_SET_JOB_PROCESSOR_ID + threadDesc.m_cpuId = 0; // Don't set processors IDs on windows +#endif + + uint32_t numWorkerThreads = AZStd::thread::hardware_concurrency(); + + for (unsigned int i = 0; i < numWorkerThreads; ++i) + { + jobManagerDesc.m_workerThreads.push_back(threadDesc); +#if AZ_TRAIT_SET_JOB_PROCESSOR_ID + threadDesc.m_cpuId++; +#endif + } + + m_jobManager = AZStd::make_unique(jobManagerDesc); + m_jobContext = AZStd::make_unique(*m_jobManager); + JobContext::SetGlobalContext(m_jobContext.get()); + // Startup default local FileIO (hits OSAllocator) if not already setup. if (AZ::IO::FileIOBase::GetInstance() == nullptr) { @@ -192,6 +220,10 @@ namespace UnitTest delete AZ::IO::FileIOBase::GetInstance(); AZ::IO::FileIOBase::SetInstance(nullptr); + JobContext::SetGlobalContext(nullptr); + m_jobContext = nullptr; + m_jobManager = nullptr; + m_jsonRegistrationContext->EnableRemoveReflection(); m_jsonSystemComponent->Reflect(m_jsonRegistrationContext.get()); BuilderPluginComponent::Reflect(m_jsonRegistrationContext.get()); @@ -223,7 +255,7 @@ namespace UnitTest Image_512X288_RGB8_Tga, Image_1024X1024_RGB8_Tif, Image_UpperCase_Tga, - Image_512x512_Normal_Tga, // QImage doesn't support loading this file. + Image_1024x1024_normal_tiff, Image_128x128_Transparent_Tga, Image_237x177_RGB_Jpg, Image_GreyScale_Png, @@ -251,7 +283,7 @@ namespace UnitTest m_imagFileNameMap[Image_512X288_RGB8_Tga] = m_testFileFolder + "512x288_24bit.tga"; m_imagFileNameMap[Image_1024X1024_RGB8_Tif] = m_testFileFolder + "1024x1024_24bit.tif"; m_imagFileNameMap[Image_UpperCase_Tga] = m_testFileFolder + "uppercase.TGA"; - m_imagFileNameMap[Image_512x512_Normal_Tga] = m_testFileFolder + "512x512_RGB_N.tga"; + m_imagFileNameMap[Image_1024x1024_normal_tiff] = m_testFileFolder + "1024x1024_normal.tiff"; m_imagFileNameMap[Image_128x128_Transparent_Tga] = m_testFileFolder + "128x128_RGBA8.tga"; m_imagFileNameMap[Image_237x177_RGB_Jpg] = m_testFileFolder + "237x177_RGB.jpg"; m_imagFileNameMap[Image_GreyScale_Png] = m_testFileFolder + "greyscale.png"; @@ -801,8 +833,7 @@ namespace UnitTest auto formatInfo = CPixelFormats::GetInstance().GetPixelFormatInfo(pixelFormat); if (formatInfo->bCompressed) { - // exclude astc formats until we add astc compressor to all platforms - // exclude pvrtc formats (deprecating) + // skip ASTC formats which are tested in TestConvertASTCCompressor if (!IsASTCFormat(pixelFormat) && pixelFormat != ePixelFormat_PVRTC2 && pixelFormat != ePixelFormat_PVRTC4 && !IsETCFormat(pixelFormat)) // skip ETC since it's very slow @@ -830,32 +861,121 @@ namespace UnitTest continue; } - [[maybe_unused]] auto formatInfo = CPixelFormats::GetInstance().GetPixelFormatInfo(pixelFormat); - imageToProcess.Set(srcImage); - imageToProcess.ConvertFormat(pixelFormat); + auto formatInfo = CPixelFormats::GetInstance().GetPixelFormatInfo(pixelFormat); + ColorSpace sourceColorSpace = srcImage->HasImageFlags(EIF_SRGBRead) ? ColorSpace::sRGB : ColorSpace::linear; + ICompressorPtr compressor = ICompressor::FindCompressor(pixelFormat, sourceColorSpace, true); - if (!imageToProcess.Get()) + if (!compressor) { AZ_Warning("test", false, "unsupported format: %s", formatInfo->szName); continue; } + + imageToProcess.Set(srcImage); + imageToProcess.ConvertFormat(pixelFormat); + ASSERT_TRUE(imageToProcess.Get()); ASSERT_TRUE(imageToProcess.Get()->GetPixelFormat() == pixelFormat); - // Get compressor name - ColorSpace sourceColorSpace = srcImage->HasImageFlags(EIF_SRGBRead) ? ColorSpace::sRGB : ColorSpace::linear; - ICompressorPtr compressor = ICompressor::FindCompressor(pixelFormat, sourceColorSpace, true); + //convert back to an uncompressed format and expect it will be successful + imageToProcess.ConvertFormat(srcImage->GetPixelFormat()); + ASSERT_TRUE(imageToProcess.Get()->GetPixelFormat() == srcImage->GetPixelFormat()); - //save the image to a file so we can check the visual result + // Save the image to a file so we can check the visual result AZStd::string outputName = AZStd::string::format("%s_%s", imageName.c_str(), compressor->GetName()); SaveImageToFile(imageToProcess.Get(), outputName, 1); - - //convert back to an uncompressed format and expect it will be successful - imageToProcess.ConvertFormat(ePixelFormat_R8G8B8A8); - ASSERT_TRUE(imageToProcess.Get()->GetPixelFormat() == ePixelFormat_R8G8B8A8); } } } + + TEST_F(ImageProcessingTest, Test_ConvertAllAstc_Success) + { + // Compress/Decompress to all astc formats (LDR) + auto imageIdx = Image_237x177_RGB_Jpg; + IImageObjectPtr srcImage = IImageObjectPtr(LoadImageFromFile(m_imagFileNameMap[imageIdx])); + QFileInfo fi(m_imagFileNameMap[imageIdx].c_str()); + AZStd::string imageName = fi.baseName().toUtf8().constData(); + for (uint32 i = 0; i < ePixelFormat_Count; i++) + { + EPixelFormat pixelFormat = (EPixelFormat)i; + if (IsASTCFormat(pixelFormat)) + { + ImageToProcess imageToProcess(srcImage); + imageToProcess.ConvertFormat(pixelFormat); + + ASSERT_TRUE(imageToProcess.Get()); + ASSERT_TRUE(imageToProcess.Get()->GetPixelFormat() == pixelFormat); + ASSERT_TRUE(imageToProcess.Get()->GetWidth(0) == srcImage->GetWidth(0)); + ASSERT_TRUE(imageToProcess.Get()->GetHeight(0) == srcImage->GetHeight(0)); + + // convert back to an uncompressed format and expect it will be successful + imageToProcess.ConvertFormat(srcImage->GetPixelFormat()); + ASSERT_TRUE(imageToProcess.Get()->GetPixelFormat() == srcImage->GetPixelFormat()); + + // save the image to a file so we can check the visual result + AZStd::string outputName = AZStd::string::format("ASTC_%s", imageName.c_str()); + SaveImageToFile(imageToProcess.Get(), outputName, 1); + } + } + } + + TEST_F(ImageProcessingTest, Test_ConvertHdrToAstc_Success) + { + // Compress/Decompress HDR + auto imageIdx = Image_defaultprobe_cm_1536x256_64bits_tif; + IImageObjectPtr srcImage = IImageObjectPtr(LoadImageFromFile(m_imagFileNameMap[imageIdx])); + + EPixelFormat dstFormat = ePixelFormat_ASTC_4x4; + ImageToProcess imageToProcess(srcImage); + imageToProcess.ConvertFormat(ePixelFormat_ASTC_4x4); + + ASSERT_TRUE(imageToProcess.Get()); + ASSERT_TRUE(imageToProcess.Get()->GetPixelFormat() == dstFormat); + ASSERT_TRUE(imageToProcess.Get()->GetWidth(0) == srcImage->GetWidth(0)); + ASSERT_TRUE(imageToProcess.Get()->GetHeight(0) == srcImage->GetHeight(0)); + + //convert back to an uncompressed format and expect it will be successful + imageToProcess.ConvertFormat(srcImage->GetPixelFormat()); + ASSERT_TRUE(imageToProcess.Get()->GetPixelFormat() == srcImage->GetPixelFormat()); + + //save the image to a file so we can check the visual result + SaveImageToFile(imageToProcess.Get(), "ASTC_HDR", 1); + } + + TEST_F(ImageProcessingTest, Test_AstcNormalPreset_Success) + { + // Normal.preset which uses ASTC as output format + // This test compress a normal texture and its mipmaps + + auto outcome = BuilderSettingManager::Instance()->LoadConfigFromFolder(m_defaultSettingFolder); + ASSERT_TRUE(outcome.IsSuccess()); + + AZStd::string inputFile; + AZStd::vector outProducts; + + inputFile = m_imagFileNameMap[Image_1024x1024_normal_tiff]; + IImageObjectPtr srcImage = IImageObjectPtr(LoadImageFromFile(inputFile)); + + ImageConvertProcess* process = CreateImageConvertProcess(inputFile, m_outputFolder, "ios", outProducts, m_context.get()); + + const PresetSettings* preset = &process->GetInputDesc()->m_presetSetting; + + if (process != nullptr) + { + process->ProcessAll(); + + //get process result + ASSERT_TRUE(process->IsSucceed()); + auto outputImage = process->GetOutputImage(); + ASSERT_TRUE(outputImage->GetPixelFormat() == preset->m_pixelFormat); + ASSERT_TRUE(outputImage->GetWidth(0) == srcImage->GetWidth(0)); + ASSERT_TRUE(outputImage->GetHeight(0) == srcImage->GetHeight(0)); + + SaveImageToFile(outputImage, "ASTC_Normal", 10); + + delete process; + } + } TEST_F(ImageProcessingTest, DISABLED_TestImageFilter) { diff --git a/Gems/Atom/Asset/ImageProcessingAtom/Code/Tests/TestAssets/1024x1024_normal.tiff b/Gems/Atom/Asset/ImageProcessingAtom/Code/Tests/TestAssets/1024x1024_normal.tiff new file mode 100644 index 0000000000..8120514ddc --- /dev/null +++ b/Gems/Atom/Asset/ImageProcessingAtom/Code/Tests/TestAssets/1024x1024_normal.tiff @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:120aaf43057b07fb3c784264eb48b899cc612f30917d316fe843bb839220dc22 +size 203062 diff --git a/Gems/Atom/Asset/ImageProcessingAtom/Code/Tests/TestAssets/512x512_RGB_N.tga b/Gems/Atom/Asset/ImageProcessingAtom/Code/Tests/TestAssets/512x512_RGB_N.tga deleted file mode 100644 index d47f00912a..0000000000 --- a/Gems/Atom/Asset/ImageProcessingAtom/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/Atom/Asset/ImageProcessingAtom/Code/imageprocessing_files.cmake b/Gems/Atom/Asset/ImageProcessingAtom/Code/imageprocessing_files.cmake index 55ccdf1d89..ba9e9f29b7 100644 --- a/Gems/Atom/Asset/ImageProcessingAtom/Code/imageprocessing_files.cmake +++ b/Gems/Atom/Asset/ImageProcessingAtom/Code/imageprocessing_files.cmake @@ -114,6 +114,8 @@ set(FILES ../External/CubeMapGen/CImageSurface.cpp ../External/CubeMapGen/CImageSurface.h ../External/CubeMapGen/VectorMacros.h + Source/Compressors/ASTCCompressor.cpp + Source/Compressors/ASTCCompressor.h Source/Compressors/Compressor.h Source/Compressors/Compressor.cpp Source/Compressors/CTSquisher.h diff --git a/Gems/Atom/Asset/Shader/Code/AZSL/Platform/Android/Vulkan/AzslcHeader.azsli b/Gems/Atom/Asset/Shader/Code/AZSL/Platform/Android/Vulkan/AzslcHeader.azsli index 54c9430f87..0cab4d7a38 100644 --- a/Gems/Atom/Asset/Shader/Code/AZSL/Platform/Android/Vulkan/AzslcHeader.azsli +++ b/Gems/Atom/Asset/Shader/Code/AZSL/Platform/Android/Vulkan/AzslcHeader.azsli @@ -16,6 +16,11 @@ static const float4 s_AzslDebugColor = float4(165.0 / 255.0, 30.0 / 255.0, 36.0 / 255.0, 1); -// Uniform limitation need to be taken into consideration for mobile devices +// Uniform limitation need to be taken into consideration for mobile devices. This would help alleviate device lost errors if the constant buffer +// size overshoots the device's memory constraints. An example is a large number of constant buffers associated with mesh instances that would result in device lost, +// but otherwise OK on PC. We can separate out the number of instances for the different platforms with this define. // [ATOM-14949] -#define AZ_TRAIT_CONSTANT_BUFFER_LIMITATIONS 1 \ No newline at end of file +#define AZ_TRAIT_CONSTANT_BUFFER_LIMITATIONS 1 + +// Different constant buffer alignment on platforms +#define AZ_TRAIT_CONSTANT_BUFFER_ALIGNMENT 16 diff --git a/Gems/Atom/Asset/Shader/Code/AZSL/Platform/Windows/Vulkan/AzslcHeader.azsli b/Gems/Atom/Asset/Shader/Code/AZSL/Platform/Windows/Vulkan/AzslcHeader.azsli index b620c0d696..58395ef6a4 100644 --- a/Gems/Atom/Asset/Shader/Code/AZSL/Platform/Windows/Vulkan/AzslcHeader.azsli +++ b/Gems/Atom/Asset/Shader/Code/AZSL/Platform/Windows/Vulkan/AzslcHeader.azsli @@ -12,3 +12,7 @@ */ static const float4 s_AzslDebugColor = float4(165.0 / 255.0, 30.0 / 255.0, 36.0 / 255.0, 1); + + +// Different constant buffer alignment on platforms +#define AZ_TRAIT_CONSTANT_BUFFER_ALIGNMENT 128 \ No newline at end of file diff --git a/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardMultilayerPBR_Common.azsli b/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardMultilayerPBR_Common.azsli index 2f84aaf5b2..4a66c52bf2 100644 --- a/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardMultilayerPBR_Common.azsli +++ b/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardMultilayerPBR_Common.azsli @@ -104,6 +104,7 @@ option bool o_layer3_enabled; enum class DebugDrawMode { None, BlendMask, Displacement, FinalBlendWeights }; option DebugDrawMode o_debugDrawMode; +// If you modify this enum, you must update the BlendSourceUsesDisplacement function in StandardMultilayerPBR_Displacement.lua enum class LayerBlendSource { BlendMaskTexture, BlendMaskVertexColors, Displacement, Displacement_With_BlendMaskTexture, Displacement_With_BlendMaskVertexColors, Fallback }; option LayerBlendSource o_layerBlendSource; diff --git a/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardMultilayerPBR_Displacement.lua b/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardMultilayerPBR_Displacement.lua index 8fa010f7bd..a032479d19 100644 --- a/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardMultilayerPBR_Displacement.lua +++ b/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardMultilayerPBR_Displacement.lua @@ -88,7 +88,7 @@ end -- @return a table with two values {min,max}. Negative values are below the surface and positive values are above the surface. function CalcOverallHeightRange(context) - local heightMinMax = {nil, nil} + local heightMinMax = {} local function GetMergedHeightRange(heightMinMax, offset, factor) top = offset @@ -138,7 +138,8 @@ function CalcOverallHeightRange(context) if(enableLayer3) then GetMergedHeightRange(heightMinMax, offsetLayer3, factorLayer3) end else - heightMinMax = {0,0} + heightMinMax[0] = 0 + heightMinMax[1] = 0 end return heightMinMax diff --git a/Gems/Atom/Feature/Common/Assets/Passes/HDRColorGrading.pass b/Gems/Atom/Feature/Common/Assets/Passes/HDRColorGrading.pass index f1e8304b30..adcd43ce83 100644 --- a/Gems/Atom/Feature/Common/Assets/Passes/HDRColorGrading.pass +++ b/Gems/Atom/Feature/Common/Assets/Passes/HDRColorGrading.pass @@ -5,7 +5,7 @@ "ClassData": { "PassTemplate": { "Name": "HDRColorGradingTemplate", - "PassClass": "FullScreenTriangle", + "PassClass": "HDRColorGradingPass", "Slots": [ { "Name": "Input", @@ -85,7 +85,7 @@ }, { "Name": "m_whiteBalanceKelvin", - "Value": 6500.0 // 1000.0f ... 40000.0f kelvin + "Value": 6600.0 // 1000.0f ... 40000.0f kelvin }, { "Name": "m_whiteBalanceTint", @@ -96,7 +96,7 @@ "Value": 0.0 // -1 ... 1 }, { - "Name": "m_splitToneMix", + "Name": "m_splitToneWeight", "Value": 0.0 // 0 ... 1 }, { @@ -120,7 +120,7 @@ "Value": 1.0 // 0 ... 1 }, { - "Name": "m_smhMix", + "Name": "m_smhWeight", "Value": 0.0 // 0 ... 1 } ], diff --git a/Gems/Atom/Feature/Common/Assets/Passes/LightAdaptationParent.pass b/Gems/Atom/Feature/Common/Assets/Passes/LightAdaptationParent.pass index ff55ebc200..eec3634045 100644 --- a/Gems/Atom/Feature/Common/Assets/Passes/LightAdaptationParent.pass +++ b/Gems/Atom/Feature/Common/Assets/Passes/LightAdaptationParent.pass @@ -92,8 +92,8 @@ ] }, { - "Name": "LookModificationTransformPass", - "TemplateName": "LookModificationTransformTemplate", + "Name": "HDRColorGradingPass", + "TemplateName": "HDRColorGradingTemplate", "Enabled": true, "Connections": [ { @@ -102,6 +102,20 @@ "Pass": "Parent", "Attachment": "LightingInput" } + } + ] + }, + { + "Name": "LookModificationTransformPass", + "TemplateName": "LookModificationTransformTemplate", + "Enabled": true, + "Connections": [ + { + "LocalSlot": "Input", + "AttachmentRef": { + "Pass": "HDRColorGradingPass", + "Attachment": "Output" + } }, { "LocalSlot": "EyeAdaptationDataInput", diff --git a/Gems/Atom/Feature/Common/Assets/Shaders/PostProcessing/HDRColorGrading.azsl b/Gems/Atom/Feature/Common/Assets/Shaders/PostProcessing/HDRColorGrading.azsl index 9ae4a2bd68..cfa149f0d5 100644 --- a/Gems/Atom/Feature/Common/Assets/Shaders/PostProcessing/HDRColorGrading.azsl +++ b/Gems/Atom/Feature/Common/Assets/Shaders/PostProcessing/HDRColorGrading.azsl @@ -50,13 +50,13 @@ ShaderResourceGroup PassSrg : SRG_PerPass_WithFallback float m_whiteBalanceKelvin; float m_whiteBalanceTint; float m_splitToneBalance; - float m_splitToneMix; + float m_splitToneWeight; float m_colorGradingPostSaturation; float m_smhShadowsStart; float m_smhShadowsEnd; float m_smhHighlightsStart; float m_smhHighlightsEnd; - float m_smhMix; + float m_smhWeight; float3 m_channelMixingRed; float3 m_channelMixingGreen; @@ -69,9 +69,6 @@ ShaderResourceGroup PassSrg : SRG_PerPass_WithFallback float4 m_smhShadowsColor; float4 m_smhMidtonesColor; float4 m_smhHighlightsColor; - - // my color grading output - float4 m_color; } float SaturateWithEpsilon(float value) @@ -133,7 +130,7 @@ float3 NoNanPow(float3 base, float3 power) return pow(max(abs(base), float3(FloatEpsilon, FloatEpsilon, FloatEpsilon)), power); } -float3 ColorGradeSplitTone (float3 frameColor, float balance, float mix) +float3 ColorGradeSplitTone (float3 frameColor, float balance, float weight) { float3 frameSplitTone = NoNanPow(frameColor, 1.0 / 2.2); const float t = SaturateWithEpsilon(CalculateLuminance(SaturateWithEpsilon(frameSplitTone), ColorSpaceId::ACEScg) + balance); @@ -142,7 +139,7 @@ float3 ColorGradeSplitTone (float3 frameColor, float balance, float mix) frameSplitTone = BlendMode_SoftLight(frameSplitTone, shadows); frameSplitTone = BlendMode_SoftLight(frameSplitTone, highlights); frameSplitTone = NoNanPow(frameSplitTone, 2.2); - return lerp(frameColor.rgb, frameSplitTone.rgb, mix); + return lerp(frameColor.rgb, frameSplitTone.rgb, weight); } float3 ColorGradeChannelMixer (float3 frameColor) @@ -154,7 +151,7 @@ float3 ColorGradeChannelMixer (float3 frameColor) } float3 ColorGradeShadowsMidtonesHighlights (float3 frameColor, float shadowsStart, float shadowsEnd, - float highlightsStart, float highlightsEnd, float mix, + float highlightsStart, float highlightsEnd, float weight, float4 shadowsColor, float4 midtonesColor, float4 highlightsColor) { const float3 shadowsColorACEScg = TransformColor(shadowsColor.rgb, ColorSpaceId::LinearSRGB, ColorSpaceId::ACEScg); @@ -169,7 +166,7 @@ float3 ColorGradeShadowsMidtonesHighlights (float3 frameColor, float shadowsStar const float3 frameSmh = frameColor * shadowsColorACEScg * shadowsWeight + frameColor * midtonesColorACEScg * midtonesWeight + frameColor * highlightsColorACEScg * highlightsWeight; - return lerp(frameColor.rgb, frameSmh.rgb, mix); + return lerp(frameColor.rgb, frameSmh.rgb, weight); } float3 ColorGrade (float3 frameColor) @@ -181,11 +178,11 @@ float3 ColorGrade (float3 frameColor) PassSrg::m_colorFilterMultiply); frameColor = max(frameColor, 0.0); frameColor = ColorGradeSaturation(frameColor, PassSrg::m_colorGradingPreSaturation); - frameColor = ColorGradeSplitTone(frameColor, PassSrg::m_splitToneBalance, PassSrg::m_splitToneMix); + frameColor = ColorGradeSplitTone(frameColor, PassSrg::m_splitToneBalance, PassSrg::m_splitToneWeight); frameColor = ColorGradeChannelMixer(frameColor); frameColor = max(frameColor, 0.0); frameColor = ColorGradeShadowsMidtonesHighlights(frameColor, PassSrg::m_smhShadowsStart, PassSrg::m_smhShadowsEnd, - PassSrg::m_smhHighlightsStart, PassSrg::m_smhHighlightsEnd, PassSrg::m_smhMix, + PassSrg::m_smhHighlightsStart, PassSrg::m_smhHighlightsEnd, PassSrg::m_smhWeight, PassSrg::m_smhShadowsColor, PassSrg::m_smhMidtonesColor, PassSrg::m_smhHighlightsColor); frameColor = ColorGradeHueShift(frameColor, PassSrg::m_colorGradingHueShift); frameColor = ColorGradeSaturation(frameColor, PassSrg::m_colorGradingPostSaturation); diff --git a/Gems/Atom/Feature/Common/Code/CMakeLists.txt b/Gems/Atom/Feature/Common/Code/CMakeLists.txt index b8c414dcc6..9c4ffe5b5e 100644 --- a/Gems/Atom/Feature/Common/Code/CMakeLists.txt +++ b/Gems/Atom/Feature/Common/Code/CMakeLists.txt @@ -40,6 +40,8 @@ ly_add_target( Gem::Atom_Feature_Common.Public Gem::ImGui.imguilib #3rdParty::lux_core # AZ_TRAIT_LUXCORE_SUPPORTED is disabled in every platform, Issue #3915 will remove + RUNTIME_DEPENDENCIES + Gem::ImGui.imguilib ) ly_add_target( diff --git a/Gems/Atom/Feature/Common/Code/Include/Atom/Feature/PostProcess/ColorGrading/HDRColorGradingParams.inl b/Gems/Atom/Feature/Common/Code/Include/Atom/Feature/PostProcess/ColorGrading/HDRColorGradingParams.inl new file mode 100644 index 0000000000..241ba3b5de --- /dev/null +++ b/Gems/Atom/Feature/Common/Code/Include/Atom/Feature/PostProcess/ColorGrading/HDRColorGradingParams.inl @@ -0,0 +1,37 @@ +/* + * Copyright (c) Contributors to the Open 3D Engine Project. + * For complete copyright and license terms please see the LICENSE at the root of this distribution. + * + * SPDX-License-Identifier: Apache-2.0 OR MIT + * + */ + +// Macros below are of the form: +// PARAM(NAME, MEMBER_NAME, DEFAULT_VALUE, ...) + +AZ_GFX_BOOL_PARAM(Enabled, m_enabled, false) +AZ_GFX_FLOAT_PARAM(ColorGradingExposure, m_colorGradingExposure, 0.0) +AZ_GFX_FLOAT_PARAM(ColorGradingContrast, m_colorGradingContrast, 0.0) +AZ_GFX_FLOAT_PARAM(ColorGradingHueShift, m_colorGradingHueShift, 0.0) +AZ_GFX_FLOAT_PARAM(ColorGradingPreSaturation, m_colorGradingPreSaturation, 1.0) +AZ_GFX_FLOAT_PARAM(ColorGradingFilterIntensity, m_colorGradingFilterIntensity, 1.0) +AZ_GFX_FLOAT_PARAM(ColorGradingFilterMultiply, m_colorGradingFilterMultiply, 0.0) +AZ_GFX_FLOAT_PARAM(ColorGradingPostSaturation, m_colorGradingPostSaturation, 1.0) +AZ_GFX_FLOAT_PARAM(WhiteBalanceKelvin, m_whiteBalanceKelvin, 6600.0) +AZ_GFX_FLOAT_PARAM(WhiteBalanceTint, m_whiteBalanceTint, 0.0) +AZ_GFX_FLOAT_PARAM(SplitToneBalance, m_splitToneBalance, 0.0) +AZ_GFX_FLOAT_PARAM(SplitToneWeight, m_splitToneWeight, 0.0) +AZ_GFX_FLOAT_PARAM(SmhShadowsStart, m_smhShadowsStart, 0.0) +AZ_GFX_FLOAT_PARAM(SmhShadowsEnd, m_smhShadowsEnd, 0.3) +AZ_GFX_FLOAT_PARAM(SmhHighlightsStart, m_smhHighlightsStart, 0.55) +AZ_GFX_FLOAT_PARAM(SmhHighlightsEnd, m_smhHighlightsEnd, 1.0) +AZ_GFX_FLOAT_PARAM(SmhWeight, m_smhWeight, 0.0) +AZ_GFX_VEC3_PARAM(ChannelMixingRed, m_channelMixingRed, AZ::Vector3(1.0f, 0.0f, 0.0f)) +AZ_GFX_VEC3_PARAM(ChannelMixingGreen, m_channelMixingGreen, AZ::Vector3(0.0f, 1.0f, 0.0f)) +AZ_GFX_VEC3_PARAM(ChannelMixingBlue, m_channelMixingBlue, AZ::Vector3(0.0f, 0.f, 1.0f)) +AZ_GFX_VEC3_PARAM(ColorFilterSwatch, m_colorFilterSwatch, AZ::Vector3(1.0f, 0.5f, 0.5f)) +AZ_GFX_VEC3_PARAM(SplitToneShadowsColor, m_splitToneShadowsColor, AZ::Vector3(1.0f, 0.5f, 0.5f)) +AZ_GFX_VEC3_PARAM(SplitToneHighlightsColor, m_splitToneHighlightsColor, AZ::Vector3(0.1f, 1.0f, 0.1f)) +AZ_GFX_VEC3_PARAM(SmhShadowsColor, m_smhShadowsColor, AZ::Vector3(1.0f, 0.25f, 0.25f)) +AZ_GFX_VEC3_PARAM(SmhMidtonesColor, m_smhMidtonesColor, AZ::Vector3(0.1f, 0.1f, 1.0f)) +AZ_GFX_VEC3_PARAM(SmhHighlightsColor, m_smhHighlightsColor, AZ::Vector3(1.0f, 0.0f, 1.0f)) diff --git a/Gems/Atom/Feature/Common/Code/Include/Atom/Feature/PostProcess/ColorGrading/HDRColorGradingSettingsInterface.h b/Gems/Atom/Feature/Common/Code/Include/Atom/Feature/PostProcess/ColorGrading/HDRColorGradingSettingsInterface.h new file mode 100644 index 0000000000..019df206eb --- /dev/null +++ b/Gems/Atom/Feature/Common/Code/Include/Atom/Feature/PostProcess/ColorGrading/HDRColorGradingSettingsInterface.h @@ -0,0 +1,33 @@ +/* + * Copyright (c) Contributors to the Open 3D Engine Project. + * For complete copyright and license terms please see the LICENSE at the root of this distribution. + * + * SPDX-License-Identifier: Apache-2.0 OR MIT + * + */ + +#pragma once + +#include +#include +#include +#include + +namespace AZ +{ + namespace Render + { + class HDRColorGradingSettingsInterface + { + public: + AZ_RTTI(AZ::Render::HDRColorGradingSettingsInterface, "{CB5ADF78-27DE-438C-A991-1E5433046A42}"); + + // Auto-gen virtual getter and setter functions... +#include +#include +#include + + virtual void OnConfigChanged() = 0; + }; + } +} diff --git a/Gems/Atom/Feature/Common/Code/Include/Atom/Feature/PostProcess/PostProcessSettings.inl b/Gems/Atom/Feature/Common/Code/Include/Atom/Feature/PostProcess/PostProcessSettings.inl index 0259f07525..8409732f34 100644 --- a/Gems/Atom/Feature/Common/Code/Include/Atom/Feature/PostProcess/PostProcessSettings.inl +++ b/Gems/Atom/Feature/Common/Code/Include/Atom/Feature/PostProcess/PostProcessSettings.inl @@ -25,3 +25,4 @@ POST_PROCESS_MEMBER(ExposureControlSettings, m_exposureControlSettings) POST_PROCESS_MEMBER(SsaoSettings, m_ssaoSettings) POST_PROCESS_MEMBER(LookModificationSettings, m_lookModificationSettings) POST_PROCESS_MEMBER(DeferredFogSettings, m_deferredFogSettings) +POST_PROCESS_MEMBER(HDRColorGradingSettings, m_hdrColorGradingSettings) diff --git a/Gems/Atom/Feature/Common/Code/Include/Atom/Feature/PostProcess/PostProcessSettingsInterface.h b/Gems/Atom/Feature/Common/Code/Include/Atom/Feature/PostProcess/PostProcessSettingsInterface.h index 12c0017aad..905aa9f2ca 100644 --- a/Gems/Atom/Feature/Common/Code/Include/Atom/Feature/PostProcess/PostProcessSettingsInterface.h +++ b/Gems/Atom/Feature/Common/Code/Include/Atom/Feature/PostProcess/PostProcessSettingsInterface.h @@ -14,6 +14,7 @@ #include #include #include +#include #include #include diff --git a/Gems/Atom/Feature/Common/Code/Source/AuxGeom/AuxGeomDrawQueue.cpp b/Gems/Atom/Feature/Common/Code/Source/AuxGeom/AuxGeomDrawQueue.cpp index 214643505a..2057c596e5 100644 --- a/Gems/Atom/Feature/Common/Code/Source/AuxGeom/AuxGeomDrawQueue.cpp +++ b/Gems/Atom/Feature/Common/Code/Source/AuxGeom/AuxGeomDrawQueue.cpp @@ -565,7 +565,7 @@ namespace AZ AuxGeomBufferData* AuxGeomDrawQueue::Commit() { - AZ_ATOM_PROFILE_FUNCTION("AuxGeom", "AuxGeomDrawQueue: Commit"); + AZ_PROFILE_SCOPE(AzRender, "AuxGeomDrawQueue: Commit"); // get a mutually exclusive lock and then switch to the next buffer, returning a pointer to the current buffer (before the switch) // grab the lock @@ -585,7 +585,7 @@ namespace AZ void AuxGeomDrawQueue::ClearCurrentBufferData() { - AZ_ATOM_PROFILE_FUNCTION("AuxGeom", "AuxGeomDrawQueue: ClearCurrentBufferData"); + AZ_PROFILE_SCOPE(AzRender, "AuxGeomDrawQueue: ClearCurrentBufferData"); // no need for mutex here, this function is only called from a function holding a lock AuxGeomBufferData& data = m_buffers[m_currentBufferIndex]; @@ -649,7 +649,7 @@ namespace AZ AZ::u8 width, int32_t viewProjOverrideIndex) { - AZ_PROFILE_FUNCTION(AzRender); + AZ_PROFILE_SCOPE(AzRender, "AuxGeomDrawQueue: DrawPrimitiveWithSharedVerticesCommon"); // grab a mutex lock for the rest of this function so that a commit cannot happen during it and // other threads can't add geometry during it @@ -720,8 +720,7 @@ namespace AZ AZ::u8 width, int32_t viewProjOverrideIndex) { - AZ_PROFILE_FUNCTION(AzRender); - AZ_ATOM_PROFILE_FUNCTION("AuxGeom", "AuxGeomDrawQueue: DrawPrimitiveWithSharedVerticesCommon"); + AZ_PROFILE_SCOPE(AzRender, "AuxGeomDrawQueue: DrawPrimitiveWithSharedVerticesCommon"); AZ_Assert(indexCount >= verticesPerPrimitiveType && (indexCount % verticesPerPrimitiveType == 0), "Index count must be at least %d and must be a multiple of %d", diff --git a/Gems/Atom/Feature/Common/Code/Source/AuxGeom/AuxGeomFeatureProcessor.cpp b/Gems/Atom/Feature/Common/Code/Source/AuxGeom/AuxGeomFeatureProcessor.cpp index feeb1dedcc..ee6d3ba4a3 100644 --- a/Gems/Atom/Feature/Common/Code/Source/AuxGeom/AuxGeomFeatureProcessor.cpp +++ b/Gems/Atom/Feature/Common/Code/Source/AuxGeom/AuxGeomFeatureProcessor.cpp @@ -80,7 +80,7 @@ namespace AZ void AuxGeomFeatureProcessor::Render(const FeatureProcessor::RenderPacket& fpPacket) { - AZ_ATOM_PROFILE_FUNCTION("AuxGeom", "AuxGeomFeatureProcessor: Render"); + AZ_PROFILE_SCOPE(AzRender, "AuxGeomFeatureProcessor: Render"); // Get the scene data and switch buffers so that other threads can continue to queue requests AuxGeomBufferData* bufferData = static_cast(m_sceneDrawQueue.get())->Commit(); diff --git a/Gems/Atom/Feature/Common/Code/Source/AuxGeom/DynamicPrimitiveProcessor.cpp b/Gems/Atom/Feature/Common/Code/Source/AuxGeom/DynamicPrimitiveProcessor.cpp index f35809f148..9af6493413 100644 --- a/Gems/Atom/Feature/Common/Code/Source/AuxGeom/DynamicPrimitiveProcessor.cpp +++ b/Gems/Atom/Feature/Common/Code/Source/AuxGeom/DynamicPrimitiveProcessor.cpp @@ -70,7 +70,7 @@ namespace AZ void DynamicPrimitiveProcessor::PrepareFrame() { - AZ_ATOM_PROFILE_FUNCTION("AuxGeom", "DynamicPrimitiveProcessor: PrepareFrame"); + AZ_PROFILE_SCOPE(AzRender, "DynamicPrimitiveProcessor: PrepareFrame"); m_drawPackets.clear(); m_processSrgs.clear(); @@ -88,7 +88,7 @@ namespace AZ void DynamicPrimitiveProcessor::ProcessDynamicPrimitives(const AuxGeomBufferData* bufferData, const RPI::FeatureProcessor::RenderPacket& fpPacket) { - AZ_ATOM_PROFILE_FUNCTION("AuxGeom", "DynamicPrimitiveProcessor: ProcessDynamicPrimitives"); + AZ_PROFILE_SCOPE(AzRender, "DynamicPrimitiveProcessor: ProcessDynamicPrimitives"); RHI::DrawPacketBuilder drawPacketBuilder; const DynamicPrimitiveData& srcPrimitives = bufferData->m_primitiveData; diff --git a/Gems/Atom/Feature/Common/Code/Source/AuxGeom/FixedShapeProcessor.cpp b/Gems/Atom/Feature/Common/Code/Source/AuxGeom/FixedShapeProcessor.cpp index 0045311bef..8b5e439ca0 100644 --- a/Gems/Atom/Feature/Common/Code/Source/AuxGeom/FixedShapeProcessor.cpp +++ b/Gems/Atom/Feature/Common/Code/Source/AuxGeom/FixedShapeProcessor.cpp @@ -108,8 +108,8 @@ namespace AZ } void FixedShapeProcessor::PrepareFrame() - { - AZ_ATOM_PROFILE_FUNCTION("AuxGeom", "FixedShapeProcessor: PrepareFrame"); + { + AZ_PROFILE_SCOPE(AzRender, "FixedShapeProcessor: PrepareFrame"); m_processSrgs.clear(); m_drawPackets.clear(); @@ -127,8 +127,7 @@ namespace AZ void FixedShapeProcessor::ProcessObjects(const AuxGeomBufferData* bufferData, const RPI::FeatureProcessor::RenderPacket& fpPacket) { - AZ_PROFILE_FUNCTION(AzRender); - AZ_ATOM_PROFILE_FUNCTION("AuxGeom", "FixedShapeProcessor: ProcessObjects"); + AZ_PROFILE_SCOPE(AzRender, "FixedShapeProcessor: ProcessObjects"); RHI::DrawPacketBuilder drawPacketBuilder; diff --git a/Gems/Atom/Feature/Common/Code/Source/CommonSystemComponent.cpp b/Gems/Atom/Feature/Common/Code/Source/CommonSystemComponent.cpp index de03c08c6f..db49fba96f 100644 --- a/Gems/Atom/Feature/Common/Code/Source/CommonSystemComponent.cpp +++ b/Gems/Atom/Feature/Common/Code/Source/CommonSystemComponent.cpp @@ -42,6 +42,7 @@ #include #include #include +#include #include #include #include @@ -222,6 +223,7 @@ namespace AZ passSystem->AddPassCreator(Name("LightCullingRemapPass"), &LightCullingRemap::Create); passSystem->AddPassCreator(Name("LightCullingTilePreparePass"), &LightCullingTilePreparePass::Create); passSystem->AddPassCreator(Name("BlendColorGradingLutsPass"), &BlendColorGradingLutsPass::Create); + passSystem->AddPassCreator(Name("HDRColorGradingPass"), &HDRColorGradingPass::Create); passSystem->AddPassCreator(Name("LookModificationCompositePass"), &LookModificationCompositePass::Create); passSystem->AddPassCreator(Name("LookModificationTransformPass"), &LookModificationPass::Create); passSystem->AddPassCreator(Name("SMAAEdgeDetectionPass"), &SMAAEdgeDetectionPass::Create); diff --git a/Gems/Atom/Feature/Common/Code/Source/CoreLights/CapsuleLightFeatureProcessor.cpp b/Gems/Atom/Feature/Common/Code/Source/CoreLights/CapsuleLightFeatureProcessor.cpp index 683295cf5b..849c930afd 100644 --- a/Gems/Atom/Feature/Common/Code/Source/CoreLights/CapsuleLightFeatureProcessor.cpp +++ b/Gems/Atom/Feature/Common/Code/Source/CoreLights/CapsuleLightFeatureProcessor.cpp @@ -102,7 +102,7 @@ namespace AZ void CapsuleLightFeatureProcessor::Simulate(const FeatureProcessor::SimulatePacket& packet) { - AZ_ATOM_PROFILE_FUNCTION("RPI", "CapsuleLightFeatureProcessor: Simulate"); + AZ_PROFILE_SCOPE(RPI, "CapsuleLightFeatureProcessor: Simulate"); AZ_UNUSED(packet); if (m_deviceBufferNeedsUpdate) @@ -114,7 +114,7 @@ namespace AZ void CapsuleLightFeatureProcessor::Render(const CapsuleLightFeatureProcessor::RenderPacket& packet) { - AZ_ATOM_PROFILE_FUNCTION("RPI", "CapsuleLightFeatureProcessor: Render"); + AZ_PROFILE_SCOPE(RPI, "CapsuleLightFeatureProcessor: Render"); for (const RPI::ViewPtr& view : packet.m_views) { diff --git a/Gems/Atom/Feature/Common/Code/Source/CoreLights/DirectionalLightFeatureProcessor.cpp b/Gems/Atom/Feature/Common/Code/Source/CoreLights/DirectionalLightFeatureProcessor.cpp index c235f78595..702818dcd9 100644 --- a/Gems/Atom/Feature/Common/Code/Source/CoreLights/DirectionalLightFeatureProcessor.cpp +++ b/Gems/Atom/Feature/Common/Code/Source/CoreLights/DirectionalLightFeatureProcessor.cpp @@ -196,7 +196,7 @@ namespace AZ void DirectionalLightFeatureProcessor::Simulate(const FeatureProcessor::SimulatePacket&) { - AZ_ATOM_PROFILE_FUNCTION("RPI", "DirectionalLightFeatureProcessor: Simulate"); + AZ_PROFILE_SCOPE(RPI, "DirectionalLightFeatureProcessor: Simulate"); if (m_shadowingLightHandle.IsValid()) { @@ -293,7 +293,7 @@ namespace AZ void DirectionalLightFeatureProcessor::Render(const FeatureProcessor::RenderPacket& packet) { - AZ_ATOM_PROFILE_FUNCTION("RPI", "DirectionalLightFeatureProcessor: Render"); + AZ_PROFILE_SCOPE(RPI, "DirectionalLightFeatureProcessor: Render"); if (m_shadowingLightHandle.IsValid()) { @@ -1232,7 +1232,7 @@ namespace AZ void DirectionalLightFeatureProcessor::SetFilterParameterToPass(LightHandle handle, const RPI::View* cameraView) { - AZ_ATOM_PROFILE_FUNCTION("DirectionalLightFeatureProcessor", "DirectionalLightFeatureProcessor::SetFilterParameterToPass"); + AZ_PROFILE_SCOPE(RPI, "DirectionalLightFeatureProcessor::SetFilterParameterToPass"); if (handle != m_shadowingLightHandle) { diff --git a/Gems/Atom/Feature/Common/Code/Source/CoreLights/DiskLightFeatureProcessor.cpp b/Gems/Atom/Feature/Common/Code/Source/CoreLights/DiskLightFeatureProcessor.cpp index dfbeea0ffe..ca2c038e46 100644 --- a/Gems/Atom/Feature/Common/Code/Source/CoreLights/DiskLightFeatureProcessor.cpp +++ b/Gems/Atom/Feature/Common/Code/Source/CoreLights/DiskLightFeatureProcessor.cpp @@ -123,7 +123,7 @@ namespace AZ void DiskLightFeatureProcessor::Simulate(const FeatureProcessor::SimulatePacket& packet) { - AZ_ATOM_PROFILE_FUNCTION("RPI", "DiskLightFeatureProcessor: Simulate"); + AZ_PROFILE_SCOPE(RPI, "DiskLightFeatureProcessor: Simulate"); AZ_UNUSED(packet); if (m_deviceBufferNeedsUpdate) @@ -135,7 +135,7 @@ namespace AZ void DiskLightFeatureProcessor::Render(const DiskLightFeatureProcessor::RenderPacket& packet) { - AZ_ATOM_PROFILE_FUNCTION("RPI", "DiskLightFeatureProcessor: Simulate"); + AZ_PROFILE_SCOPE(RPI, "DiskLightFeatureProcessor: Simulate"); for (const RPI::ViewPtr& view : packet.m_views) { diff --git a/Gems/Atom/Feature/Common/Code/Source/CoreLights/PointLightFeatureProcessor.cpp b/Gems/Atom/Feature/Common/Code/Source/CoreLights/PointLightFeatureProcessor.cpp index af440e5040..bfb0b1252b 100644 --- a/Gems/Atom/Feature/Common/Code/Source/CoreLights/PointLightFeatureProcessor.cpp +++ b/Gems/Atom/Feature/Common/Code/Source/CoreLights/PointLightFeatureProcessor.cpp @@ -119,7 +119,7 @@ namespace AZ void PointLightFeatureProcessor::Simulate(const FeatureProcessor::SimulatePacket& packet) { - AZ_ATOM_PROFILE_FUNCTION("RPI", "PointLightFeatureProcessor: Simulate"); + AZ_PROFILE_SCOPE(RPI, "PointLightFeatureProcessor: Simulate"); AZ_UNUSED(packet); if (m_deviceBufferNeedsUpdate) @@ -131,7 +131,7 @@ namespace AZ void PointLightFeatureProcessor::Render(const PointLightFeatureProcessor::RenderPacket& packet) { - AZ_ATOM_PROFILE_FUNCTION("RPI", "PointLightFeatureProcessor: Render"); + AZ_PROFILE_SCOPE(RPI, "PointLightFeatureProcessor: Render"); for (const RPI::ViewPtr& view : packet.m_views) { diff --git a/Gems/Atom/Feature/Common/Code/Source/CoreLights/PolygonLightFeatureProcessor.cpp b/Gems/Atom/Feature/Common/Code/Source/CoreLights/PolygonLightFeatureProcessor.cpp index 089adf4621..9dbf01ae26 100644 --- a/Gems/Atom/Feature/Common/Code/Source/CoreLights/PolygonLightFeatureProcessor.cpp +++ b/Gems/Atom/Feature/Common/Code/Source/CoreLights/PolygonLightFeatureProcessor.cpp @@ -132,7 +132,7 @@ namespace AZ::Render void PolygonLightFeatureProcessor::Simulate(const FeatureProcessor::SimulatePacket& packet) { - AZ_ATOM_PROFILE_FUNCTION("RPI", "PolygonLightFeatureProcessor: Simulate"); + AZ_PROFILE_SCOPE(RPI, "PolygonLightFeatureProcessor: Simulate"); AZ_UNUSED(packet); if (m_deviceBufferNeedsUpdate) @@ -153,7 +153,7 @@ namespace AZ::Render void PolygonLightFeatureProcessor::Render(const PolygonLightFeatureProcessor::RenderPacket& packet) { - AZ_ATOM_PROFILE_FUNCTION("RPI", "PolygonLightFeatureProcessor: Render"); + AZ_PROFILE_SCOPE(RPI, "PolygonLightFeatureProcessor: Render"); for (const RPI::ViewPtr& view : packet.m_views) { diff --git a/Gems/Atom/Feature/Common/Code/Source/CoreLights/QuadLightFeatureProcessor.cpp b/Gems/Atom/Feature/Common/Code/Source/CoreLights/QuadLightFeatureProcessor.cpp index e22174225d..aadc8c2020 100644 --- a/Gems/Atom/Feature/Common/Code/Source/CoreLights/QuadLightFeatureProcessor.cpp +++ b/Gems/Atom/Feature/Common/Code/Source/CoreLights/QuadLightFeatureProcessor.cpp @@ -107,7 +107,7 @@ namespace AZ void QuadLightFeatureProcessor::Simulate(const FeatureProcessor::SimulatePacket& packet) { - AZ_ATOM_PROFILE_FUNCTION("RPI", "QuadLightFeatureProcessor: Simulate"); + AZ_PROFILE_SCOPE(RPI, "QuadLightFeatureProcessor: Simulate"); AZ_UNUSED(packet); if (m_deviceBufferNeedsUpdate) @@ -119,7 +119,7 @@ namespace AZ void QuadLightFeatureProcessor::Render(const QuadLightFeatureProcessor::RenderPacket& packet) { - AZ_ATOM_PROFILE_FUNCTION("RPI", "QuadLightFeatureProcessor: Render"); + AZ_PROFILE_SCOPE(RPI, "QuadLightFeatureProcessor: Render"); for (const RPI::ViewPtr& view : packet.m_views) { diff --git a/Gems/Atom/Feature/Common/Code/Source/CoreLights/SimplePointLightFeatureProcessor.cpp b/Gems/Atom/Feature/Common/Code/Source/CoreLights/SimplePointLightFeatureProcessor.cpp index b8bbb03335..f49a5e94fc 100644 --- a/Gems/Atom/Feature/Common/Code/Source/CoreLights/SimplePointLightFeatureProcessor.cpp +++ b/Gems/Atom/Feature/Common/Code/Source/CoreLights/SimplePointLightFeatureProcessor.cpp @@ -102,7 +102,7 @@ namespace AZ void SimplePointLightFeatureProcessor::Simulate(const FeatureProcessor::SimulatePacket& packet) { - AZ_ATOM_PROFILE_FUNCTION("RPI", "SimplePointLightFeatureProcessor: Simulate"); + AZ_PROFILE_SCOPE(RPI, "SimplePointLightFeatureProcessor: Simulate"); AZ_UNUSED(packet); if (m_deviceBufferNeedsUpdate) @@ -114,7 +114,7 @@ namespace AZ void SimplePointLightFeatureProcessor::Render(const SimplePointLightFeatureProcessor::RenderPacket& packet) { - AZ_ATOM_PROFILE_FUNCTION("RPI", "SimplePointLightFeatureProcessor: Render"); + AZ_PROFILE_SCOPE(RPI, "SimplePointLightFeatureProcessor: Render"); for (const RPI::ViewPtr& view : packet.m_views) { diff --git a/Gems/Atom/Feature/Common/Code/Source/CoreLights/SimpleSpotLightFeatureProcessor.cpp b/Gems/Atom/Feature/Common/Code/Source/CoreLights/SimpleSpotLightFeatureProcessor.cpp index d4776faec6..277b5026d7 100644 --- a/Gems/Atom/Feature/Common/Code/Source/CoreLights/SimpleSpotLightFeatureProcessor.cpp +++ b/Gems/Atom/Feature/Common/Code/Source/CoreLights/SimpleSpotLightFeatureProcessor.cpp @@ -102,7 +102,7 @@ namespace AZ void SimpleSpotLightFeatureProcessor::Simulate(const FeatureProcessor::SimulatePacket& packet) { - AZ_ATOM_PROFILE_FUNCTION("RPI", "SimpleSpotLightFeatureProcessor: Simulate"); + AZ_PROFILE_SCOPE(RPI, "SimpleSpotLightFeatureProcessor: Simulate"); AZ_UNUSED(packet); if (m_deviceBufferNeedsUpdate) @@ -114,7 +114,7 @@ namespace AZ void SimpleSpotLightFeatureProcessor::Render(const SimpleSpotLightFeatureProcessor::RenderPacket& packet) { - AZ_ATOM_PROFILE_FUNCTION("RPI", "SimpleSpotLightFeatureProcessor: Render"); + AZ_PROFILE_SCOPE(RPI, "SimpleSpotLightFeatureProcessor: Render"); for (const RPI::ViewPtr& view : packet.m_views) { diff --git a/Gems/Atom/Feature/Common/Code/Source/Decals/DecalFeatureProcessor.cpp b/Gems/Atom/Feature/Common/Code/Source/Decals/DecalFeatureProcessor.cpp index 4954ffc01c..4ff718b5ad 100644 --- a/Gems/Atom/Feature/Common/Code/Source/Decals/DecalFeatureProcessor.cpp +++ b/Gems/Atom/Feature/Common/Code/Source/Decals/DecalFeatureProcessor.cpp @@ -107,7 +107,7 @@ namespace AZ void DecalFeatureProcessor::Simulate(const RPI::FeatureProcessor::SimulatePacket& packet) { - AZ_ATOM_PROFILE_FUNCTION("RPI", "DecalFeatureProcessor: Simulate"); + AZ_PROFILE_SCOPE(RPI, "DecalFeatureProcessor: Simulate"); AZ_UNUSED(packet); if (m_deviceBufferNeedsUpdate) @@ -131,7 +131,7 @@ namespace AZ void DecalFeatureProcessor::Render(const RPI::FeatureProcessor::RenderPacket& packet) { - AZ_ATOM_PROFILE_FUNCTION("RPI", "DecalFeatureProcessor: Render"); + AZ_PROFILE_SCOPE(RPI, "DecalFeatureProcessor: Render"); AZStd::array_view> baseMaps = GetImagesFromDecalData<1>(); AZStd::array_view> opacityMaps = GetImagesFromDecalData<2>(); diff --git a/Gems/Atom/Feature/Common/Code/Source/Decals/DecalTextureArrayFeatureProcessor.cpp b/Gems/Atom/Feature/Common/Code/Source/Decals/DecalTextureArrayFeatureProcessor.cpp index 4ecfd7fc09..c0b8f3315a 100644 --- a/Gems/Atom/Feature/Common/Code/Source/Decals/DecalTextureArrayFeatureProcessor.cpp +++ b/Gems/Atom/Feature/Common/Code/Source/Decals/DecalTextureArrayFeatureProcessor.cpp @@ -145,7 +145,7 @@ namespace AZ void DecalTextureArrayFeatureProcessor::Simulate(const RPI::FeatureProcessor::SimulatePacket& packet) { - AZ_PROFILE_FUNCTION(AzRender); + AZ_PROFILE_SCOPE(AzRender, "DecalTextureArrayFeatureProcessor: Simulate"); AZ_UNUSED(packet); if (m_deviceBufferNeedsUpdate) @@ -158,7 +158,7 @@ namespace AZ void DecalTextureArrayFeatureProcessor::Render(const RPI::FeatureProcessor::RenderPacket& packet) { // Note that decals are rendered as part of the forward shading pipeline. We only need to bind the decal buffers/textures in here. - AZ_PROFILE_FUNCTION(AzRender); + AZ_PROFILE_SCOPE(AzRender, "DecalTextureArrayFeatureProcessor: Render"); for (const RPI::ViewPtr& view : packet.m_views) { @@ -294,7 +294,7 @@ namespace AZ void DecalTextureArrayFeatureProcessor::SetDecalMaterial(const DecalHandle handle, const AZ::Data::AssetId material) { - AZ_PROFILE_FUNCTION(AzRender); + AZ_PROFILE_SCOPE(AzRender, "DecalTextureArrayFeatureProcessor: SetDecalMaterial"); if (handle.IsNull()) { AZ_Warning("DecalTextureArrayFeatureProcessor", false, "Invalid handle passed to DecalTextureArrayFeatureProcessor::SetDecalMaterial()."); @@ -364,7 +364,7 @@ namespace AZ void DecalTextureArrayFeatureProcessor::OnAssetReady(const Data::Asset asset) { - AZ_PROFILE_FUNCTION(AzRender); + AZ_PROFILE_SCOPE(AzRender, "DecalTextureArrayFeatureProcessor: OnAssetReady"); const Data::AssetId& assetId = asset->GetId(); const RPI::MaterialAsset* materialAsset = asset.GetAs(); diff --git a/Gems/Atom/Feature/Common/Code/Source/DiffuseGlobalIllumination/DiffuseProbeGridFeatureProcessor.cpp b/Gems/Atom/Feature/Common/Code/Source/DiffuseGlobalIllumination/DiffuseProbeGridFeatureProcessor.cpp index 543851da0f..d79240d4f1 100644 --- a/Gems/Atom/Feature/Common/Code/Source/DiffuseGlobalIllumination/DiffuseProbeGridFeatureProcessor.cpp +++ b/Gems/Atom/Feature/Common/Code/Source/DiffuseGlobalIllumination/DiffuseProbeGridFeatureProcessor.cpp @@ -111,7 +111,7 @@ namespace AZ void DiffuseProbeGridFeatureProcessor::Simulate([[maybe_unused]] const FeatureProcessor::SimulatePacket& packet) { - AZ_PROFILE_FUNCTION(AzRender); + AZ_PROFILE_SCOPE(AzRender, "DiffuseProbeGridFeatureProcessor: Simulate"); // update pipeline states if (m_needUpdatePipelineStates) diff --git a/Gems/Atom/Feature/Common/Code/Source/ImGui/ImGuiPass.cpp b/Gems/Atom/Feature/Common/Code/Source/ImGui/ImGuiPass.cpp index b6ca1191dd..1a68317532 100644 --- a/Gems/Atom/Feature/Common/Code/Source/ImGui/ImGuiPass.cpp +++ b/Gems/Atom/Feature/Common/Code/Source/ImGui/ImGuiPass.cpp @@ -577,8 +577,7 @@ namespace AZ void ImGuiPass::BuildCommandListInternal(const RHI::FrameGraphExecuteContext& context) { - AZ_PROFILE_FUNCTION(AzRender); - AZ_ATOM_PROFILE_FUNCTION("Pass", "ImGuiPass: Execute"); + AZ_PROFILE_SCOPE(AzRender, "ImGuiPass: BuildCommandListInternal"); context.GetCommandList()->SetViewport(m_viewportState); @@ -607,8 +606,7 @@ namespace AZ uint32_t ImGuiPass::UpdateImGuiResources() { - AZ_PROFILE_FUNCTION(AzRender); - AZ_ATOM_PROFILE_FUNCTION("Pass", "ImGuiPass: UpdateImGuiResources"); + AZ_PROFILE_SCOPE(AzRender, "ImGuiPass: UpdateImGuiResources"); auto imguiContextScope = ImguiContextScope(m_imguiContext); diff --git a/Gems/Atom/Feature/Common/Code/Source/ImageBasedLights/ImageBasedLightFeatureProcessor.cpp b/Gems/Atom/Feature/Common/Code/Source/ImageBasedLights/ImageBasedLightFeatureProcessor.cpp index 7c41379a14..9cdad34f17 100644 --- a/Gems/Atom/Feature/Common/Code/Source/ImageBasedLights/ImageBasedLightFeatureProcessor.cpp +++ b/Gems/Atom/Feature/Common/Code/Source/ImageBasedLights/ImageBasedLightFeatureProcessor.cpp @@ -50,7 +50,7 @@ namespace AZ void ImageBasedLightFeatureProcessor::Simulate(const FeatureProcessor::SimulatePacket& packet) { - AZ_ATOM_PROFILE_FUNCTION("RPI", "ImageBasedLightFeatureProcessor: Simulate"); + AZ_PROFILE_SCOPE(RPI, "ImageBasedLightFeatureProcessor: Simulate"); AZ_UNUSED(packet); m_sceneSrg->SetImage(m_specularEnvMapIndex, m_specular); diff --git a/Gems/Atom/Feature/Common/Code/Source/Mesh/MeshFeatureProcessor.cpp b/Gems/Atom/Feature/Common/Code/Source/Mesh/MeshFeatureProcessor.cpp index 8ab324cdf7..fe201f9ca8 100644 --- a/Gems/Atom/Feature/Common/Code/Source/Mesh/MeshFeatureProcessor.cpp +++ b/Gems/Atom/Feature/Common/Code/Source/Mesh/MeshFeatureProcessor.cpp @@ -75,8 +75,7 @@ namespace AZ void MeshFeatureProcessor::Simulate(const FeatureProcessor::SimulatePacket& packet) { - AZ_PROFILE_FUNCTION(AzRender); - AZ_ATOM_PROFILE_FUNCTION("RPI", "MeshFeatureProcessor: Simulate"); + AZ_PROFILE_SCOPE(RPI, "MeshFeatureProcessor: Simulate"); AZ_UNUSED(packet); AZStd::concurrency_check_scope scopeCheck(m_meshDataChecker); @@ -149,7 +148,7 @@ namespace AZ const MeshHandleDescriptor& descriptor, const MaterialAssignmentMap& materials) { - AZ_PROFILE_FUNCTION(AzRender); + AZ_PROFILE_SCOPE(AzRender, "MeshFeatureProcessor: AcquireMesh"); // don't need to check the concurrency during emplace() because the StableDynamicArray won't move the other elements during insertion MeshHandle meshDataHandle = m_meshData.emplace(); @@ -952,7 +951,7 @@ namespace AZ subMeshes.push_back(subMesh); } - rayTracingFeatureProcessor->SetMesh(m_objectId, subMeshes); + rayTracingFeatureProcessor->SetMesh(m_objectId, m_model->GetModelAsset()->GetId(), subMeshes); } void MeshDataInstance::SetSortKey(RHI::DrawItemSortKey sortKey) @@ -984,7 +983,7 @@ namespace AZ void MeshDataInstance::UpdateDrawPackets(bool forceUpdate /*= false*/) { - AZ_PROFILE_FUNCTION(AzRender); + AZ_PROFILE_SCOPE(AzRender, "MeshDataInstance:: UpdateDrawPackets"); for (auto& drawPacketList : m_drawPacketListsByLod) { for (auto& drawPacket : drawPacketList) @@ -999,7 +998,7 @@ namespace AZ void MeshDataInstance::BuildCullable() { - AZ_PROFILE_FUNCTION(AzRender); + AZ_PROFILE_SCOPE(AzRender, "MeshDataInstance: BuildCullable"); AZ_Assert(m_cullableNeedsRebuild, "This function only needs to be called if the cullable to be rebuilt"); AZ_Assert(m_model, "The model has not finished loading yet"); @@ -1076,7 +1075,7 @@ namespace AZ void MeshDataInstance::UpdateCullBounds(const TransformServiceFeatureProcessor* transformService) { - AZ_PROFILE_FUNCTION(AzRender); + AZ_PROFILE_SCOPE(AzRender, "MeshDataInstance: UpdateCullBounds"); AZ_Assert(m_cullBoundsNeedsUpdate, "This function only needs to be called if the culling bounds need to be rebuilt"); AZ_Assert(m_model, "The model has not finished loading yet"); diff --git a/Gems/Atom/Feature/Common/Code/Source/PostProcess/ColorGrading/HDRColorGradingSettings.cpp b/Gems/Atom/Feature/Common/Code/Source/PostProcess/ColorGrading/HDRColorGradingSettings.cpp new file mode 100644 index 0000000000..4542b53a15 --- /dev/null +++ b/Gems/Atom/Feature/Common/Code/Source/PostProcess/ColorGrading/HDRColorGradingSettings.cpp @@ -0,0 +1,59 @@ +/* + * Copyright (c) Contributors to the Open 3D Engine Project. + * For complete copyright and license terms please see the LICENSE at the root of this distribution. + * + * SPDX-License-Identifier: Apache-2.0 OR MIT + * + */ +#include + +#include +#include + +namespace AZ +{ + namespace Render + { + HDRColorGradingSettings::HDRColorGradingSettings(PostProcessFeatureProcessor* featureProcessor) + : PostProcessBase(featureProcessor) + { + } + + void HDRColorGradingSettings::OnConfigChanged() + { + m_parentSettings->OnConfigChanged(); + } + + void HDRColorGradingSettings::ApplySettingsTo(HDRColorGradingSettings* target, [[maybe_unused]] float alpha) const + { + AZ_Assert(target != nullptr, "HDRColorGradingSettings::ApplySettingsTo called with nullptr as argument."); + + if (GetEnabled()) + { + target->m_enabled = m_enabled; + +#define AZ_GFX_BOOL_PARAM(NAME, MEMBER_NAME, DefaultValue) ; +#define AZ_GFX_FLOAT_PARAM(NAME, MEMBER_NAME, DefaultValue) \ + { \ + target->Set##NAME(AZ::Lerp(target->MEMBER_NAME, MEMBER_NAME, alpha)); \ + } + +#define AZ_GFX_VEC3_PARAM(NAME, MEMBER_NAME, DefaultValue) \ + { \ + target->MEMBER_NAME.Set(AZ::Lerp(target->MEMBER_NAME.GetX(), MEMBER_NAME.GetX(), alpha), \ + AZ::Lerp(target->MEMBER_NAME.GetY(), MEMBER_NAME.GetY(), alpha), \ + AZ::Lerp(target->MEMBER_NAME.GetZ(), MEMBER_NAME.GetZ(), alpha)); \ + } + +#include +#include + } + } + + void HDRColorGradingSettings::Simulate([[maybe_unused]] float deltaTime) + { + } + } // namespace Render +} // namespace AZ + + diff --git a/Gems/Atom/Feature/Common/Code/Source/PostProcess/ColorGrading/HDRColorGradingSettings.h b/Gems/Atom/Feature/Common/Code/Source/PostProcess/ColorGrading/HDRColorGradingSettings.h new file mode 100644 index 0000000000..2358919c28 --- /dev/null +++ b/Gems/Atom/Feature/Common/Code/Source/PostProcess/ColorGrading/HDRColorGradingSettings.h @@ -0,0 +1,69 @@ +/* + * Copyright (c) Contributors to the Open 3D Engine Project. + * For complete copyright and license terms please see the LICENSE at the root of this distribution. + * + * SPDX-License-Identifier: Apache-2.0 OR MIT + * + */ + +#pragma once + +#include + +#include + +#include + +namespace AZ +{ + namespace Render + { + class PostProcessSettings; + + class HDRColorGradingSettings final + : public HDRColorGradingSettingsInterface + , public PostProcessBase + { + friend class PostProcessSettings; + friend class PostProcessFeatureProcessor; + + public: + AZ_RTTI(HDRColorGradingSettings, "{EA8C05D4-66D0-4141-8D4D-68E5D764C2ED}", HDRColorGradingSettingsInterface, PostProcessBase); + AZ_CLASS_ALLOCATOR(HDRColorGradingSettings, SystemAllocator, 0); + + HDRColorGradingSettings(PostProcessFeatureProcessor* featureProcessor); + ~HDRColorGradingSettings() = default; + + void OnConfigChanged() override; + + void ApplySettingsTo(HDRColorGradingSettings* target, float alpha) const; + + // Generate all getters and override setters. + // Declare non-override setters, which will be defined in the .cpp +#define AZ_GFX_COMMON_PARAM(ValueType, Name, MemberName, DefaultValue) \ + ValueType Get##Name() const override { return MemberName; } \ + void Set##Name(ValueType val) override \ + { \ + MemberName = val; \ + } \ + +#define AZ_GFX_COMMON_OVERRIDE(ValueType, Name, MemberName, OverrideValueType) \ + OverrideValueType Get##Name##Override() const override { return MemberName##Override; } \ + void Set##Name##Override(OverrideValueType val) override { MemberName##Override = val; } \ + +#include +#include +#include + + private: + // Generate members... +#include +#include +#include + + void Simulate(float deltaTime); + + PostProcessSettings* m_parentSettings = nullptr; + }; + } +} diff --git a/Gems/Atom/Feature/Common/Code/Source/PostProcess/PostProcessFeatureProcessor.cpp b/Gems/Atom/Feature/Common/Code/Source/PostProcess/PostProcessFeatureProcessor.cpp index 35294d7403..d5b3ebd63b 100644 --- a/Gems/Atom/Feature/Common/Code/Source/PostProcess/PostProcessFeatureProcessor.cpp +++ b/Gems/Atom/Feature/Common/Code/Source/PostProcess/PostProcessFeatureProcessor.cpp @@ -49,7 +49,7 @@ namespace AZ void PostProcessFeatureProcessor::Simulate(const FeatureProcessor::SimulatePacket& packet) { - AZ_ATOM_PROFILE_FUNCTION("RPI", "PostProcessFeatureProcessor: Simulate"); + AZ_PROFILE_SCOPE(RPI, "PostProcessFeatureProcessor: Simulate"); AZ_UNUSED(packet); UpdateTime(); diff --git a/Gems/Atom/Feature/Common/Code/Source/PostProcess/PostProcessSettings.h b/Gems/Atom/Feature/Common/Code/Source/PostProcess/PostProcessSettings.h index 515326e357..c2a32e6cee 100644 --- a/Gems/Atom/Feature/Common/Code/Source/PostProcess/PostProcessSettings.h +++ b/Gems/Atom/Feature/Common/Code/Source/PostProcess/PostProcessSettings.h @@ -17,6 +17,7 @@ #include #include #include +#include #include namespace AZ diff --git a/Gems/Atom/Feature/Common/Code/Source/PostProcessing/HDRColorGradingPass.cpp b/Gems/Atom/Feature/Common/Code/Source/PostProcessing/HDRColorGradingPass.cpp new file mode 100644 index 0000000000..62fff6b6fe --- /dev/null +++ b/Gems/Atom/Feature/Common/Code/Source/PostProcessing/HDRColorGradingPass.cpp @@ -0,0 +1,135 @@ +/* + * Copyright (c) Contributors to the Open 3D Engine Project. + * For complete copyright and license terms please see the LICENSE at the root of this distribution. + * + * SPDX-License-Identifier: Apache-2.0 OR MIT + * + */ + +#include +#include + +#include +#include +#include + + namespace AZ +{ + namespace Render + { + RPI::Ptr HDRColorGradingPass::Create(const RPI::PassDescriptor& descriptor) + { + RPI::Ptr pass = aznew HDRColorGradingPass(descriptor); + return AZStd::move(pass); + } + + HDRColorGradingPass::HDRColorGradingPass(const RPI::PassDescriptor& descriptor) + : AZ::RPI::FullscreenTrianglePass(descriptor) + { + } + + void HDRColorGradingPass::InitializeInternal() + { + FullscreenTrianglePass::InitializeInternal(); + + m_colorGradingExposureIndex.Reset(); + m_colorGradingContrastIndex.Reset(); + m_colorGradingHueShiftIndex.Reset(); + m_colorGradingPreSaturationIndex.Reset(); + m_colorFilterIntensityIndex.Reset(); + m_colorFilterMultiplyIndex.Reset(); + m_whiteBalanceKelvinIndex.Reset(); + m_whiteBalanceTintIndex.Reset(); + m_splitToneBalanceIndex.Reset(); + m_splitToneWeightIndex.Reset(); + m_colorGradingPostSaturationIndex.Reset(); + m_smhShadowsStartIndex.Reset(); + m_smhShadowsEndIndex.Reset(); + m_smhHighlightsStartIndex.Reset(); + m_smhHighlightsEndIndex.Reset(); + m_smhWeightIndex.Reset(); + + m_channelMixingRedIndex.Reset(); + m_channelMixingGreenIndex.Reset(); + m_channelMixingBlueIndex.Reset(); + + m_colorFilterSwatchIndex.Reset(); + m_splitToneShadowsColorIndex.Reset(); + m_splitToneHighlightsColorIndex.Reset(); + m_smhShadowsColorIndex.Reset(); + m_smhMidtonesColorIndex.Reset(); + m_smhHighlightsColorIndex.Reset(); + } + + void HDRColorGradingPass::FrameBeginInternal(FramePrepareParams params) + { + SetSrgConstants(); + + FullscreenTrianglePass::FrameBeginInternal(params); + } + + bool HDRColorGradingPass::IsEnabled() const + { + const auto* colorGradingSettings = GetHDRColorGradingSettings(); + return colorGradingSettings ? colorGradingSettings->GetEnabled() : false; + } + + void HDRColorGradingPass::SetSrgConstants() + { + const HDRColorGradingSettings* settings = GetHDRColorGradingSettings(); + if (settings) + { + m_shaderResourceGroup->SetConstant(m_colorGradingExposureIndex, settings->GetColorGradingExposure()); + m_shaderResourceGroup->SetConstant(m_colorGradingContrastIndex, settings->GetColorGradingContrast()); + m_shaderResourceGroup->SetConstant(m_colorGradingHueShiftIndex, settings->GetColorGradingHueShift()); + m_shaderResourceGroup->SetConstant(m_colorGradingPreSaturationIndex, settings->GetColorGradingPreSaturation()); + m_shaderResourceGroup->SetConstant(m_colorFilterIntensityIndex, settings->GetColorGradingFilterIntensity()); + m_shaderResourceGroup->SetConstant(m_colorFilterMultiplyIndex, settings->GetColorGradingFilterMultiply()); + m_shaderResourceGroup->SetConstant(m_whiteBalanceKelvinIndex, settings->GetWhiteBalanceKelvin()); + m_shaderResourceGroup->SetConstant(m_whiteBalanceTintIndex, settings->GetWhiteBalanceTint()); + m_shaderResourceGroup->SetConstant(m_splitToneBalanceIndex, settings->GetSplitToneBalance()); + m_shaderResourceGroup->SetConstant(m_splitToneWeightIndex, settings->GetSplitToneWeight()); + m_shaderResourceGroup->SetConstant(m_colorGradingPostSaturationIndex, settings->GetColorGradingPostSaturation()); + m_shaderResourceGroup->SetConstant(m_smhShadowsStartIndex, settings->GetSmhShadowsStart()); + m_shaderResourceGroup->SetConstant(m_smhShadowsEndIndex, settings->GetSmhShadowsEnd()); + m_shaderResourceGroup->SetConstant(m_smhHighlightsStartIndex, settings->GetSmhHighlightsStart()); + m_shaderResourceGroup->SetConstant(m_smhHighlightsEndIndex, settings->GetSmhHighlightsEnd()); + m_shaderResourceGroup->SetConstant(m_smhWeightIndex, settings->GetSmhWeight()); + + m_shaderResourceGroup->SetConstant(m_channelMixingRedIndex, settings->GetChannelMixingRed()); + m_shaderResourceGroup->SetConstant(m_channelMixingGreenIndex, settings->GetChannelMixingGreen()); + m_shaderResourceGroup->SetConstant(m_channelMixingBlueIndex, settings->GetChannelMixingBlue()); + + m_shaderResourceGroup->SetConstant(m_colorFilterSwatchIndex, AZ::Vector4(settings->GetColorFilterSwatch())); + m_shaderResourceGroup->SetConstant(m_splitToneShadowsColorIndex, AZ::Vector4(settings->GetSplitToneShadowsColor())); + m_shaderResourceGroup->SetConstant(m_splitToneHighlightsColorIndex, AZ::Vector4(settings->GetSplitToneHighlightsColor())); + m_shaderResourceGroup->SetConstant(m_smhShadowsColorIndex, AZ::Vector4(settings->GetSmhShadowsColor())); + m_shaderResourceGroup->SetConstant(m_smhMidtonesColorIndex, AZ::Vector4(settings->GetSmhMidtonesColor())); + m_shaderResourceGroup->SetConstant(m_smhHighlightsColorIndex, AZ::Vector4(settings->GetSmhHighlightsColor())); + } + } + + const AZ::Render::HDRColorGradingSettings* HDRColorGradingPass::GetHDRColorGradingSettings() const + { + RPI::Scene* scene = GetScene(); + if (scene) + { + PostProcessFeatureProcessor* fp = scene->GetFeatureProcessor(); + AZ::RPI::ViewPtr view = scene->GetDefaultRenderPipeline()->GetDefaultView(); + if (fp) + { + PostProcessSettings* postProcessSettings = fp->GetLevelSettingsFromView(view); + if (postProcessSettings) + { + const HDRColorGradingSettings* colorGradingSettings = postProcessSettings->GetHDRColorGradingSettings(); + if (colorGradingSettings != nullptr && colorGradingSettings->GetEnabled()) + { + return postProcessSettings->GetHDRColorGradingSettings(); + } + } + } + } + return nullptr; + } + } +} diff --git a/Gems/Atom/Feature/Common/Code/Source/PostProcessing/HDRColorGradingPass.h b/Gems/Atom/Feature/Common/Code/Source/PostProcessing/HDRColorGradingPass.h new file mode 100644 index 0000000000..e5eaf7db26 --- /dev/null +++ b/Gems/Atom/Feature/Common/Code/Source/PostProcessing/HDRColorGradingPass.h @@ -0,0 +1,77 @@ +/* + * Copyright (c) Contributors to the Open 3D Engine Project. + * For complete copyright and license terms please see the LICENSE at the root of this distribution. + * + * SPDX-License-Identifier: Apache-2.0 OR MIT + * + */ +#pragma once + +#include +#include +#include +#include +#include + +namespace AZ +{ + namespace Render + { + /** + * The color grading pass. + */ + class HDRColorGradingPass + : public AZ::RPI::FullscreenTrianglePass + //TODO: , public PostProcessingShaderOptionBase + { + public: + AZ_RTTI(HDRColorGradingPass, "{E68E31A1-DB24-4AFF-A029-456A8B74C03C}", AZ::RPI::FullscreenTrianglePass); + AZ_CLASS_ALLOCATOR(HDRColorGradingPass, SystemAllocator, 0); + + virtual ~HDRColorGradingPass() = default; + + //! Creates a ColorGradingPass + static RPI::Ptr Create(const RPI::PassDescriptor& descriptor); + + protected: + HDRColorGradingPass(const RPI::PassDescriptor& descriptor); + + //! Pass behavior overrides + void InitializeInternal() override; + void FrameBeginInternal(FramePrepareParams params) override; + bool IsEnabled() const override; + + private: + const HDRColorGradingSettings* GetHDRColorGradingSettings() const; + void SetSrgConstants(); + + RHI::ShaderInputNameIndex m_colorGradingExposureIndex = "m_colorGradingExposure"; + RHI::ShaderInputNameIndex m_colorGradingContrastIndex = "m_colorGradingContrast"; + RHI::ShaderInputNameIndex m_colorGradingHueShiftIndex = "m_colorGradingHueShift"; + RHI::ShaderInputNameIndex m_colorGradingPreSaturationIndex = "m_colorGradingPreSaturation"; + RHI::ShaderInputNameIndex m_colorFilterIntensityIndex = "m_colorFilterIntensity"; + RHI::ShaderInputNameIndex m_colorFilterMultiplyIndex = "m_colorFilterMultiply"; + RHI::ShaderInputNameIndex m_whiteBalanceKelvinIndex = "m_whiteBalanceKelvin"; + RHI::ShaderInputNameIndex m_whiteBalanceTintIndex = "m_whiteBalanceTint"; + RHI::ShaderInputNameIndex m_splitToneBalanceIndex = "m_splitToneBalance"; + RHI::ShaderInputNameIndex m_splitToneWeightIndex = "m_splitToneWeight"; + RHI::ShaderInputNameIndex m_colorGradingPostSaturationIndex = "m_colorGradingPostSaturation"; + RHI::ShaderInputNameIndex m_smhShadowsStartIndex = "m_smhShadowsStart"; + RHI::ShaderInputNameIndex m_smhShadowsEndIndex = "m_smhShadowsEnd"; + RHI::ShaderInputNameIndex m_smhHighlightsStartIndex = "m_smhHighlightsStart"; + RHI::ShaderInputNameIndex m_smhHighlightsEndIndex = "m_smhHighlightsEnd"; + RHI::ShaderInputNameIndex m_smhWeightIndex = "m_smhWeight"; + + RHI::ShaderInputNameIndex m_channelMixingRedIndex = "m_channelMixingRed"; + RHI::ShaderInputNameIndex m_channelMixingGreenIndex = "m_channelMixingGreen"; + RHI::ShaderInputNameIndex m_channelMixingBlueIndex = "m_channelMixingBlue"; + + RHI::ShaderInputNameIndex m_colorFilterSwatchIndex = "m_colorFilterSwatch"; + RHI::ShaderInputNameIndex m_splitToneShadowsColorIndex = "m_splitToneShadowsColor"; + RHI::ShaderInputNameIndex m_splitToneHighlightsColorIndex = "m_splitToneHighlightsColor"; + RHI::ShaderInputNameIndex m_smhShadowsColorIndex = "m_smhShadowsColor"; + RHI::ShaderInputNameIndex m_smhMidtonesColorIndex = "m_smhMidtonesColor"; + RHI::ShaderInputNameIndex m_smhHighlightsColorIndex = "m_smhHighlightsColor"; + }; + } // namespace Render +} // namespace AZ diff --git a/Gems/Atom/Feature/Common/Code/Source/PostProcessing/SMAAFeatureProcessor.cpp b/Gems/Atom/Feature/Common/Code/Source/PostProcessing/SMAAFeatureProcessor.cpp index 56d413e84f..a795d88212 100644 --- a/Gems/Atom/Feature/Common/Code/Source/PostProcessing/SMAAFeatureProcessor.cpp +++ b/Gems/Atom/Feature/Common/Code/Source/PostProcessing/SMAAFeatureProcessor.cpp @@ -161,7 +161,7 @@ namespace AZ void SMAAFeatureProcessor::Render([[maybe_unused]] const SMAAFeatureProcessor::RenderPacket& packet) { - AZ_ATOM_PROFILE_FUNCTION("RPI", "SMAAFeatureProcessor: Render"); + AZ_PROFILE_SCOPE(RPI, "SMAAFeatureProcessor: Render"); UpdateConvertToPerceptualPass(); UpdateEdgeDetectionPass(); diff --git a/Gems/Atom/Feature/Common/Code/Source/RayTracing/RayTracingFeatureProcessor.cpp b/Gems/Atom/Feature/Common/Code/Source/RayTracing/RayTracingFeatureProcessor.cpp index ea89f64b73..a17ecaf1aa 100644 --- a/Gems/Atom/Feature/Common/Code/Source/RayTracing/RayTracingFeatureProcessor.cpp +++ b/Gems/Atom/Feature/Common/Code/Source/RayTracing/RayTracingFeatureProcessor.cpp @@ -79,7 +79,7 @@ namespace AZ AZ_Assert(m_rayTracingMaterialSrg, "Failed to create RayTracingMaterialSrg"); } - void RayTracingFeatureProcessor::SetMesh(const ObjectId objectId, const SubMeshVector& subMeshes) + void RayTracingFeatureProcessor::SetMesh(const ObjectId objectId, const AZ::Data::AssetId& assetId, const SubMeshVector& subMeshes) { if (!m_rayTracingEnabled) { @@ -89,10 +89,13 @@ namespace AZ RHI::Ptr device = RHI::RHISystemInterface::Get()->GetDevice(); uint32_t objectIndex = objectId.GetIndex(); + // lock the mutex to protect the mesh and BLAS lists + AZStd::unique_lock lock(m_mutex); + MeshMap::iterator itMesh = m_meshes.find(objectIndex); if (itMesh == m_meshes.end()) { - m_meshes.insert(AZStd::make_pair(objectIndex, Mesh{ subMeshes })); + m_meshes.insert(AZStd::make_pair(objectIndex, Mesh{ assetId, subMeshes })); } else { @@ -102,9 +105,12 @@ namespace AZ m_meshes[objectIndex].m_subMeshes = subMeshes; } - // create the BLAS buffers for each sub-mesh + // create the BLAS buffers for each sub-mesh, or re-use existing BLAS objects if they were already created. + // Note: all sub-meshes must either create new BLAS objects or re-use existing ones, otherwise it's an error (it's the same model in both cases) // Note: the buffer is just reserved here, the BLAS is built in the RayTracingAccelerationStructurePass Mesh& mesh = m_meshes[objectIndex]; + bool blasInstanceFound = false; + for (auto& subMesh : mesh.m_subMeshes) { RHI::RayTracingBlasDescriptor blasDescriptor; @@ -115,11 +121,37 @@ namespace AZ ->IndexBuffer(subMesh.m_indexBufferView) ; - // create the BLAS object - subMesh.m_blas = AZ::RHI::RayTracingBlas::CreateRHIRayTracingBlas(); + // search for an existing BLAS object for this model + RayTracingBlasMap::iterator itBlas = m_blasMap.find(assetId); + if (itBlas != m_blasMap.end()) + { + // re-use existing BLAS + subMesh.m_blas = itBlas->second.m_blas; + itBlas->second.m_count++; - // create the buffers from the descriptor - subMesh.m_blas->CreateBuffers(*device, &blasDescriptor, *m_bufferPools); + // keep track of the fact that we re-used a BLAS + blasInstanceFound = true; + } + else + { + AZ_Assert(blasInstanceFound == false, "Partial set of RayTracingBlas objects found for mesh"); + + // create the BLAS object + subMesh.m_blas = AZ::RHI::RayTracingBlas::CreateRHIRayTracingBlas(); + + // create the buffers from the descriptor + subMesh.m_blas->CreateBuffers(*device, &blasDescriptor, *m_bufferPools); + + // store the BLAS in the side list + RayTracingBlasInstance blasInstance = { subMesh.m_blas, 1 }; + m_blasMap.insert({ assetId, blasInstance }); + } + } + + if (blasInstanceFound) + { + // set the mesh BLAS flag so we don't try to rebuild it in the RayTracingAccelerationStructurePass + mesh.m_blasBuilt = true; } // set initial transform @@ -140,12 +172,26 @@ namespace AZ return; } + // lock the mutex to protect the mesh and BLAS lists + AZStd::unique_lock lock(m_mutex); + MeshMap::iterator itMesh = m_meshes.find(objectId.GetIndex()); if (itMesh != m_meshes.end()) { m_subMeshCount -= aznumeric_cast(itMesh->second.m_subMeshes.size()); m_meshes.erase(itMesh); m_revision++; + + // decrement the count from the BLAS instance, and check to see if we can remove it + RayTracingBlasMap::iterator itBlas = m_blasMap.find(itMesh->second.m_assetId); + if (itBlas != m_blasMap.end()) + { + itBlas->second.m_count--; + if (itBlas->second.m_count == 0) + { + m_blasMap.erase(itBlas); + } + } } m_meshInfoBufferNeedsUpdate = true; diff --git a/Gems/Atom/Feature/Common/Code/Source/RayTracing/RayTracingFeatureProcessor.h b/Gems/Atom/Feature/Common/Code/Source/RayTracing/RayTracingFeatureProcessor.h index 6bd9829c7e..be75f0fac9 100644 --- a/Gems/Atom/Feature/Common/Code/Source/RayTracing/RayTracingFeatureProcessor.h +++ b/Gems/Atom/Feature/Common/Code/Source/RayTracing/RayTracingFeatureProcessor.h @@ -116,6 +116,9 @@ namespace AZ //! Contains data for the top level mesh, including the list of sub-meshes struct Mesh { + // assetId of the model + AZ::Data::AssetId m_assetId = AZ::Data::AssetId{}; + // sub-mesh list SubMeshVector m_subMeshes; @@ -134,7 +137,7 @@ namespace AZ //! Sets ray tracing data for a mesh. //! This will cause an update to the RayTracing acceleration structure on the next frame - void SetMesh(const ObjectId objectId, const SubMeshVector& subMeshes); + void SetMesh(const ObjectId objectId, const AZ::Data::AssetId& assetId, const SubMeshVector& subMeshes); //! Removes ray tracing data for a mesh. //! This will cause an update to the RayTracing acceleration structure on the next frame @@ -220,6 +223,9 @@ namespace AZ // cached TransformServiceFeatureProcessor TransformServiceFeatureProcessor* m_transformServiceFeatureProcessor = nullptr; + // mutex for the mesh and BLAS lists + AZStd::mutex m_mutex; + // structure for data in the m_meshInfoBuffer, shaders that use the buffer must match this type struct MeshInfo { @@ -260,6 +266,16 @@ namespace AZ // flag indicating we need to update the materialInfo buffer bool m_materialInfoBufferNeedsUpdate = false; + + // side list for looking up existing BLAS objects so they can be re-used when the same mesh is added multiple times + struct RayTracingBlasInstance + { + RHI::Ptr m_blas; + uint32_t m_count = 0; + }; + + using RayTracingBlasMap = AZStd::unordered_map; + RayTracingBlasMap m_blasMap; }; } } diff --git a/Gems/Atom/Feature/Common/Code/Source/ReflectionProbe/ReflectionProbeFeatureProcessor.cpp b/Gems/Atom/Feature/Common/Code/Source/ReflectionProbe/ReflectionProbeFeatureProcessor.cpp index 341d1a0274..91c72013dd 100644 --- a/Gems/Atom/Feature/Common/Code/Source/ReflectionProbe/ReflectionProbeFeatureProcessor.cpp +++ b/Gems/Atom/Feature/Common/Code/Source/ReflectionProbe/ReflectionProbeFeatureProcessor.cpp @@ -154,8 +154,7 @@ namespace AZ void ReflectionProbeFeatureProcessor::Simulate([[maybe_unused]] const FeatureProcessor::SimulatePacket& packet) { - AZ_PROFILE_FUNCTION(AzRender); - AZ_ATOM_PROFILE_FUNCTION("ReflectionProbe", "ReflectionProbeFeatureProcessor: Simulate"); + AZ_PROFILE_SCOPE(AzRender, "ReflectionProbeFeatureProcessor: Simulate"); // update pipeline states if (m_needUpdatePipelineStates) @@ -194,7 +193,6 @@ namespace AZ if (m_probeSortRequired) { AZ_PROFILE_SCOPE(AzRender, "Sort reflection probes"); - AZ_ATOM_PROFILE_FUNCTION("ReflectionProbe", "ReflectionProbeFeatureProcessor: Sort reflection probes"); // sort the probes by descending inner volume size, so the smallest volumes are rendered last auto sortFn = [](AZStd::shared_ptr const& probe1, AZStd::shared_ptr const& probe2) -> bool diff --git a/Gems/Atom/Feature/Common/Code/Source/Shadows/ProjectedShadowFeatureProcessor.cpp b/Gems/Atom/Feature/Common/Code/Source/Shadows/ProjectedShadowFeatureProcessor.cpp index 68c31bd859..8fb971f8f5 100644 --- a/Gems/Atom/Feature/Common/Code/Source/Shadows/ProjectedShadowFeatureProcessor.cpp +++ b/Gems/Atom/Feature/Common/Code/Source/Shadows/ProjectedShadowFeatureProcessor.cpp @@ -486,7 +486,7 @@ namespace AZ::Render void ProjectedShadowFeatureProcessor::Simulate(const FeatureProcessor::SimulatePacket& /*packet*/) { - AZ_ATOM_PROFILE_FUNCTION("RPI", "ProjectedShadowFeatureProcessor: Simulate"); + AZ_PROFILE_SCOPE(RPI, "ProjectedShadowFeatureProcessor: Simulate"); if (m_shadowmapPassNeedsUpdate) { @@ -581,7 +581,7 @@ namespace AZ::Render void ProjectedShadowFeatureProcessor::Render(const ProjectedShadowFeatureProcessor::RenderPacket& packet) { - AZ_ATOM_PROFILE_FUNCTION("RPI", "ProjectedShadowFeatureProcessor: Render"); + AZ_PROFILE_SCOPE(RPI, "ProjectedShadowFeatureProcessor: Render"); if (!m_projectedShadowmapsPasses.empty()) { diff --git a/Gems/Atom/Feature/Common/Code/Source/SkinnedMesh/SkinnedMeshFeatureProcessor.cpp b/Gems/Atom/Feature/Common/Code/Source/SkinnedMesh/SkinnedMeshFeatureProcessor.cpp index 0aa72bf2ca..500eadf110 100644 --- a/Gems/Atom/Feature/Common/Code/Source/SkinnedMesh/SkinnedMeshFeatureProcessor.cpp +++ b/Gems/Atom/Feature/Common/Code/Source/SkinnedMesh/SkinnedMeshFeatureProcessor.cpp @@ -69,8 +69,7 @@ namespace AZ void SkinnedMeshFeatureProcessor::Render(const FeatureProcessor::RenderPacket& packet) { - AZ_PROFILE_FUNCTION(AzRender); - AZ_ATOM_PROFILE_FUNCTION("SkinnedMesh", "SkinnedMeshFeatureProcessor: Render"); + AZ_PROFILE_SCOPE(AzRender, "SkinnedMeshFeatureProcessor: Render"); #if 0 //[GFX_TODO][ATOM-13564] Temporarily disable skinning culling until we figure out how to hook up visibility & lod selection with skinning: //Setup the culling workgroup (it will be re-used for each view) diff --git a/Gems/Atom/Feature/Common/Code/Source/SkinnedMesh/SkinnedMeshInputBuffers.cpp b/Gems/Atom/Feature/Common/Code/Source/SkinnedMesh/SkinnedMeshInputBuffers.cpp index b84d4347a7..4146a669fe 100644 --- a/Gems/Atom/Feature/Common/Code/Source/SkinnedMesh/SkinnedMeshInputBuffers.cpp +++ b/Gems/Atom/Feature/Common/Code/Source/SkinnedMesh/SkinnedMeshInputBuffers.cpp @@ -534,7 +534,7 @@ namespace AZ // lod0 Positions[^ ^] lod0Normals[^ ^] lod1Positions[^ ^] lod1Normals[^ ^] // lod0 subMesh0+1 Positions[^ ^^ ^] lod0 subMesh0+1 Normals[^ ^^ ^] lod1 sm0+1 pos[^ ^^ ^] lod1 sm0+1 norm[^ ^^ ^] - AZ_PROFILE_FUNCTION(AzRender); + AZ_PROFILE_SCOPE(AzRender, "SkinnedMeshInputBuffers: CreateSkinnedMeshInstance"); AZStd::intrusive_ptr instance = aznew SkinnedMeshInstance; // Each model gets a unique, random ID, so if the same source model is used for multiple instances, multiple target models will be created. diff --git a/Gems/Atom/Feature/Common/Code/Source/SkyBox/SkyBoxFeatureProcessor.cpp b/Gems/Atom/Feature/Common/Code/Source/SkyBox/SkyBoxFeatureProcessor.cpp index d0150fc0c2..d4fa3f52be 100644 --- a/Gems/Atom/Feature/Common/Code/Source/SkyBox/SkyBoxFeatureProcessor.cpp +++ b/Gems/Atom/Feature/Common/Code/Source/SkyBox/SkyBoxFeatureProcessor.cpp @@ -105,7 +105,7 @@ namespace AZ void SkyBoxFeatureProcessor::Simulate(const FeatureProcessor::SimulatePacket& packet) { - AZ_ATOM_PROFILE_FUNCTION("RPI", "SkyBoxFeatureProcessor: Simulate"); + AZ_PROFILE_SCOPE(RPI, "SkyBoxFeatureProcessor: Simulate"); AZ_UNUSED(packet); m_sceneSrg->SetConstant(m_skyboxEnableIndex, m_enable); diff --git a/Gems/Atom/Feature/Common/Code/atom_feature_common_files.cmake b/Gems/Atom/Feature/Common/Code/atom_feature_common_files.cmake index 40188109ca..92f96a591b 100644 --- a/Gems/Atom/Feature/Common/Code/atom_feature_common_files.cmake +++ b/Gems/Atom/Feature/Common/Code/atom_feature_common_files.cmake @@ -183,6 +183,8 @@ set(FILES Source/PostProcess/PostProcessFeatureProcessor.h Source/PostProcess/PostProcessSettings.cpp Source/PostProcess/PostProcessSettings.h + Source/PostProcess/ColorGrading/HDRColorGradingSettings.h + Source/PostProcess/ColorGrading/HDRColorGradingSettings.cpp Source/PostProcess/Bloom/BloomSettings.cpp Source/PostProcess/Bloom/BloomSettings.h Source/PostProcess/DepthOfField/DepthOfFieldSettings.cpp @@ -205,6 +207,8 @@ set(FILES Source/PostProcessing/BloomCompositePass.cpp Source/PostProcessing/BloomParentPass.h Source/PostProcessing/BloomParentPass.cpp + Source/PostProcessing/HDRColorGradingPass.cpp + Source/PostProcessing/HDRColorGradingPass.h Source/PostProcessing/DepthOfFieldCompositePass.h Source/PostProcessing/DepthOfFieldCompositePass.cpp Source/PostProcessing/DepthOfFieldBokehBlurPass.h diff --git a/Gems/Atom/Feature/Common/Code/atom_feature_common_public_files.cmake b/Gems/Atom/Feature/Common/Code/atom_feature_common_public_files.cmake index 89febbcf3d..d7af7b0108 100644 --- a/Gems/Atom/Feature/Common/Code/atom_feature_common_public_files.cmake +++ b/Gems/Atom/Feature/Common/Code/atom_feature_common_public_files.cmake @@ -51,6 +51,8 @@ set(FILES Include/Atom/Feature/PostProcess/Bloom/BloomConstants.h Include/Atom/Feature/PostProcess/Bloom/BloomParams.inl Include/Atom/Feature/PostProcess/Bloom/BloomSettingsInterface.h + Include/Atom/Feature/PostProcess/ColorGrading/HDRColorGradingParams.inl + Include/Atom/Feature/PostProcess/ColorGrading/HDRColorGradingSettingsInterface.h Include/Atom/Feature/PostProcess/DepthOfField/DepthOfFieldConstants.h Include/Atom/Feature/PostProcess/DepthOfField/DepthOfFieldParams.inl Include/Atom/Feature/PostProcess/DepthOfField/DepthOfFieldSettingsInterface.h diff --git a/Gems/Atom/RHI/Code/Include/Atom/RHI/CpuProfiler.h b/Gems/Atom/RHI/Code/Include/Atom/RHI/CpuProfiler.h index 3fedc99566..70c5771b57 100644 --- a/Gems/Atom/RHI/Code/Include/Atom/RHI/CpuProfiler.h +++ b/Gems/Atom/RHI/Code/Include/Atom/RHI/CpuProfiler.h @@ -9,6 +9,7 @@ #pragma once #include +#include #include #include #include @@ -21,15 +22,15 @@ namespace AZ //! Structure that is used to cache a timed region into the thread's local storage. struct CachedTimeRegion { - //! Structure that the profiling macro utilizes to create statically initialized instance to create string - //! literals in static memory + //! Structure used internally for caching assumed global string pointers (ideally literals) to the marker group/region + //! NOTE: When used in a separate shared library, the library mustn't be unloaded before the CpuProfiler is shutdown. struct GroupRegionName { GroupRegionName() = delete; GroupRegionName(const char* const group, const char* const region); - - const char* const m_groupName = nullptr; - const char* const m_regionName = nullptr; + + const char* m_groupName = nullptr; + const char* m_regionName = nullptr; struct Hash { @@ -39,31 +40,16 @@ namespace AZ }; CachedTimeRegion() = default; - CachedTimeRegion(const GroupRegionName* groupRegionName); - CachedTimeRegion(const GroupRegionName* groupRegionName, uint16_t stackDepth, uint64_t startTick, uint64_t endTick); + CachedTimeRegion(const GroupRegionName& groupRegionName); + CachedTimeRegion(const GroupRegionName& groupRegionName, uint16_t stackDepth, uint64_t startTick, uint64_t endTick); - //! Pointer to the GroupRegionName static instance. - //! NOTE: When used in a separate shared library, the library mustn't be unloaded before - //! the CpuProfiler is shutdown. - const GroupRegionName* m_groupRegionName = nullptr; + GroupRegionName m_groupRegionName{nullptr, nullptr}; uint16_t m_stackDepth = 0u; AZStd::sys_time_t m_startTick = 0; AZStd::sys_time_t m_endTick = 0; }; - //! Helper class used as a RAII-style mechanism for the macros to begin and end a region. - class TimeRegion : public CachedTimeRegion - { - public: - TimeRegion() = delete; - TimeRegion(const GroupRegionName* groupRegionName); - ~TimeRegion(); - - //! End region - void EndRegion(); - }; - //! Interface class of the CpuProfiler class CpuProfiler { @@ -80,12 +66,6 @@ namespace AZ static CpuProfiler* Get(); - //! Add a new time region - virtual void BeginTimeRegion(TimeRegion& timeRegion) = 0; - - //! Ends a time region - virtual void EndTimeRegion() = 0; - //! Get the last frame's TimeRegionMap virtual const TimeRegionMap& GetTimeRegionMap() const = 0; @@ -101,38 +81,7 @@ namespace AZ virtual void SetProfilerEnabled(bool enabled) = 0; virtual bool IsProfilerEnabled() const = 0 ; - - //! Used by AZ_ATOM_PROFILE_DYNAMIC to create GroupRegionNames with known lifetimes. - virtual const CachedTimeRegion::GroupRegionName& InsertDynamicName(const char* groupName, const AZStd::string& regionName) = 0; }; } // namespace RPI } // namespace AZ - -//! Utility functions for timing a section of code and writing the timing (in cycles) to a new, named time region inside the -//! provided statistics data. - -//! Supply a group and region to the time region -#define AZ_ATOM_PROFILE_TIME_GROUP_REGION(groupName, regionName) \ - static const AZ::RHI::CachedTimeRegion::GroupRegionName AZ_JOIN(groupRegionName, __LINE__)(groupName, regionName); \ - AZ::RHI::TimeRegion AZ_JOIN(timeRegion, __LINE__)(&AZ_JOIN(groupRegionName, __LINE__)); - -//! Supply a region to the time region; "Default" will be used for the group -#define AZ_ATOM_PROFILE_TIME_REGION(regionName) \ - AZ_ATOM_PROFILE_TIME_GROUP_REGION("Default", regionName) - -//! Used to create a time region; "Default" will be used for the group, and __FUNCTION__ macro for the region -#define AZ_ATOM_PROFILE_TIME_FUNCTION() \ - AZ_ATOM_PROFILE_TIME_GROUP_REGION("Default", AZ_FUNCTION_SIGNATURE) - -//! Macro that combines the AZ_TRACE_METHOD with time profiling macro -#define AZ_ATOM_PROFILE_FUNCTION(groupName, regionName) \ - AZ_TRACE_METHOD(); \ - AZ_ATOM_PROFILE_TIME_GROUP_REGION(groupName, regionName) \ - -//! Macro that allows for region names to be submitted at runtime. Use sparingly - this acquires a lock and allocates new objects within a map. -#define AZ_ATOM_PROFILE_DYNAMIC(groupName, regionName) \ - static_assert(AZStd::is_convertible_v, "Runtime group names are not allowed, use a static string literal instead."); \ - const AZ::RHI::CachedTimeRegion::GroupRegionName& AZ_JOIN(groupRegionName, __LINE__) = \ - AZ::RHI::CpuProfiler::Get()->InsertDynamicName(groupName, regionName); \ - AZ::RHI::TimeRegion AZ_JOIN(timeRegion, __LINE__)(&AZ_JOIN(groupRegionName, __LINE__)); diff --git a/Gems/Atom/RHI/Code/Include/Atom/RHI/CpuProfilerImpl.h b/Gems/Atom/RHI/Code/Include/Atom/RHI/CpuProfilerImpl.h index 92b56880b7..29886625ea 100644 --- a/Gems/Atom/RHI/Code/Include/Atom/RHI/CpuProfilerImpl.h +++ b/Gems/Atom/RHI/Code/Include/Atom/RHI/CpuProfilerImpl.h @@ -43,13 +43,13 @@ namespace AZ static constexpr uint32_t TimeRegionStackSize = 2048u; // Adds a region to the stack, gets called each time a region begins - void RegionStackPushBack(TimeRegion& timeRegion); + void RegionStackPushBack(CachedTimeRegion& timeRegion); // Pops a region from the stack, gets called each time a region ends void RegionStackPopBack(); // Add a new cached time region. If the stack is empty, flush all entries to the cached map - void AddCachedRegion(CachedTimeRegion&& timeRegionCached); + void AddCachedRegion(const CachedTimeRegion& timeRegionCached); // Tries to flush the map to the passed parameter, only if the thread's mutex is unlocked void TryFlushCachedMap(CpuProfiler::ThreadTimeRegionMap& cachedRegionMap); @@ -63,7 +63,7 @@ namespace AZ // Use fixed vectors to avoid re-allocating new elements // Keeps track of the regions that added and removed using the macro - AZStd::fixed_vector m_timeRegionStack; + AZStd::fixed_vector m_timeRegionStack; // Keeps track of regions that completed (i.e regions that was pushed and popped from the stack) // Intermediate storage point for the CachedTimeRegions, when the stack is empty, all entries will be @@ -85,7 +85,8 @@ namespace AZ //! forwards the request to profile a region to the appropriate thread. The user is able to request all //! cached regions, which are stored on a per thread frequency. class CpuProfilerImpl final - : public CpuProfiler + : public AZ::Debug::Profiler + , public CpuProfiler , public SystemTickBus::Handler { friend class CpuTimingLocalStorage; @@ -107,16 +108,17 @@ namespace AZ // m_timeRegionMap so that the next frame has up-to-date profiling data. void OnSystemTick() final override; + //! AZ::Debug::Profiler overrides... + void BeginRegion(const AZ::Debug::Budget* budget, const char* eventName) final override; + void EndRegion(const AZ::Debug::Budget* budget) final override; + //! CpuProfiler overrides... - void BeginTimeRegion(TimeRegion& timeRegion) final override; - void EndTimeRegion() final override; const TimeRegionMap& GetTimeRegionMap() const final override; bool BeginContinuousCapture() final override; bool EndContinuousCapture(AZStd::ring_buffer& flushTarget) final override; bool IsContinuousCaptureInProgress() const final override; void SetProfilerEnabled(bool enabled) final override; bool IsProfilerEnabled() const final override; - const CachedTimeRegion::GroupRegionName& InsertDynamicName(const char* groupName, const AZStd::string& regionName) final override; private: static constexpr AZStd::size_t MaxFramesToSave = 2 * 60 * 120; // 2 minutes of 120fps @@ -133,15 +135,6 @@ namespace AZ AZStd::vector, AZ::OSStdAllocator> m_registeredThreads; AZStd::mutex m_threadRegisterMutex; - // Pool for GroupRegionNames that are generated at runtime through AZ_ATOM_PROFILE_DYNAMIC. Each unique - // combination of group name and region name submitted will be stored in this pool to emulate static lifetime. - AZStd::unordered_set m_dynamicGroupRegionNamePool; - - // String pool for storing region names submitted at runtime. Each call to AZ_ATOM_PROFILE_DYNAMIC will either construct - // a string in this pool or use an already-existing entry. - AZStd::unordered_set m_regionNameStringPool; - AZStd::mutex m_dynamicNameMutex; - // Thread local storage, gets lazily allocated when a thread is created static thread_local CpuTimingLocalStorage* ms_threadLocalStorage; diff --git a/Gems/Atom/RHI/Code/Include/Atom/RHI/MemorySubAllocator.h b/Gems/Atom/RHI/Code/Include/Atom/RHI/MemorySubAllocator.h index a10afd880f..bdeb252174 100644 --- a/Gems/Atom/RHI/Code/Include/Atom/RHI/MemorySubAllocator.h +++ b/Gems/Atom/RHI/Code/Include/Atom/RHI/MemorySubAllocator.h @@ -157,7 +157,7 @@ namespace AZ template void MemorySubAllocator::GarbageCollect() { - AZ_ATOM_PROFILE_FUNCTION("RHI", "MemorySubAllocator: GarbageCollect"); + AZ_PROFILE_SCOPE(RHI, "MemorySubAllocator: GarbageCollect"); for (PageContext& pageContext : m_pageContexts) { pageContext.m_allocator.GarbageCollect(); diff --git a/Gems/Atom/RHI/Code/Include/Atom/RHI/ObjectCollector.h b/Gems/Atom/RHI/Code/Include/Atom/RHI/ObjectCollector.h index cd8a85a385..988416326e 100644 --- a/Gems/Atom/RHI/Code/Include/Atom/RHI/ObjectCollector.h +++ b/Gems/Atom/RHI/Code/Include/Atom/RHI/ObjectCollector.h @@ -173,7 +173,7 @@ namespace AZ template void ObjectCollector::Collect(bool forceFlush) { - AZ_ATOM_PROFILE_FUNCTION("DX12", "ObjectCollector: Collect"); + AZ_PROFILE_SCOPE(RHI, "ObjectCollector: Collect"); m_mutex.lock(); if (m_pendingObjects.size()) { diff --git a/Gems/Atom/RHI/Code/Include/Atom/RHI/SwapChain.h b/Gems/Atom/RHI/Code/Include/Atom/RHI/SwapChain.h index 42ba2d2e25..14e9968e42 100644 --- a/Gems/Atom/RHI/Code/Include/Atom/RHI/SwapChain.h +++ b/Gems/Atom/RHI/Code/Include/Atom/RHI/SwapChain.h @@ -81,15 +81,6 @@ namespace AZ AZ_RTTI(SwapChain, "{888B64A5-D956-406F-9C33-CF6A54FC41B0}", Object); -#if defined(PAL_TRAIT_LINUX_WINDOW_MANAGER_XCB) - // On Linux platforms that uses XCB, a resize may occur in the swap chain but the command queue may still - // reference the original surface. This flag is a temporary fix to make sure the swap chain is ready to present - // We need to remove this work around with - - // [GFX TODO][GHI - 2678] - AZStd::atomic_bool m_readyToPresent { false }; -#endif // PAL_TRAIT_LINUX_WINDOW_MANAGER_XCB - protected: SwapChain(); diff --git a/Gems/Atom/RHI/Code/Source/RHI/AsyncWorkQueue.cpp b/Gems/Atom/RHI/Code/Source/RHI/AsyncWorkQueue.cpp index 52021fa736..a076bf3e58 100644 --- a/Gems/Atom/RHI/Code/Source/RHI/AsyncWorkQueue.cpp +++ b/Gems/Atom/RHI/Code/Source/RHI/AsyncWorkQueue.cpp @@ -128,7 +128,7 @@ namespace AZ return; } - AZ_PROFILE_FUNCTION(RHI); + AZ_PROFILE_SCOPE(RHI, "AsyncWorkQueue: WaitToFinish"); AZStd::unique_lock lock(m_waitWorkItemMutex); m_waitWorkItemCondition.wait(lock, [&]() {return HasFinishedWork(workHandle); }); diff --git a/Gems/Atom/RHI/Code/Source/RHI/BufferPool.cpp b/Gems/Atom/RHI/Code/Source/RHI/BufferPool.cpp index 9849db254e..5d06d02668 100644 --- a/Gems/Atom/RHI/Code/Source/RHI/BufferPool.cpp +++ b/Gems/Atom/RHI/Code/Source/RHI/BufferPool.cpp @@ -163,7 +163,7 @@ namespace AZ return ResultCode::InvalidArgument; } - AZ_ATOM_PROFILE_FUNCTION("RHI", "BufferPool::OrphanBuffer"); + AZ_PROFILE_SCOPE(RHI, "BufferPool::OrphanBuffer"); return OrphanBufferInternal(buffer); } diff --git a/Gems/Atom/RHI/Code/Source/RHI/CommandQueue.cpp b/Gems/Atom/RHI/Code/Source/RHI/CommandQueue.cpp index 15621c7f2b..0983d4db22 100644 --- a/Gems/Atom/RHI/Code/Source/RHI/CommandQueue.cpp +++ b/Gems/Atom/RHI/Code/Source/RHI/CommandQueue.cpp @@ -22,7 +22,7 @@ namespace AZ ResultCode CommandQueue::Init(Device& device, const CommandQueueDescriptor& descriptor) { - AZ_PROFILE_FUNCTION(RHI); + AZ_PROFILE_SCOPE(RHI, "CommandQueue: Init"); #if defined (AZ_RHI_ENABLE_VALIDATION) if (IsInitialized()) @@ -83,7 +83,7 @@ namespace AZ void CommandQueue::FlushCommands() { - AZ_ATOM_PROFILE_FUNCTION("RHI", "CommandQueue: FlushCommands"); + AZ_PROFILE_SCOPE(RHI, "CommandQueue: FlushCommands"); while (!m_isWorkQueueEmpty && !m_isQuitting) { AZStd::this_thread::yield(); diff --git a/Gems/Atom/RHI/Code/Source/RHI/CpuProfilerImpl.cpp b/Gems/Atom/RHI/Code/Source/RHI/CpuProfilerImpl.cpp index e16b89b5cd..1bc17adb22 100644 --- a/Gems/Atom/RHI/Code/Source/RHI/CpuProfilerImpl.cpp +++ b/Gems/Atom/RHI/Code/Source/RHI/CpuProfilerImpl.cpp @@ -27,38 +27,14 @@ namespace AZ return Interface::Get(); } - // --- TimeRegion --- - - TimeRegion::TimeRegion(const GroupRegionName* groupRegionName) : - CachedTimeRegion(groupRegionName) - { - if (CpuProfiler::Get()) - { - CpuProfiler::Get()->BeginTimeRegion(*this); - } - } - - TimeRegion::~TimeRegion() - { - EndRegion(); - } - - void TimeRegion::EndRegion() - { - if (CpuProfiler::Get()) - { - CpuProfiler::Get()->EndTimeRegion(); - } - } - // --- CachedTimeRegion --- - CachedTimeRegion::CachedTimeRegion(const GroupRegionName* groupRegionName) + CachedTimeRegion::CachedTimeRegion(const GroupRegionName& groupRegionName) { m_groupRegionName = groupRegionName; } - CachedTimeRegion::CachedTimeRegion(const GroupRegionName* groupRegionName, uint16_t stackDepth, uint64_t startTick, uint64_t endTick) + CachedTimeRegion::CachedTimeRegion(const GroupRegionName& groupRegionName, uint16_t stackDepth, uint64_t startTick, uint64_t endTick) { m_groupRegionName = groupRegionName; m_stackDepth = stackDepth; @@ -92,6 +68,7 @@ namespace AZ void CpuProfilerImpl::Init() { + Interface::Register(this); Interface::Register(this); m_initialized = true; SystemTickBus::Handler::BusConnect(); @@ -106,6 +83,7 @@ namespace AZ } // When this call is made, no more thread profiling calls can be performed anymore Interface::Unregister(this); + Interface::Unregister(this); // Wait for the remaining threads that might still be processing its profiling calls AZStd::unique_lock shutdownLock(m_shutdownMutex); @@ -121,7 +99,7 @@ namespace AZ SystemTickBus::Handler::BusDisconnect(); } - void CpuProfilerImpl::BeginTimeRegion(TimeRegion& timeRegion) + void CpuProfilerImpl::BeginRegion(const AZ::Debug::Budget* budget, const char* eventName) { // Try to lock here, the shutdownMutex will only be contested when the CpuProfiler is shutting down. if (m_shutdownMutex.try_lock_shared()) @@ -132,6 +110,7 @@ namespace AZ RegisterThreadStorage(); // Push it to the stack + CachedTimeRegion timeRegion({budget->Name(), eventName}); ms_threadLocalStorage->RegionStackPushBack(timeRegion); } @@ -139,11 +118,12 @@ namespace AZ } } - void CpuProfilerImpl::EndTimeRegion() + void CpuProfilerImpl::EndRegion([[maybe_unused]] const AZ::Debug::Budget* budget) { // Try to lock here, the shutdownMutex will only be contested when the CpuProfiler is shutting down. if (m_shutdownMutex.try_lock_shared()) { + // guard against enabling mid-marker if (m_enabled && ms_threadLocalStorage != nullptr) { ms_threadLocalStorage->RegionStackPopBack(); @@ -232,19 +212,6 @@ namespace AZ return m_enabled; } - const CachedTimeRegion::GroupRegionName& CpuProfilerImpl::InsertDynamicName(const char* groupName, const AZStd::string& regionName) - { - AZStd::scoped_lock lock(m_dynamicNameMutex); - AZ_Warning("CpuProfiler", m_regionNameStringPool.size() < MaxRegionStringPoolSize, - "Stored dynamic region names are accumulating. Consider removing a AZ_ATOM_PROFILE_DYNAMIC invocation."); - auto [regionNameItr, wasRegionInserted] = m_regionNameStringPool.insert(regionName); - - CachedTimeRegion::GroupRegionName newGroupRegionName(groupName, regionNameItr->c_str()); - auto [groupRegionNameItr, wasGroupRegionInserted] = m_dynamicGroupRegionNamePool.insert(newGroupRegionName); - - return *groupRegionNameItr; - } - void CpuProfilerImpl::OnSystemTick() { if (!m_enabled) @@ -307,7 +274,7 @@ namespace AZ m_deleteFlag = true; } - void CpuTimingLocalStorage::RegionStackPushBack(TimeRegion& timeRegion) + void CpuTimingLocalStorage::RegionStackPushBack(CachedTimeRegion& timeRegion) { // If it was (re)enabled, clear the lists first if (m_clearContainers) @@ -323,13 +290,13 @@ namespace AZ timeRegion.m_stackDepth = static_cast(m_stackLevel); AZ_Assert(m_timeRegionStack.size() < TimeRegionStackSize, "Adding too many time regions to the stack. Increase the size of TimeRegionStackSize."); - m_timeRegionStack.push_back(&timeRegion); + m_timeRegionStack.push_back(timeRegion); // Increment the stack m_stackLevel++; // Set the starting time at the end, to avoid recording the minor overhead - timeRegion.m_startTick = AZStd::GetTimeNowTicks(); + m_timeRegionStack.back().m_startTick = AZStd::GetTimeNowTicks(); } void CpuTimingLocalStorage::RegionStackPopBack() @@ -344,23 +311,23 @@ namespace AZ const AZStd::sys_time_t endRegionTime = AZStd::GetTimeNowTicks(); AZ_Assert(!m_timeRegionStack.empty(), "Trying to pop an element in the stack, but it's empty."); - TimeRegion* back = m_timeRegionStack.back(); + CachedTimeRegion back = m_timeRegionStack.back(); m_timeRegionStack.pop_back(); // Set the ending time - back->m_endTick = endRegionTime; + back.m_endTick = endRegionTime; // Decrement the stack m_stackLevel--; // Add an entry to the cached region - AddCachedRegion(CachedTimeRegion(back->m_groupRegionName, back->m_stackDepth, back->m_startTick, back->m_endTick)); + AddCachedRegion(back); } // Gets called when region ends and all data is set - void CpuTimingLocalStorage::AddCachedRegion(CachedTimeRegion&& timeRegionCached) + void CpuTimingLocalStorage::AddCachedRegion(const CachedTimeRegion& timeRegionCached) { - if (m_hitSizeLimitMap[timeRegionCached.m_groupRegionName->m_regionName]) + if (m_hitSizeLimitMap[timeRegionCached.m_groupRegionName.m_regionName]) { return; } @@ -379,12 +346,12 @@ namespace AZ // Add the cached regions to the map for (auto& cachedTimeRegion : m_cachedTimeRegions) { - const AZStd::string regionName = cachedTimeRegion.m_groupRegionName->m_regionName; + const AZStd::string regionName = cachedTimeRegion.m_groupRegionName.m_regionName; AZStd::vector& regionVec = m_cachedTimeRegionMap[regionName]; regionVec.push_back(cachedTimeRegion); if (regionVec.size() >= TimeRegionStackSize) { - m_hitSizeLimitMap[cachedTimeRegion.m_groupRegionName->m_regionName] = true; + m_hitSizeLimitMap.insert_or_assign(AZStd::move(regionName), true); } } @@ -448,8 +415,8 @@ namespace AZ CpuProfilingStatisticsSerializer::CpuProfilingStatisticsSerializerEntry::CpuProfilingStatisticsSerializerEntry( const RHI::CachedTimeRegion& cachedTimeRegion, AZStd::thread_id threadId) { - m_groupName = cachedTimeRegion.m_groupRegionName->m_groupName; - m_regionName = cachedTimeRegion.m_groupRegionName->m_regionName; + m_groupName = cachedTimeRegion.m_groupRegionName.m_groupName; + m_regionName = cachedTimeRegion.m_groupRegionName.m_regionName; m_stackDepth = cachedTimeRegion.m_stackDepth; m_startTick = cachedTimeRegion.m_startTick; m_endTick = cachedTimeRegion.m_endTick; diff --git a/Gems/Atom/RHI/Code/Source/RHI/Device.cpp b/Gems/Atom/RHI/Code/Source/RHI/Device.cpp index 3af09717df..9453ff79ee 100644 --- a/Gems/Atom/RHI/Code/Source/RHI/Device.cpp +++ b/Gems/Atom/RHI/Code/Source/RHI/Device.cpp @@ -128,7 +128,7 @@ namespace AZ { if (ValidateIsInitialized() && ValidateIsInFrame()) { - AZ_ATOM_PROFILE_FUNCTION("RHI", "Device: EndFrame"); + AZ_PROFILE_SCOPE(RHI, "Device: EndFrame"); EndFrameInternal(); m_isInFrame = false; return ResultCode::Success; @@ -150,7 +150,7 @@ namespace AZ { if (ValidateIsInitialized() && ValidateIsNotInFrame()) { - AZ_ATOM_PROFILE_FUNCTION("RHI", "Device: CompileMemoryStatistics"); + AZ_PROFILE_SCOPE(RHI, "Device: CompileMemoryStatistics"); MemoryStatisticsBuilder builder; builder.Begin(memoryStatistics, reportFlags); CompileMemoryStatisticsInternal(builder); diff --git a/Gems/Atom/RHI/Code/Source/RHI/Fence.cpp b/Gems/Atom/RHI/Code/Source/RHI/Fence.cpp index b35260caca..ca0493a52c 100644 --- a/Gems/Atom/RHI/Code/Source/RHI/Fence.cpp +++ b/Gems/Atom/RHI/Code/Source/RHI/Fence.cpp @@ -81,7 +81,7 @@ namespace AZ return ResultCode::InvalidOperation; } - AZ_PROFILE_FUNCTION(RHI); + AZ_PROFILE_SCOPE(RHI, "Fence: WaitOnCpu"); WaitOnCpuInternal(); return ResultCode::Success; } diff --git a/Gems/Atom/RHI/Code/Source/RHI/FrameGraph.cpp b/Gems/Atom/RHI/Code/Source/RHI/FrameGraph.cpp index ff6ecb4df5..b85fa88f34 100644 --- a/Gems/Atom/RHI/Code/Source/RHI/FrameGraph.cpp +++ b/Gems/Atom/RHI/Code/Source/RHI/FrameGraph.cpp @@ -73,7 +73,7 @@ namespace AZ void FrameGraph::Clear() { - AZ_ATOM_PROFILE_FUNCTION("RHI", "FrameGraph: Clear"); + AZ_PROFILE_SCOPE(RHI, "FrameGraph: Clear"); for (Scope* scope : m_scopes) { scope->Deactivate(); @@ -126,7 +126,7 @@ namespace AZ ResultCode FrameGraph::End() { - AZ_ATOM_PROFILE_FUNCTION("RHI", "FrameGraph: End"); + AZ_PROFILE_SCOPE(RHI, "FrameGraph: End"); ResultCode resultCode = ValidateEnd(); if (resultCode != ResultCode::Success) { diff --git a/Gems/Atom/RHI/Code/Source/RHI/FrameGraphCompiler.cpp b/Gems/Atom/RHI/Code/Source/RHI/FrameGraphCompiler.cpp index c4204a4a90..5c5691d975 100644 --- a/Gems/Atom/RHI/Code/Source/RHI/FrameGraphCompiler.cpp +++ b/Gems/Atom/RHI/Code/Source/RHI/FrameGraphCompiler.cpp @@ -121,7 +121,7 @@ namespace AZ */ MessageOutcome FrameGraphCompiler::Compile(const FrameGraphCompileRequest& request) { - AZ_ATOM_PROFILE_FUNCTION("RHI", "FrameGraphCompiler: Compile"); + AZ_PROFILE_SCOPE(RHI, "FrameGraphCompiler: Compile"); MessageOutcome outcome = ValidateCompileRequest(request); if (!outcome) @@ -146,7 +146,7 @@ namespace AZ /// [Phase 4] Compile platform-specific scope data after all attachments and views have been compiled. { - AZ_ATOM_PROFILE_FUNCTION("RHI", "FrameGraphCompiler: Scope Compile"); + AZ_PROFILE_SCOPE(RHI, "FrameGraphCompiler: Scope Compile"); for (Scope* scope : frameGraph.GetScopes()) { @@ -162,7 +162,7 @@ namespace AZ FrameGraph& frameGraph, FrameSchedulerCompileFlags compileFlags) { - AZ_ATOM_PROFILE_FUNCTION("RHI", "FrameGraphCompiler: CompileQueueCentricScopeGraph"); + AZ_PROFILE_SCOPE(RHI, "FrameGraphCompiler: CompileQueueCentricScopeGraph"); const bool disableAsyncQueues = CheckBitsAll(compileFlags, FrameSchedulerCompileFlags::DisableAsyncQueues); if (disableAsyncQueues) @@ -480,7 +480,7 @@ namespace AZ return; } - AZ_ATOM_PROFILE_FUNCTION("RHI", "FrameGraphCompiler: CompileTransientAttachments"); + AZ_PROFILE_SCOPE(RHI, "FrameGraphCompiler: CompileTransientAttachments"); ExtendTransientAttachmentAsyncQueueLifetimes(frameGraph, compileFlags); @@ -769,7 +769,7 @@ namespace AZ void FrameGraphCompiler::CompileResourceViews(const FrameGraphAttachmentDatabase& attachmentDatabase) { - AZ_ATOM_PROFILE_FUNCTION("RHI", "FrameGraphCompiler: CompileResourceViews"); + AZ_PROFILE_SCOPE(RHI, "FrameGraphCompiler: CompileResourceViews"); for (ImageFrameAttachment* imageAttachment : attachmentDatabase.GetImageAttachments()) { diff --git a/Gems/Atom/RHI/Code/Source/RHI/FrameGraphExecuter.cpp b/Gems/Atom/RHI/Code/Source/RHI/FrameGraphExecuter.cpp index 342e537993..429081cd2c 100644 --- a/Gems/Atom/RHI/Code/Source/RHI/FrameGraphExecuter.cpp +++ b/Gems/Atom/RHI/Code/Source/RHI/FrameGraphExecuter.cpp @@ -71,14 +71,13 @@ namespace AZ void FrameGraphExecuter::Begin(const FrameGraph& frameGraph) { - AZ_TRACE_METHOD(); - AZ_ATOM_PROFILE_FUNCTION("RHI", "FrameGraphExecuter: Begin"); + AZ_PROFILE_SCOPE(RHI, "FrameGraphExecuter: Begin"); BeginInternal(frameGraph); } void FrameGraphExecuter::End() { - AZ_ATOM_PROFILE_FUNCTION("RHI", "FrameGraphExecuter: End"); + AZ_PROFILE_SCOPE(RHI, "FrameGraphExecuter: End"); AZ_Assert(m_pendingGroups.empty(), "Pending contexts in queue."); m_groups.clear(); EndInternal(); diff --git a/Gems/Atom/RHI/Code/Source/RHI/FrameScheduler.cpp b/Gems/Atom/RHI/Code/Source/RHI/FrameScheduler.cpp index fe69f56856..90218709fa 100644 --- a/Gems/Atom/RHI/Code/Source/RHI/FrameScheduler.cpp +++ b/Gems/Atom/RHI/Code/Source/RHI/FrameScheduler.cpp @@ -137,7 +137,7 @@ namespace AZ ResultCode FrameScheduler::ImportScopeProducer(ScopeProducer& scopeProducer) { - AZ_PROFILE_FUNCTION(RHI); + AZ_PROFILE_SCOPE(RHI, "FrameScheduler: ImportScopeProducer"); if (!ValidateIsProcessing()) { @@ -171,14 +171,14 @@ namespace AZ MessageOutcome FrameScheduler::Compile(const FrameSchedulerCompileRequest& compileRequest) { - AZ_ATOM_PROFILE_FUNCTION("RHI", "FrameScheduler: Compile"); + AZ_PROFILE_SCOPE(RHI, "FrameScheduler: Compile"); PrepareProducers(); m_compileRequest = compileRequest; { - AZ_ATOM_PROFILE_TIME_GROUP_REGION("RHI", "FrameScheduler: Compile: OnFrameCompile"); + AZ_PROFILE_SCOPE(RHI, "FrameScheduler: Compile: OnFrameCompile"); FrameEventBus::Broadcast(&FrameEventBus::Events::OnFrameCompile); } @@ -193,7 +193,7 @@ namespace AZ if (outcome.IsSuccess()) { { - AZ_ATOM_PROFILE_TIME_GROUP_REGION("RHI", "FrameScheduler: Compile: OnFrameCompileEnd"); + AZ_PROFILE_SCOPE(RHI, "FrameScheduler: Compile: OnFrameCompileEnd"); FrameEventBus::Broadcast(&FrameEventBus::Events::OnFrameCompileEnd, *m_frameGraph); } @@ -216,8 +216,7 @@ namespace AZ void FrameScheduler::PrepareProducers() { - AZ_PROFILE_FUNCTION(RHI); - AZ_ATOM_PROFILE_FUNCTION("RHI", "FrameScheduler: PrepareProducers"); + AZ_PROFILE_SCOPE(RHI, "FrameScheduler: PrepareProducers"); for (ScopeProducer* scopeProducer : m_scopeProducers) { @@ -237,8 +236,7 @@ namespace AZ void FrameScheduler::CompileProducers() { - AZ_PROFILE_FUNCTION(RHI); - AZ_ATOM_PROFILE_FUNCTION("RHI", "FrameScheduler: CompileProducers"); + AZ_PROFILE_SCOPE(RHI, "FrameScheduler: CompileProducers"); for (ScopeProducer* scopeProducer : m_scopeProducers) { @@ -249,8 +247,7 @@ namespace AZ void FrameScheduler::CompileShaderResourceGroups() { - AZ_PROFILE_FUNCTION(RHI); - AZ_ATOM_PROFILE_FUNCTION("RHI", "FrameScheduler: CompileShaderResourceGroups"); + AZ_PROFILE_SCOPE(RHI, "FrameScheduler: CompileShaderResourceGroups"); // Execute all queued resource invalidations, which will mark SRG's for compilation. { @@ -286,7 +283,7 @@ namespace AZ const auto compileGroupsForIntervalLambda = [srgPool, interval]() { - AZ_ATOM_PROFILE_FUNCTION("RHI", "FrameScheduler : compileGroupsForIntervalLambda"); + AZ_PROFILE_SCOPE(RHI, "FrameScheduler : compileGroupsForIntervalLambda"); srgPool->CompileGroupsForInterval(interval); }; @@ -322,8 +319,7 @@ namespace AZ void FrameScheduler::BuildRayTracingShaderTables() { - AZ_PROFILE_FUNCTION(RHI); - AZ_ATOM_PROFILE_FUNCTION("RHI", "FrameScheduler: BuildRayTracingShaderTables"); + AZ_PROFILE_SCOPE(RHI, "FrameScheduler: BuildRayTracingShaderTables"); for (auto rayTracingShaderTable : m_rayTracingShaderTablesToBuild) { @@ -341,8 +337,7 @@ namespace AZ ResultCode FrameScheduler::BeginFrame() { - AZ_PROFILE_FUNCTION(RHI); - AZ_ATOM_PROFILE_FUNCTION("RHI", "FrameScheduler: BeginFrame"); + AZ_PROFILE_SCOPE(RHI, "FrameScheduler: BeginFrame"); if (!ValidateIsInitialized()) { @@ -376,8 +371,7 @@ namespace AZ ResultCode FrameScheduler::EndFrame() { - AZ_PROFILE_FUNCTION(RHI); - AZ_ATOM_PROFILE_FUNCTION("RHI", "FrameScheduler: EndFrame"); + AZ_PROFILE_SCOPE(RHI, "FrameScheduler: EndFrame"); if (Validation::IsEnabled()) { @@ -404,7 +398,7 @@ namespace AZ m_scopeProducerLookup.clear(); { - AZ_ATOM_PROFILE_TIME_GROUP_REGION("RHI", "FrameScheduler: EndFrame: OnFrameEnd"); + AZ_PROFILE_SCOPE(RHI, "FrameScheduler: EndFrame: OnFrameEnd"); FrameEventBus::Event(m_device, &FrameEventBus::Events::OnFrameEnd); } @@ -431,8 +425,7 @@ namespace AZ void FrameScheduler::ExecuteGroupInternal(AZ::Job* parentJob, uint32_t groupIndex) { - AZ_PROFILE_FUNCTION(RHI); - AZ_ATOM_PROFILE_FUNCTION("RHI", "FrameScheduler: ExecuteGroupInternal"); + AZ_PROFILE_SCOPE(RHI, "FrameScheduler: ExecuteGroupInternal"); FrameGraphExecuteGroup* executeGroup = m_frameGraphExecuter->BeginGroup(groupIndex); const uint32_t contextCount = executeGroup->GetContextCount(); @@ -474,8 +467,7 @@ namespace AZ void FrameScheduler::Execute(JobPolicy overrideJobPolicy) { - AZ_PROFILE_FUNCTION(RHI); - AZ_ATOM_PROFILE_FUNCTION("RHI", "FrameScheduler: Execute"); + AZ_PROFILE_SCOPE(RHI, "FrameScheduler: Execute"); const uint32_t groupCount = m_frameGraphExecuter->GetGroupCount(); const JobPolicy platformJobPolicy = m_frameGraphExecuter->GetJobPolicy(); diff --git a/Gems/Atom/RHI/Code/Source/RHI/PipelineStateCache.cpp b/Gems/Atom/RHI/Code/Source/RHI/PipelineStateCache.cpp index 6e98456933..868580f0c7 100644 --- a/Gems/Atom/RHI/Code/Source/RHI/PipelineStateCache.cpp +++ b/Gems/Atom/RHI/Code/Source/RHI/PipelineStateCache.cpp @@ -212,7 +212,7 @@ namespace AZ void PipelineStateCache::Compact() { - AZ_ATOM_PROFILE_FUNCTION("RHI", "PipelineStateCache: Compact"); + AZ_PROFILE_SCOPE(RHI, "PipelineStateCache: Compact"); AZStd::unique_lock lock(m_mutex); // Merge the pending cache into the read-only cache. diff --git a/Gems/Atom/RHI/Code/Source/RHI/RHISystem.cpp b/Gems/Atom/RHI/Code/Source/RHI/RHISystem.cpp index a381209d2b..69f7002435 100644 --- a/Gems/Atom/RHI/Code/Source/RHI/RHISystem.cpp +++ b/Gems/Atom/RHI/Code/Source/RHI/RHISystem.cpp @@ -187,8 +187,7 @@ namespace AZ void RHISystem::FrameUpdate(FrameGraphCallback frameGraphCallback) { - AZ_PROFILE_FUNCTION(RHI); - AZ_ATOM_PROFILE_FUNCTION("RHI", "RHISystem: FrameUpdate"); + AZ_PROFILE_SCOPE(RHI, "RHISystem: FrameUpdate"); { AZ_PROFILE_SCOPE(RHI, "main per-frame work"); @@ -201,7 +200,7 @@ namespace AZ * own RHI scopes to the frame scheduler. This happens prior to the RPI pass graph registration. */ { - AZ_ATOM_PROFILE_TIME_GROUP_REGION("RHI", "RHISystem: FrameUpdate: OnFramePrepare"); + AZ_PROFILE_SCOPE(RHI, "RHISystem: FrameUpdate: OnFramePrepare"); RHISystemNotificationBus::Broadcast(&RHISystemNotificationBus::Events::OnFramePrepare, m_frameScheduler); } diff --git a/Gems/Atom/RHI/Code/Source/RHI/SwapChain.cpp b/Gems/Atom/RHI/Code/Source/RHI/SwapChain.cpp index 92d7a125d8..b0501d937d 100644 --- a/Gems/Atom/RHI/Code/Source/RHI/SwapChain.cpp +++ b/Gems/Atom/RHI/Code/Source/RHI/SwapChain.cpp @@ -164,12 +164,6 @@ namespace AZ m_currentImageIndex = 0; } -#if defined(PAL_TRAIT_LINUX_WINDOW_MANAGER_XCB) - // If we are presenting through the editor, the resize is triggered through the editor's window, which - // won't happen until after the surface is ready to present - m_readyToPresent.store(true); -#endif // PAL_TRAIT_LINUX_WINDOW_MANAGER_XCB - return resultCode; } diff --git a/Gems/Atom/RHI/DX12/Code/Source/RHI/AsyncUploadQueue.cpp b/Gems/Atom/RHI/DX12/Code/Source/RHI/AsyncUploadQueue.cpp index 29b210e17e..cb9dac3864 100644 --- a/Gems/Atom/RHI/DX12/Code/Source/RHI/AsyncUploadQueue.cpp +++ b/Gems/Atom/RHI/DX12/Code/Source/RHI/AsyncUploadQueue.cpp @@ -196,7 +196,7 @@ namespace AZ AsyncUploadQueue::FramePacket* AsyncUploadQueue::BeginFramePacket() { - AZ_PROFILE_FUNCTION(RHI); + AZ_PROFILE_SCOPE(RHI, "AsyncUploadQueue: BeginFramePacket"); AZ_Assert(!m_recordingFrame, "The previous frame packet isn't ended"); FramePacket* framePacket = &m_framePackets[m_frameIndex]; @@ -212,7 +212,7 @@ namespace AZ void AsyncUploadQueue::EndFramePacket(ID3D12CommandQueue* commandQueue) { - AZ_PROFILE_FUNCTION(RHI); + AZ_PROFILE_SCOPE(RHI, "AsyncUploadQueue: EndFramePacket"); AZ_Assert(m_recordingFrame, "The frame packet wasn't started. You need to call StartFramePacket first."); AssertSuccess(m_commandList->Close()); @@ -229,7 +229,7 @@ namespace AZ // [GFX TODO][ATOM-4205] Stage/Upload 3D streaming images more efficiently. uint64_t AsyncUploadQueue::QueueUpload(const RHI::StreamingImageExpandRequest& request, uint32_t residentMip) { - AZ_PROFILE_FUNCTION(RHI); + AZ_PROFILE_SCOPE(RHI, "AsyncUploadQueue: QueueUpload"); uint64_t fenceValue = m_uploadFence.Increment(); @@ -475,7 +475,7 @@ namespace AZ void AsyncUploadQueue::WaitForUpload(uint64_t fenceValue) { - AZ_PROFILE_FUNCTION(RHI); + AZ_PROFILE_SCOPE(RHI, "AsyncUploadQueue: WaitForUpload"); if (!IsUploadFinished(fenceValue)) { @@ -489,7 +489,7 @@ namespace AZ void AsyncUploadQueue::ProcessCallbacks(uint64_t fenceValue) { - AZ_PROFILE_FUNCTION(RHI); + AZ_PROFILE_SCOPE(RHI, "AsyncUploadQueue: ProcessCallbacks"); AZStd::lock_guard lock(m_callbackMutex); while (m_callbacks.size() > 0 && m_callbacks.front().second <= fenceValue) { diff --git a/Gems/Atom/RHI/DX12/Code/Source/RHI/CommandListBase.cpp b/Gems/Atom/RHI/DX12/Code/Source/RHI/CommandListBase.cpp index c5c71a9f43..efa9518ee1 100644 --- a/Gems/Atom/RHI/DX12/Code/Source/RHI/CommandListBase.cpp +++ b/Gems/Atom/RHI/DX12/Code/Source/RHI/CommandListBase.cpp @@ -33,7 +33,7 @@ namespace AZ void CommandListBase::Reset(ID3D12CommandAllocator* commandAllocator) { - AZ_PROFILE_FUNCTION(RHI); + AZ_PROFILE_SCOPE(RHI, "CommandListBase: Reset"); AZ_Assert(m_queuedBarriers.empty(), "Unflushed barriers in command list."); m_commandList->Reset(commandAllocator, nullptr); @@ -95,7 +95,7 @@ namespace AZ { if (m_queuedBarriers.size()) { - AZ_PROFILE_FUNCTION(RHI); + AZ_PROFILE_SCOPE(RHI, "CommandListBase: FlushBarriers"); m_commandList->ResourceBarrier((UINT)m_queuedBarriers.size(), m_queuedBarriers.data()); m_queuedBarriers.clear(); diff --git a/Gems/Atom/RHI/DX12/Code/Source/RHI/CommandListPool.cpp b/Gems/Atom/RHI/DX12/Code/Source/RHI/CommandListPool.cpp index c31fe8ada8..94262064da 100644 --- a/Gems/Atom/RHI/DX12/Code/Source/RHI/CommandListPool.cpp +++ b/Gems/Atom/RHI/DX12/Code/Source/RHI/CommandListPool.cpp @@ -175,7 +175,7 @@ namespace AZ void CommandListAllocator::Collect() { - AZ_ATOM_PROFILE_FUNCTION("DX12", "CommandListAllocator: Collect"); + AZ_PROFILE_SCOPE(RHI, "CommandListAllocator: Collect(DX12)"); for (uint32_t queueIdx = 0; queueIdx < RHI::HardwareQueueClassCount; ++queueIdx) { m_commandListSubAllocators[queueIdx].ForEach([](Internal::CommandListSubAllocator& commandListSubAllocator) diff --git a/Gems/Atom/RHI/DX12/Code/Source/RHI/CommandQueue.cpp b/Gems/Atom/RHI/DX12/Code/Source/RHI/CommandQueue.cpp index 9d58217f01..0cde6aeb09 100644 --- a/Gems/Atom/RHI/DX12/Code/Source/RHI/CommandQueue.cpp +++ b/Gems/Atom/RHI/DX12/Code/Source/RHI/CommandQueue.cpp @@ -195,7 +195,7 @@ namespace AZ void CommandQueue::UpdateTileMappings(CommandList& commandList) { - AZ_PROFILE_FUNCTION(RHI); + AZ_PROFILE_SCOPE(RHI, "CommandQueue: UpdateTileMappings"); for (const CommandList::TileMapRequest& request : commandList.GetTileMapRequests()) { const uint32_t tileCount = request.m_sourceRegionSize.NumTiles; @@ -229,7 +229,7 @@ namespace AZ void CommandQueue::WaitForIdle() { - AZ_PROFILE_FUNCTION(RHI); + AZ_PROFILE_SCOPE(RHI, "CommandQueue: WaitForIdle"); Fence fence; fence.Init(m_device.get(), RHI::FenceState::Reset); diff --git a/Gems/Atom/RHI/DX12/Code/Source/RHI/CommandQueueContext.cpp b/Gems/Atom/RHI/DX12/Code/Source/RHI/CommandQueueContext.cpp index 96d621df59..eee137026d 100644 --- a/Gems/Atom/RHI/DX12/Code/Source/RHI/CommandQueueContext.cpp +++ b/Gems/Atom/RHI/DX12/Code/Source/RHI/CommandQueueContext.cpp @@ -101,7 +101,7 @@ namespace AZ void CommandQueueContext::WaitForIdle() { - AZ_PROFILE_FUNCTION(RHI); + AZ_PROFILE_SCOPE(RHI, "CommandQueueContext: WaitForIdle"); for (uint32_t hardwareQueueIdx = 0; hardwareQueueIdx < RHI::HardwareQueueClassCount; ++hardwareQueueIdx) { if (m_commandQueues[hardwareQueueIdx]) @@ -113,7 +113,7 @@ namespace AZ void CommandQueueContext::Begin() { - AZ_PROFILE_FUNCTION(RHI); + AZ_PROFILE_SCOPE(RHI, "CommandQueueContext: Begin"); { AZ_PROFILE_SCOPE(RHI, "Clearing Command Queue Timers"); @@ -131,8 +131,7 @@ namespace AZ void CommandQueueContext::End() { - AZ_PROFILE_FUNCTION(RHI); - AZ_ATOM_PROFILE_FUNCTION("DX12", "CommandQueueContext: End"); + AZ_PROFILE_SCOPE(RHI, "CommandQueueContext: End"); QueueGpuSignals(m_frameFences[m_currentFrameIndex]); @@ -146,7 +145,6 @@ namespace AZ { AZ_PROFILE_SCOPE(RHI, "Wait and Reset Fence"); - AZ_ATOM_PROFILE_TIME_GROUP_REGION("DX12", "CommandQueueContext: Wait on Fences"); FenceEvent event("FrameFence"); m_frameFences[m_currentFrameIndex].Wait(event); diff --git a/Gems/Atom/RHI/DX12/Code/Source/RHI/DescriptorContext.cpp b/Gems/Atom/RHI/DX12/Code/Source/RHI/DescriptorContext.cpp index 942b514b97..816b904e16 100644 --- a/Gems/Atom/RHI/DX12/Code/Source/RHI/DescriptorContext.cpp +++ b/Gems/Atom/RHI/DX12/Code/Source/RHI/DescriptorContext.cpp @@ -341,7 +341,7 @@ namespace AZ void DescriptorContext::GarbageCollect() { - AZ_ATOM_PROFILE_FUNCTION("DX12", "DescriptorContext: GarbageCollect"); + AZ_PROFILE_SCOPE(RHI, "DescriptorContext: GarbageCollect(DX12)"); for (const auto& itr : m_platformLimitsDescriptor->m_descriptorHeapLimits) { for (uint32_t shaderVisibleIdx = 0; shaderVisibleIdx < PlatformLimitsDescriptor::NumHeapFlags; ++shaderVisibleIdx) diff --git a/Gems/Atom/RHI/DX12/Code/Source/RHI/FrameGraphCompiler.cpp b/Gems/Atom/RHI/DX12/Code/Source/RHI/FrameGraphCompiler.cpp index 7eaafc3705..722d535cb1 100644 --- a/Gems/Atom/RHI/DX12/Code/Source/RHI/FrameGraphCompiler.cpp +++ b/Gems/Atom/RHI/DX12/Code/Source/RHI/FrameGraphCompiler.cpp @@ -204,7 +204,7 @@ namespace AZ RHI::MessageOutcome FrameGraphCompiler::CompileInternal(const RHI::FrameGraphCompileRequest& request) { - AZ_ATOM_PROFILE_FUNCTION("RHI", "FrameGraphCompiler: CompileInternal(DX12)"); + AZ_PROFILE_SCOPE(RHI, "FrameGraphCompiler: CompileInternal(DX12)"); RHI::FrameGraph& frameGraph = *request.m_frameGraph; @@ -373,7 +373,7 @@ namespace AZ void FrameGraphCompiler::CompileResourceBarriers(Scope* rootScope, const RHI::FrameGraphAttachmentDatabase& attachmentDatabase) { - AZ_ATOM_PROFILE_FUNCTION("RHI", "FrameGraphCompiler: CompileResourceBarriers(DX12)"); + AZ_PROFILE_SCOPE(RHI, "FrameGraphCompiler: CompileResourceBarriers(DX12)"); for (RHI::BufferFrameAttachment* bufferFrameAttachment : attachmentDatabase.GetBufferAttachments()) { @@ -394,7 +394,7 @@ namespace AZ ResourceTransitionLoggerNull logger(bufferFrameAttachment.GetId()); #endif - AZ_ATOM_PROFILE_FUNCTION("RHI", "FrameGraphCompiler: CompileBufferBarriers(DX12)"); + AZ_PROFILE_SCOPE(RHI, "FrameGraphCompiler: CompileBufferBarriers(DX12)"); Buffer& buffer = static_cast(*bufferFrameAttachment.GetBuffer()); RHI::BufferScopeAttachment* scopeAttachment = bufferFrameAttachment.GetFirstScopeAttachment(); @@ -469,7 +469,7 @@ namespace AZ ResourceTransitionLoggerNull logger(imageFrameAttachment.GetId()); #endif - AZ_ATOM_PROFILE_FUNCTION("RHI", "FrameGraphCompiler: CompileImageBarriers (DX12)"); + AZ_PROFILE_SCOPE(RHI, "FrameGraphCompiler: CompileImageBarriers (DX12)"); Image& image = static_cast(*imageFrameAttachment.GetImage()); RHI::ImageScopeAttachment* scopeAttachment = imageFrameAttachment.GetFirstScopeAttachment(); diff --git a/Gems/Atom/RHI/DX12/Code/Source/RHI/StagingMemoryAllocator.cpp b/Gems/Atom/RHI/DX12/Code/Source/RHI/StagingMemoryAllocator.cpp index 1a32f06fa2..337b25a793 100644 --- a/Gems/Atom/RHI/DX12/Code/Source/RHI/StagingMemoryAllocator.cpp +++ b/Gems/Atom/RHI/DX12/Code/Source/RHI/StagingMemoryAllocator.cpp @@ -55,7 +55,7 @@ namespace AZ void StagingMemoryAllocator::GarbageCollect() { - AZ_ATOM_PROFILE_FUNCTION("DX12", "StagingMemoryAllocator: GarbageCollect"); + AZ_PROFILE_SCOPE(RHI, "StagingMemoryAllocator: GarbageCollect(DX12)"); m_mediumBlockAllocators.ForEach([](MemoryLinearSubAllocator& subAllocator) { subAllocator.GarbageCollect(); diff --git a/Gems/Atom/RHI/Metal/Code/Source/RHI/CommandQueueContext.cpp b/Gems/Atom/RHI/Metal/Code/Source/RHI/CommandQueueContext.cpp index 7f0c535383..fb11700e04 100644 --- a/Gems/Atom/RHI/Metal/Code/Source/RHI/CommandQueueContext.cpp +++ b/Gems/Atom/RHI/Metal/Code/Source/RHI/CommandQueueContext.cpp @@ -79,8 +79,8 @@ namespace AZ void CommandQueueContext::End() { - AZ_PROFILE_FUNCTION(RHI); - + AZ_PROFILE_SCOPE(RHI, "CommandQueueContext: End"); + QueueGpuSignals(m_frameFences[m_currentFrameIndex]); for (uint32_t hardwareQueueIdx = 0; hardwareQueueIdx < RHI::HardwareQueueClassCount; ++hardwareQueueIdx) { @@ -92,7 +92,6 @@ namespace AZ { AZ_PROFILE_SCOPE(RHI, "Wait and Reset Fence"); - AZ_ATOM_PROFILE_TIME_GROUP_REGION("RHI", "CommandQueueContext: Wait on Fences"); //Synchronize the CPU with the GPU by waiting on the fence until signalled by the GPU. CPU can only go upto //RHI::Limits::Device::FrameCountMax frames ahead of the GPU diff --git a/Gems/Atom/RHI/Metal/Code/Source/RHI/FrameGraphCompiler.cpp b/Gems/Atom/RHI/Metal/Code/Source/RHI/FrameGraphCompiler.cpp index 520e417f6b..a347ed9b12 100644 --- a/Gems/Atom/RHI/Metal/Code/Source/RHI/FrameGraphCompiler.cpp +++ b/Gems/Atom/RHI/Metal/Code/Source/RHI/FrameGraphCompiler.cpp @@ -33,7 +33,7 @@ namespace AZ RHI::MessageOutcome FrameGraphCompiler::CompileInternal(const RHI::FrameGraphCompileRequest& request) { - AZ_ATOM_PROFILE_FUNCTION("RHI", "FrameGraphCompiler: CompileInternal(Metal)"); + AZ_PROFILE_SCOPE(RHI, "FrameGraphCompiler: CompileInternal(Metal)"); RHI::FrameGraph& frameGraph = *request.m_frameGraph; if (!RHI::CheckBitsAny(request.m_compileFlags, RHI::FrameSchedulerCompileFlags::DisableAsyncQueues)) { diff --git a/Gems/Atom/RHI/Metal/Code/Source/RHI/SwapChain.cpp b/Gems/Atom/RHI/Metal/Code/Source/RHI/SwapChain.cpp index 90ba04c3db..567f89b6e0 100644 --- a/Gems/Atom/RHI/Metal/Code/Source/RHI/SwapChain.cpp +++ b/Gems/Atom/RHI/Metal/Code/Source/RHI/SwapChain.cpp @@ -192,7 +192,7 @@ namespace AZ id SwapChain::RequestDrawable(bool isFrameCaptureEnabled) { - AZ_ATOM_PROFILE_FUNCTION("RHI", "SwapChain::RequestDrawable"); + AZ_PROFILE_SCOPE(RHI, "SwapChain::RequestDrawable"); m_metalView.metalLayer.framebufferOnly = !isFrameCaptureEnabled; const uint32_t currentImageIndex = GetCurrentImageIndex(); if(m_drawables[currentImageIndex]) diff --git a/Gems/Atom/RHI/Vulkan/Code/Source/RHI/AsyncUploadQueue.cpp b/Gems/Atom/RHI/Vulkan/Code/Source/RHI/AsyncUploadQueue.cpp index 7a8499ab9d..2c3958cb65 100644 --- a/Gems/Atom/RHI/Vulkan/Code/Source/RHI/AsyncUploadQueue.cpp +++ b/Gems/Atom/RHI/Vulkan/Code/Source/RHI/AsyncUploadQueue.cpp @@ -451,7 +451,7 @@ namespace AZ AsyncUploadQueue::FramePacket* AsyncUploadQueue::BeginFramePacket(Queue* queue) { - AZ_PROFILE_FUNCTION(RHI); + AZ_PROFILE_SCOPE(RHI, "AsyncUploadQueue: BeginFramePacket"); AZ_Assert(!m_recordingFrame, "The previous frame packet isn't ended."); auto& device = static_cast(GetDevice()); @@ -471,7 +471,7 @@ namespace AZ void AsyncUploadQueue::EndFramePacket(Queue* queue, Semaphore* semaphoreToSignal /*=nullptr*/) { - AZ_PROFILE_FUNCTION(RHI); + AZ_PROFILE_SCOPE(RHI, "AsyncUploadQueue: EndFramePacket"); AZ_Assert(m_recordingFrame, "The frame packet wasn't started. You need to call StartFramePacket first."); m_commandList->EndCommandBuffer(); @@ -636,7 +636,7 @@ namespace AZ void AsyncUploadQueue::ProcessCallback(const RHI::AsyncWorkHandle& handle) { - AZ_PROFILE_FUNCTION(RHI); + AZ_PROFILE_SCOPE(RHI, "AsyncUploadQueue: ProcessCallback"); AZStd::unique_lock lock(m_callbackListMutex); auto findIter = m_callbackList.find(handle); if (findIter != m_callbackList.end()) diff --git a/Gems/Atom/RHI/Vulkan/Code/Source/RHI/CommandQueue.cpp b/Gems/Atom/RHI/Vulkan/Code/Source/RHI/CommandQueue.cpp index e4d8212228..c712099172 100644 --- a/Gems/Atom/RHI/Vulkan/Code/Source/RHI/CommandQueue.cpp +++ b/Gems/Atom/RHI/Vulkan/Code/Source/RHI/CommandQueue.cpp @@ -42,15 +42,6 @@ namespace AZ void CommandQueue::ExecuteWork(const RHI::ExecuteWorkRequest& rhiRequest) { -#if defined(PAL_TRAIT_LINUX_WINDOW_MANAGER_XCB) - for (RHI::SwapChain* swapChain : rhiRequest.m_swapChainsToPresent) - { - if (!swapChain->m_readyToPresent) - { - return; - } - } -#endif // PAL_TRAIT_LINUX_WINDOW_MANAGER_XCB const ExecuteWorkRequest& request = static_cast(rhiRequest); QueueCommand([=](void* queue) { diff --git a/Gems/Atom/RHI/Vulkan/Code/Source/RHI/CommandQueueContext.cpp b/Gems/Atom/RHI/Vulkan/Code/Source/RHI/CommandQueueContext.cpp index 39f0ac9d58..c0d34e2bf9 100644 --- a/Gems/Atom/RHI/Vulkan/Code/Source/RHI/CommandQueueContext.cpp +++ b/Gems/Atom/RHI/Vulkan/Code/Source/RHI/CommandQueueContext.cpp @@ -42,7 +42,7 @@ namespace AZ void CommandQueueContext::End() { - AZ_PROFILE_FUNCTION(RHI); + AZ_PROFILE_SCOPE(RHI, "CommandQueueContext: End"); for (auto& commandQueue : m_commandQueues) { @@ -55,7 +55,6 @@ namespace AZ { AZ_PROFILE_SCOPE(RHI, "Wait on Fences"); - AZ_ATOM_PROFILE_FUNCTION("RHI", "CommandQueueContext: Wait on Fences"); FencesPerQueue& nextFences = m_frameFences[m_currentFrameIndex]; for (auto& fence : nextFences) @@ -79,7 +78,7 @@ namespace AZ void CommandQueueContext::WaitForIdle() { - AZ_PROFILE_FUNCTION(RHI); + AZ_PROFILE_SCOPE(RHI, "CommandQueueContext: WaitForIdle"); for (auto& commandQueue : m_commandQueues) { commandQueue->WaitForIdle(); diff --git a/Gems/Atom/RHI/Vulkan/Code/Source/RHI/Device.cpp b/Gems/Atom/RHI/Vulkan/Code/Source/RHI/Device.cpp index 4f800f114b..35bc966d1d 100644 --- a/Gems/Atom/RHI/Vulkan/Code/Source/RHI/Device.cpp +++ b/Gems/Atom/RHI/Vulkan/Code/Source/RHI/Device.cpp @@ -235,8 +235,6 @@ namespace AZ //Load device features now that we have loaded all extension info physicalDevice.LoadSupportedFeatures(); - - InitFeaturesAndLimits(physicalDevice); return RHI::ResultCode::Success; } @@ -247,6 +245,8 @@ namespace AZ RHI::ResultCode result = m_commandQueueContext.Init(*this, commandQueueContextDescriptor); RETURN_RESULT_IF_UNSUCCESSFUL(result); + InitFeaturesAndLimits(static_cast(GetPhysicalDevice())); + // Initialize member variables. ReleaseQueue::Descriptor releaseQueueDescriptor; releaseQueueDescriptor.m_collectLatency = m_descriptor.m_frameCountMax - 1; diff --git a/Gems/Atom/RHI/Vulkan/Code/Source/RHI/FrameGraphCompiler.cpp b/Gems/Atom/RHI/Vulkan/Code/Source/RHI/FrameGraphCompiler.cpp index 372ebc273d..2a30e36e04 100644 --- a/Gems/Atom/RHI/Vulkan/Code/Source/RHI/FrameGraphCompiler.cpp +++ b/Gems/Atom/RHI/Vulkan/Code/Source/RHI/FrameGraphCompiler.cpp @@ -45,7 +45,7 @@ namespace AZ RHI::MessageOutcome FrameGraphCompiler::CompileInternal(const RHI::FrameGraphCompileRequest& request) { - AZ_ATOM_PROFILE_FUNCTION("RHI", "FrameGraphCompiler: CompileInternal(Vulkan)"); + AZ_PROFILE_SCOPE(RHI, "FrameGraphCompiler: CompileInternal(Vulkan)"); AZ_Assert(request.m_frameGraph, "FrameGraph is null."); RHI::FrameGraph& frameGraph = *request.m_frameGraph; @@ -89,7 +89,7 @@ namespace AZ void FrameGraphCompiler::CompileResourceBarriers(const RHI::FrameGraphAttachmentDatabase& attachmentDatabase) { - AZ_ATOM_PROFILE_FUNCTION("RHI", "FrameGraphCompiler: CompileResourceBarriers(Vulkan)"); + AZ_PROFILE_SCOPE(RHI, "FrameGraphCompiler: CompileResourceBarriers(Vulkan)"); for (RHI::BufferFrameAttachment* bufferFrameAttachment : attachmentDatabase.GetBufferAttachments()) { diff --git a/Gems/Atom/RHI/Vulkan/Code/Source/RHI/SwapChain.cpp b/Gems/Atom/RHI/Vulkan/Code/Source/RHI/SwapChain.cpp index e1d3e8c060..7040defca8 100644 --- a/Gems/Atom/RHI/Vulkan/Code/Source/RHI/SwapChain.cpp +++ b/Gems/Atom/RHI/Vulkan/Code/Source/RHI/SwapChain.cpp @@ -128,17 +128,6 @@ namespace AZ nativeDimensions->m_imageFormat = ConvertFormat(m_surfaceFormat.format); } -#if defined(PAL_TRAIT_LINUX_WINDOW_MANAGER_XCB) - // When launching in game mode, the surface will be ready at this point, meaning that after - // intialization, this swap chain is ready to present - AZ::ApplicationTypeQuery appType; - ComponentApplicationBus::Broadcast(&AZ::ComponentApplicationBus::Events::QueryApplicationType, appType); - if (appType.IsGame()) - { - m_readyToPresent.store(true); - } -#endif // PAL_TRAIT_LINUX_WINDOW_MANAGER_XCB - SetName(GetName()); return result; } diff --git a/Gems/Atom/RPI/Code/Include/Atom/RPI.Reflect/Material/MaterialAsset.h b/Gems/Atom/RPI/Code/Include/Atom/RPI.Reflect/Material/MaterialAsset.h index 52af56ba0e..6ca3bca652 100644 --- a/Gems/Atom/RPI/Code/Include/Atom/RPI.Reflect/Material/MaterialAsset.h +++ b/Gems/Atom/RPI/Code/Include/Atom/RPI.Reflect/Material/MaterialAsset.h @@ -19,6 +19,11 @@ #include +namespace UnitTest +{ + class MaterialTests; +} + namespace AZ { class ReflectContext; @@ -40,6 +45,7 @@ namespace AZ friend class MaterialAssetCreator; friend class MaterialAssetHandler; friend class MaterialAssetCreatorCommon; + friend class UnitTest::MaterialTests; public: AZ_RTTI(MaterialAsset, "{522C7BE0-501D-463E-92C6-15184A2B7AD8}", AZ::Data::AssetData); diff --git a/Gems/Atom/RPI/Code/Source/RPI.Public/Culling.cpp b/Gems/Atom/RPI/Code/Source/RPI.Public/Culling.cpp index bedf4fe989..fbfabe4f2a 100644 --- a/Gems/Atom/RPI/Code/Source/RPI.Public/Culling.cpp +++ b/Gems/Atom/RPI/Code/Source/RPI.Public/Culling.cpp @@ -299,7 +299,7 @@ namespace AZ //work function void Process() override { - AZ_PROFILE_FUNCTION(RPI); + AZ_PROFILE_SCOPE(RPI, "AddObjectsToViewJob: Process"); const View::UsageFlags viewFlags = m_jobData->m_view->GetUsageFlags(); const RHI::DrawListMask drawListMask = m_jobData->m_view->GetDrawListMask(); @@ -645,7 +645,7 @@ namespace AZ uint32_t AddLodDataToView(const Vector3& pos, const Cullable::LodData& lodData, RPI::View& view) { #ifdef AZ_CULL_PROFILE_DETAILED - AZ_PROFILE_FUNCTION(RPI); + AZ_PROFILE_SCOPE(RPI, "AddLodDataToView"); #endif const Matrix4x4& viewToClip = view.GetViewToClipMatrix(); @@ -725,17 +725,27 @@ namespace AZ void CullingScene::BeginCulling(const AZStd::vector& views) { - AZ_ATOM_PROFILE_FUNCTION("RPI", "CullingScene: BeginCulling"); + AZ_PROFILE_SCOPE(RPI, "CullingScene: BeginCulling"); m_cullDataConcurrencyCheck.soft_lock(); m_debugCtx.ResetCullStats(); m_debugCtx.m_numCullablesInScene = GetNumCullables(); + AZ::JobCompletion beginCullingCompletion; for (auto& view : views) { - view->BeginCulling(); + const auto cullingLambda = [&view]() + { + view->BeginCulling(); + }; + + AZ::Job* cullingJob = AZ::CreateJobFunction(AZStd::move(cullingLambda), true, nullptr); + cullingJob->SetDependent(&beginCullingCompletion); + cullingJob->Start(); } + beginCullingCompletion.StartAndWaitForCompletion(); + AuxGeomDrawPtr auxGeom; if (m_debugCtx.m_debugDraw) { diff --git a/Gems/Atom/RPI/Code/Source/RPI.Public/GpuQuery/GpuQuerySystem.cpp b/Gems/Atom/RPI/Code/Source/RPI.Public/GpuQuery/GpuQuerySystem.cpp index 257bb689ee..8077038ea7 100644 --- a/Gems/Atom/RPI/Code/Source/RPI.Public/GpuQuery/GpuQuerySystem.cpp +++ b/Gems/Atom/RPI/Code/Source/RPI.Public/GpuQuery/GpuQuerySystem.cpp @@ -75,7 +75,7 @@ namespace AZ void GpuQuerySystem::Update() { - AZ_ATOM_PROFILE_FUNCTION("RPI", "GpuQuerySystem: Update"); + AZ_PROFILE_SCOPE(RPI, "GpuQuerySystem: Update"); for (auto& queryPool : m_queryPoolArray) { if (queryPool) 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 d4a55d1c29..71e2eaa2f5 100644 --- a/Gems/Atom/RPI/Code/Source/RPI.Public/Image/ImageSystem.cpp +++ b/Gems/Atom/RPI/Code/Source/RPI.Public/Image/ImageSystem.cpp @@ -34,6 +34,8 @@ #include #include +AZ_DECLARE_BUDGET(RPI); + namespace AZ { namespace RPI @@ -171,7 +173,7 @@ namespace AZ void ImageSystem::Update() { - AZ_ATOM_PROFILE_FUNCTION("RPI", "ImageSystem: Update"); + AZ_PROFILE_SCOPE(RPI, "ImageSystem: Update"); AZStd::lock_guard lock(m_activeStreamingPoolMutex); for (StreamingImagePool* imagePool : m_activeStreamingPools) diff --git a/Gems/Atom/RPI/Code/Source/RPI.Public/Material/Material.cpp b/Gems/Atom/RPI/Code/Source/RPI.Public/Material/Material.cpp index 2dcaa70deb..d44ed40c7b 100644 --- a/Gems/Atom/RPI/Code/Source/RPI.Public/Material/Material.cpp +++ b/Gems/Atom/RPI/Code/Source/RPI.Public/Material/Material.cpp @@ -100,9 +100,15 @@ namespace AZ ShaderReloadNotificationBus::MultiHandler::BusConnect(shaderItem.GetShaderAsset().GetId()); } + // If this Init() is actually a re-initialize, we need to re-apply any overridden property values + // after loading the property values from the asset, so we save that data here. MaterialPropertyFlags prevOverrideFlags = m_propertyOverrideFlags; AZStd::vector prevPropertyValues = m_propertyValues; + // The property values are cleared to their default state to ensure that SetPropertyValue() does not early-return + // when called below. This is important when Init() is actually a re-initialize. + m_propertyValues.clear(); + // Initialize the shader runtime data like shader constant buffers and shader variants by applying the // material's property values. This will feed through the normal runtime material value-change data flow, which may // include custom property change handlers provided by the material type. @@ -504,7 +510,7 @@ namespace AZ MaterialPropertyValue& savedPropertyValue = m_propertyValues[index.GetIndex()]; - // If the property value didn't actually change, don't waste time running functors and compiling the changes + // If the property value didn't actually change, don't waste time running functors and compiling the changes. if (savedPropertyValue == value) { return false; diff --git a/Gems/Atom/RPI/Code/Source/RPI.Public/Model/Model.cpp b/Gems/Atom/RPI/Code/Source/RPI.Public/Model/Model.cpp index 6fd313e27f..50da470ec4 100644 --- a/Gems/Atom/RPI/Code/Source/RPI.Public/Model/Model.cpp +++ b/Gems/Atom/RPI/Code/Source/RPI.Public/Model/Model.cpp @@ -42,7 +42,7 @@ namespace AZ Data::Instance Model::CreateInternal(const Data::Asset& modelAsset) { - AZ_PROFILE_FUNCTION(RPI); + AZ_PROFILE_SCOPE(RPI, "Model: CreateInternal"); Data::Instance model = aznew Model(); const RHI::ResultCode resultCode = model->Init(modelAsset); @@ -56,7 +56,7 @@ namespace AZ RHI::ResultCode Model::Init(const Data::Asset& modelAsset) { - AZ_PROFILE_FUNCTION(RPI); + AZ_PROFILE_SCOPE(RPI, "Model: Init"); m_lods.resize(modelAsset->GetLodAssets().size()); @@ -128,7 +128,7 @@ namespace AZ bool Model::LocalRayIntersection(const AZ::Vector3& rayStart, const AZ::Vector3& rayDir, float& distanceNormalized, AZ::Vector3& normal) const { - AZ_PROFILE_FUNCTION(RPI); + AZ_PROFILE_SCOPE(RPI, "Model: LocalRayIntersection"); if (!GetModelAsset()) { @@ -171,7 +171,7 @@ namespace AZ float& distanceNormalized, AZ::Vector3& normal) const { - AZ_PROFILE_FUNCTION(RPI); + AZ_PROFILE_SCOPE(RPI, "Model: RayIntersection"); const AZ::Vector3 clampedScale = nonUniformScale.GetMax(AZ::Vector3(AZ::MinTransformScale)); const AZ::Transform inverseTM = modelTransform.GetInverse(); diff --git a/Gems/Atom/RPI/Code/Source/RPI.Public/Model/ModelLodUtils.cpp b/Gems/Atom/RPI/Code/Source/RPI.Public/Model/ModelLodUtils.cpp index ef9521d23c..a1651defbc 100644 --- a/Gems/Atom/RPI/Code/Source/RPI.Public/Model/ModelLodUtils.cpp +++ b/Gems/Atom/RPI/Code/Source/RPI.Public/Model/ModelLodUtils.cpp @@ -27,7 +27,7 @@ namespace AZ ModelLodIndex SelectLod(const View* view, const Vector3& position, const Model& model, ModelLodIndex lodOverride) { - AZ_PROFILE_FUNCTION(RPI); + AZ_PROFILE_SCOPE(RPI, "ModelLodUtils: SelectLod"); ModelLodIndex lodIndex; if (model.GetLodCount() == 1) { 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 a8feeb1047..34d72338dc 100644 --- a/Gems/Atom/RPI/Code/Source/RPI.Public/Pass/PassSystem.cpp +++ b/Gems/Atom/RPI/Code/Source/RPI.Public/Pass/PassSystem.cpp @@ -169,7 +169,7 @@ namespace AZ void PassSystem::RemovePasses() { m_state = PassSystemState::RemovingPasses; - AZ_ATOM_PROFILE_FUNCTION("RPI", "PassSystem: RemovePasses"); + AZ_PROFILE_SCOPE(RPI, "PassSystem: RemovePasses"); if (!m_removePassList.empty()) { @@ -189,8 +189,7 @@ namespace AZ void PassSystem::BuildPasses() { m_state = PassSystemState::BuildingPasses; - AZ_PROFILE_FUNCTION(RPI); - AZ_ATOM_PROFILE_FUNCTION("RPI", "PassSystem: BuildPassAttachments"); + AZ_PROFILE_SCOPE(RPI, "PassSystem: BuildPasses"); m_passHierarchyChanged = m_passHierarchyChanged || !m_buildPassList.empty(); @@ -239,8 +238,7 @@ namespace AZ void PassSystem::InitializePasses() { m_state = PassSystemState::InitializingPasses; - AZ_PROFILE_FUNCTION(RPI); - AZ_ATOM_PROFILE_FUNCTION("RPI", "PassSystem: BuildPassAttachments"); + AZ_PROFILE_SCOPE(RPI, "PassSystem: InitializePasses"); m_passHierarchyChanged = m_passHierarchyChanged || !m_initializePassList.empty(); @@ -277,7 +275,6 @@ namespace AZ void PassSystem::Validate() { m_state = PassSystemState::ValidatingPasses; - AZ_ATOM_PROFILE_FUNCTION("RPI", "PassSystem: Validate"); if (PassValidation::IsEnabled()) { @@ -286,7 +283,7 @@ namespace AZ return; } - AZ_PROFILE_FUNCTION(RPI); + AZ_PROFILE_SCOPE(RPI, "PassSystem: Validate"); PassValidationResults validationResults; m_rootPass->Validate(validationResults); @@ -298,7 +295,7 @@ namespace AZ void PassSystem::ProcessQueuedChanges() { - AZ_ATOM_PROFILE_FUNCTION("RPI", "PassSystem: ProcessQueuedChanges"); + AZ_PROFILE_SCOPE(RPI, "PassSystem: ProcessQueuedChanges"); RemovePasses(); BuildPasses(); InitializePasses(); @@ -307,8 +304,7 @@ namespace AZ void PassSystem::FrameUpdate(RHI::FrameGraphBuilder& frameGraphBuilder) { - AZ_PROFILE_FUNCTION(RPI); - AZ_ATOM_PROFILE_FUNCTION("RPI", "PassSystem: FrameUpdate"); + AZ_PROFILE_SCOPE(RPI, "PassSystem: FrameUpdate"); ResetFrameStatistics(); ProcessQueuedChanges(); @@ -317,14 +313,14 @@ namespace AZ Pass::FramePrepareParams params{ &frameGraphBuilder }; { - AZ_ATOM_PROFILE_TIME_GROUP_REGION("RPI", "Pass: FrameBegin"); + AZ_PROFILE_SCOPE(RPI, "Pass: FrameBegin"); m_rootPass->FrameBegin(params); } } void PassSystem::FrameEnd() { - AZ_ATOM_PROFILE_FUNCTION("RHI", "PassSystem: FrameEnd"); + AZ_PROFILE_SCOPE(RHI, "PassSystem: FrameEnd"); m_state = PassSystemState::FrameEnd; diff --git a/Gems/Atom/RPI/Code/Source/RPI.Public/Pass/RasterPass.cpp b/Gems/Atom/RPI/Code/Source/RPI.Public/Pass/RasterPass.cpp index 4c923d4a1a..d9f98c11d3 100644 --- a/Gems/Atom/RPI/Code/Source/RPI.Public/Pass/RasterPass.cpp +++ b/Gems/Atom/RPI/Code/Source/RPI.Public/Pass/RasterPass.cpp @@ -216,7 +216,7 @@ namespace AZ void RasterPass::CompileResources(const RHI::FrameGraphCompileContext& context) { - AZ_PROFILE_FUNCTION(RPI); + AZ_PROFILE_SCOPE(RPI, "RasterPass: CompileResources"); if (m_shaderResourceGroup == nullptr) { diff --git a/Gems/Atom/RPI/Code/Source/RPI.Public/RPISystem.cpp b/Gems/Atom/RPI/Code/Source/RPI.Public/RPISystem.cpp index 500bf21628..5df1c655d6 100644 --- a/Gems/Atom/RPI/Code/Source/RPI.Public/RPISystem.cpp +++ b/Gems/Atom/RPI/Code/Source/RPI.Public/RPISystem.cpp @@ -233,7 +233,7 @@ namespace AZ void RPISystem::OnSystemTick() { - AZ_ATOM_PROFILE_FUNCTION("RPI", "RPISystem: OnSystemTick"); + AZ_PROFILE_SCOPE(RPI, "RPISystem: OnSystemTick"); // Image system update is using system tick but not game tick so it can stream images in background even game is pausing m_imageSystem.Update(); @@ -245,7 +245,7 @@ namespace AZ { return; } - AZ_ATOM_PROFILE_FUNCTION("RPI", "RPISystem: SimulationTick"); + AZ_PROFILE_SCOPE(RPI, "RPISystem: SimulationTick"); AssetInitBus::Broadcast(&AssetInitBus::Events::PostLoadInit); @@ -273,8 +273,7 @@ namespace AZ return; } - AZ_PROFILE_FUNCTION(RPI); - AZ_ATOM_PROFILE_FUNCTION("RPI", "RPISystem: RenderTick"); + AZ_PROFILE_SCOPE(RPI, "RPISystem: RenderTick"); // Query system update is to increment the frame count m_querySystem.Update(); @@ -301,7 +300,7 @@ namespace AZ }); { - AZ_ATOM_PROFILE_TIME_GROUP_REGION("RPI", "RPISystem: FrameEnd"); + AZ_PROFILE_SCOPE(RPI, "RPISystem: FrameEnd"); m_dynamicDraw.FrameEnd(); m_passSystem.FrameEnd(); diff --git a/Gems/Atom/RPI/Code/Source/RPI.Public/RenderPipeline.cpp b/Gems/Atom/RPI/Code/Source/RPI.Public/RenderPipeline.cpp index 7f0ab9c8aa..409a084e4f 100644 --- a/Gems/Atom/RPI/Code/Source/RPI.Public/RenderPipeline.cpp +++ b/Gems/Atom/RPI/Code/Source/RPI.Public/RenderPipeline.cpp @@ -397,7 +397,7 @@ namespace AZ void RenderPipeline::OnStartFrame() { - AZ_PROFILE_FUNCTION(RPI); + AZ_PROFILE_SCOPE(RPI, "RenderPipeline: OnStartFrame"); m_lastRenderStartTime = m_lastRenderRequestTime; diff --git a/Gems/Atom/RPI/Code/Source/RPI.Public/Scene.cpp b/Gems/Atom/RPI/Code/Source/RPI.Public/Scene.cpp index 9fa49f7f2a..778548f14c 100644 --- a/Gems/Atom/RPI/Code/Source/RPI.Public/Scene.cpp +++ b/Gems/Atom/RPI/Code/Source/RPI.Public/Scene.cpp @@ -350,7 +350,7 @@ namespace AZ void Scene::Simulate([[maybe_unused]] const TickTimeInfo& tickInfo, RHI::JobPolicy jobPolicy) { - AZ_ATOM_PROFILE_FUNCTION("RPI", "Scene: Simulate"); + AZ_PROFILE_SCOPE(RPI, "Scene: Simulate"); m_simulationTime = tickInfo.m_currentGameTime; @@ -389,7 +389,7 @@ namespace AZ { if (completionJob) { - AZ_ATOM_PROFILE_FUNCTION("RPI", "Scene: WaitAndCleanCompletionJob"); + AZ_PROFILE_SCOPE(RPI, "Scene: WaitAndCleanCompletionJob"); //[GFX TODO]: the completion job should start earlier and wait for completion here completionJob->StartAndWaitForCompletion(); delete completionJob; @@ -422,11 +422,10 @@ namespace AZ void Scene::PrepareRender([[maybe_unused]]const TickTimeInfo& tickInfo, RHI::JobPolicy jobPolicy) { - AZ_ATOM_PROFILE_FUNCTION("RPI", "Scene: PrepareRender"); + AZ_PROFILE_SCOPE(RPI, "Scene: PrepareRender"); { AZ_PROFILE_SCOPE(RPI, "WaitForSimulationCompletion"); - AZ_ATOM_PROFILE_TIME_GROUP_REGION("RPI", "WaitForSimulationCompletion"); WaitAndCleanCompletionJob(m_simulationCompletion); } @@ -435,7 +434,7 @@ namespace AZ // Get active pipelines which need to be rendered and notify them of an impending frame. AZStd::vector activePipelines; { - AZ_ATOM_PROFILE_TIME_GROUP_REGION("RPI", "Scene: OnPrepareFrame"); + AZ_PROFILE_SCOPE(RPI, "Scene: OnPrepareFrame"); for (auto& pipeline : m_pipelines) { pipeline->OnPrepareFrame(); @@ -449,7 +448,7 @@ namespace AZ // Get active pipelines which need to be rendered and notify them frame started for (const auto& pipeline : activePipelines) { - AZ_ATOM_PROFILE_TIME_GROUP_REGION("RPI", "Scene: OnStartFrame"); + AZ_PROFILE_SCOPE(RPI, "Scene: OnStartFrame"); pipeline->OnStartFrame(); } @@ -468,7 +467,7 @@ namespace AZ { - AZ_ATOM_PROFILE_TIME_GROUP_REGION("RPI", "Setup Views"); + AZ_PROFILE_SCOPE(RPI, "Setup Views"); // Collect persistent views from all pipelines to be rendered AZStd::map persistentViews; @@ -506,8 +505,7 @@ namespace AZ } { - AZ_PROFILE_SCOPE(RPI, "CollectDrawPackets"); - AZ_ATOM_PROFILE_TIME_GROUP_REGION("RPI", "CollectDrawPackets"); + AZ_PROFILE_SCOPE(RPI, "CollectDrawPackets"); AZ::JobCompletion* collectDrawPacketsCompletion = aznew AZ::JobCompletion(); // Launch FeatureProcessor::Render() jobs @@ -550,14 +548,13 @@ namespace AZ // Add dynamic draw data for all the views if (m_dynamicDrawSystem) { - AZ_ATOM_PROFILE_TIME_GROUP_REGION("RPI", "DynamicDraw SubmitDrawData"); + AZ_PROFILE_SCOPE(RPI, "DynamicDraw SubmitDrawData"); m_dynamicDrawSystem->SubmitDrawData(this, m_renderPacket.m_views); } } { AZ_PROFILE_BEGIN(RPI, "FinalizeDrawLists"); - AZ_ATOM_PROFILE_TIME_GROUP_REGION("RPI", "FinalizeDrawLists"); if (jobPolicy == RHI::JobPolicy::Serial) { for (auto& view : m_renderPacket.m_views) @@ -586,14 +583,14 @@ namespace AZ } { - AZ_ATOM_PROFILE_TIME_GROUP_REGION("RPI", "Scene OnEndPrepareRender"); + AZ_PROFILE_SCOPE(RPI, "Scene OnEndPrepareRender"); SceneNotificationBus::Event(GetId(), &SceneNotification::OnEndPrepareRender); } } void Scene::OnFrameEnd() { - AZ_ATOM_PROFILE_FUNCTION("RPI", "Scene: OnFrameEnd"); + AZ_PROFILE_SCOPE(RPI, "Scene: OnFrameEnd"); bool didRender = false; for (auto& pipeline : m_pipelines) { @@ -730,7 +727,7 @@ namespace AZ void Scene::RebuildPipelineStatesLookup() { - AZ_ATOM_PROFILE_FUNCTION("RPI", "Scene: RebuildPipelineStatesLookup"); + AZ_PROFILE_SCOPE(RPI, "Scene: RebuildPipelineStatesLookup"); m_pipelineStatesLookup.clear(); AZStd::queue parents; diff --git a/Gems/Atom/RPI/Code/Source/RPI.Public/Shader/Metrics/ShaderMetricsSystem.cpp b/Gems/Atom/RPI/Code/Source/RPI.Public/Shader/Metrics/ShaderMetricsSystem.cpp index 9e633077e7..528d32e217 100644 --- a/Gems/Atom/RPI/Code/Source/RPI.Public/Shader/Metrics/ShaderMetricsSystem.cpp +++ b/Gems/Atom/RPI/Code/Source/RPI.Public/Shader/Metrics/ShaderMetricsSystem.cpp @@ -113,7 +113,7 @@ namespace AZ return; } - AZ_PROFILE_FUNCTION(RPI); + AZ_PROFILE_SCOPE(RPI, "ShaderMetricsSystem: RequestShaderVariant"); AZStd::lock_guard lock(m_metricsMutex); diff --git a/Gems/Atom/RPI/Code/Source/RPI.Public/View.cpp b/Gems/Atom/RPI/Code/Source/RPI.Public/View.cpp index bdb3ea8899..c2356cea45 100644 --- a/Gems/Atom/RPI/Code/Source/RPI.Public/View.cpp +++ b/Gems/Atom/RPI/Code/Source/RPI.Public/View.cpp @@ -239,7 +239,7 @@ namespace AZ void View::FinalizeDrawLists() { - AZ_PROFILE_FUNCTION(RPI); + AZ_PROFILE_SCOPE(RPI, "View: FinalizeDrawLists"); m_drawListContext.FinalizeLists(); if (m_passesByDrawList) { diff --git a/Gems/Atom/RPI/Code/Source/RPI.Reflect/Material/MaterialPropertyValue.cpp b/Gems/Atom/RPI/Code/Source/RPI.Reflect/Material/MaterialPropertyValue.cpp index 849e6cfffb..13ecea52dc 100644 --- a/Gems/Atom/RPI/Code/Source/RPI.Reflect/Material/MaterialPropertyValue.cpp +++ b/Gems/Atom/RPI/Code/Source/RPI.Reflect/Material/MaterialPropertyValue.cpp @@ -109,11 +109,20 @@ namespace AZ { result.m_value = AZStd::any_cast(value); } + else if (value.is()) + { + result.m_value = Data::Asset( + AZStd::any_cast(value), azrtti_typeid()); + } + else if (value.is>()) + { + result.m_value = Data::Asset( + AZStd::any_cast>(value).GetId(), azrtti_typeid()); + } else if (value.is>()) { result.m_value = Data::Asset( - AZStd::any_cast>(value).GetId(), - azrtti_typeid()); + AZStd::any_cast>(value).GetId(), azrtti_typeid()); } else if (value.is>()) { @@ -129,7 +138,8 @@ namespace AZ } else { - AZ_Warning("MaterialPropertyValue", false, "Cannot convert any to variant. Type in any is: %s.", + AZ_Warning( + "MaterialPropertyValue", false, "Cannot convert any to variant. Type in any is: %s.", value.get_type_info().m_id.ToString().data()); } @@ -187,5 +197,5 @@ namespace AZ return result; } - } -} + } // namespace RPI +} // namespace AZ diff --git a/Gems/Atom/RPI/Code/Tests/Material/MaterialTests.cpp b/Gems/Atom/RPI/Code/Tests/Material/MaterialTests.cpp index d82a17e1f3..f202747bf6 100644 --- a/Gems/Atom/RPI/Code/Tests/Material/MaterialTests.cpp +++ b/Gems/Atom/RPI/Code/Tests/Material/MaterialTests.cpp @@ -182,6 +182,13 @@ namespace UnitTest EXPECT_EQ(srgData.GetImageView(srgData.FindShaderInputImageIndex(Name{ "m_image" }), 0), m_testImage->GetImageView()); EXPECT_EQ(srgData.GetConstant(srgData.FindShaderInputConstantIndex(Name{ "m_enum" })), 2u); } + + //! Provides write access to private material asset property values, primarily for simulating + //! MaterialAsset hot reload. + MaterialPropertyValue& AccessMaterialAssetPropertyValue(Data::Asset materialAsset, Name propertyName) + { + return materialAsset->m_propertyValues[materialAsset->GetMaterialPropertiesLayout()->FindPropertyIndex(propertyName).GetIndex()]; + } }; TEST_F(MaterialTests, TestCreateVsFindOrCreate) @@ -313,6 +320,30 @@ namespace UnitTest EXPECT_EQ(srgData.GetConstant(srgData.FindShaderInputConstantIndex(Name{ "m_uint" })), 42u); } + TEST_F(MaterialTests, TestSetPropertyValueWhenValueIsUnchanged) + { + Data::Instance material = Material::FindOrCreate(m_testMaterialAsset); + + EXPECT_TRUE(material->SetPropertyValue(material->FindPropertyIndex(Name{ "MyFloat" }), 2.5f)); + + ProcessQueuedSrgCompilations(m_testMaterialShaderAsset, m_testMaterialSrgLayout->GetName()); + EXPECT_TRUE(material->Compile()); + + // Taint the SRG so we can check whether it was set by the SetPropertyValue() calls below. + const RHI::ShaderResourceGroup* srg = material->GetRHIShaderResourceGroup(); + const RHI::ShaderResourceGroupData& srgData = srg->GetData(); + const_cast(&srgData)->SetConstant(m_testMaterialSrgLayout->FindShaderInputConstantIndex(Name{"m_float"}), 0.0f); + + // Set the properties to the same values as before + EXPECT_FALSE(material->SetPropertyValue(material->FindPropertyIndex(Name{ "MyFloat" }), 2.5f)); + + ProcessQueuedSrgCompilations(m_testMaterialShaderAsset, m_testMaterialSrgLayout->GetName()); + EXPECT_FALSE(material->Compile()); + + // Make sure the SRG is still tainted, because the SetPropertyValue() functions weren't processed + EXPECT_EQ(srgData.GetConstant(srgData.FindShaderInputConstantIndex(Name{ "m_float" })), 0.0f); + } + TEST_F(MaterialTests, TestImageNotProvided) { Data::Asset materialAssetWithEmptyImage; @@ -785,4 +816,45 @@ namespace UnitTest EXPECT_EQ((float)inputColor.GetElement(i), (float)colorFromMaterial.GetElement(i)); } } + + TEST_F(MaterialTests, TestReinitializeForHotReload) + { + Data::Instance material = Material::FindOrCreate(m_testMaterialAsset); + const RHI::ShaderResourceGroupData* srgData = &material->GetRHIShaderResourceGroup()->GetData(); + ProcessQueuedSrgCompilations(m_testMaterialShaderAsset, m_testMaterialSrgLayout->GetName()); + + // Check the default property value + EXPECT_EQ(material->GetPropertyValue(material->FindPropertyIndex(Name{ "MyFloat" })), 1.5f); + EXPECT_EQ(srgData->GetConstant(srgData->FindShaderInputConstantIndex(Name{ "m_float" })), 1.5f); + EXPECT_EQ(material->GetPropertyValue(material->FindPropertyIndex(Name{ "MyInt" })), -2); + EXPECT_EQ(srgData->GetConstant(srgData->FindShaderInputConstantIndex(Name{ "m_int" })), -2); + + // Override a property value + EXPECT_TRUE(material->SetPropertyValue(material->FindPropertyIndex(Name{ "MyFloat" }), 5.5f)); + + // Apply the changes + EXPECT_TRUE(material->Compile()); + ProcessQueuedSrgCompilations(m_testMaterialShaderAsset, m_testMaterialSrgLayout->GetName()); + + // Check the updated values with one overridden + EXPECT_EQ(material->GetPropertyValue(material->FindPropertyIndex(Name{ "MyFloat" })), 5.5f); + EXPECT_EQ(srgData->GetConstant(srgData->FindShaderInputConstantIndex(Name{ "m_float" })), 5.5f); + EXPECT_EQ(material->GetPropertyValue(material->FindPropertyIndex(Name{ "MyInt" })), -2); + EXPECT_EQ(srgData->GetConstant(srgData->FindShaderInputConstantIndex(Name{ "m_int" })), -2); + + // Pretend there was a hot-reload with new default values + AccessMaterialAssetPropertyValue(m_testMaterialAsset, Name{"MyFloat"}) = 0.5f; + AccessMaterialAssetPropertyValue(m_testMaterialAsset, Name{"MyInt"}) = -7; + AZ::Data::AssetBus::Event(m_testMaterialAsset.GetId(), &AZ::Data::AssetBus::Handler::OnAssetReloaded, m_testMaterialAsset); + srgData = &material->GetRHIShaderResourceGroup()->GetData(); + ProcessQueuedSrgCompilations(m_testMaterialShaderAsset, m_testMaterialSrgLayout->GetName()); + + // Make sure the override values are still there + EXPECT_EQ(srgData->GetConstant(srgData->FindShaderInputConstantIndex(Name{ "m_float" })), 5.5f); + EXPECT_EQ(material->GetPropertyValue(material->FindPropertyIndex(Name{ "MyFloat" })), 5.5f); + + // Make sure the new default value is applied where it was not overridden + EXPECT_EQ(material->GetPropertyValue(material->FindPropertyIndex(Name{ "MyInt" })), -7); + EXPECT_EQ(srgData->GetConstant(srgData->FindShaderInputConstantIndex(Name{ "m_int" })), -7); + } } 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 ec16653540..900dc3535c 100644 --- a/Gems/Atom/Tools/AtomToolsFramework/Code/Include/AtomToolsFramework/Inspector/InspectorRequestBus.h +++ b/Gems/Atom/Tools/AtomToolsFramework/Code/Include/AtomToolsFramework/Inspector/InspectorRequestBus.h @@ -24,6 +24,12 @@ namespace AtomToolsFramework static const AZ::EBusAddressPolicy AddressPolicy = AZ::EBusAddressPolicy::ById; typedef AZ::Uuid BusIdType; + //! Add heading widget above scroll area + virtual void AddHeading(QWidget* headingWidget) = 0; + + //! Clear heading widgets + virtual void ClearHeading() = 0; + //! Clear all inspector groups and content virtual void Reset() = 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 3d4e252967..adcd94ca10 100644 --- a/Gems/Atom/Tools/AtomToolsFramework/Code/Include/AtomToolsFramework/Inspector/InspectorWidget.h +++ b/Gems/Atom/Tools/AtomToolsFramework/Code/Include/AtomToolsFramework/Inspector/InspectorWidget.h @@ -41,6 +41,10 @@ namespace AtomToolsFramework ~InspectorWidget() override; // InspectorRequestBus::Handler overrides... + void AddHeading(QWidget* headingWidget) override; + + void ClearHeading() override; + void Reset() override; void AddGroupsBegin() override; @@ -77,7 +81,6 @@ namespace AtomToolsFramework virtual void OnHeaderClicked(const AZStd::string& groupNameId, QMouseEvent* event); private: - QVBoxLayout* m_layout = nullptr; QScopedPointer m_ui; struct GroupWidgetPair 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 1b718f7710..318a49027a 100644 --- a/Gems/Atom/Tools/AtomToolsFramework/Code/Include/AtomToolsFramework/Viewport/RenderViewportWidget.h +++ b/Gems/Atom/Tools/AtomToolsFramework/Code/Include/AtomToolsFramework/Viewport/RenderViewportWidget.h @@ -159,8 +159,6 @@ namespace AtomToolsFramework AZ::RPI::ViewPtr m_defaultCamera; // Our viewport-local aux geom pipeline for supplemental rendering. AZ::RPI::AuxGeomDrawPtr m_auxGeom; - // Used to keep track of a pending resize event to avoid initialization before window activate. - bool m_windowResizedEvent = false; // Tracks whether the cursor is currently over our viewport, used for mouse input event book-keeping. bool m_mouseOver = false; // The last recorded mouse position, in local viewport screen coordinates. diff --git a/Gems/Atom/Tools/AtomToolsFramework/Code/Source/Inspector/InspectorPropertyGroupWidget.cpp b/Gems/Atom/Tools/AtomToolsFramework/Code/Source/Inspector/InspectorPropertyGroupWidget.cpp index 56f9538452..e1f8573bb3 100644 --- a/Gems/Atom/Tools/AtomToolsFramework/Code/Source/Inspector/InspectorPropertyGroupWidget.cpp +++ b/Gems/Atom/Tools/AtomToolsFramework/Code/Source/Inspector/InspectorPropertyGroupWidget.cpp @@ -38,7 +38,7 @@ namespace AtomToolsFramework m_propertyEditor->Setup(context, instanceNotificationHandler, false); m_propertyEditor->AddInstance(instance, instanceClassId, nullptr, instanceToCompare); m_propertyEditor->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Preferred); - m_propertyEditor->QueueInvalidation(AzToolsFramework::PropertyModificationRefreshLevel::Refresh_EntireTree); + m_propertyEditor->InvalidateAll(); m_layout->addWidget(m_propertyEditor); setLayout(m_layout); diff --git a/Gems/Atom/Tools/AtomToolsFramework/Code/Source/Inspector/InspectorWidget.cpp b/Gems/Atom/Tools/AtomToolsFramework/Code/Source/Inspector/InspectorWidget.cpp index fe3af1d0ef..5eda93ca59 100644 --- a/Gems/Atom/Tools/AtomToolsFramework/Code/Source/Inspector/InspectorWidget.cpp +++ b/Gems/Atom/Tools/AtomToolsFramework/Code/Source/Inspector/InspectorWidget.cpp @@ -29,30 +29,40 @@ namespace AtomToolsFramework { } + void InspectorWidget::AddHeading(QWidget* headingWidget) + { + headingWidget->setParent(m_ui->m_headingSection); + m_ui->m_headingSectionLayout->addWidget(headingWidget); + } + + void InspectorWidget::ClearHeading() + { + qDeleteAll(m_ui->m_headingSection->findChildren(QString(), Qt::FindDirectChildrenOnly)); + qDeleteAll(m_ui->m_headingSectionLayout->children()); + } + void InspectorWidget::Reset() { - qDeleteAll(m_ui->m_propertyContent->children()); - m_layout = new QVBoxLayout(m_ui->m_propertyContent); - m_layout->setContentsMargins(0, 0, 0, 0); - m_layout->setSpacing(0); + qDeleteAll(m_ui->m_groupContents->findChildren(QString(), Qt::FindDirectChildrenOnly)); + qDeleteAll(m_ui->m_groupContentsLayout->children()); m_groups.clear(); } void InspectorWidget::AddGroupsBegin() { - setUpdatesEnabled(false); + setVisible(false); Reset(); } void InspectorWidget::AddGroupsEnd() { - m_layout->addStretch(); + m_ui->m_groupContentsLayout->addStretch(); // Scroll to top whenever there is new content - m_ui->m_propertyScrollArea->verticalScrollBar()->setValue(m_ui->m_propertyScrollArea->verticalScrollBar()->minimum()); + m_ui->m_groupScrollArea->verticalScrollBar()->setValue(m_ui->m_groupScrollArea->verticalScrollBar()->minimum()); - setUpdatesEnabled(true); + setVisible(true); } void InspectorWidget::AddGroup( @@ -61,14 +71,14 @@ namespace AtomToolsFramework const AZStd::string& groupDescription, QWidget* groupWidget) { - InspectorGroupHeaderWidget* groupHeader = new InspectorGroupHeaderWidget(m_ui->m_propertyContent); + InspectorGroupHeaderWidget* groupHeader = new InspectorGroupHeaderWidget(m_ui->m_groupContents); groupHeader->setText(groupDisplayName.c_str()); groupHeader->setToolTip(groupDescription.c_str()); - m_layout->addWidget(groupHeader); + m_ui->m_groupContentsLayout->addWidget(groupHeader); groupWidget->setObjectName(groupNameId.c_str()); - groupWidget->setParent(m_ui->m_propertyContent); - m_layout->addWidget(groupWidget); + groupWidget->setParent(m_ui->m_groupContents); + m_ui->m_groupContentsLayout->addWidget(groupWidget); m_groups[groupNameId] = {groupHeader, groupWidget}; @@ -101,28 +111,18 @@ namespace AtomToolsFramework bool InspectorWidget::IsGroupVisible(const AZStd::string& groupNameId) const { auto groupItr = m_groups.find(groupNameId); - if (groupItr != m_groups.end()) - { - return groupItr->second.m_header->isVisible(); - } - - return false; + return groupItr != m_groups.end() ? groupItr->second.m_header->isVisible() : false; } bool InspectorWidget::IsGroupHidden(const AZStd::string& groupNameId) const { auto groupItr = m_groups.find(groupNameId); - if (groupItr != m_groups.end()) - { - return groupItr->second.m_header->isHidden(); - } - - return false; + return groupItr != m_groups.end() ? groupItr->second.m_header->isHidden() : false; } void InspectorWidget::RefreshGroup(const AZStd::string& groupNameId) { - for (auto groupWidget : m_ui->m_propertyContent->findChildren(groupNameId.c_str())) + for (auto groupWidget : m_ui->m_groupContents->findChildren(groupNameId.c_str())) { groupWidget->Refresh(); } @@ -130,7 +130,7 @@ namespace AtomToolsFramework void InspectorWidget::RebuildGroup(const AZStd::string& groupNameId) { - for (auto groupWidget : m_ui->m_propertyContent->findChildren(groupNameId.c_str())) + for (auto groupWidget : m_ui->m_groupContents->findChildren(groupNameId.c_str())) { groupWidget->Rebuild(); } @@ -138,7 +138,7 @@ namespace AtomToolsFramework void InspectorWidget::RefreshAll() { - for (auto groupWidget : m_ui->m_propertyContent->findChildren()) + for (auto groupWidget : m_ui->m_groupContents->findChildren()) { groupWidget->Refresh(); } @@ -146,7 +146,7 @@ namespace AtomToolsFramework void InspectorWidget::RebuildAll() { - for (auto groupWidget : m_ui->m_propertyContent->findChildren()) + for (auto groupWidget : m_ui->m_groupContents->findChildren()) { groupWidget->Rebuild(); } diff --git a/Gems/Atom/Tools/AtomToolsFramework/Code/Source/Inspector/InspectorWidget.ui b/Gems/Atom/Tools/AtomToolsFramework/Code/Source/Inspector/InspectorWidget.ui index 54976db849..13f9c9e41c 100644 --- a/Gems/Atom/Tools/AtomToolsFramework/Code/Source/Inspector/InspectorWidget.ui +++ b/Gems/Atom/Tools/AtomToolsFramework/Code/Source/Inspector/InspectorWidget.ui @@ -6,20 +6,14 @@ 0 0 - 693 - 798 + 685 + 775 - - - 0 - 0 - - Inspector - + 0 @@ -36,50 +30,103 @@ 0 - - - Qt::ScrollBarAsNeeded - - - true - - - - - 0 - 0 - 691 - 796 - + + + + 0 - - - 0 - - - 0 - - - 0 - - - 0 - - - 0 - - - - - QFrame::StyledPanel + + 0 + + + 0 + + + 0 + + + 0 + + + + + + 0 - - QFrame::Raised + + 0 - - - - + + 0 + + + 0 + + + 0 + + + + + + + + + 0 + + + 0 + + + 0 + + + 0 + + + 0 + + + + + Qt::ScrollBarAsNeeded + + + true + + + + + 0 + 0 + 683 + 763 + + + + + 0 + + + 0 + + + 0 + + + 0 + + + 0 + + + + + + + + + diff --git a/Gems/Atom/Tools/AtomToolsFramework/Code/Source/Viewport/RenderViewportWidget.cpp b/Gems/Atom/Tools/AtomToolsFramework/Code/Source/Viewport/RenderViewportWidget.cpp index 4446e11231..2a15041e20 100644 --- a/Gems/Atom/Tools/AtomToolsFramework/Code/Source/Viewport/RenderViewportWidget.cpp +++ b/Gems/Atom/Tools/AtomToolsFramework/Code/Source/Viewport/RenderViewportWidget.cpp @@ -254,28 +254,11 @@ namespace AtomToolsFramework void RenderViewportWidget::resizeEvent([[maybe_unused]] QResizeEvent* event) { - // We need to wait until the window is activated, so the underlying surface - // has been created and has the correct size. - if (windowHandle()->isActive()) - { - SendWindowResizeEvent(); - } - else - { - m_windowResizedEvent = true; - } + SendWindowResizeEvent(); } bool RenderViewportWidget::event(QEvent* event) { - // Check if we have a pending resize event. - // At this point the surface has been created and has - // the proper dimensions. - if (event->type() == QEvent::WindowActivate && m_windowResizedEvent) - { - SendWindowResizeEvent(); - } - return QWidget::event(event); } @@ -372,7 +355,6 @@ namespace AtomToolsFramework AzFramework::WindowNotificationBus::Event( GetNativeWindowHandle(), &AzFramework::WindowNotifications::OnWindowResized, windowSize.width(), windowSize.height()); - m_windowResizedEvent = false; } void RenderViewportWidget::NotifyUpdateRefreshRate() diff --git a/Gems/Atom/Utils/Code/Include/Atom/Utils/ImGuiCpuProfiler.h b/Gems/Atom/Utils/Code/Include/Atom/Utils/ImGuiCpuProfiler.h index ea4dd20250..a649fcf0f7 100644 --- a/Gems/Atom/Utils/Code/Include/Atom/Utils/ImGuiCpuProfiler.h +++ b/Gems/Atom/Utils/Code/Include/Atom/Utils/ImGuiCpuProfiler.h @@ -174,7 +174,7 @@ namespace AZ AZStd::unordered_map> m_savedData; // Region color cache - AZStd::unordered_map m_regionColorMap; + AZStd::unordered_map m_regionColorMap; // Tracks the frame boundaries AZStd::vector m_frameEndTicks = { INT64_MIN }; diff --git a/Gems/Atom/Utils/Code/Include/Atom/Utils/ImGuiCpuProfiler.inl b/Gems/Atom/Utils/Code/Include/Atom/Utils/ImGuiCpuProfiler.inl index 61f68197b6..a573e3019a 100644 --- a/Gems/Atom/Utils/Code/Include/Atom/Utils/ImGuiCpuProfiler.inl +++ b/Gems/Atom/Utils/Code/Include/Atom/Utils/ImGuiCpuProfiler.inl @@ -124,7 +124,7 @@ namespace AZ m_cpuTimingStatisticsWhenPause = currentCpuTimingStatistics; CollectFrameData(); - CullFrameData(currentCpuTimingStatistics); + CullFrameData(currentCpuTimingStatistics); // Only listen to system ticks when the profiler is active if (!SystemTickBus::Handler::BusIsConnected()) @@ -148,7 +148,7 @@ namespace AZ } } ImGui::End(); - + if (m_captureToFile) { AZStd::sys_time_t timeNow = AZStd::GetTimeNowSecond(); @@ -325,7 +325,7 @@ namespace AZ { const bool ascending = sortSpecs->Specs->SortDirection == ImGuiSortDirection_Ascending; const ImS16 columnToSort = sortSpecs->Specs->ColumnIndex; - + switch (columnToSort) { case (0): // Sort by group name @@ -343,7 +343,7 @@ namespace AZ case (4): // Sort by invocations AZStd::sort(m_tableData.begin(), m_tableData.end(), TableRow::TableRowCompareFunctor(&TableRow::m_invocationsLastFrame, ascending)); break; - case (5): // Sort by total time + case (5): // Sort by total time AZStd::sort(m_tableData.begin(), m_tableData.end(), TableRow::TableRowCompareFunctor(&TableRow::m_lastFrameTotalTicks, ascending)); break; } @@ -401,7 +401,7 @@ namespace AZ } DrawTable(); - } + } } inline void ImGuiCpuProfiler::DrawFilePicker() @@ -460,17 +460,17 @@ namespace AZ const auto [groupRegionNameItr, wasGroupRegionNameInserted] = m_deserializedGroupRegionNamePool.emplace(groupNameItr->c_str(), regionNameItr->c_str()); - const RHI::CachedTimeRegion newRegion(&(*groupRegionNameItr), entry.m_stackDepth, entry.m_startTick, entry.m_endTick); + const RHI::CachedTimeRegion newRegion(*groupRegionNameItr, entry.m_stackDepth, entry.m_startTick, entry.m_endTick); m_savedData[entry.m_threadId].push_back(newRegion); - // Since we don't serialize the frame boundaries, we need to use the RPI's OnSystemTick event as a heuristic. + // Since we don't serialize the frame boundaries, we need to use the RPI's OnSystemTick event as a heuristic. const static Name frameBoundaryName = Name("RPISystem: OnSystemTick"); if (entry.m_regionName == frameBoundaryName) { m_frameEndTicks.push_back(entry.m_endTick); - } + } - // Update running statistics + // Update running statistics if (!m_groupRegionMap[*groupNameItr].contains(*regionNameItr)) { m_groupRegionMap[*groupNameItr][*regionNameItr].m_groupName = *groupNameItr; @@ -487,7 +487,7 @@ namespace AZ // Invariant: each vector in m_savedData must be sorted so that we can efficiently cull region data. for (auto& [threadId, singleThreadData] : m_savedData) { - AZStd::sort(singleThreadData.begin(), singleThreadData.end(), + AZStd::sort(singleThreadData.begin(), singleThreadData.end(), [](const TimeRegion& lhs, const TimeRegion& rhs) { return lhs.m_startTick < rhs.m_startTick; @@ -669,7 +669,7 @@ namespace AZ // Iterate through the entire TimeRegionMap and copy the data since it will get deleted on the next frame for (const auto& [threadId, singleThreadRegionMap] : timeRegionMap) { - const size_t threadIdHashed = AZStd::hash{}(threadId); + const size_t threadIdHashed = AZStd::hash{}(threadId); // The profiler can sometime return threads without any profiling events when dropping threads, FIXME(ATOM-15949) if (singleThreadRegionMap.size() == 0) { @@ -686,7 +686,7 @@ namespace AZ newVisualizerData.push_back(region); // Copies // Also update the statistical view's data - const AZStd::string& groupName = region.m_groupRegionName->m_groupName; + const AZStd::string& groupName = region.m_groupRegionName.m_groupName; if (!m_groupRegionMap[groupName].contains(regionName)) { @@ -765,7 +765,7 @@ namespace AZ inline void ImGuiCpuProfiler::DrawBlock(const TimeRegion& block, u64 targetRow) { // Don't draw anything if the user is searching for regions and this block doesn't pass the filter - if (!m_visualizerHighlightFilter.PassFilter(block.m_groupRegionName->m_regionName)) + if (!m_visualizerHighlightFilter.PassFilter(block.m_groupRegionName.m_regionName)) { return; } @@ -798,7 +798,7 @@ namespace AZ if (regionPixelWidth > maxCharWidth) // We can draw at least one character { const AZStd::string label = - AZStd::string::format("%s/ %s", block.m_groupRegionName->m_groupName, block.m_groupRegionName->m_regionName); + AZStd::string::format("%s/ %s", block.m_groupRegionName.m_groupName, block.m_groupRegionName.m_regionName); const float textWidth = ImGui::CalcTextSize(label.c_str()).x; if (regionPixelWidth < textWidth) // Not enough space in the block to draw the whole name, draw clipped text. @@ -809,7 +809,7 @@ namespace AZ // so we must adjust for the scale manually. const float scaleFactor = ImGui::GetIO().FontGlobalScale; const float fontSize = ImGui::GetFont()->FontSize * scaleFactor; - + ImGui::GetFont()->RenderText(drawList, fontSize, startPoint, IM_COL32_WHITE, clipRect, label.c_str(), 0); } else // We have enough space to draw the entire label, draw and center text. @@ -828,7 +828,7 @@ namespace AZ if (ImGui::IsMouseClicked(ImGuiMouseButton_Left)) { m_enableVisualizer = false; - const auto newFilter = AZStd::string(block.m_groupRegionName->m_regionName); + const auto newFilter = AZStd::string(block.m_groupRegionName.m_regionName); m_timedRegionFilter = ImGuiTextFilter(newFilter.c_str()); m_timedRegionFilter.Build(); } @@ -836,7 +836,7 @@ namespace AZ drawList->AddRect(startPoint, endPoint, ImGui::GetColorU32({ 1, 1, 1, 1 }), 0.0, 0, 1.5); ImGui::BeginTooltip(); - ImGui::Text("%s::%s", block.m_groupRegionName->m_groupName, block.m_groupRegionName->m_regionName); + ImGui::Text("%s::%s", block.m_groupRegionName.m_groupName, block.m_groupRegionName.m_regionName); ImGui::Text("Execution time: %.3f ms", CpuProfilerImGuiHelper::TicksToMs(block.m_endTick - block.m_startTick)); ImGui::Text("Ticks %lld => %lld", block.m_startTick, block.m_endTick); ImGui::EndTooltip(); @@ -846,10 +846,10 @@ namespace AZ inline ImU32 ImGuiCpuProfiler::GetBlockColor(const TimeRegion& block) { // Use the GroupRegionName pointer a key into the cache, equal regions will have equal pointers - const GroupRegionName* key = block.m_groupRegionName; - if (m_regionColorMap.contains(key)) // Cache hit + const GroupRegionName& key = block.m_groupRegionName; + if (auto iter = m_regionColorMap.find(key); iter != m_regionColorMap.end()) // Cache hit { - return ImGui::GetColorU32(m_regionColorMap[key]); + return ImGui::GetColorU32(iter->second); } // Cache miss, generate a new random color diff --git a/Gems/AtomLyIntegration/AtomFont/Code/Include/AtomLyIntegration/AtomFont/FFont.h b/Gems/AtomLyIntegration/AtomFont/Code/Include/AtomLyIntegration/AtomFont/FFont.h index 83f53ffec2..2cc8a67cfa 100644 --- a/Gems/AtomLyIntegration/AtomFont/Code/Include/AtomLyIntegration/AtomFont/FFont.h +++ b/Gems/AtomLyIntegration/AtomFont/Code/Include/AtomLyIntegration/AtomFont/FFont.h @@ -283,7 +283,7 @@ namespace AZ FontTexture* m_fontTexture = nullptr; size_t m_fontBufferSize = 0; - unsigned char* m_fontBuffer = nullptr; + AZStd::unique_ptr m_fontBuffer; AZ::Data::Instance m_fontStreamingImage; AZ::RHI::Ptr m_fontImage; diff --git a/Gems/AtomLyIntegration/AtomFont/Code/Source/FFont.cpp b/Gems/AtomLyIntegration/AtomFont/Code/Source/FFont.cpp index 5e96af0b1b..c5268b427f 100644 --- a/Gems/AtomLyIntegration/AtomFont/Code/Source/FFont.cpp +++ b/Gems/AtomLyIntegration/AtomFont/Code/Source/FFont.cpp @@ -13,8 +13,6 @@ #if !defined(USE_NULLFONT_ALWAYS) -#include - #include #include #include @@ -124,17 +122,10 @@ bool AZ::FFont::Load(const char* fontFilePath, unsigned int width, unsigned int Free(); - auto pPak = gEnv->pCryPak; + auto fileIoBase = AZ::IO::FileIOBase::GetInstance(); - AZStd::string fullFile; - if (pPak->IsAbsPath(fontFilePath)) - { - fullFile = fontFilePath; - } - else - { - fullFile = m_curPath + fontFilePath; - } + AZ::IO::Path fullFile(m_curPath); + fullFile /= fontFilePath; int smoothMethodFlag = (flags & TTFFLAG_SMOOTH_MASK) >> TTFFLAG_SMOOTH_SHIFT; AZ::FontSmoothMethod smoothMethod = AZ::FontSmoothMethod::None; @@ -161,42 +152,41 @@ bool AZ::FFont::Load(const char* fontFilePath, unsigned int width, unsigned int } - AZ::IO::HandleType fileHandle = pPak->FOpen(fullFile.c_str(), "rb"); + AZ::IO::HandleType fileHandle = AZ::IO::InvalidHandle; + fileIoBase->Open(fullFile.c_str(), AZ::IO::GetOpenModeFromStringMode("rb"), fileHandle); if (fileHandle == AZ::IO::InvalidHandle) { return false; } - size_t fileSize = pPak->FGetSize(fileHandle); + AZ::u64 fileSize{}; + fileIoBase->Size(fileHandle, fileSize); if (!fileSize) { - pPak->FClose(fileHandle); + fileIoBase->Close(fileHandle); return false; } - unsigned char* buffer = new unsigned char[fileSize]; - if (!pPak->FReadRaw(buffer, fileSize, 1, fileHandle)) + auto buffer = AZStd::make_unique(fileSize); + if (!fileIoBase->Read(fileHandle, buffer.get(), fileSize)) { - pPak->FClose(fileHandle); - delete [] buffer; + fileIoBase->Close(fileHandle); return false; } - pPak->FClose(fileHandle); + fileIoBase->Close(fileHandle); if (!m_fontTexture) { m_fontTexture = new FontTexture(); } - - if (!m_fontTexture || !m_fontTexture->CreateFromMemory(buffer, (int)fileSize, width, height, smoothMethod, smoothAmount, widthNumSlots, heightNumSlots, sizeRatio)) + if (!m_fontTexture || !m_fontTexture->CreateFromMemory(buffer.get(), (int)fileSize, width, height, smoothMethod, smoothAmount, widthNumSlots, heightNumSlots, sizeRatio)) { - delete [] buffer; return false; } m_monospacedFont = m_fontTexture->GetMonospaced(); - m_fontBuffer = buffer; + m_fontBuffer = AZStd::move(buffer); m_fontBufferSize = fileSize; m_fontTexDirty = false; m_sizeRatio = sizeRatio; @@ -213,10 +203,9 @@ void AZ::FFont::Free() m_fontImageVersion = 0; delete m_fontTexture; - m_fontTexture = 0; + m_fontTexture = nullptr; - delete[] m_fontBuffer; - m_fontBuffer = 0; + m_fontBuffer.reset(); m_fontBufferSize = 0; } diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/CMakeLists.txt b/Gems/AtomLyIntegration/CommonFeatures/Code/CMakeLists.txt index df5ab134fa..e68681315e 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/CMakeLists.txt +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/CMakeLists.txt @@ -109,12 +109,14 @@ if(PAL_TRAIT_BUILD_HOST_TOOLS) RUNTIME_DEPENDENCIES Gem::Atom_RPI.Editor Gem::Atom_Feature_Common.Editor + Legacy::EditorCommon ) # The AtomLyIntegration_CommonFeatures.Editor module is used for Builders and Tools ly_create_alias(NAME AtomLyIntegration_CommonFeatures.Builders NAMESPACE Gem TARGETS Gem::AtomLyIntegration_CommonFeatures.Editor + Gem::Atom_Feature_Common.Builders Gem::Atom_RPI.Builders Gem::GradientSignal.Builders ) diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Include/AtomLyIntegration/CommonFeatures/Material/EditorMaterialSystemComponentRequestBus.h b/Gems/AtomLyIntegration/CommonFeatures/Code/Include/AtomLyIntegration/CommonFeatures/Material/EditorMaterialSystemComponentRequestBus.h index c75d596b52..47fad038b6 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Include/AtomLyIntegration/CommonFeatures/Material/EditorMaterialSystemComponentRequestBus.h +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Include/AtomLyIntegration/CommonFeatures/Material/EditorMaterialSystemComponentRequestBus.h @@ -7,6 +7,8 @@ */ #pragma once +#include +#include #include #include @@ -23,8 +25,12 @@ namespace AZ static const AZ::EBusAddressPolicy AddressPolicy = AZ::EBusAddressPolicy::Single; static const AZ::EBusHandlerPolicy HandlerPolicy = AZ::EBusHandlerPolicy::Single; - //! Open document in material editor - virtual void OpenInMaterialEditor(const AZStd::string& sourcePath) = 0; + //! Open source material in material editor + virtual void OpenMaterialEditor(const AZStd::string& sourcePath) = 0; + + //! Open material instance editor + virtual void OpenMaterialInspector( + const AZ::EntityId& entityId, const AZ::Render::MaterialAssignmentId& materialAssignmentId) = 0; }; using EditorMaterialSystemComponentRequestBus = AZ::EBus; } // namespace Render diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Include/AtomLyIntegration/CommonFeatures/Material/MaterialComponentBus.h b/Gems/AtomLyIntegration/CommonFeatures/Code/Include/AtomLyIntegration/CommonFeatures/Material/MaterialComponentBus.h index 1ed8469749..ace16ba6ca 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Include/AtomLyIntegration/CommonFeatures/Material/MaterialComponentBus.h +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Include/AtomLyIntegration/CommonFeatures/Material/MaterialComponentBus.h @@ -23,12 +23,26 @@ namespace AZ virtual MaterialAssignmentMap GetOriginalMaterialAssignments() const = 0; //! Get material assignment id matching lod and label substring virtual MaterialAssignmentId FindMaterialAssignmentId(const MaterialAssignmentLodIndex lod, const AZStd::string& label) const = 0; + //! Get default material asset + virtual AZ::Data::AssetId GetDefaultMaterialAssetId(const MaterialAssignmentId& materialAssignmentId) const = 0; + //! Get material slot label + virtual AZStd::string GetMaterialSlotLabel(const MaterialAssignmentId& materialAssignmentId) const = 0; //! Set material overrides virtual void SetMaterialOverrides(const MaterialAssignmentMap& materials) = 0; //! Get material overrides virtual const MaterialAssignmentMap& GetMaterialOverrides() const = 0; //! Clear all material overrides virtual void ClearAllMaterialOverrides() = 0; + //! Clear non-lod material overrides + virtual void ClearModelMaterialOverrides() = 0; + //! Clear lod material overrides + virtual void ClearLodMaterialOverrides() = 0; + //! Clear residual materials that don't correspond to the associated model + virtual void ClearIncompatibleMaterialOverrides() = 0; + //! Clear materials that reference missing assets + virtual void ClearInvalidMaterialOverrides() = 0; + //! Repair materials that reference missing assets by assigning the default asset + virtual void RepairInvalidMaterialOverrides() = 0; //! Set default material override virtual void SetDefaultMaterialOverride(const AZ::Data::AssetId& materialAssetId) = 0; //! Get default material override @@ -38,7 +52,7 @@ namespace AZ //! Set material override virtual void SetMaterialOverride(const MaterialAssignmentId& materialAssignmentId, const AZ::Data::AssetId& materialAssetId) = 0; //! Get material override - virtual const AZ::Data::AssetId GetMaterialOverride(const MaterialAssignmentId& materialAssignmentId) const = 0; + virtual AZ::Data::AssetId GetMaterialOverride(const MaterialAssignmentId& materialAssignmentId) const = 0; //! Clear material override virtual void ClearMaterialOverride(const MaterialAssignmentId& materialAssignmentId) = 0; //! Set a material property override value wrapped by an AZStd::any @@ -95,8 +109,16 @@ namespace AZ virtual void ClearPropertyOverrides(const MaterialAssignmentId& materialAssignmentId) = 0; //! Clear all property overrides virtual void ClearAllPropertyOverrides() = 0; + //! Set Property overrides for a specific material assignment + virtual void SetPropertyOverrides( + const MaterialAssignmentId& materialAssignmentId, const MaterialPropertyOverrideMap& propertyOverrides) = 0; //! Get Property overrides for a specific material assignment virtual MaterialPropertyOverrideMap GetPropertyOverrides(const MaterialAssignmentId& materialAssignmentId) const = 0; + //! Set Model UV overrides for a specific material assignment + virtual void SetModelUvOverrides( + const MaterialAssignmentId& materialAssignmentId, const AZ::RPI::MaterialModelUvOverrideMap& modelUvOverrides) = 0; + //! Get Model UV overrides for a specific material assignment + virtual AZ::RPI::MaterialModelUvOverrideMap GetModelUvOverrides(const MaterialAssignmentId& materialAssignmentId) const = 0; }; using MaterialComponentRequestBus = EBus; @@ -106,8 +128,8 @@ namespace AZ { public: - //! This message is sent every time a material property is updated. - virtual void OnMaterialsEdited([[maybe_unused]] const MaterialAssignmentMap& materials) {} + //! This message is sent every time a material or property update affects UI. + virtual void OnMaterialsEdited() {} //! This message is sent when one or more material property changes have been applied, at most once per frame. virtual void OnMaterialsUpdated([[maybe_unused]] const MaterialAssignmentMap& materials) {} diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Include/AtomLyIntegration/CommonFeatures/PostProcess/ColorGrading/HDRColorGradingBus.h b/Gems/AtomLyIntegration/CommonFeatures/Code/Include/AtomLyIntegration/CommonFeatures/PostProcess/ColorGrading/HDRColorGradingBus.h new file mode 100644 index 0000000000..32b1c97429 --- /dev/null +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Include/AtomLyIntegration/CommonFeatures/PostProcess/ColorGrading/HDRColorGradingBus.h @@ -0,0 +1,34 @@ +/* + * Copyright (c) Contributors to the Open 3D Engine Project. + * For complete copyright and license terms please see the LICENSE at the root of this distribution. + * + * SPDX-License-Identifier: Apache-2.0 OR MIT + * + */ + +#pragma once + +#include + +namespace AZ +{ + namespace Render + { + class HDRColorGradingRequests + : public ComponentBus + { + public: + AZ_RTTI(AZ::Render::HDRColorGradingRequests, "{E414A96B-0AA7-4574-ABC0-968B1F5CEE56}"); + + /// Overrides the default AZ::EBusTraits handler policy to allow one listener only. + static const EBusHandlerPolicy HandlerPolicy = EBusHandlerPolicy::Single; + virtual ~HDRColorGradingRequests() {} + // Auto-gen virtual getters/setters... +#include +#include +#include + }; + + typedef AZ::EBus HDRColorGradingRequestBus; + } // namespace Render +} // namespace AZ diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Include/AtomLyIntegration/CommonFeatures/PostProcess/ColorGrading/HDRColorGradingComponentConfig.h b/Gems/AtomLyIntegration/CommonFeatures/Code/Include/AtomLyIntegration/CommonFeatures/PostProcess/ColorGrading/HDRColorGradingComponentConfig.h new file mode 100644 index 0000000000..fe7bc874a4 --- /dev/null +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Include/AtomLyIntegration/CommonFeatures/PostProcess/ColorGrading/HDRColorGradingComponentConfig.h @@ -0,0 +1,39 @@ +/* + * Copyright (c) Contributors to the Open 3D Engine Project. + * For complete copyright and license terms please see the LICENSE at the root of this distribution. + * + * SPDX-License-Identifier: Apache-2.0 OR MIT + * + */ + +#pragma once + +#include +#include + +namespace AZ +{ + namespace Render + { + class HDRColorGradingComponentConfig final + : public ComponentConfig + { + public: + AZ_RTTI(AZ::Render::HDRColorGradingComponentConfig, "{8613EA4A-6E1C-49AD-87F3-9FECCB7EA36D}", AZ::ComponentConfig); + + static void Reflect(ReflectContext* context); + + // Generate members... +#include +#include +#include + + // Generate Getters/Setters... +#include +#include +#include + + void CopySettingsTo(HDRColorGradingSettingsInterface* settings); + }; + } // namespace Render +} // namespace AZ diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Decals/EditorDecalComponent.cpp b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Decals/EditorDecalComponent.cpp index c10e7e2e30..c5d61dd54a 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Decals/EditorDecalComponent.cpp +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Decals/EditorDecalComponent.cpp @@ -32,7 +32,7 @@ namespace AZ if (AZ::EditContext* editContext = serializeContext->GetEditContext()) { editContext->Class( - "Decal (Atom)", "The Decal component allows an entity to project a texture or material onto a mesh") + "Decal", "The Decal component allows an entity to project a texture or material onto a mesh") ->ClassElement(AZ::Edit::ClassElements::EditorData, "") ->Attribute(AZ::Edit::Attributes::Category, "Atom") ->Attribute(AZ::Edit::Attributes::Icon, "Icons/Components/Decal.svg") @@ -97,13 +97,25 @@ namespace AZ BaseClass::Deactivate(); } - AZ::Transform EditorDecalComponent::GetTransform() const + AZ::Transform EditorDecalComponent::GetWorldTransform() const { AZ::Transform transform = AZ::Transform::CreateIdentity(); AZ::TransformBus::EventResult(transform, GetEntityId(), &AZ::TransformBus::Events::GetWorldTM); return transform; } + AZ::Matrix3x4 EditorDecalComponent::GetWorldTransformWithNonUniformScale() const + { + const AZ::Transform worldTransform = GetWorldTransform(); + const AZ::Matrix3x3 rotationMat = AZ::Matrix3x3::CreateFromQuaternion(worldTransform.GetRotation()); + + const AZ::Vector3 nonUniformScale = m_controller.m_cachedNonUniformScale * worldTransform.GetUniformScale(); + const AZ::Matrix3x3 nonUniformScaleMat = AZ::Matrix3x3::CreateScale(nonUniformScale); + const AZ::Matrix3x3 rotationAndScale = rotationMat * nonUniformScaleMat; + + return AZ::Matrix3x4::CreateFromMatrix3x3AndTranslation(rotationAndScale, worldTransform.GetTranslation()); + } + void EditorDecalComponent::DisplayEntityViewport( [[maybe_unused]] const AzFramework::ViewportInfo& viewportInfo, AzFramework::DebugDisplayRequests& debugDisplay) @@ -113,11 +125,9 @@ namespace AZ return; } - AZ::Transform transform = GetTransform(); - - debugDisplay.SetColor(AZ::Colors::Red); - debugDisplay.PushMatrix(transform); + const AZ::Matrix3x4 transform = GetWorldTransformWithNonUniformScale(); + debugDisplay.PushPremultipliedMatrix(transform); debugDisplay.DrawWireBox(-AZ::Vector3::CreateOne(), AZ::Vector3::CreateOne()); AZ::Vector3 x1 = AZ::Vector3(-1, 0, 1); @@ -136,7 +146,7 @@ namespace AZ // Two diagonal edges debugDisplay.DrawLine(p0, p2); debugDisplay.DrawLine(p1, p3); - debugDisplay.PopMatrix(); + debugDisplay.PopPremultipliedMatrix(); } AZ::Aabb EditorDecalComponent::GetEditorSelectionBoundsViewport([[maybe_unused]] const AzFramework::ViewportInfo& viewportInfo) diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Decals/EditorDecalComponent.h b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Decals/EditorDecalComponent.h index f0748dfef5..1ca88d23fc 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Decals/EditorDecalComponent.h +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Decals/EditorDecalComponent.h @@ -56,7 +56,11 @@ namespace AZ private: - AZ::Transform GetTransform() const; + // Returns the component transform which includes uniform-scale, rotation and translation + AZ::Transform GetWorldTransform() const; + + // Returns the full transform, including both the uniform scale and non-uniform scale along with rotation and translation + AZ::Matrix3x4 GetWorldTransformWithNonUniformScale() const; //! EditorRenderComponentAdapter overrides ... u32 OnConfigurationChanged() override; diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Material/EditorMaterialComponent.cpp b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Material/EditorMaterialComponent.cpp index 4249ed0c3b..b7bf191bc9 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Material/EditorMaterialComponent.cpp +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Material/EditorMaterialComponent.cpp @@ -32,9 +32,6 @@ namespace AZ const char* EditorMaterialComponent::GenerateMaterialsButtonText = "Generate/Manage Source Materials..."; const char* EditorMaterialComponent::GenerateMaterialsToolTipText = "Generate editable source material files from materials provided by the model."; - const char* EditorMaterialComponent::ResetMaterialsButtonText = "Reset Materials"; - const char* EditorMaterialComponent::ResetMaterialsToolTipText = "Clear all settings, materials, and properties then rebuild material slots from the associated model."; - // Update serialized data to the new format and data types bool EditorMaterialComponent::ConvertVersion(AZ::SerializeContext& context, AZ::SerializeContext::DataElementNode& classElement) { @@ -178,86 +175,81 @@ namespace AZ menu->addSeparator(); - action = menu->addAction(ResetMaterialsButtonText, [this]() { ResetMaterialSlots(); }); - action->setToolTip(ResetMaterialsToolTipText); + action = menu->addAction("Clear All Materials", [this]() { + AzToolsFramework::ScopedUndoBatch undoBatch("Clearing all materials."); + SetDirty(); - menu->addSeparator(); + MaterialComponentRequestBus::Event(GetEntityId(), &MaterialComponentRequestBus::Events::ClearAllMaterialOverrides); + + m_materialSlotsByLodEnabled = false; + + UpdateMaterialSlots(); + }); + action->setToolTip("Clear all materials and properties then rebuild material slots from the associated model."); action = menu->addAction("Clear Model Materials", [this]() { AzToolsFramework::ScopedUndoBatch undoBatch("Clearing model materials."); SetDirty(); - for (auto& materialSlotPair : GetMaterialSlots()) - { - EditorMaterialComponentSlot* materialSlot = materialSlotPair.second; - if (materialSlot->m_id.IsSlotIdOnly()) - { - materialSlot->Clear(); - } - } - }); + MaterialComponentRequestBus::Event(GetEntityId(), &MaterialComponentRequestBus::Events::ClearModelMaterialOverrides); + + UpdateMaterialSlots(); + }); + action->setToolTip("Clear model materials and properties then rebuild material slots from the associated model."); + action = menu->addAction("Clear LOD Materials", [this]() { AzToolsFramework::ScopedUndoBatch undoBatch("Clearing LOD materials."); SetDirty(); - for (auto& materialSlotPair : GetMaterialSlots()) - { - EditorMaterialComponentSlot* materialSlot = materialSlotPair.second; - if (materialSlot->m_id.IsLodAndSlotId()) - { - materialSlot->Clear(); - } - } - }); - action->setEnabled(m_materialSlotsByLodEnabled); + MaterialComponentRequestBus::Event(GetEntityId(), &MaterialComponentRequestBus::Events::ClearLodMaterialOverrides); + + m_materialSlotsByLodEnabled = false; + + UpdateMaterialSlots(); + }); + action->setToolTip("Clear LOD materials and properties then rebuild material slots from the associated model."); + + action = menu->addAction("Clear Incompatible Materials", [this]() { + AzToolsFramework::ScopedUndoBatch undoBatch("Clearing incompatible materials."); + SetDirty(); + + MaterialComponentRequestBus::Event(GetEntityId(), &MaterialComponentRequestBus::Events::ClearIncompatibleMaterialOverrides); + + UpdateMaterialSlots(); + }); + action->setToolTip("Clear residual materials that don't correspond to the associated model."); + + action = menu->addAction("Clear Invalid Materials", [this]() { + AzToolsFramework::ScopedUndoBatch undoBatch("Clearing invalid materials."); + SetDirty(); + + MaterialComponentRequestBus::Event(GetEntityId(), &MaterialComponentRequestBus::Events::ClearInvalidMaterialOverrides); + + UpdateMaterialSlots(); + }); + action->setToolTip("Clear materials that reference missing assets."); + + action = menu->addAction("Repair Invalid Materials", [this]() { + AzToolsFramework::ScopedUndoBatch undoBatch("Repairing invalid materials."); + SetDirty(); + + MaterialComponentRequestBus::Event(GetEntityId(), &MaterialComponentRequestBus::Events::RepairInvalidMaterialOverrides); + + UpdateMaterialSlots(); + }); + action->setToolTip("Repair materials that reference missing assets by assigning the default asset."); } void EditorMaterialComponent::SetPrimaryAsset(const AZ::Data::AssetId& assetId) { - m_controller.SetDefaultMaterialOverride(assetId); - } + MaterialComponentRequestBus::Event(GetEntityId(), &MaterialComponentRequestBus::Events::SetDefaultMaterialOverride, assetId); - AZ::u32 EditorMaterialComponent::OnConfigurationChanged() - { - // Whenever the user makes changes to the editor component data the controller configuration must be rebuilt - m_configurationChangeInProgress = true; - UpdateController(); - m_configurationChangeInProgress = false; - - return AZ::Edit::PropertyRefreshLevels::AttributesAndValues; - } - - void EditorMaterialComponent::OnMaterialAssignmentsChanged() - { - // [GFX TODO][ATOM-4604] remove flag after mesh component material handling is fixed to not recreate/reload mesh for material changes - if (!m_configurationChangeInProgress) - { - UpdateMaterialSlots(); - } - } - - void EditorMaterialComponent::OnMaterialsEdited(const MaterialAssignmentMap& materials) - { - AzToolsFramework::ScopedUndoBatch undoBatch("Materials edited."); - SetDirty(); - - // The layout of the materials slots is already set. - // We just need to read the values from any edited overrides into the editor component - // and refresh. - for (auto& materialSlotPair : GetMaterialSlots()) - { - EditorMaterialComponentSlot& slot = *materialSlotPair.second; - const MaterialAssignment& materialFromController = GetMaterialAssignmentFromMap(materials, slot.m_id); - slot.m_materialAsset = materialFromController.m_materialAsset; - slot.m_propertyOverrides = materialFromController.m_propertyOverrides; - slot.m_matModUvOverrides = materialFromController.m_matModUvOverrides; - } + MaterialComponentNotificationBus::Event(GetEntityId(), &MaterialComponentNotifications::OnMaterialsEdited); AzToolsFramework::ToolsApplicationEvents::Bus::Broadcast( - &AzToolsFramework::ToolsApplicationEvents::InvalidatePropertyDisplay, - AzToolsFramework::Refresh_AttributesAndValues); + &AzToolsFramework::ToolsApplicationEvents::InvalidatePropertyDisplay, AzToolsFramework::Refresh_AttributesAndValues); } - + void EditorMaterialComponent::OnMaterialInstanceCreated(const MaterialAssignment& materialAssignment) { // PSO-impacting property changes are allowed in the editor @@ -268,48 +260,14 @@ namespace AZ } } - void EditorMaterialComponent::UpdateConfiguration(const MaterialComponentConfig& config) + AZ::u32 EditorMaterialComponent::OnConfigurationChanged() { - m_controller.SetMaterialOverrides(config.m_materials); + return AZ::Edit::PropertyRefreshLevels::AttributesAndValues; } - void EditorMaterialComponent::UpdateController() + void EditorMaterialComponent::OnMaterialAssignmentsChanged() { - SetDirty(); - - // Build the controller configuration from the editor configuration - MaterialComponentConfig config = m_controller.GetConfiguration(); - config.m_materials.clear(); - - for (const auto& materialSlotPair : GetMaterialSlots()) - { - const EditorMaterialComponentSlot* materialSlot = materialSlotPair.second; - - // Do not apply materials for lods if they are disabled - if (materialSlot->m_id.m_lodIndex != MaterialAssignmentId::NonLodIndex && !m_materialSlotsByLodEnabled) - { - continue; - } - - MaterialAssignment& materialAssignment = config.m_materials[materialSlot->m_id]; - - // Only material slots with a valid asset IDs or property overrides will be copied - // to minimize the amount of data stored in the controller and game component - if (materialSlot->m_materialAsset.GetId().IsValid()) - { - materialAssignment.m_materialAsset = materialSlot->m_materialAsset; - materialAssignment.m_propertyOverrides = materialSlot->m_propertyOverrides; - materialAssignment.m_matModUvOverrides = materialSlot->m_matModUvOverrides; - } - else if (!materialSlot->m_propertyOverrides.empty() || !materialSlot->m_matModUvOverrides.empty()) - { - materialAssignment.m_materialAsset = materialSlot->m_defaultMaterialAsset; - materialAssignment.m_propertyOverrides = materialSlot->m_propertyOverrides; - materialAssignment.m_matModUvOverrides = materialSlot->m_matModUvOverrides; - } - } - - UpdateConfiguration(config); + UpdateMaterialSlots(); } void EditorMaterialComponent::UpdateMaterialSlots() @@ -319,70 +277,28 @@ namespace AZ m_materialSlots = {}; m_materialSlotsByLod = {}; - const MaterialComponentConfig& config = m_controller.GetConfiguration(); + // Get current material assignments + MaterialAssignmentMap currentMaterials; + MaterialComponentRequestBus::EventResult( + currentMaterials, GetEntityId(), &MaterialComponentRequestBus::Events::GetMaterialOverrides); // Get the known material assignment slots from the associated model or other source - MaterialAssignmentMap materialsFromSource; - MaterialReceiverRequestBus::EventResult(materialsFromSource, GetEntityId(), &MaterialReceiverRequestBus::Events::GetMaterialAssignments); + MaterialAssignmentMap originalMaterials; + MaterialComponentRequestBus::EventResult( + originalMaterials, GetEntityId(), &MaterialComponentRequestBus::Events::GetOriginalMaterialAssignments); - RPI::ModelMaterialSlotMap modelMaterialSlots; - MaterialReceiverRequestBus::EventResult(modelMaterialSlots, GetEntityId(), &MaterialReceiverRequestBus::Events::GetModelMaterialSlots); - // Generate the table of editable materials using the source data to define number of groups, elements, and initial values - for (const auto& materialPair : materialsFromSource) + for (const auto& materialPair : originalMaterials) { // Setup the material slot entry EditorMaterialComponentSlot slot; + slot.m_entityId = GetEntityId(); slot.m_id = materialPair.first; - slot.m_materialChangedCallback = [this]() { - // This callback is triggered whenever an individual material slot changes outside of normal inspector interactions - // So we must manually handle undo, update configuration, and refresh the inspector to display the new values - AzToolsFramework::ScopedUndoBatch undoBatch("Material slot changed."); - SetDirty(); - - OnConfigurationChanged(); - - AzToolsFramework::ToolsApplicationEvents::Bus::Broadcast( - &AzToolsFramework::ToolsApplicationEvents::InvalidatePropertyDisplay, - AzToolsFramework::Refresh_AttributesAndValues); - }; - slot.m_propertyChangedCallback = [this]() { - OnConfigurationChanged(); - }; - - const char* UnknownSlotName = ""; - - // If this is the default material assignment ID then it represents the default slot which is not contained in any other group - if (slot.m_id == DefaultMaterialAssignmentId) - { - slot.m_label = "Default Material"; - } - else - { - auto slotIter = modelMaterialSlots.find(slot.m_id.m_materialSlotStableId); - if (slotIter != modelMaterialSlots.end()) - { - const Name& displayName = slotIter->second.m_displayName; - slot.m_label = !displayName.IsEmpty() ? displayName.GetStringView() : UnknownSlotName; - - slot.m_defaultMaterialAsset = slotIter->second.m_defaultMaterialAsset; - } - else - { - slot.m_label = UnknownSlotName; - } - } // if material is present in controller configuration, assign its data - const MaterialAssignment& materialFromController = GetMaterialAssignmentFromMap(config.m_materials, slot.m_id); + const MaterialAssignment& materialFromController = GetMaterialAssignmentFromMap(currentMaterials, slot.m_id); slot.m_materialAsset = materialFromController.m_materialAsset; - slot.m_propertyOverrides = materialFromController.m_propertyOverrides; - slot.m_matModUvOverrides = materialFromController.m_matModUvOverrides; - - // Attempt to get the UV names from model meshes. - MaterialReceiverRequestBus::EventResult(slot.m_modelUvNames, GetEntityId(), &MaterialReceiverRequestBus::Events::GetModelUvNames); - if (slot.m_id.IsDefault()) { m_defaultMaterialSlot = slot; @@ -398,13 +314,14 @@ namespace AZ if (slot.m_id.IsLodAndSlotId()) { // Resize the containers to fit all elements - m_materialSlotsByLod.resize(AZ::GetMax(m_materialSlotsByLod.size(), aznumeric_cast(slot.m_id.m_lodIndex + 1))); + m_materialSlotsByLod.resize( + AZ::GetMax(m_materialSlotsByLod.size(), aznumeric_cast(slot.m_id.m_lodIndex + 1))); m_materialSlotsByLod[slot.m_id.m_lodIndex].push_back(slot); continue; } } - // Sort all of the slots by label to ensure stable index values (materialsFromSource is an unordered map) + // Sort all of the slots by label to ensure stable index values (originalMaterials is an unordered map) AZStd::sort(m_materialSlots.begin(), m_materialSlots.end(), [](const auto& a, const auto& b) { return a.GetLabel() < b.GetLabel(); }); @@ -414,54 +331,42 @@ namespace AZ [](const auto& a, const auto& b) { return a.GetLabel() < b.GetLabel(); }); } + MaterialComponentNotificationBus::Event(GetEntityId(), &MaterialComponentNotifications::OnMaterialsEdited); + AzToolsFramework::ToolsApplicationEvents::Bus::Broadcast( - &AzToolsFramework::ToolsApplicationEvents::InvalidatePropertyDisplay, - AzToolsFramework::Refresh_EntireTree); - } - - AZ::u32 EditorMaterialComponent::ResetMaterialSlots() - { - AzToolsFramework::ScopedUndoBatch undoBatch("Resetting materials."); - SetDirty(); - - UpdateConfiguration(MaterialComponentConfig()); - UpdateMaterialSlots(); - - m_materialSlotsByLodEnabled = false; - - // Forcing refresh in case triggered from context menu action - AzToolsFramework::ToolsApplicationEvents::Bus::Broadcast( - &AzToolsFramework::ToolsApplicationEvents::InvalidatePropertyDisplay, - AzToolsFramework::Refresh_EntireTree); - - return AZ::Edit::PropertyRefreshLevels::EntireTree; + &AzToolsFramework::ToolsApplicationEvents::InvalidatePropertyDisplay, AzToolsFramework::Refresh_EntireTree); } AZ::u32 EditorMaterialComponent::OpenMaterialExporter() { AzToolsFramework::ScopedUndoBatch undoBatch("Generating materials."); SetDirty(); - - // First generating a unique set of all material asset IDs that will be used for source data generation - AZStd::unordered_map assetIdMap; - auto materialSlots = GetMaterialSlots(); - for (auto& materialSlotPair : materialSlots) + MaterialAssignmentMap originalMaterials; + MaterialComponentRequestBus::EventResult( + originalMaterials, GetEntityId(), &MaterialComponentRequestBus::Events::GetOriginalMaterialAssignments); + + // Generate a unique set of all material asset IDs that will be used for source data generation + AZStd::unordered_map assetIdToSlotNameMap; + for (const auto& materialPair : originalMaterials) { - Data::AssetId defaultMaterialAssetId = materialSlotPair.second->m_defaultMaterialAsset.GetId(); - if (defaultMaterialAssetId.IsValid()) + const Data::AssetId originalAssetId = materialPair.second.m_materialAsset.GetId(); + if (originalAssetId.IsValid()) { - assetIdMap[defaultMaterialAssetId] = materialSlotPair.second->GetLabel(); + MaterialComponentRequestBus::EventResult( + assetIdToSlotNameMap[originalAssetId], GetEntityId(), &MaterialComponentRequestBus::Events::GetMaterialSlotLabel, + materialPair.first); } } - // Convert the unique set of asset IDs into export items that can be configured in the dialog + // Convert the unique set of asset IDs into export items that can be configured in the dialog // The order should not matter because the table in the dialog can sort itself for a specific row EditorMaterialComponentExporter::ExportItemsContainer exportItems; - for (auto assetIdInfo : assetIdMap) + exportItems.reserve(assetIdToSlotNameMap.size()); + + for (const auto& [assetId, slotName] : assetIdToSlotNameMap) { - EditorMaterialComponentExporter::ExportItem exportItem{assetIdInfo.first, assetIdInfo.second}; - exportItems.push_back(exportItem); + exportItems.emplace_back(assetId, slotName); } // Display the export dialog so that the user can configure how they want different materials to be exported @@ -477,16 +382,17 @@ namespace AZ const auto& assetIdOutcome = AZ::RPI::AssetUtils::MakeAssetId(exportItem.GetExportPath(), 0); if (assetIdOutcome) { - for (auto& materialSlotPair : materialSlots) + for (const auto& materialPair : originalMaterials) { - EditorMaterialComponentSlot* editorMaterialSlot = materialSlotPair.second; - - if (editorMaterialSlot) + // We need to check whether replaced material corresponds to this slot's default material. + const Data::AssetId originalAssetId = materialPair.second.m_materialAsset.GetId(); + if (originalAssetId == exportItem.GetOriginalAssetId()) { - // We need to check whether replaced material corresponds to this slot's default material. - if (editorMaterialSlot->m_defaultMaterialAsset.GetId() == exportItem.GetOriginalAssetId()) + if (m_materialSlotsByLodEnabled || !materialPair.first.IsLodAndSlotId()) { - editorMaterialSlot->m_materialAsset.Create(assetIdOutcome.GetValue()); + MaterialComponentRequestBus::Event( + GetEntityId(), &MaterialComponentRequestBus::Events::SetMaterialOverride, materialPair.first, + assetIdOutcome.GetValue()); } } } @@ -494,17 +400,23 @@ namespace AZ } } - // Forcing refresh in case triggered from context menu action - AzToolsFramework::ToolsApplicationEvents::Bus::Broadcast( - &AzToolsFramework::ToolsApplicationEvents::InvalidatePropertyDisplay, - AzToolsFramework::Refresh_AttributesAndValues); + UpdateMaterialSlots(); - return OnConfigurationChanged(); + return AZ::Edit::PropertyRefreshLevels::EntireTree; } AZ::u32 EditorMaterialComponent::OnLodsToggled() { - OnConfigurationChanged(); + AzToolsFramework::ScopedUndoBatch undoBatch("Toggling LOD materials."); + SetDirty(); + + if (!m_materialSlotsByLodEnabled) + { + MaterialComponentRequestBus::Event(GetEntityId(), &MaterialComponentRequestBus::Events::ClearLodMaterialOverrides); + } + + UpdateMaterialSlots(); + return AZ::Edit::PropertyRefreshLevels::EntireTree; } @@ -540,39 +452,5 @@ namespace AZ { return AZStd::string::format("LOD %d", lodIndex); } - - template - void EditorMaterialComponent::BuildMaterialSlotMap(ComponentType& component, ContainerType& materialSlots) - { - materialSlots[DefaultMaterialAssignmentId] = &component.m_defaultMaterialSlot; - - for (auto& slot : component.m_materialSlots) - { - materialSlots[slot.m_id] = &slot; - } - - for (auto& slotsForLod : component.m_materialSlotsByLod) - { - for (auto& slot : slotsForLod) - { - materialSlots[slot.m_id] = &slot; - } - } - } - - AZStd::unordered_map EditorMaterialComponent::GetMaterialSlots() - { - AZStd::unordered_map materialSlots; - BuildMaterialSlotMap(*this, materialSlots); - return AZStd::move(materialSlots); - } - - AZStd::unordered_map EditorMaterialComponent::GetMaterialSlots() const - { - AZStd::unordered_map materialSlots; - BuildMaterialSlotMap(*this, materialSlots); - return AZStd::move(materialSlots); - } } // namespace Render } // namespace AZ - diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Material/EditorMaterialComponent.h b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Material/EditorMaterialComponent.h index 0c468b10a6..f8895d994f 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Material/EditorMaterialComponent.h +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Material/EditorMaterialComponent.h @@ -8,11 +8,11 @@ #pragma once +#include #include #include -#include -#include #include +#include namespace AZ { @@ -50,25 +50,14 @@ namespace AZ void OnMaterialAssignmentsChanged() override; //! MaterialComponentNotificationBus::Handler overrides... - void OnMaterialsEdited(const MaterialAssignmentMap& materials) override; void OnMaterialInstanceCreated(const MaterialAssignment& materialAssignment) override; - // Apply a material component configuration to the active controller - void UpdateConfiguration(const MaterialComponentConfig& config); - - // Converts the editor components material slots to the material component - // configuration and updates the controller - void UpdateController(); - // Regenerates the editor component material slots based on the material and // LOD mapping from the model or other consumer of materials. // If any corresponding material assignments are found in the component // controller configuration then those values will be assigned to the editor component slots. void UpdateMaterialSlots(); - // Clears all values related to the material component and regenerates the editor slots - AZ::u32 ResetMaterialSlots(); - // Opens the source material export dialog and updates editor material slots based on // selected actions AZ::u32 OpenMaterialExporter(); @@ -90,10 +79,6 @@ namespace AZ // Evaluate if materials can be edited bool IsEditingAllowed() const; - template - static void BuildMaterialSlotMap(ComponentType& component, ContainerType& materialSlots); - AZStd::unordered_map GetMaterialSlots(); - AZStd::unordered_map GetMaterialSlots() const; AZStd::string GetLabelForLod(int lodIndex) const; AZStd::string m_message; @@ -102,8 +87,6 @@ namespace AZ EditorMaterialComponentSlotsByLodContainer m_materialSlotsByLod; bool m_materialSlotsByLodEnabled = false; - bool m_configurationChangeInProgress = false; // when true, model changes are ignored - static const char* GenerateMaterialsButtonText; static const char* GenerateMaterialsToolTipText; static const char* ResetMaterialsButtonText; diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Material/EditorMaterialComponentExporter.cpp b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Material/EditorMaterialComponentExporter.cpp index f55da28fa6..14cc28b91e 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Material/EditorMaterialComponentExporter.cpp +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Material/EditorMaterialComponentExporter.cpp @@ -55,6 +55,10 @@ namespace AZ bool OpenExportDialog(ExportItemsContainer& exportItems) { + // Sort material entries so they are ordered by name in the table + AZStd::sort(exportItems.begin(), exportItems.end(), + [](const auto& a, const auto& b) { return a.GetMaterialSlotName() < b.GetMaterialSlotName(); }); + QWidget* activeWindow = nullptr; AzToolsFramework::EditorWindowRequestBus::BroadcastResult(activeWindow, &AzToolsFramework::EditorWindowRequests::GetAppMainWindow); diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Material/EditorMaterialComponentInspector.cpp b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Material/EditorMaterialComponentInspector.cpp index b9a4adc068..a3152faf87 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Material/EditorMaterialComponentInspector.cpp +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Material/EditorMaterialComponentInspector.cpp @@ -27,19 +27,16 @@ #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 @@ -49,26 +46,59 @@ namespace AZ { namespace EditorMaterialComponentInspector { - MaterialPropertyInspector::MaterialPropertyInspector( - const AZStd::string& slotName, const AZ::Data::AssetId& assetId, PropertyChangedCallback propertyChangedCallback, - QWidget* parent) + MaterialPropertyInspector::MaterialPropertyInspector(QWidget* parent) : AtomToolsFramework::InspectorWidget(parent) - , m_slotName(slotName) - , m_materialAssetId(assetId) - , m_propertyChangedCallback(propertyChangedCallback) { + // Create the menu button + QToolButton* menuButton = new QToolButton(this); + menuButton->setAutoRaise(true); + menuButton->setIcon(QIcon(":/Cards/img/UI20/Cards/menu_ico.svg")); + menuButton->setVisible(true); + QObject::connect(menuButton, &QToolButton::clicked, this, [this]() { OpenMenu(); }); + AddHeading(menuButton); + + m_messageLabel = new QLabel(this); + m_messageLabel->setWordWrap(true); + m_messageLabel->setVisible(true); + m_messageLabel->setAlignment(Qt::AlignCenter); + m_messageLabel->setText(tr("Material not available")); + AddHeading(m_messageLabel); + + AZ::EntitySystemBus::Handler::BusConnect(); } MaterialPropertyInspector::~MaterialPropertyInspector() { AtomToolsFramework::InspectorRequestBus::Handler::BusDisconnect(); + AZ::EntitySystemBus::Handler::BusDisconnect(); + AZ::TickBus::Handler::BusDisconnect(); + MaterialComponentNotificationBus::Handler::BusDisconnect(); } - bool MaterialPropertyInspector::LoadMaterial() + bool MaterialPropertyInspector::LoadMaterial( + const AZ::EntityId& entityId, const AZ::Render::MaterialAssignmentId& materialAssignmentId) { - if (!EditorMaterialComponentUtil::LoadMaterialEditDataFromAssetId(m_materialAssetId, m_editData)) + UnloadMaterial(); + + m_entityId = entityId; + m_materialAssignmentId = materialAssignmentId; + MaterialComponentNotificationBus::Handler::BusDisconnect(); + MaterialComponentNotificationBus::Handler::BusConnect(m_entityId); + + AZ::Data::AssetId materialAssetId = {}; + MaterialComponentRequestBus::EventResult( + materialAssetId, m_entityId, &MaterialComponentRequestBus::Events::GetMaterialOverride, m_materialAssignmentId); + + if (!materialAssetId.IsValid()) + { + UnloadMaterial(); + return false; + } + + if (!EditorMaterialComponentUtil::LoadMaterialEditDataFromAssetId(materialAssetId, m_editData)) { AZ_Warning("AZ::Render::EditorMaterialComponentInspector", false, "Failed to load material data."); + UnloadMaterial(); return false; } @@ -77,6 +107,7 @@ namespace AZ if (!m_materialInstance) { AZ_Error("AZ::Render::EditorMaterialComponentInspector", false, "Material instance could not be created."); + UnloadMaterial(); return false; } @@ -102,15 +133,36 @@ namespace AZ } } + Populate(); + m_messageLabel->setVisible(false); return true; } + void MaterialPropertyInspector::UnloadMaterial() + { + Reset(); + m_editData = EditorMaterialComponentUtil::MaterialEditData(); + m_materialInstance = {}; + m_dirtyPropertyFlags.set(); + m_editorFunctors = {}; + m_internalEditNotification = {}; + m_messageLabel->setVisible(true); + m_messageLabel->setText(tr("Material not available")); + } + + bool MaterialPropertyInspector::IsLoaded() const + { + return m_entityId.IsValid() && m_materialInstance && m_editData.m_materialAsset.IsReady(); + } + void MaterialPropertyInspector::Reset() { m_activeProperty = {}; m_groups = {}; m_dirtyPropertyFlags.set(); + m_internalEditNotification = {}; + AZ::TickBus::Handler::BusDisconnect(); AtomToolsFramework::InspectorRequestBus::Handler::BusDisconnect(); AtomToolsFramework::InspectorWidget::Reset(); } @@ -150,9 +202,18 @@ namespace AZ QFileInfo materialTypeSourceFileInfo(m_editData.m_materialTypeSourcePath.c_str()); QFileInfo materialParentSourceFileInfo(AZ::RPI::AssetUtils::GetSourcePathByAssetId(m_editData.m_materialParentAsset.GetId()).c_str()); + AZStd::string entityName; + AZ::ComponentApplicationBus::BroadcastResult( + entityName, &AZ::ComponentApplicationBus::Events::GetEntityName, m_entityId); + + AZStd::string slotName; + MaterialComponentRequestBus::EventResult( + slotName, m_entityId, &MaterialComponentRequestBus::Events::GetMaterialSlotLabel, m_materialAssignmentId); + QString materialInfo; materialInfo += tr(""); - materialInfo += tr("").arg(m_slotName.c_str()); + materialInfo += tr("").arg(entityName.c_str()); + materialInfo += tr("").arg(slotName.c_str()); if (!materialFileInfo.fileName().isEmpty()) { materialInfo += tr("").arg(materialFileInfo.fileName()); @@ -209,16 +270,8 @@ namespace AZ } // Passing in same group as main and comparison instance to enable custom value comparison for highlighting modified properties - const AZ::Crc32 saveStateKey(AZStd::string::format( - "MaterialPropertyInspector::PropertyGroup::%s::%s", m_materialAssetId.ToString().c_str(), - groupNameId.c_str())); auto propertyGroupWidget = new AtomToolsFramework::InspectorPropertyGroupWidget( - &group, &group, group.TYPEINFO_Uuid(), this, this, saveStateKey, - [](const AzToolsFramework::InstanceDataNode* source, const AzToolsFramework::InstanceDataNode* target) { - AZ_UNUSED(source); - const AtomToolsFramework::DynamicProperty* property = AtomToolsFramework::FindDynamicPropertyForInstanceDataNode(target); - return property && AtomToolsFramework::ArePropertyValuesEqual(property->GetValue(), property->GetConfig().m_parentValue); - }); + &group, nullptr, group.TYPEINFO_Uuid(), this, this, GetSaveStateKeyForGroup(groupNameId)); AddGroup(groupNameId, groupDisplayName, groupDescription, propertyGroupWidget); } @@ -262,35 +315,90 @@ namespace AZ } // Passing in same group as main and comparison instance to enable custom value comparison for highlighting modified properties - const AZ::Crc32 saveStateKey(AZStd::string::format( - "MaterialPropertyInspector::PropertyGroup::%s::%s", m_materialAssetId.ToString().c_str(), - groupNameId.c_str())); auto propertyGroupWidget = new AtomToolsFramework::InspectorPropertyGroupWidget( - &group, &group, group.TYPEINFO_Uuid(), this, this, saveStateKey, - [](const AzToolsFramework::InstanceDataNode* source, const AzToolsFramework::InstanceDataNode* target) { - AZ_UNUSED(source); - const AtomToolsFramework::DynamicProperty* property = AtomToolsFramework::FindDynamicPropertyForInstanceDataNode(target); - return property && AtomToolsFramework::ArePropertyValuesEqual(property->GetValue(), property->GetConfig().m_parentValue); - }); + &group, nullptr, group.TYPEINFO_Uuid(), this, this, GetSaveStateKeyForGroup(groupNameId)); AddGroup(groupNameId, groupDisplayName, groupDescription, propertyGroupWidget); } AddGroupsEnd(); - m_dirtyPropertyFlags.set(); - RunEditorMaterialFunctors(); + LoadOverridesFromEntity(); } - void MaterialPropertyInspector::RunPropertyChangedCallback() + void MaterialPropertyInspector::LoadOverridesFromEntity() { - if (m_propertyChangedCallback) + if (!IsLoaded()) { - m_propertyChangedCallback(m_editData.m_materialPropertyOverrideMap); + return; + } + + m_editData.m_materialPropertyOverrideMap.clear(); + MaterialComponentRequestBus::EventResult( + m_editData.m_materialPropertyOverrideMap, m_entityId, &MaterialComponentRequestBus::Events::GetPropertyOverrides, + m_materialAssignmentId); + + for (auto& group : m_groups) + { + for (auto& property : group.second.m_properties) + { + const AtomToolsFramework::DynamicPropertyConfig& propertyConfig = property.GetConfig(); + const auto overrideItr = m_editData.m_materialPropertyOverrideMap.find(propertyConfig.m_id); + const auto& editValue = overrideItr != m_editData.m_materialPropertyOverrideMap.end() ? overrideItr->second : propertyConfig.m_originalValue; + + // This first converts to an acceptable runtime type in case the value came from script + const auto propertyIndex = m_materialInstance->FindPropertyIndex(property.GetId()); + if (!propertyIndex.IsNull()) + { + const auto runtimeValue = AtomToolsFramework::ConvertToRuntimeType(editValue); + if (runtimeValue.IsValid()) + { + property.SetValue(AtomToolsFramework::ConvertToEditableType(runtimeValue)); + } + } + else + { + property.SetValue(editValue); + } + + UpdateMaterialInstanceProperty(property); + } + } + + m_dirtyPropertyFlags.set(); + RunEditorMaterialFunctors(); + RebuildAll(); + } + + void MaterialPropertyInspector::SaveOverridesToEntity(bool commitChanges) + { + if (!IsLoaded()) + { + return; + } + + MaterialComponentRequestBus::Event( + m_entityId, &MaterialComponentRequestBus::Events::SetPropertyOverrides, m_materialAssignmentId, + m_editData.m_materialPropertyOverrideMap); + + if (commitChanges) + { + AzToolsFramework::ScopedUndoBatch undoBatch("Material slot changed."); + AzToolsFramework::ToolsApplicationRequests::Bus::Broadcast( + &AzToolsFramework::ToolsApplicationRequests::Bus::Events::AddDirtyEntity, m_entityId); + + m_internalEditNotification = true; + MaterialComponentNotificationBus::Event(m_entityId, &MaterialComponentNotifications::OnMaterialsEdited); + m_internalEditNotification = false; } } void MaterialPropertyInspector::RunEditorMaterialFunctors() { + if (!IsLoaded()) + { + return; + } + AZStd::unordered_set changedPropertyNames; AZStd::unordered_set changedPropertyGroupNames; @@ -337,11 +445,13 @@ namespace AZ // Apply any changes to material property meta data back to the editor property configurations for (auto& groupPair : m_groups) { - AZ::Name groupName{groupPair.first}; + AZ::Name groupName{ groupPair.first }; if (changedPropertyGroupNames.find(groupName) != changedPropertyGroupNames.end()) { - SetGroupVisible(groupPair.first, propertyGroupDynamicMetadata[groupName].m_visibility == AZ::RPI::MaterialPropertyGroupVisibility::Enabled); + SetGroupVisible( + groupPair.first, + propertyGroupDynamicMetadata[groupName].m_visibility == AZ::RPI::MaterialPropertyGroupVisibility::Enabled); } for (auto& property : groupPair.second.m_properties) @@ -355,12 +465,12 @@ namespace AZ if (oldReadOnly != propertyConfig.m_readOnly) { - RefreshAll(); + RefreshGroup(groupPair.first); } if (oldVisible != propertyConfig.m_visible) { - RebuildAll(); + RebuildGroup(groupPair.first); } } } @@ -368,57 +478,37 @@ namespace AZ void MaterialPropertyInspector::UpdateMaterialInstanceProperty(const AtomToolsFramework::DynamicProperty& property) { - if (m_materialInstance) + if (!IsLoaded()) { - const auto propertyIndex = m_materialInstance->FindPropertyIndex(property.GetId()); - if (!propertyIndex.IsNull()) - { - m_dirtyPropertyFlags.set(propertyIndex.GetIndex()); + return; + } - const auto runtimeValue = AtomToolsFramework::ConvertToRuntimeType(property.GetValue()); - if (runtimeValue.IsValid()) - { - m_materialInstance->SetPropertyValue(propertyIndex, runtimeValue); - } + const auto propertyIndex = m_materialInstance->FindPropertyIndex(property.GetId()); + if (!propertyIndex.IsNull()) + { + m_dirtyPropertyFlags.set(propertyIndex.GetIndex()); + + const auto runtimeValue = AtomToolsFramework::ConvertToRuntimeType(property.GetValue()); + if (runtimeValue.IsValid()) + { + m_materialInstance->SetPropertyValue(propertyIndex, runtimeValue); } } } - void MaterialPropertyInspector::SetOverrides(const MaterialPropertyOverrideMap& propertyOverrideMap) + AZ::Crc32 MaterialPropertyInspector::GetSaveStateKeyForGroup(const AZStd::string& groupNameId) const { - m_editData.m_materialPropertyOverrideMap = propertyOverrideMap; + return AZ::Crc32(AZStd::string::format( + "MaterialPropertyInspector::PropertyGroup::%s::%s", m_editData.m_materialAssetId.ToString().c_str(), + groupNameId.c_str())); + } - for (auto& group : m_groups) - { - for (auto& property : group.second.m_properties) - { - const AtomToolsFramework::DynamicPropertyConfig& propertyConfig = property.GetConfig(); - const auto overrideItr = m_editData.m_materialPropertyOverrideMap.find(propertyConfig.m_id); - const auto& editValue = overrideItr != m_editData.m_materialPropertyOverrideMap.end() ? overrideItr->second : propertyConfig.m_originalValue; - - // This first converts to an acceptable runtime type in case the value came from script - const auto propertyIndex = m_materialInstance->FindPropertyIndex(property.GetId()); - if (!propertyIndex.IsNull()) - { - const auto runtimeValue = AtomToolsFramework::ConvertToRuntimeType(editValue); - if (runtimeValue.IsValid()) - { - property.SetValue(AtomToolsFramework::ConvertToEditableType(runtimeValue)); - } - } - else - { - property.SetValue(editValue); - } - - UpdateMaterialInstanceProperty(property); - } - } - - m_dirtyPropertyFlags.set(); - RunPropertyChangedCallback(); - RunEditorMaterialFunctors(); - RebuildAll(); + bool MaterialPropertyInspector::AreNodePropertyValuesEqual( + 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); } bool MaterialPropertyInspector::SaveMaterial() const @@ -446,7 +536,8 @@ namespace AZ bool MaterialPropertyInspector::SaveMaterialToSource() const { - const QString saveFilePath = AtomToolsFramework::GetSaveFileInfo(m_editData.m_materialSourcePath.c_str()).absoluteFilePath(); + const QString saveFilePath = + AtomToolsFramework::GetSaveFileInfo(m_editData.m_materialSourcePath.c_str()).absoluteFilePath(); if (saveFilePath.isEmpty()) { return false; @@ -463,13 +554,13 @@ namespace AZ bool MaterialPropertyInspector::HasMaterialSource() const { - return !m_editData.m_materialSourcePath.empty() && + return IsLoaded() && !m_editData.m_materialSourcePath.empty() && AZ::StringFunc::Path::IsExtension(m_editData.m_materialSourcePath.c_str(), AZ::RPI::MaterialSourceData::Extension); } bool MaterialPropertyInspector::HasMaterialParentSource() const { - return !m_editData.m_materialParentSourcePath.empty() && + return IsLoaded() && !m_editData.m_materialParentSourcePath.empty() && AZ::StringFunc::Path::IsExtension( m_editData.m_materialParentSourcePath.c_str(), AZ::RPI::MaterialSourceData::Extension); } @@ -479,7 +570,7 @@ namespace AZ if (HasMaterialSource()) { EditorMaterialSystemComponentRequestBus::Broadcast( - &EditorMaterialSystemComponentRequestBus::Events::OpenInMaterialEditor, m_editData.m_materialSourcePath); + &EditorMaterialSystemComponentRequestBus::Events::OpenMaterialEditor, m_editData.m_materialSourcePath); } } @@ -488,10 +579,42 @@ namespace AZ if (HasMaterialParentSource()) { EditorMaterialSystemComponentRequestBus::Broadcast( - &EditorMaterialSystemComponentRequestBus::Events::OpenInMaterialEditor, m_editData.m_materialParentSourcePath); + &EditorMaterialSystemComponentRequestBus::Events::OpenMaterialEditor, m_editData.m_materialParentSourcePath); } } + void MaterialPropertyInspector::OpenMenu() + { + QAction* action = nullptr; + + QMenu menu(this); + action = menu.addAction("Clear Overrides", [this] { + MaterialComponentRequestBus::Event( + m_entityId, &MaterialComponentRequestBus::Events::SetPropertyOverrides, m_materialAssignmentId, + MaterialPropertyOverrideMap()); + QueueUpdateUI(); + }); + action->setEnabled(IsLoaded()); + + menu.addSeparator(); + + action = menu.addAction("Save Material", [this] { SaveMaterial(); }); + action->setEnabled(IsLoaded()); + + action = menu.addAction("Save Material To Source", [this] { SaveMaterialToSource(); }); + action->setEnabled(HasMaterialSource()); + + menu.addSeparator(); + + action = menu.addAction("Open Source Material In Editor", [this] { OpenMaterialSourceInEditor(); }); + action->setEnabled(HasMaterialSource()); + + action = menu.addAction("Open Parent Material In Editor", [this] { OpenMaterialParentSourceInEditor(); }); + action->setEnabled(HasMaterialParentSource()); + + menu.exec(QCursor::pos()); + } + const EditorMaterialComponentUtil::MaterialEditData& MaterialPropertyInspector::GetEditData() const { return m_editData; @@ -501,7 +624,8 @@ namespace AZ { // 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) { @@ -521,15 +645,16 @@ namespace AZ { m_editData.m_materialPropertyOverrideMap[m_activeProperty->GetId()] = m_activeProperty->GetValue(); UpdateMaterialInstanceProperty(*m_activeProperty); - RunPropertyChangedCallback(); + SaveOverridesToEntity(false); } } } void MaterialPropertyInspector::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) { @@ -537,85 +662,92 @@ namespace AZ { m_editData.m_materialPropertyOverrideMap[m_activeProperty->GetId()] = m_activeProperty->GetValue(); UpdateMaterialInstanceProperty(*m_activeProperty); - RunPropertyChangedCallback(); + SaveOverridesToEntity(true); RunEditorMaterialFunctors(); m_activeProperty = nullptr; } } } - bool OpenInspectorDialog( - const AZStd::string& slotName, const AZ::Data::AssetId& assetId, MaterialPropertyOverrideMap propertyOverrideMap, - PropertyChangedCallback propertyChangedCallback) + void MaterialPropertyInspector::OnEntityInitialized(const AZ::EntityId& entityId) { - QWidget* activeWindow = nullptr; - AzToolsFramework::EditorWindowRequestBus::BroadcastResult(activeWindow, &AzToolsFramework::EditorWindowRequests::GetAppMainWindow); - - // Constructing a dialog with a table to display all configurable material export items - QDialog dialog(activeWindow); - dialog.setWindowTitle("Material Inspector"); - - MaterialPropertyInspector* inspector = new MaterialPropertyInspector(slotName, assetId, propertyChangedCallback, &dialog); - if (!inspector->LoadMaterial()) + if (m_entityId == entityId) { - return false; + UnloadMaterial(); } + } - inspector->Populate(); - inspector->SetOverrides(propertyOverrideMap); + void MaterialPropertyInspector::OnEntityDestroyed(const AZ::EntityId& entityId) + { + if (m_entityId == entityId) + { + UnloadMaterial(); + } + } - // Create the menu button - QToolButton* menuButton = new QToolButton(&dialog); - menuButton->setAutoRaise(true); - menuButton->setIcon(QIcon(":/Cards/img/UI20/Cards/menu_ico.svg")); - menuButton->setVisible(true); - QObject::connect(menuButton, &QToolButton::clicked, &dialog, [&]() { - QAction* action = nullptr; + void MaterialPropertyInspector::OnEntityActivated(const AZ::EntityId& entityId) + { + if (m_entityId == entityId) + { + QueueUpdateUI(); + } + } - QMenu menu(&dialog); - action = menu.addAction("Clear Overrides", [&] { inspector->SetOverrides(MaterialPropertyOverrideMap()); }); - action = menu.addAction("Revert Changes", [&] { inspector->SetOverrides(propertyOverrideMap); }); + void MaterialPropertyInspector::OnEntityDeactivated(const AZ::EntityId& entityId) + { + if (m_entityId == entityId) + { + UnloadMaterial(); + } + } - menu.addSeparator(); - action = menu.addAction("Save Material", [&] { inspector->SaveMaterial(); }); - action = menu.addAction("Save Material To Source", [&] { inspector->SaveMaterialToSource(); }); - action->setEnabled(inspector->HasMaterialSource()); + void MaterialPropertyInspector::OnEntityNameChanged(const AZ::EntityId& entityId, const AZStd::string& name) + { + AZ_UNUSED(name); + if (m_entityId == entityId) + { + QueueUpdateUI(); + } + } - menu.addSeparator(); - action = menu.addAction("Open Source Material In Editor", [&] { inspector->OpenMaterialSourceInEditor(); }); - action->setEnabled(inspector->HasMaterialSource()); - action = menu.addAction("Open Parent Material In Editor", [&] { inspector->OpenMaterialParentSourceInEditor(); }); - action->setEnabled(inspector->HasMaterialParentSource()); - menu.exec(QCursor::pos()); - }); + void MaterialPropertyInspector::OnTick(float deltaTime, ScriptTimePoint time) + { + AZ_UNUSED(time); + AZ_UNUSED(deltaTime); + UpdateUI(); + AZ::TickBus::Handler::BusDisconnect(); + } - QDialogButtonBox* buttonBox = new QDialogButtonBox(&dialog); - buttonBox->setStandardButtons(QDialogButtonBox::Cancel | QDialogButtonBox::Ok); - QObject::connect(buttonBox, &QDialogButtonBox::accepted, &dialog, &QDialog::accept); - QObject::connect(buttonBox, &QDialogButtonBox::rejected, &dialog, &QDialog::reject); + void MaterialPropertyInspector::OnMaterialsEdited() + { + if (!m_internalEditNotification) + { + QueueUpdateUI(); + } + } - QObject::connect(&dialog, &QDialog::rejected, &dialog, [&] { inspector->SetOverrides(propertyOverrideMap); }); + void MaterialPropertyInspector::UpdateUI() + { + AZ::Data::AssetId assetId; + MaterialComponentRequestBus::EventResult( + assetId, m_entityId, &MaterialComponentRequestBus::Events::GetMaterialOverride, m_materialAssignmentId); - QVBoxLayout* dialogLayout = new QVBoxLayout(&dialog); - dialogLayout->addWidget(menuButton); - dialogLayout->addWidget(inspector); - dialogLayout->addWidget(buttonBox); - dialog.setLayout(dialogLayout); - dialog.setModal(true); + if (IsLoaded() && m_editData.m_materialAssetId == assetId) + { + LoadOverridesFromEntity(); + } + else + { + LoadMaterial(m_entityId, m_materialAssignmentId); + } + } - // Forcing the initial dialog size to accomodate typical content. - // Temporarily settng fixed size because dialog.show/exec invokes WindowDecorationWrapper::showEvent. - // This forces the dialog to be centered and sized based on the layout of content. - // Resizing the dialog after show will not be centered and moving the dialog programatically doesn't m0ve the custmk frame. - dialog.setFixedSize(500, 800); - dialog.show(); - - // Removing fixed size to allow drag resizing - dialog.setMinimumSize(0, 0); - dialog.setMaximumSize(QWIDGETSIZE_MAX, QWIDGETSIZE_MAX); - - // Return true if the user press the export button - return dialog.exec() == QDialog::Accepted; + void MaterialPropertyInspector::QueueUpdateUI() + { + if (!AZ::TickBus::Handler::BusIsConnected()) + { + AZ::TickBus::Handler::BusConnect(); + } } } // namespace EditorMaterialComponentInspector } // namespace Render diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Material/EditorMaterialComponentInspector.h b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Material/EditorMaterialComponentInspector.h index 12c4fbfdd9..11eb2cec51 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Material/EditorMaterialComponentInspector.h +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Material/EditorMaterialComponentInspector.h @@ -9,17 +9,22 @@ #pragma once #if !defined(Q_MOC_RUN) +#include #include #include #include +#include +#include #include #include -#include #include +#include #include #include #endif +class QLabel; + namespace AZ { namespace Render @@ -31,31 +36,33 @@ namespace AZ class MaterialPropertyInspector : public AtomToolsFramework::InspectorWidget , public AzToolsFramework::IPropertyEditorNotify - { + , public AZ::EntitySystemBus::Handler + , public AZ::TickBus::Handler + , public MaterialComponentNotificationBus::Handler + { Q_OBJECT public: AZ_CLASS_ALLOCATOR(MaterialPropertyInspector, AZ::SystemAllocator, 0); - explicit MaterialPropertyInspector( - const AZStd::string& slotName, const AZ::Data::AssetId& assetId, PropertyChangedCallback propertyChangedCallback, - QWidget* parent = nullptr); + MaterialPropertyInspector(QWidget* parent = nullptr); ~MaterialPropertyInspector() override; - bool LoadMaterial(); + bool LoadMaterial(const AZ::EntityId& entityId, const AZ::Render::MaterialAssignmentId& materialAssignmentId); + void UnloadMaterial(); + bool IsLoaded() const; // AtomToolsFramework::InspectorRequestBus::Handler overrides... void Reset() override; void Populate(); - void SetOverrides(const MaterialPropertyOverrideMap& propertyOverrideMap); - bool SaveMaterial() const; bool SaveMaterialToSource() const; bool HasMaterialSource() const; bool HasMaterialParentSource() const; void OpenMaterialSourceInEditor() const; void OpenMaterialParentSourceInEditor() const; + void OpenMenu(); const EditorMaterialComponentUtil::MaterialEditData& GetEditData() const; private: @@ -69,28 +76,47 @@ namespace AZ void RequestPropertyContextMenu([[maybe_unused]] AzToolsFramework::InstanceDataNode*, const QPoint&) override {} void PropertySelectionChanged([[maybe_unused]] AzToolsFramework::InstanceDataNode*, bool) override {} + // AZ::EntitySystemBus::Handler overrides... + void OnEntityInitialized(const AZ::EntityId& entityId) override; + void OnEntityDestroyed(const AZ::EntityId& entityId) override; + void OnEntityActivated(const AZ::EntityId& entityId) override; + void OnEntityDeactivated(const AZ::EntityId& entityId) override; + void OnEntityNameChanged(const AZ::EntityId& entityId, const AZStd::string& name) override; + + //! AZ::TickBus::Handler overrides... + void OnTick(float deltaTime, ScriptTimePoint time) override; + + //! MaterialComponentNotificationBus::Handler overrides... + void OnMaterialsEdited() override; + + void UpdateUI(); + void QueueUpdateUI(); + void AddDetailsGroup(); void AddUvNamesGroup(); - void RunPropertyChangedCallback(); + + void LoadOverridesFromEntity(); + void SaveOverridesToEntity(bool commitChanges); void RunEditorMaterialFunctors(); void UpdateMaterialInstanceProperty(const AtomToolsFramework::DynamicProperty& property); + AZ::Crc32 GetSaveStateKeyForGroup(const AZStd::string& groupNameId) const; + static bool AreNodePropertyValuesEqual( + const AzToolsFramework::InstanceDataNode* source, const AzToolsFramework::InstanceDataNode* target); + // Tracking the property that is actively being edited in the inspector const AtomToolsFramework::DynamicProperty* m_activeProperty = {}; - AZStd::string m_slotName; - AZ::Data::AssetId m_materialAssetId = {}; + AZ::EntityId m_entityId; + AZ::Render::MaterialAssignmentId m_materialAssignmentId; EditorMaterialComponentUtil::MaterialEditData m_editData; - PropertyChangedCallback m_propertyChangedCallback = {}; AZ::Data::Instance m_materialInstance = {}; AZStd::vector> m_editorFunctors = {}; AZ::RPI::MaterialPropertyFlags m_dirtyPropertyFlags = {}; AZStd::unordered_map m_groups = {}; - }; - - bool OpenInspectorDialog( - const AZStd::string& slotName, const AZ::Data::AssetId& assetId, MaterialPropertyOverrideMap propertyOverrideMap, - PropertyChangedCallback propertyChangedCallback); + bool m_internalEditNotification = {}; + QLabel* m_messageLabel = {}; + }; } // namespace EditorMaterialComponentInspector } // namespace Render } // namespace AZ diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Material/EditorMaterialComponentSlot.cpp b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Material/EditorMaterialComponentSlot.cpp index 39dde65a99..363221d3fc 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Material/EditorMaterialComponentSlot.cpp +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Material/EditorMaterialComponentSlot.cpp @@ -80,10 +80,9 @@ namespace AZ if (AZ::SerializeContext* serializeContext = azrtti_cast(context)) { serializeContext->Class() - ->Version(6, &EditorMaterialComponentSlot::ConvertVersion) + ->Version(7, &EditorMaterialComponentSlot::ConvertVersion) ->Field("id", &EditorMaterialComponentSlot::m_id) ->Field("materialAsset", &EditorMaterialComponentSlot::m_materialAsset) - ->Field("defaultMaterialAsset", &EditorMaterialComponentSlot::m_defaultMaterialAsset) ; if (AZ::EditContext* editContext = serializeContext->GetEditContext()) @@ -114,20 +113,22 @@ namespace AZ ->Constructor() ->Property("id", BehaviorValueProperty(&EditorMaterialComponentSlot::m_id)) ->Property("materialAsset", BehaviorValueProperty(&EditorMaterialComponentSlot::m_materialAsset)) - ->Property("propertyOverrides", BehaviorValueProperty(&EditorMaterialComponentSlot::m_propertyOverrides)) - ->Property("matModUvOverrides", BehaviorValueProperty(&EditorMaterialComponentSlot::m_matModUvOverrides)) ; } }; AZ::Data::AssetId EditorMaterialComponentSlot::GetDefaultAssetId() const { - return m_defaultMaterialAsset.GetId(); + AZ::Data::AssetId assetId; + MaterialComponentRequestBus::EventResult(assetId, m_entityId, &MaterialComponentRequestBus::Events::GetDefaultMaterialAssetId, m_id); + return assetId; } AZStd::string EditorMaterialComponentSlot::GetLabel() const { - return m_label; + AZStd::string label; + MaterialComponentRequestBus::EventResult(label, m_entityId, &MaterialComponentRequestBus::Events::GetMaterialSlotLabel, m_id); + return label; } bool EditorMaterialComponentSlot::HasSourceData() const @@ -137,50 +138,45 @@ namespace AZ return !sourcePath.empty() && AZ::StringFunc::Path::IsExtension(sourcePath.c_str(), AZ::RPI::MaterialSourceData::Extension); } - void EditorMaterialComponentSlot::OnMaterialChanged() const + void EditorMaterialComponentSlot::SetAsset(const Data::AssetId& assetId) { - if (m_materialChangedCallback) - { - m_materialChangedCallback(); - } + m_materialAsset = AZ::Data::Asset(assetId, AZ::AzTypeInfo::Uuid()); + MaterialComponentRequestBus::Event( + m_entityId, &MaterialComponentRequestBus::Events::SetMaterialOverride, m_id, m_materialAsset.GetId()); + OnDataChanged(); } - void EditorMaterialComponentSlot::OnPropertyChanged() const + void EditorMaterialComponentSlot::SetAsset(const Data::Asset& asset) { - if (m_propertyChangedCallback) - { - m_propertyChangedCallback(); - } - } - - void EditorMaterialComponentSlot::OpenMaterialEditor() const - { - const AZStd::string& sourcePath = AZ::RPI::AssetUtils::GetSourcePathByAssetId(m_materialAsset.GetId()); - if (!sourcePath.empty() && AZ::StringFunc::Path::IsExtension(sourcePath.c_str(), AZ::RPI::MaterialSourceData::Extension)) - { - EditorMaterialSystemComponentRequestBus::Broadcast(&EditorMaterialSystemComponentRequestBus::Events::OpenInMaterialEditor, sourcePath); - } + m_materialAsset = asset; + MaterialComponentRequestBus::Event( + m_entityId, &MaterialComponentRequestBus::Events::SetMaterialOverride, m_id, m_materialAsset.GetId()); + OnDataChanged(); } void EditorMaterialComponentSlot::Clear() { m_materialAsset = {}; + MaterialComponentRequestBus::Event( + m_entityId, &MaterialComponentRequestBus::Events::SetMaterialOverride, m_id, m_materialAsset.GetId()); + ClearOverrides(); + } + + void EditorMaterialComponentSlot::ClearToDefaultAsset() + { + m_materialAsset = AZ::Data::Asset(GetDefaultAssetId(), AZ::AzTypeInfo::Uuid()); + MaterialComponentRequestBus::Event( + m_entityId, &MaterialComponentRequestBus::Events::SetMaterialOverride, m_id, m_materialAsset.GetId()); ClearOverrides(); } void EditorMaterialComponentSlot::ClearOverrides() { - m_propertyOverrides = {}; - m_matModUvOverrides = {}; - OnMaterialChanged(); - } - - void EditorMaterialComponentSlot::ResetToDefaultAsset() - { - m_materialAsset = m_defaultMaterialAsset; - m_propertyOverrides = {}; - m_matModUvOverrides = {}; - OnMaterialChanged(); + MaterialComponentRequestBus::Event( + m_entityId, &MaterialComponentRequestBus::Events::SetPropertyOverrides, m_id, MaterialPropertyOverrideMap()); + MaterialComponentRequestBus::Event( + m_entityId, &MaterialComponentRequestBus::Events::SetModelUvOverrides, m_id, AZ::RPI::MaterialModelUvOverrideMap()); + OnDataChanged(); } void EditorMaterialComponentSlot::OpenMaterialExporter() @@ -189,7 +185,7 @@ namespace AZ // But we still need to allow the user to reconfigure it using the dialog EditorMaterialComponentExporter::ExportItemsContainer exportItems; { - EditorMaterialComponentExporter::ExportItem exportItem{m_defaultMaterialAsset.GetId(), m_label}; + EditorMaterialComponentExporter::ExportItem exportItem{ GetDefaultAssetId(), GetLabel() }; exportItems.push_back(exportItem); } @@ -203,11 +199,13 @@ namespace AZ continue; } - // Generate a new asset ID utilizing the export file path so that we can update this material slot to reference the new asset + // Generate a new asset ID utilizing the export file path so that we can update this material slot to reference the new + // asset const auto& assetIdOutcome = AZ::RPI::AssetUtils::MakeAssetId(exportItem.GetExportPath(), 0); if (assetIdOutcome) { - m_materialAsset.Create(assetIdOutcome.GetValue()); + m_materialAsset = AZ::Data::Asset( + assetIdOutcome.GetValue(), AZ::AzTypeInfo::Uuid()); changed = true; } } @@ -219,37 +217,43 @@ namespace AZ } } + void EditorMaterialComponentSlot::OpenMaterialEditor() const + { + const AZStd::string& sourcePath = AZ::RPI::AssetUtils::GetSourcePathByAssetId(m_materialAsset.GetId()); + if (!sourcePath.empty() && AZ::StringFunc::Path::IsExtension(sourcePath.c_str(), AZ::RPI::MaterialSourceData::Extension)) + { + EditorMaterialSystemComponentRequestBus::Broadcast( + &EditorMaterialSystemComponentRequestBus::Events::OpenMaterialEditor, sourcePath); + } + } + void EditorMaterialComponentSlot::OpenMaterialInspector() { - MaterialPropertyOverrideMap initialPropertyOverrides = m_propertyOverrides; - auto applyPropertyChangedCallback = [this](const MaterialPropertyOverrideMap& propertyOverrides) { - m_propertyOverrides = propertyOverrides; - OnPropertyChanged(); - }; - - if (m_materialAsset.GetId().IsValid()) - { - if (EditorMaterialComponentInspector::OpenInspectorDialog(GetLabel(), m_materialAsset.GetId(), m_propertyOverrides, applyPropertyChangedCallback)) - { - OnMaterialChanged(); - } - } + EditorMaterialSystemComponentRequestBus::Broadcast( + &EditorMaterialSystemComponentRequestBus::Events::OpenMaterialInspector, m_entityId, m_id); } void EditorMaterialComponentSlot::OpenUvNameMapInspector() { - RPI::MaterialModelUvOverrideMap initialUvOverrides = m_matModUvOverrides; - auto applyMatModUvOverrideChangedCallback = [this](const RPI::MaterialModelUvOverrideMap& matModUvOverrides) { - m_matModUvOverrides = matModUvOverrides; - // Treated as a special property. It will be updated together with properties. - OnPropertyChanged(); - }; - if (m_materialAsset.GetId().IsValid()) { - if (EditorMaterialComponentInspector::OpenInspectorDialog(m_materialAsset.GetId(), m_matModUvOverrides, m_modelUvNames, applyMatModUvOverrideChangedCallback)) + AZStd::unordered_set modelUvNames; + MaterialReceiverRequestBus::EventResult(modelUvNames, m_entityId, &MaterialReceiverRequestBus::Events::GetModelUvNames); + + RPI::MaterialModelUvOverrideMap matModUvOverrides; + MaterialComponentRequestBus::EventResult( + matModUvOverrides, m_entityId, &MaterialComponentRequestBus::Events::GetModelUvOverrides, m_id); + + auto applyMatModUvOverrideChangedCallback = [this](const RPI::MaterialModelUvOverrideMap& matModUvOverrides) { - OnMaterialChanged(); + MaterialComponentRequestBus::Event( + m_entityId, &MaterialComponentRequestBus::Events::SetModelUvOverrides, m_id, matModUvOverrides); + }; + + if (EditorMaterialComponentInspector::OpenInspectorDialog( + m_materialAsset.GetId(), matModUvOverrides, modelUvNames, applyMatModUvOverrideChangedCallback)) + { + OnDataChanged(); } } } @@ -261,7 +265,7 @@ namespace AZ QAction* action = nullptr; action = menu.addAction("Generate/Manage Source Material...", [this]() { OpenMaterialExporter(); }); - action->setEnabled(m_defaultMaterialAsset.GetId().IsValid()); + action->setEnabled(GetDefaultAssetId().IsValid()); menu.addSeparator(); @@ -276,10 +280,38 @@ namespace AZ menu.addSeparator(); + MaterialPropertyOverrideMap propertyOverrides; + MaterialComponentRequestBus::EventResult( + propertyOverrides, m_entityId, &MaterialComponentRequestBus::Events::GetPropertyOverrides, m_id); + RPI::MaterialModelUvOverrideMap matModUvOverrides; + MaterialComponentRequestBus::EventResult( + matModUvOverrides, m_entityId, &MaterialComponentRequestBus::Events::GetModelUvOverrides, m_id); + action = menu.addAction("Clear Material Instance Overrides", [this]() { ClearOverrides(); }); - action->setEnabled(!m_propertyOverrides.empty() || !m_matModUvOverrides.empty()); + action->setEnabled(!propertyOverrides.empty() || !matModUvOverrides.empty()); menu.exec(QCursor::pos()); } + + void EditorMaterialComponentSlot::OnMaterialChanged() const + { + MaterialComponentRequestBus::Event( + m_entityId, &MaterialComponentRequestBus::Events::SetMaterialOverride, m_id, m_materialAsset.GetId()); + OnDataChanged(); + } + + void EditorMaterialComponentSlot::OnDataChanged() const + { + // This is triggered whenever a material slot changes outside of normal inspector interactions + // Handle undo, update configuration, and refresh the inspector to display the new values + AzToolsFramework::ScopedUndoBatch undoBatch("Material slot changed."); + AzToolsFramework::ToolsApplicationRequests::Bus::Broadcast( + &AzToolsFramework::ToolsApplicationRequests::Bus::Events::AddDirtyEntity, m_entityId); + + MaterialComponentNotificationBus::Event(m_entityId, &MaterialComponentNotifications::OnMaterialsEdited); + + AzToolsFramework::ToolsApplicationEvents::Bus::Broadcast( + &AzToolsFramework::ToolsApplicationEvents::InvalidatePropertyDisplay, AzToolsFramework::Refresh_AttributesAndValues); + } } // namespace Render } // namespace AZ diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Material/EditorMaterialComponentSlot.h b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Material/EditorMaterialComponentSlot.h index 58d6fa9ab0..01e357f1bb 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Material/EditorMaterialComponentSlot.h +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Material/EditorMaterialComponentSlot.h @@ -33,29 +33,26 @@ namespace AZ AZ::Data::AssetId GetDefaultAssetId() const; AZStd::string GetLabel() const; bool HasSourceData() const; - void OpenMaterialEditor() const; - void ResetToDefaultAsset(); + + void SetAsset(const Data::AssetId& assetId); + void SetAsset(const Data::Asset& asset); void Clear(); + void ClearToDefaultAsset(); void ClearOverrides(); + void OpenMaterialExporter(); + void OpenMaterialEditor() const; void OpenMaterialInspector(); void OpenUvNameMapInspector(); + AZ::EntityId m_entityId; MaterialAssignmentId m_id; - AZStd::string m_label; Data::Asset m_materialAsset; - Data::Asset m_defaultMaterialAsset; - MaterialPropertyOverrideMap m_propertyOverrides; - AZStd::function m_materialChangedCallback; - AZStd::function m_propertyChangedCallback; - - RPI::MaterialModelUvOverrideMap m_matModUvOverrides; - AZStd::unordered_set m_modelUvNames; // Cached for override options. private: void OpenPopupMenu(const AZ::Data::AssetId& assetId, const AZ::Data::AssetType& assetType); void OnMaterialChanged() const; - void OnPropertyChanged() const; + void OnDataChanged() const; }; // Vector of slots for assignable or overridable material data. diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Material/EditorMaterialSystemComponent.cpp b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Material/EditorMaterialSystemComponent.cpp index e25653988e..83ddbf46c5 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Material/EditorMaterialSystemComponent.cpp +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Material/EditorMaterialSystemComponent.cpp @@ -6,33 +6,31 @@ * */ -#include - -#include +#include +#include #include #include +#include #include #include - #include - #include +#include #include - -#include - -#include - +#include +#include +#include #include // Disables warning messages triggered by the Qt library // 4251: class needs to have dll-interface to be used by clients of class // 4800: forcing value to bool 'true' or 'false' (performance warning) AZ_PUSH_DISABLE_WARNING(4251 4800, "-Wunknown-warning-option") -#include -#include -#include #include +#include +#include +#include +#include AZ_POP_DISABLE_WARNING void InitMaterialEditorResources() @@ -95,6 +93,7 @@ namespace AZ AzFramework::ApplicationLifecycleEvents::Bus::Handler::BusConnect(); AzToolsFramework::AssetBrowser::AssetBrowserInteractionNotificationBus::Handler::BusConnect(); AzToolsFramework::EditorMenuNotificationBus::Handler::BusConnect(); + AzToolsFramework::EditorEvents::Bus::Handler::BusConnect(); SetupThumbnails(); m_materialBrowserInteractions.reset(aznew MaterialBrowserInteractions); @@ -106,6 +105,7 @@ namespace AZ AzFramework::ApplicationLifecycleEvents::Bus::Handler::BusDisconnect(); AzToolsFramework::AssetBrowser::AssetBrowserInteractionNotificationBus::Handler::BusDisconnect(); AzToolsFramework::EditorMenuNotificationBus::Handler::BusDisconnect(); + AzToolsFramework::EditorEvents::Bus::Handler::BusDisconnect(); TeardownThumbnails(); m_materialBrowserInteractions.reset(); @@ -117,7 +117,7 @@ namespace AZ } } - void EditorMaterialSystemComponent::OpenInMaterialEditor(const AZStd::string& sourcePath) + void EditorMaterialSystemComponent::OpenMaterialEditor(const AZStd::string& sourcePath) { AZ_TracePrintf("MaterialComponent", "Launching Material Editor"); @@ -140,6 +140,20 @@ namespace AZ AtomToolsFramework::LaunchTool("MaterialEditor", ".exe", arguments); } + void EditorMaterialSystemComponent::OpenMaterialInspector( + const AZ::EntityId& entityId, const AZ::Render::MaterialAssignmentId& materialAssignmentId) + { + auto dockWidget = AzToolsFramework::InstanceViewPane("Material Property Inspector"); + if (dockWidget) + { + auto inspector = static_cast(dockWidget->widget()); + if (inspector) + { + inspector->LoadMaterial(entityId, materialAssignmentId); + } + } + } + void EditorMaterialSystemComponent::OnApplicationAboutToStop() { TeardownThumbnails(); @@ -157,11 +171,12 @@ namespace AZ QObject::connect( m_openMaterialEditorAction, &QAction::triggered, m_openMaterialEditorAction, [this]() { - OpenInMaterialEditor(""); + OpenMaterialEditor(""); } ); - AzToolsFramework::EditorMenuRequestBus::Broadcast(&AzToolsFramework::EditorMenuRequestBus::Handler::AddMenuAction, "ToolMenu", m_openMaterialEditorAction, true); + AzToolsFramework::EditorMenuRequestBus::Broadcast( + &AzToolsFramework::EditorMenuRequestBus::Handler::AddMenuAction, "ToolMenu", m_openMaterialEditorAction, true); } } @@ -174,13 +189,25 @@ namespace AZ } } + void EditorMaterialSystemComponent::NotifyRegisterViews() + { + AzToolsFramework::ViewPaneOptions inspectorOptions; + inspectorOptions.canHaveMultipleInstances = true; + inspectorOptions.preferedDockingArea = Qt::NoDockWidgetArea; + inspectorOptions.paneRect = QRect(50, 50, 400, 700); + inspectorOptions.showInMenu = false; + inspectorOptions.showOnToolsToolbar = false; + AzToolsFramework::RegisterViewPane( + "Material Property Inspector", LyViewPane::CategoryTools, inspectorOptions); + } + void EditorMaterialSystemComponent::SetupThumbnails() { using namespace AzToolsFramework::Thumbnailer; using namespace LyIntegration; - ThumbnailerRequestsBus::Broadcast(&ThumbnailerRequests::RegisterThumbnailProvider, - MAKE_TCACHE(Thumbnails::MaterialThumbnailCache), + ThumbnailerRequestsBus::Broadcast( + &ThumbnailerRequests::RegisterThumbnailProvider, MAKE_TCACHE(Thumbnails::MaterialThumbnailCache), ThumbnailContext::DefaultContext); } @@ -189,12 +216,13 @@ namespace AZ using namespace AzToolsFramework::Thumbnailer; using namespace LyIntegration; - ThumbnailerRequestsBus::Broadcast(&ThumbnailerRequests::UnregisterThumbnailProvider, - Thumbnails::MaterialThumbnailCache::ProviderName, + ThumbnailerRequestsBus::Broadcast( + &ThumbnailerRequests::UnregisterThumbnailProvider, Thumbnails::MaterialThumbnailCache::ProviderName, ThumbnailContext::DefaultContext); } - AzToolsFramework::AssetBrowser::SourceFileDetails EditorMaterialSystemComponent::GetSourceFileDetails(const char* fullSourceFileName) + AzToolsFramework::AssetBrowser::SourceFileDetails EditorMaterialSystemComponent::GetSourceFileDetails( + const char* fullSourceFileName) { static const char* MaterialTypeIconPath = ":/Icons/materialtype.svg"; static const char* MaterialTypeExtension = "materialtype"; diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Material/EditorMaterialSystemComponent.h b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Material/EditorMaterialSystemComponent.h index 267f31f92b..7fa43ea309 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Material/EditorMaterialSystemComponent.h +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Material/EditorMaterialSystemComponent.h @@ -8,11 +8,10 @@ #pragma once #include - #include - -#include +#include #include +#include #include #include @@ -28,8 +27,9 @@ namespace AZ : public AZ::Component , private EditorMaterialSystemComponentRequestBus::Handler , private AzFramework::ApplicationLifecycleEvents::Bus::Handler - , public AzToolsFramework::AssetBrowser::AssetBrowserInteractionNotificationBus::Handler - , public AzToolsFramework::EditorMenuNotificationBus::Handler + , private AzToolsFramework::AssetBrowser::AssetBrowserInteractionNotificationBus::Handler + , private AzToolsFramework::EditorMenuNotificationBus::Handler + , private AzToolsFramework::EditorEvents::Bus::Handler { public: AZ_COMPONENT(EditorMaterialSystemComponent, "{96652157-DA0B-420F-B49C-0207C585144C}"); @@ -49,7 +49,8 @@ namespace AZ private: //! EditorMaterialSystemComponentRequestBus::Handler overrides... - void OpenInMaterialEditor(const AZStd::string& sourcePath) override; + void OpenMaterialEditor(const AZStd::string& sourcePath) override; + void OpenMaterialInspector(const AZ::EntityId& entityId, const AZ::Render::MaterialAssignmentId& materialAssignmentId) override; // AzFramework::ApplicationLifecycleEvents overrides... void OnApplicationAboutToStop() override; @@ -61,6 +62,9 @@ namespace AZ void OnPopulateToolMenuItems() override; void OnResetToolMenuItems() override; + // AztoolsFramework::EditorEvents::Bus::Handler overrides... + void NotifyRegisterViews() override; + void SetupThumbnails(); void TeardownThumbnails(); diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Material/MaterialBrowserInteractions.cpp b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Material/MaterialBrowserInteractions.cpp index 258727e835..18812d45e9 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Material/MaterialBrowserInteractions.cpp +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Material/MaterialBrowserInteractions.cpp @@ -29,16 +29,13 @@ namespace AZ { if (HandlesSource(fullSourceFileName)) { - openers.push_back( - { - "Material_Editor", - "Open in Material Editor...", - QIcon(), + openers.push_back({ "Material_Editor", "Open in Material Editor...", QIcon(), [&](const char* fullSourceFileNameInCallback, [[maybe_unused]] const AZ::Uuid& sourceUUID) - { - EditorMaterialSystemComponentRequestBus::Broadcast(&EditorMaterialSystemComponentRequestBus::Events::OpenInMaterialEditor, fullSourceFileNameInCallback); - } - }); + { + EditorMaterialSystemComponentRequestBus::Broadcast( + &EditorMaterialSystemComponentRequestBus::Events::OpenMaterialEditor, + fullSourceFileNameInCallback); + } }); } } diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Material/MaterialComponentController.cpp b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Material/MaterialComponentController.cpp index 97e8301bc9..1d9f1e81dd 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Material/MaterialComponentController.cpp +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Material/MaterialComponentController.cpp @@ -35,12 +35,19 @@ namespace AZ ->Attribute(AZ::Script::Attributes::Module, "render") ->Event("GetOriginalMaterialAssignments", &MaterialComponentRequestBus::Events::GetOriginalMaterialAssignments) ->Event("FindMaterialAssignmentId", &MaterialComponentRequestBus::Events::FindMaterialAssignmentId) + ->Event("GetDefaultMaterialAssetId", &MaterialComponentRequestBus::Events::GetDefaultMaterialAssetId) + ->Event("GetMaterialSlotLabel", &MaterialComponentRequestBus::Events::GetMaterialSlotLabel) ->Event("SetMaterialOverrides", &MaterialComponentRequestBus::Events::SetMaterialOverrides) ->Event("GetMaterialOverrides", &MaterialComponentRequestBus::Events::GetMaterialOverrides) ->Event("ClearAllMaterialOverrides", &MaterialComponentRequestBus::Events::ClearAllMaterialOverrides) ->Event("SetDefaultMaterialOverride", &MaterialComponentRequestBus::Events::SetDefaultMaterialOverride) ->Event("GetDefaultMaterialOverride", &MaterialComponentRequestBus::Events::GetDefaultMaterialOverride) ->Event("ClearDefaultMaterialOverride", &MaterialComponentRequestBus::Events::ClearDefaultMaterialOverride) + ->Event("ClearModelMaterialOverrides", &MaterialComponentRequestBus::Events::ClearModelMaterialOverrides) + ->Event("ClearLodMaterialOverrides", &MaterialComponentRequestBus::Events::ClearLodMaterialOverrides) + ->Event("ClearIncompatibleMaterialOverrides", &MaterialComponentRequestBus::Events::ClearIncompatibleMaterialOverrides) + ->Event("ClearInvalidMaterialOverrides", &MaterialComponentRequestBus::Events::ClearInvalidMaterialOverrides) + ->Event("RepairInvalidMaterialOverrides", &MaterialComponentRequestBus::Events::RepairInvalidMaterialOverrides) ->Event("SetMaterialOverride", &MaterialComponentRequestBus::Events::SetMaterialOverride) ->Event("GetMaterialOverride", &MaterialComponentRequestBus::Events::GetMaterialOverride) ->Event("ClearMaterialOverride", &MaterialComponentRequestBus::Events::ClearMaterialOverride) @@ -71,6 +78,7 @@ namespace AZ ->Event("ClearPropertyOverride", &MaterialComponentRequestBus::Events::ClearPropertyOverride) ->Event("ClearPropertyOverrides", &MaterialComponentRequestBus::Events::ClearPropertyOverrides) ->Event("ClearAllPropertyOverrides", &MaterialComponentRequestBus::Events::ClearAllPropertyOverrides) + ->Event("SetPropertyOverrides", &MaterialComponentRequestBus::Events::SetPropertyOverrides) ->Event("GetPropertyOverrides", &MaterialComponentRequestBus::Events::GetPropertyOverrides) ; } @@ -168,20 +176,18 @@ namespace AZ const auto& propertyOverrides2 = materialIt->second.m_propertyOverrides; for (auto& propertyPair : propertyOverrides2) { - const auto& materialPropertyIndex = materialInstance->FindPropertyIndex(propertyPair.first); - if (!materialPropertyIndex.IsNull()) + if (propertyPair.second.empty()) { - if (propertyPair.second.is()) - { - const auto& assetId = *AZStd::any_cast(&propertyPair.second); - Data::Asset imageAsset(assetId, azrtti_typeid()); - materialInstance->SetPropertyValue(materialPropertyIndex, AZ::RPI::MaterialPropertyValue(imageAsset)); - } - else - { - materialInstance->SetPropertyValue(materialPropertyIndex, AZ::RPI::MaterialPropertyValue::FromAny(propertyPair.second)); - } + continue; } + + const auto& materialPropertyIndex = materialInstance->FindPropertyIndex(propertyPair.first); + if (materialPropertyIndex.IsNull()) + { + continue; + } + + materialInstance->SetPropertyValue(materialPropertyIndex, AZ::RPI::MaterialPropertyValue::FromAny(propertyPair.second)); } materialInstance->Compile(); @@ -274,10 +280,10 @@ namespace AZ MaterialAssignmentMap MaterialComponentController::GetOriginalMaterialAssignments() const { - MaterialAssignmentMap materialAssignmentMap; + MaterialAssignmentMap originalMaterials; MaterialReceiverRequestBus::EventResult( - materialAssignmentMap, m_entityId, &MaterialReceiverRequestBus::Events::GetMaterialAssignments); - return materialAssignmentMap; + originalMaterials, m_entityId, &MaterialReceiverRequestBus::Events::GetMaterialAssignments); + return originalMaterials; } MaterialAssignmentId MaterialComponentController::FindMaterialAssignmentId( @@ -289,6 +295,40 @@ namespace AZ return materialAssignmentId; } + AZ::Data::AssetId MaterialComponentController::GetDefaultMaterialAssetId(const MaterialAssignmentId& materialAssignmentId) const + { + RPI::ModelMaterialSlotMap modelMaterialSlots; + MaterialReceiverRequestBus::EventResult( + modelMaterialSlots, m_entityId, &MaterialReceiverRequestBus::Events::GetModelMaterialSlots); + + auto slotIter = modelMaterialSlots.find(materialAssignmentId.m_materialSlotStableId); + return slotIter != modelMaterialSlots.end() ? slotIter->second.m_defaultMaterialAsset.GetId() : AZ::Data::AssetId(); + } + + AZStd::string MaterialComponentController::GetMaterialSlotLabel(const MaterialAssignmentId& materialAssignmentId) const + { + if (materialAssignmentId == DefaultMaterialAssignmentId) + { + return "Default Material"; + } + + RPI::ModelMaterialSlotMap modelMaterialSlots; + MaterialReceiverRequestBus::EventResult( + modelMaterialSlots, m_entityId, &MaterialReceiverRequestBus::Events::GetModelMaterialSlots); + + auto slotIter = modelMaterialSlots.find(materialAssignmentId.m_materialSlotStableId); + if (slotIter != modelMaterialSlots.end()) + { + const Name& displayName = slotIter->second.m_displayName; + if (!displayName.IsEmpty()) + { + return displayName.GetStringView(); + } + } + + return ""; + } + void MaterialComponentController::SetMaterialOverrides(const MaterialAssignmentMap& materials) { // this function is called twice once material asset is changed, a temp variable is @@ -310,10 +350,70 @@ namespace AZ { m_configuration.m_materials.clear(); QueueMaterialUpdateNotification(); - MaterialComponentNotificationBus::Event(m_entityId, &MaterialComponentNotifications::OnMaterialsEdited, m_configuration.m_materials); } } + void MaterialComponentController::ClearModelMaterialOverrides() + { + AZStd::erase_if(m_configuration.m_materials, [](const auto& materialPair) { + return materialPair.first.IsSlotIdOnly(); + }); + QueueMaterialUpdateNotification(); + } + + void MaterialComponentController::ClearLodMaterialOverrides() + { + AZStd::erase_if(m_configuration.m_materials, [](const auto& materialPair) { + return materialPair.first.IsLodAndSlotId(); + }); + QueueMaterialUpdateNotification(); + } + + void MaterialComponentController::ClearIncompatibleMaterialOverrides() + { + const MaterialAssignmentMap& originalMaterials = GetOriginalMaterialAssignments(); + AZStd::erase_if(m_configuration.m_materials, [&originalMaterials](const auto& materialPair) { + return originalMaterials.find(materialPair.first) == originalMaterials.end(); + }); + QueueMaterialUpdateNotification(); + } + + void MaterialComponentController::ClearInvalidMaterialOverrides() + { + AZStd::erase_if(m_configuration.m_materials, [](const auto& materialPair) { + if (materialPair.second.m_materialAsset.GetId().IsValid()) + { + AZ::Data::AssetInfo assetInfo; + AZ::Data::AssetCatalogRequestBus::BroadcastResult( + assetInfo, &AZ::Data::AssetCatalogRequestBus::Events::GetAssetInfoById, + materialPair.second.m_materialAsset.GetId()); + return !assetInfo.m_assetId.IsValid(); + } + return false; + }); + QueueMaterialUpdateNotification(); + } + + void MaterialComponentController::RepairInvalidMaterialOverrides() + { + for (auto& materialPair : m_configuration.m_materials) + { + if (materialPair.second.m_materialAsset.GetId().IsValid()) + { + AZ::Data::AssetInfo assetInfo; + AZ::Data::AssetCatalogRequestBus::BroadcastResult( + assetInfo, &AZ::Data::AssetCatalogRequestBus::Events::GetAssetInfoById, + materialPair.second.m_materialAsset.GetId()); + if (!assetInfo.m_assetId.IsValid()) + { + materialPair.second.m_materialAsset = AZ::Data::Asset( + GetDefaultMaterialAssetId(materialPair.first), AZ::AzTypeInfo::Uuid()); + } + } + } + LoadMaterials(); + } + void MaterialComponentController::SetDefaultMaterialOverride(const AZ::Data::AssetId& materialAssetId) { SetMaterialOverride(DefaultMaterialAssignmentId, materialAssetId); @@ -329,18 +429,19 @@ namespace AZ ClearMaterialOverride(DefaultMaterialAssignmentId); } - void MaterialComponentController::SetMaterialOverride(const MaterialAssignmentId& materialAssignmentId, const AZ::Data::AssetId& materialAssetId) + void MaterialComponentController::SetMaterialOverride( + const MaterialAssignmentId& materialAssignmentId, const AZ::Data::AssetId& materialAssetId) { - m_configuration.m_materials[materialAssignmentId].m_materialAsset.Create(materialAssetId); + m_configuration.m_materials[materialAssignmentId].m_materialAsset = + AZ::Data::Asset(materialAssetId, AZ::AzTypeInfo::Uuid()); LoadMaterials(); } - const AZ::Data::AssetId MaterialComponentController::GetMaterialOverride(const MaterialAssignmentId& materialAssignmentId) const + AZ::Data::AssetId MaterialComponentController::GetMaterialOverride(const MaterialAssignmentId& materialAssignmentId) const { auto materialIt = m_configuration.m_materials.find(materialAssignmentId); if (materialIt == m_configuration.m_materials.end()) { - AZ_Error("MaterialComponentController", false, "MaterialAssignmentId not found."); return {}; } @@ -352,7 +453,6 @@ namespace AZ if (m_configuration.m_materials.erase(materialAssignmentId) > 0) { QueueMaterialUpdateNotification(); - MaterialComponentNotificationBus::Event(m_entityId, &MaterialComponentNotifications::OnMaterialsEdited, m_configuration.m_materials); } } @@ -374,7 +474,6 @@ namespace AZ } QueuePropertyChanges(materialAssignmentId); - MaterialComponentNotificationBus::Event(m_entityId, &MaterialComponentNotifications::OnMaterialsEdited, m_configuration.m_materials); } void MaterialComponentController::SetPropertyOverrideBool( @@ -452,14 +551,12 @@ namespace AZ const auto materialIt = m_configuration.m_materials.find(materialAssignmentId); if (materialIt == m_configuration.m_materials.end()) { - AZ_Error("MaterialComponentController", false, "MaterialAssignmentId not found."); return {}; } const auto propertyIt = materialIt->second.m_propertyOverrides.find(AZ::Name(propertyName)); if (propertyIt == materialIt->second.m_propertyOverrides.end()) { - AZ_Error("MaterialComponentController", false, "Property not found: %s.", propertyName.c_str()); return {}; } @@ -548,14 +645,12 @@ namespace AZ auto materialIt = m_configuration.m_materials.find(materialAssignmentId); if (materialIt == m_configuration.m_materials.end()) { - AZ_Error("MaterialComponentController", false, "MaterialAssignmentId not found."); return; } auto propertyIt = materialIt->second.m_propertyOverrides.find(AZ::Name(propertyName)); if (propertyIt == materialIt->second.m_propertyOverrides.end()) { - AZ_Error("MaterialComponentController", false, "Property not found: %s.", propertyName.c_str()); return; } @@ -568,7 +663,6 @@ namespace AZ } QueuePropertyChanges(materialAssignmentId); - MaterialComponentNotificationBus::Event(m_entityId, &MaterialComponentNotifications::OnMaterialsEdited, m_configuration.m_materials); } void MaterialComponentController::ClearPropertyOverrides(const MaterialAssignmentId& materialAssignmentId) @@ -576,7 +670,6 @@ namespace AZ auto materialIt = m_configuration.m_materials.find(materialAssignmentId); if (materialIt == m_configuration.m_materials.end()) { - AZ_Error("MaterialComponentController", false, "MaterialAssignmentId not found."); return; } @@ -586,13 +679,11 @@ namespace AZ materialIt->second.RebuildInstance(); MaterialComponentNotificationBus::Event(m_entityId, &MaterialComponentNotifications::OnMaterialInstanceCreated, materialIt->second); QueueMaterialUpdateNotification(); - MaterialComponentNotificationBus::Event(m_entityId, &MaterialComponentNotifications::OnMaterialsEdited, m_configuration.m_materials); } } void MaterialComponentController::ClearAllPropertyOverrides() { - bool cleared = false; for (auto& materialPair : m_configuration.m_materials) { if (!materialPair.second.m_propertyOverrides.empty()) @@ -601,14 +692,24 @@ namespace AZ materialPair.second.RebuildInstance(); MaterialComponentNotificationBus::Event(m_entityId, &MaterialComponentNotifications::OnMaterialInstanceCreated, materialPair.second); QueueMaterialUpdateNotification(); - cleared = true; } } + } - if (cleared) + void MaterialComponentController::SetPropertyOverrides( + const MaterialAssignmentId& materialAssignmentId, const MaterialPropertyOverrideMap& propertyOverrides) + { + auto& materialAssignment = m_configuration.m_materials[materialAssignmentId]; + const bool wasEmpty = materialAssignment.m_propertyOverrides.empty(); + materialAssignment.m_propertyOverrides = propertyOverrides; + + if (wasEmpty != materialAssignment.m_propertyOverrides.empty()) { - MaterialComponentNotificationBus::Event(m_entityId, &MaterialComponentNotifications::OnMaterialsEdited, m_configuration.m_materials); + materialAssignment.RebuildInstance(); + QueueMaterialUpdateNotification(); } + + QueuePropertyChanges(materialAssignmentId); } MaterialPropertyOverrideMap MaterialComponentController::GetPropertyOverrides(const MaterialAssignmentId& materialAssignmentId) const @@ -616,12 +717,38 @@ namespace AZ const auto materialIt = m_configuration.m_materials.find(materialAssignmentId); if (materialIt == m_configuration.m_materials.end()) { - AZ_Warning("MaterialComponentController", false, "MaterialAssignmentId not found."); return {}; } return materialIt->second.m_propertyOverrides; } + void MaterialComponentController::SetModelUvOverrides( + const MaterialAssignmentId& materialAssignmentId, const AZ::RPI::MaterialModelUvOverrideMap& modelUvOverrides) + { + auto& materialAssignment = m_configuration.m_materials[materialAssignmentId]; + const bool wasEmpty = materialAssignment.m_matModUvOverrides.empty(); + materialAssignment.m_matModUvOverrides = modelUvOverrides; + + if (wasEmpty != materialAssignment.m_matModUvOverrides.empty()) + { + materialAssignment.RebuildInstance(); + QueueMaterialUpdateNotification(); + } + + QueuePropertyChanges(materialAssignmentId); + } + + AZ::RPI::MaterialModelUvOverrideMap MaterialComponentController::GetModelUvOverrides( + const MaterialAssignmentId& materialAssignmentId) const + { + const auto materialIt = m_configuration.m_materials.find(materialAssignmentId); + if (materialIt == m_configuration.m_materials.end()) + { + return {}; + } + return materialIt->second.m_matModUvOverrides; + } + void MaterialComponentController::QueuePropertyChanges(const MaterialAssignmentId& materialAssignmentId) { m_queuedPropertyOverrides.emplace(materialAssignmentId); diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Material/MaterialComponentController.h b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Material/MaterialComponentController.h index 9e59bbef19..2bf15ca3b8 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Material/MaterialComponentController.h +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Material/MaterialComponentController.h @@ -47,14 +47,21 @@ namespace AZ //! MaterialComponentRequestBus overrides... MaterialAssignmentMap GetOriginalMaterialAssignments() const override; MaterialAssignmentId FindMaterialAssignmentId(const MaterialAssignmentLodIndex lod, const AZStd::string& label) const override; + AZ::Data::AssetId GetDefaultMaterialAssetId(const MaterialAssignmentId& materialAssignmentId) const override; + AZStd::string GetMaterialSlotLabel(const MaterialAssignmentId& materialAssignmentId) const override; void SetMaterialOverrides(const MaterialAssignmentMap& materials) override; const MaterialAssignmentMap& GetMaterialOverrides() const override; void ClearAllMaterialOverrides() override; + void ClearModelMaterialOverrides() override; + void ClearLodMaterialOverrides() override; + void ClearIncompatibleMaterialOverrides() override; + void ClearInvalidMaterialOverrides() override; + void RepairInvalidMaterialOverrides() override; void SetDefaultMaterialOverride(const AZ::Data::AssetId& materialAssetId) override; const AZ::Data::AssetId GetDefaultMaterialOverride() const override; void ClearDefaultMaterialOverride() override; void SetMaterialOverride(const MaterialAssignmentId& materialAssignmentId, const AZ::Data::AssetId& materialAssetId) override; - const AZ::Data::AssetId GetMaterialOverride(const MaterialAssignmentId& materialAssignmentId) const override; + AZ::Data::AssetId GetMaterialOverride(const MaterialAssignmentId& materialAssignmentId) const override; void ClearMaterialOverride(const MaterialAssignmentId& materialAssignmentId) override; void SetPropertyOverride(const MaterialAssignmentId& materialAssignmentId, const AZStd::string& propertyName, const AZStd::any& value) override; @@ -86,7 +93,12 @@ namespace AZ void ClearPropertyOverride(const MaterialAssignmentId& materialAssignmentId, const AZStd::string& propertyName) override; void ClearPropertyOverrides(const MaterialAssignmentId& materialAssignmentId) override; void ClearAllPropertyOverrides() override; + void SetPropertyOverrides( + const MaterialAssignmentId& materialAssignmentId, const MaterialPropertyOverrideMap& propertyOverrides) override; MaterialPropertyOverrideMap GetPropertyOverrides(const MaterialAssignmentId& materialAssignmentId) const override; + void SetModelUvOverrides( + const MaterialAssignmentId& materialAssignmentId, const AZ::RPI::MaterialModelUvOverrideMap& modelUvOverrides) override; + AZ::RPI::MaterialModelUvOverrideMap GetModelUvOverrides(const MaterialAssignmentId& materialAssignmentId) const override; private: diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Module.cpp b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Module.cpp index a83e2e9fa1..230130826e 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Module.cpp +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Module.cpp @@ -24,6 +24,7 @@ #include #include #include +#include #include #include #include @@ -57,6 +58,7 @@ #include #include #include +#include #include #include #include @@ -93,6 +95,7 @@ namespace AZ DecalComponent::CreateDescriptor(), DirectionalLightComponent::CreateDescriptor(), BloomComponent::CreateDescriptor(), + HDRColorGradingComponent::CreateDescriptor(), DisplayMapperComponent::CreateDescriptor(), DepthOfFieldComponent::CreateDescriptor(), ExposureControlComponent::CreateDescriptor(), @@ -124,6 +127,7 @@ namespace AZ EditorDecalComponent::CreateDescriptor(), EditorDirectionalLightComponent::CreateDescriptor(), EditorBloomComponent::CreateDescriptor(), + EditorHDRColorGradingComponent::CreateDescriptor(), EditorDepthOfFieldComponent::CreateDescriptor(), EditorDisplayMapperComponent::CreateDescriptor(), EditorExposureControlComponent::CreateDescriptor(), diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/PostProcess/ColorGrading/EditorHDRColorGradingComponent.cpp b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/PostProcess/ColorGrading/EditorHDRColorGradingComponent.cpp new file mode 100644 index 0000000000..49c8275141 --- /dev/null +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/PostProcess/ColorGrading/EditorHDRColorGradingComponent.cpp @@ -0,0 +1,145 @@ +/* + * Copyright (c) Contributors to the Open 3D Engine Project. + * For complete copyright and license terms please see the LICENSE at the root of this distribution. + * + * SPDX-License-Identifier: Apache-2.0 OR MIT + * + */ + +#include + +namespace AZ +{ + namespace Render + { + void EditorHDRColorGradingComponent::Reflect(AZ::ReflectContext* context) + { + BaseClass::Reflect(context); + + if (AZ::SerializeContext* serializeContext = azrtti_cast(context)) + { + serializeContext->Class()->Version(1); + + if (AZ::EditContext* editContext = serializeContext->GetEditContext()) + { + editContext->Class( + "HDR Color Grading", "Tune and apply color grading in HDR.") + ->ClassElement(Edit::ClassElements::EditorData, "") + ->Attribute(Edit::Attributes::Category, "Atom") + ->Attribute(AZ::Edit::Attributes::Icon, "Icons/Components/Component_Placeholder.svg") // [GFX TODO ATOM-2672][PostFX] need to create icons for PostProcessing. + ->Attribute(AZ::Edit::Attributes::ViewportIcon, "Icons/Components/Viewport/Component_Placeholder.svg") // [GFX TODO ATOM-2672][PostFX] need to create icons for PostProcessing. + ->Attribute(Edit::Attributes::AppearsInAddComponentMenu, AZ_CRC_CE("Game")) + ->Attribute(Edit::Attributes::AutoExpand, true) + ->Attribute(Edit::Attributes::HelpPageURL, "https://") // [TODO ATOM-2672][PostFX] need to create page for PostProcessing. + ; + + editContext->Class( + "HDRColorGradingComponentControl", "") + ->ClassElement(AZ::Edit::ClassElements::EditorData, "") + ->Attribute(AZ::Edit::Attributes::AutoExpand, true) + ->DataElement(AZ::Edit::UIHandlers::Default, &HDRColorGradingComponentController::m_configuration, "Configuration", "") + ->Attribute(AZ::Edit::Attributes::Visibility, AZ::Edit::PropertyVisibility::ShowChildrenOnly) + ; + + editContext->Class("HDRColorGradingComponentConfig", "") + ->DataElement(Edit::UIHandlers::CheckBox, &HDRColorGradingComponentConfig::m_enabled, + "Enable HDR color grading", + "Enable HDR color grading.") + ->ClassElement(AZ::Edit::ClassElements::Group, "Color Adjustment") + ->Attribute(AZ::Edit::Attributes::AutoExpand, true) + ->DataElement(AZ::Edit::UIHandlers::Slider, &HDRColorGradingComponentConfig::m_colorGradingExposure, "Exposure", "Exposure Value") + ->Attribute(Edit::Attributes::Min, AZStd::numeric_limits::lowest()) + ->Attribute(Edit::Attributes::Max, AZStd::numeric_limits::max()) + ->Attribute(Edit::Attributes::SoftMin, -20.0f) + ->Attribute(Edit::Attributes::SoftMax, 20.0f) + ->DataElement(AZ::Edit::UIHandlers::Slider, &HDRColorGradingComponentConfig::m_colorGradingContrast, "Contrast", "Contrast Value") + ->Attribute(Edit::Attributes::Min, -100.0f) + ->Attribute(Edit::Attributes::Max, 100.0f) + ->DataElement(AZ::Edit::UIHandlers::Slider, &HDRColorGradingComponentConfig::m_colorGradingPreSaturation, "Pre Saturation", "Pre Saturation Value") + ->Attribute(Edit::Attributes::Min, -100.0f) + ->Attribute(Edit::Attributes::Max, 100.0f) + ->DataElement(AZ::Edit::UIHandlers::Slider, &HDRColorGradingComponentConfig::m_colorGradingFilterIntensity, "Filter Intensity", "Filter Intensity Value") + ->Attribute(Edit::Attributes::Min, AZStd::numeric_limits::lowest()) + ->Attribute(Edit::Attributes::Max, AZStd::numeric_limits::max()) + ->Attribute(Edit::Attributes::SoftMin, -1.0f) + ->Attribute(Edit::Attributes::SoftMax, 1.0f) + ->DataElement(AZ::Edit::UIHandlers::Slider, &HDRColorGradingComponentConfig::m_colorGradingFilterMultiply, "Filter Multiply", "Filter Multiply Value") + ->Attribute(Edit::Attributes::Min, 0.0f) + ->Attribute(Edit::Attributes::Max, 1.0f) + ->DataElement(AZ::Edit::UIHandlers::Color, &HDRColorGradingComponentConfig::m_colorFilterSwatch, "Color Filter Swatch", "Color Filter Swatch Value") + + ->ClassElement(AZ::Edit::ClassElements::Group, "White Balance") + ->Attribute(AZ::Edit::Attributes::AutoExpand, true) + ->DataElement(AZ::Edit::UIHandlers::Slider, &HDRColorGradingComponentConfig::m_whiteBalanceKelvin, "Temperature", "Temperature in Kelvin") + ->Attribute(Edit::Attributes::Min, 1000.0f) + ->Attribute(Edit::Attributes::Max, 40000.0f) + ->DataElement(AZ::Edit::UIHandlers::Slider, &HDRColorGradingComponentConfig::m_whiteBalanceTint, "Tint", "Tint Value") + ->Attribute(Edit::Attributes::Min, -100.0f) + ->Attribute(Edit::Attributes::Max, 100.0f) + + ->ClassElement(AZ::Edit::ClassElements::Group, "Split Toning") + ->Attribute(AZ::Edit::Attributes::AutoExpand, true) + ->DataElement(AZ::Edit::UIHandlers::Slider, &HDRColorGradingComponentConfig::m_splitToneWeight, "Split Tone Weight", "Modulates the split toning effect.") + ->Attribute(Edit::Attributes::Min, 0.0f) + ->Attribute(Edit::Attributes::Max, 1.0f) + ->DataElement(AZ::Edit::UIHandlers::Slider, &HDRColorGradingComponentConfig::m_splitToneBalance, "Split Tone Balance", "Split Tone Balance Value") + ->Attribute(Edit::Attributes::Min, 0.0f) + ->Attribute(Edit::Attributes::Max, 1.0f) + ->DataElement(AZ::Edit::UIHandlers::Color, &HDRColorGradingComponentConfig::m_splitToneShadowsColor, "Split Tone Shadows Color", "Split Tone Shadows Color") + ->DataElement(AZ::Edit::UIHandlers::Color, &HDRColorGradingComponentConfig::m_splitToneHighlightsColor, "Split Tone Highlights Color", "Split Tone Highlights Color") + + ->ClassElement(AZ::Edit::ClassElements::Group, "Channel Mixing") + ->Attribute(AZ::Edit::Attributes::AutoExpand, true) + ->DataElement(AZ::Edit::UIHandlers::Slider, &HDRColorGradingComponentConfig::m_channelMixingRed, "Channel Mixing Red", "Channel Mixing Red Value") + ->Attribute(Edit::Attributes::Min, 0.0f) + ->DataElement(AZ::Edit::UIHandlers::Slider, &HDRColorGradingComponentConfig::m_channelMixingGreen, "Channel Mixing Green", "Channel Mixing Green Value") + ->Attribute(Edit::Attributes::Min, 0.0f) + ->DataElement(AZ::Edit::UIHandlers::Slider, &HDRColorGradingComponentConfig::m_channelMixingBlue, "Channel Mixing Blue", "Channel Mixing Blue Value") + ->Attribute(Edit::Attributes::Min, 0.0f) + + ->ClassElement(AZ::Edit::ClassElements::Group, "Shadow Midtones Highlights") + ->Attribute(AZ::Edit::Attributes::AutoExpand, true) + ->DataElement(AZ::Edit::UIHandlers::Slider, &HDRColorGradingComponentConfig::m_smhWeight, "SMH Weight", "Modulates the SMH effect.") + ->Attribute(Edit::Attributes::Min, 0.0f) + ->Attribute(Edit::Attributes::Max, 1.0f) + ->DataElement(AZ::Edit::UIHandlers::Slider, &HDRColorGradingComponentConfig::m_smhShadowsStart, "SMH Shadows Start", "SMH Shadows Start Value") + ->Attribute(Edit::Attributes::Min, 0.0f) + ->Attribute(Edit::Attributes::Max, 1.0f) + ->DataElement(AZ::Edit::UIHandlers::Slider, &HDRColorGradingComponentConfig::m_smhShadowsEnd, "SMH Shadows End", "SMH Shadows End Value") + ->Attribute(Edit::Attributes::Min, 0.0f) + ->Attribute(Edit::Attributes::Max, 1.0f) + ->DataElement(AZ::Edit::UIHandlers::Slider, &HDRColorGradingComponentConfig::m_smhHighlightsStart, "SMH Highlights Start", "SMH Highlights Start Value") + ->Attribute(Edit::Attributes::Min, 0.0f) + ->Attribute(Edit::Attributes::Max, 1.0f) + ->DataElement(AZ::Edit::UIHandlers::Slider, &HDRColorGradingComponentConfig::m_smhHighlightsEnd, "SMH Highlights End", "SMH Highlights End Value") + ->Attribute(Edit::Attributes::Min, 0.0f) + ->Attribute(Edit::Attributes::Max, 1.0f) + ->DataElement(AZ::Edit::UIHandlers::Color, &HDRColorGradingComponentConfig::m_smhShadowsColor, "SMH Shadows Color", "SMH Shadows Color") + ->DataElement(AZ::Edit::UIHandlers::Color, &HDRColorGradingComponentConfig::m_smhMidtonesColor, "SMH Midtones Color", "SMH Midtones Color") + ->DataElement(AZ::Edit::UIHandlers::Color, &HDRColorGradingComponentConfig::m_smhHighlightsColor, "SMH Highlights Color", "SMH Highlights Color") + + ->ClassElement(AZ::Edit::ClassElements::Group, "Final Adjustment") + ->Attribute(AZ::Edit::Attributes::AutoExpand, true) + ->DataElement(AZ::Edit::UIHandlers::Slider, &HDRColorGradingComponentConfig::m_colorGradingHueShift, "Hue Shift", "Hue Shift Value") + ->Attribute(Edit::Attributes::Min, 0.0f) + ->Attribute(Edit::Attributes::Max, 1.0f) + ->DataElement(AZ::Edit::UIHandlers::Slider, &HDRColorGradingComponentConfig::m_colorGradingPostSaturation, "Post Saturation", "Post Saturation Value") + ->Attribute(Edit::Attributes::Min, -100.0f) + ->Attribute(Edit::Attributes::Max, 100.0f) + ; + } + } + } + + EditorHDRColorGradingComponent::EditorHDRColorGradingComponent(const HDRColorGradingComponentConfig& config) + : BaseClass(config) + { + } + + u32 EditorHDRColorGradingComponent::OnConfigurationChanged() + { + m_controller.OnConfigChanged(); + return Edit::PropertyRefreshLevels::AttributesAndValues; + } + } // namespace Render +} // namespace AZ diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/PostProcess/ColorGrading/EditorHDRColorGradingComponent.h b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/PostProcess/ColorGrading/EditorHDRColorGradingComponent.h new file mode 100644 index 0000000000..8eea568e3a --- /dev/null +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/PostProcess/ColorGrading/EditorHDRColorGradingComponent.h @@ -0,0 +1,35 @@ +/* + * Copyright (c) Contributors to the Open 3D Engine Project. + * For complete copyright and license terms please see the LICENSE at the root of this distribution. + * + * SPDX-License-Identifier: Apache-2.0 OR MIT + * + */ + +#pragma once + +#include +#include + +namespace AZ +{ + namespace Render + { + class EditorHDRColorGradingComponent final + : public AzToolsFramework::Components:: + EditorComponentAdapter + { + public: + using BaseClass = AzToolsFramework::Components::EditorComponentAdapter; + AZ_EDITOR_COMPONENT(AZ::Render::EditorHDRColorGradingComponent, "{C1FAB0B1-5847-4533-B08E-7314AC807B8E}", BaseClass); + + static void Reflect(AZ::ReflectContext* context); + + EditorHDRColorGradingComponent() = default; + EditorHDRColorGradingComponent(const HDRColorGradingComponentConfig& config); + + //! EditorRenderComponentAdapter overrides... + AZ::u32 OnConfigurationChanged() override; + }; + } // namespace Render +} // namespace AZ diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/PostProcess/ColorGrading/HDRColorGradingComponent.cpp b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/PostProcess/ColorGrading/HDRColorGradingComponent.cpp new file mode 100644 index 0000000000..d91a91a09f --- /dev/null +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/PostProcess/ColorGrading/HDRColorGradingComponent.cpp @@ -0,0 +1,30 @@ +/* + * Copyright (c) Contributors to the Open 3D Engine Project. + * For complete copyright and license terms please see the LICENSE at the root of this distribution. + * + * SPDX-License-Identifier: Apache-2.0 OR MIT + * + */ + +#include + +namespace AZ +{ + namespace Render + { + HDRColorGradingComponent::HDRColorGradingComponent(const HDRColorGradingComponentConfig& config) + : BaseClass(config) + { + } + + void HDRColorGradingComponent::Reflect(AZ::ReflectContext* context) + { + BaseClass::Reflect(context); + + if (auto serializeContext = azrtti_cast(context)) + { + serializeContext->Class(); + } + } + } // namespace Render +} // namespace AZ diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/PostProcess/ColorGrading/HDRColorGradingComponent.h b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/PostProcess/ColorGrading/HDRColorGradingComponent.h new file mode 100644 index 0000000000..6c4bd1418f --- /dev/null +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/PostProcess/ColorGrading/HDRColorGradingComponent.h @@ -0,0 +1,33 @@ +/* + * Copyright (c) Contributors to the Open 3D Engine Project. + * For complete copyright and license terms please see the LICENSE at the root of this distribution. + * + * SPDX-License-Identifier: Apache-2.0 OR MIT + * + */ + +#pragma once + +#include +#include +#include +#include + +namespace AZ +{ + namespace Render + { + class HDRColorGradingComponent final + : public AzFramework::Components::ComponentAdapter + { + public: + using BaseClass = AzFramework::Components::ComponentAdapter; + AZ_COMPONENT(AZ::Render::HDRColorGradingComponent, "{51968E0F-4DF0-4851-8405-388CBB15B573}", BaseClass); + + HDRColorGradingComponent() = default; + HDRColorGradingComponent(const HDRColorGradingComponentConfig& config); + + static void Reflect(AZ::ReflectContext* context); + }; + } // namespace Render +} // namespace AZ diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/PostProcess/ColorGrading/HDRColorGradingComponentConfig.cpp b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/PostProcess/ColorGrading/HDRColorGradingComponentConfig.cpp new file mode 100644 index 0000000000..b63fa647a0 --- /dev/null +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/PostProcess/ColorGrading/HDRColorGradingComponentConfig.cpp @@ -0,0 +1,47 @@ +/* + * Copyright (c) Contributors to the Open 3D Engine Project. + * For complete copyright and license terms please see the LICENSE at the root of this distribution. + * + * SPDX-License-Identifier: Apache-2.0 OR MIT + * + */ + +#include +#include +#include + +namespace AZ +{ + namespace Render + { + void HDRColorGradingComponentConfig::Reflect(ReflectContext* context) + { + if (auto serializeContext = azrtti_cast(context)) + { + serializeContext->Class()->Version(0) + + // Auto-gen serialize context code... +#define SERIALIZE_CLASS HDRColorGradingComponentConfig +#include +#include +#include +#undef SERIALIZE_CLASS + ; + } + } + + void HDRColorGradingComponentConfig::CopySettingsTo (HDRColorGradingSettingsInterface* settings) + { + if (!settings) + { + return; + } + +#define COPY_TARGET settings +#include +#include +#include +#undef COPY_TARGET + } + } // namespace Render +} // namespace AZ diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/PostProcess/ColorGrading/HDRColorGradingComponentController.cpp b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/PostProcess/ColorGrading/HDRColorGradingComponentController.cpp new file mode 100644 index 0000000000..c0f70ab145 --- /dev/null +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/PostProcess/ColorGrading/HDRColorGradingComponentController.cpp @@ -0,0 +1,146 @@ +/* + * Copyright (c) Contributors to the Open 3D Engine Project. + * For complete copyright and license terms please see the LICENSE at the root of this distribution. + * + * SPDX-License-Identifier: Apache-2.0 OR MIT + * + */ + +#include + +#include + +#include + +namespace AZ +{ + namespace Render + { + void HDRColorGradingComponentController::Reflect(ReflectContext* context) + { + HDRColorGradingComponentConfig::Reflect(context); + + if (auto* serializeContext = azrtti_cast(context)) + { + serializeContext->Class() + ->Version(0) + ->Field("Configuration", &HDRColorGradingComponentController::m_configuration); + } + + if (auto* behaviorContext = azrtti_cast(context)) + { + behaviorContext->EBus("HDRColorGradingRequestBus") + ->Attribute(AZ::Script::Attributes::Module, "render") + ->Attribute(AZ::Script::Attributes::Scope, AZ::Script::Attributes::ScopeFlags::Common) + + // Auto-gen behavior context... +#define PARAM_EVENT_BUS HDRColorGradingRequestBus::Events +#include +#include +#include +#undef PARAM_EVENT_BUS + + ; + } + } + + void HDRColorGradingComponentController::GetProvidedServices(AZ::ComponentDescriptor::DependencyArrayType& provided) + { + provided.push_back(AZ_CRC_CE("HDRColorGradingService")); + } + + void HDRColorGradingComponentController::GetIncompatibleServices(AZ::ComponentDescriptor::DependencyArrayType& incompatible) + { + incompatible.push_back(AZ_CRC_CE("HDRColorGradingService")); + } + + void HDRColorGradingComponentController::GetRequiredServices(AZ::ComponentDescriptor::DependencyArrayType& required) + { + required.push_back(AZ_CRC_CE("PostFXLayerService")); + } + + HDRColorGradingComponentController::HDRColorGradingComponentController(const HDRColorGradingComponentConfig& config) + : m_configuration(config) + { + } + + void HDRColorGradingComponentController::Activate(EntityId entityId) + { + m_entityId = entityId; + + PostProcessFeatureProcessorInterface* fp = + RPI::Scene::GetFeatureProcessorForEntity(m_entityId); + if (fp) + { + m_postProcessInterface = fp->GetOrCreateSettingsInterface(m_entityId); + if (m_postProcessInterface) + { + m_settingsInterface = m_postProcessInterface->GetOrCreateHDRColorGradingSettingsInterface(); + OnConfigChanged(); + } + } + HDRColorGradingRequestBus::Handler::BusConnect(m_entityId); + } + + void HDRColorGradingComponentController::Deactivate() + { + HDRColorGradingRequestBus::Handler::BusDisconnect(m_entityId); + + if (m_postProcessInterface) + { + m_postProcessInterface->RemoveHDRColorGradingSettingsInterface(); + } + + m_postProcessInterface = nullptr; + m_settingsInterface = nullptr; + m_entityId.SetInvalid(); + } + + void HDRColorGradingComponentController::SetConfiguration(const HDRColorGradingComponentConfig& config) + { + m_configuration = config; + OnConfigChanged(); + } + + const HDRColorGradingComponentConfig& HDRColorGradingComponentController::GetConfiguration() const + { + return m_configuration; + } + + void HDRColorGradingComponentController::OnConfigChanged() + { + if (m_settingsInterface) + { + m_configuration.CopySettingsTo(m_settingsInterface); + m_settingsInterface->OnConfigChanged(); + } + } + + // Auto-gen getter/setter function definitions... + // The setter functions will set the values on the Atom settings class, then get the value back + // from the settings class to set the local configuration. This is in case the settings class + // applies some custom logic that results in the set value being different from the input +#define AZ_GFX_COMMON_PARAM(ValueType, Name, MemberName, DefaultValue) \ + ValueType HDRColorGradingComponentController::Get##Name() const \ + { \ + return m_configuration.MemberName; \ + } \ + void HDRColorGradingComponentController::Set##Name(ValueType val) \ + { \ + if (m_settingsInterface) \ + { \ + m_settingsInterface->Set##Name(val); \ + m_settingsInterface->OnConfigChanged(); \ + m_configuration.MemberName = m_settingsInterface->Get##Name(); \ + } \ + else \ + { \ + m_configuration.MemberName = val; \ + } \ + } + +#include +#include +#include + } // namespace Render +} // namespace AZ diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/PostProcess/ColorGrading/HDRColorGradingComponentController.h b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/PostProcess/ColorGrading/HDRColorGradingComponentController.h new file mode 100644 index 0000000000..d5743dfbf6 --- /dev/null +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/PostProcess/ColorGrading/HDRColorGradingComponentController.h @@ -0,0 +1,59 @@ +/* + * Copyright (c) Contributors to the Open 3D Engine Project. + * For complete copyright and license terms please see the LICENSE at the root of this distribution. + * + * SPDX-License-Identifier: Apache-2.0 OR MIT + * + */ + +#pragma once + +#include +#include +#include + +#include +#include +#include + +namespace AZ +{ + namespace Render + { + class HDRColorGradingComponentController final + : public HDRColorGradingRequestBus::Handler + { + public: + friend class EditorHDRColorGradingComponent; + + AZ_TYPE_INFO(AZ::Render::HDRColorGradingComponentController, "{CA1D635C-64E9-42C7-A8E0-36C6B825B15D}"); + 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); + + HDRColorGradingComponentController() = default; + HDRColorGradingComponentController(const HDRColorGradingComponentConfig& config); + + void Activate(EntityId entityId); + void Deactivate(); + void SetConfiguration(const HDRColorGradingComponentConfig& config); + const HDRColorGradingComponentConfig& GetConfiguration() const; + + // Auto-gen function override declarations (functions definitions in .cpp)... +#include +#include +#include + + private: + AZ_DISABLE_COPY(HDRColorGradingComponentController); + + void OnConfigChanged(); + + PostProcessSettingsInterface* m_postProcessInterface = nullptr; + HDRColorGradingSettingsInterface* m_settingsInterface = nullptr; + HDRColorGradingComponentConfig m_configuration; + EntityId m_entityId; + }; + } // namespace Render +} // namespace AZ diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/SurfaceData/SurfaceDataMeshComponent.cpp b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/SurfaceData/SurfaceDataMeshComponent.cpp index cbb30e6cd8..d8cae4564d 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/SurfaceData/SurfaceDataMeshComponent.cpp +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/SurfaceData/SurfaceDataMeshComponent.cpp @@ -231,7 +231,7 @@ namespace SurfaceData void SurfaceDataMeshComponent::UpdateMeshData() { - AZ_PROFILE_FUNCTION(Entity); + AZ_PROFILE_SCOPE(Entity, "SurfaceDataMeshComponent: UpdateMeshData"); bool meshValidBeforeUpdate = false; bool meshValidAfterUpdate = false; diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/atomlyintegration_commonfeatures_editor_files.cmake b/Gems/AtomLyIntegration/CommonFeatures/Code/atomlyintegration_commonfeatures_editor_files.cmake index 099cb378f5..174eb30b31 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/atomlyintegration_commonfeatures_editor_files.cmake +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/atomlyintegration_commonfeatures_editor_files.cmake @@ -63,6 +63,8 @@ set(FILES Source/PostProcess/EditorPostFxLayerComponent.h Source/PostProcess/Bloom/EditorBloomComponent.cpp Source/PostProcess/Bloom/EditorBloomComponent.h + Source/PostProcess/ColorGrading/EditorHDRColorGradingComponent.cpp + Source/PostProcess/ColorGrading/EditorHDRColorGradingComponent.h Source/PostProcess/DepthOfField/EditorDepthOfFieldComponent.cpp Source/PostProcess/DepthOfField/EditorDepthOfFieldComponent.h Source/PostProcess/DisplayMapper/EditorDisplayMapperComponent.cpp diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/atomlyintegration_commonfeatures_files.cmake b/Gems/AtomLyIntegration/CommonFeatures/Code/atomlyintegration_commonfeatures_files.cmake index e353795d04..63f5aedf33 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/atomlyintegration_commonfeatures_files.cmake +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/atomlyintegration_commonfeatures_files.cmake @@ -83,6 +83,11 @@ set(FILES Source/PostProcess/Bloom/BloomComponentConfig.cpp Source/PostProcess/Bloom/BloomComponentController.cpp Source/PostProcess/Bloom/BloomComponentController.h + Source/PostProcess/ColorGrading/HDRColorGradingComponent.cpp + Source/PostProcess/ColorGrading/HDRColorGradingComponent.h + Source/PostProcess/ColorGrading/HDRColorGradingComponentConfig.cpp + Source/PostProcess/ColorGrading/HDRColorGradingComponentController.cpp + Source/PostProcess/ColorGrading/HDRColorGradingComponentController.h Source/PostProcess/DepthOfField/DepthOfFieldComponent.cpp Source/PostProcess/DepthOfField/DepthOfFieldComponent.h Source/PostProcess/DepthOfField/DepthOfFieldComponentConfig.cpp diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/atomlyintegration_commonfeatures_public_files.cmake b/Gems/AtomLyIntegration/CommonFeatures/Code/atomlyintegration_commonfeatures_public_files.cmake index 68bbe52415..133856c900 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/atomlyintegration_commonfeatures_public_files.cmake +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/atomlyintegration_commonfeatures_public_files.cmake @@ -39,6 +39,8 @@ set(FILES Include/AtomLyIntegration/CommonFeatures/PostProcess/ExposureControl/ExposureControlBus.h Include/AtomLyIntegration/CommonFeatures/PostProcess/ExposureControl/ExposureControlComponentConfig.h Include/AtomLyIntegration/CommonFeatures/PostProcess/ExposureControl/ExposureControlComponentConstants.h + Include/AtomLyIntegration/CommonFeatures/PostProcess/ColorGrading/HDRColorGradingBus.h + Include/AtomLyIntegration/CommonFeatures/PostProcess/ColorGrading/HDRColorGradingComponentConfig.h Include/AtomLyIntegration/CommonFeatures/PostProcess/Ssao/SsaoBus.h Include/AtomLyIntegration/CommonFeatures/PostProcess/Ssao/SsaoComponentConfiguration.h Include/AtomLyIntegration/CommonFeatures/PostProcess/LookModification/LookModificationBus.h diff --git a/Gems/Camera/Code/CMakeLists.txt b/Gems/Camera/Code/CMakeLists.txt index 3fbeec0908..f34ac8a698 100644 --- a/Gems/Camera/Code/CMakeLists.txt +++ b/Gems/Camera/Code/CMakeLists.txt @@ -18,8 +18,8 @@ ly_add_target( PUBLIC Gem::Atom_RPI.Public AZ::AtomCore - PRIVATE - Legacy::CryCommon + AZ::AzCore + AZ::AzFramework ) ly_add_target( @@ -32,7 +32,6 @@ ly_add_target( Source BUILD_DEPENDENCIES PRIVATE - Legacy::CryCommon Gem::Camera.Static ) @@ -56,11 +55,10 @@ if (PAL_TRAIT_BUILD_HOST_TOOLS) Source BUILD_DEPENDENCIES PRIVATE - Legacy::CryCommon - Legacy::Editor.Headers - Legacy::EditorCommon AZ::AzToolsFramework Gem::Camera.Static + RUNTIME_DEPENDENCIES + Legacy::EditorCommon ) # tools and builders use the above module. diff --git a/Gems/Camera/Code/Source/CameraComponent.cpp b/Gems/Camera/Code/Source/CameraComponent.cpp index 0b892b0367..960f13a082 100644 --- a/Gems/Camera/Code/Source/CameraComponent.cpp +++ b/Gems/Camera/Code/Source/CameraComponent.cpp @@ -14,9 +14,7 @@ #include "CameraComponent.h" -#include #include -#include #include namespace Camera diff --git a/Gems/Camera/Code/Source/CameraComponent.h b/Gems/Camera/Code/Source/CameraComponent.h index de6e98154d..b9c94d482f 100644 --- a/Gems/Camera/Code/Source/CameraComponent.h +++ b/Gems/Camera/Code/Source/CameraComponent.h @@ -11,9 +11,6 @@ #include #include -#include -#include -#include #include #include diff --git a/Gems/Camera/Code/Source/CameraComponentController.cpp b/Gems/Camera/Code/Source/CameraComponentController.cpp index a8b5b8992e..b8e5738145 100644 --- a/Gems/Camera/Code/Source/CameraComponentController.cpp +++ b/Gems/Camera/Code/Source/CameraComponentController.cpp @@ -9,7 +9,6 @@ #include "CameraComponentController.h" #include "CameraViewRegistrationBus.h" -#include #include #include #include @@ -53,7 +52,7 @@ namespace Camera ->Attribute(AZ::Edit::Attributes::ChangeNotify, AZ::Edit::PropertyRefreshLevels::ValuesOnly) ->DataElement(AZ::Edit::UIHandlers::Default, &CameraComponentConfig::m_fov, "Field of view", "Vertical field of view in degrees") - ->Attribute(AZ::Edit::Attributes::Min, MIN_FOV) + ->Attribute(AZ::Edit::Attributes::Min, MinFoV) ->Attribute(AZ::Edit::Attributes::Suffix, " degrees") ->Attribute(AZ::Edit::Attributes::Step, 1.f) ->Attribute(AZ::Edit::Attributes::Max, AZ::RadToDeg(AZ::Constants::Pi) - 0.0001f) //We assert at fovs >= Pi so set the max for this field to be just under that @@ -61,7 +60,7 @@ namespace Camera ->Attribute(AZ::Edit::Attributes::Visibility, &CameraComponentConfig::GetPerspectiveParameterVisibility) ->DataElement(AZ::Edit::UIHandlers::Default, &CameraComponentConfig::m_nearClipDistance, "Near clip distance", "Distance to the near clip plane of the view Frustum") - ->Attribute(AZ::Edit::Attributes::Min, CAMERA_MIN_NEAR) + ->Attribute(AZ::Edit::Attributes::Min, MinimumNearPlaneDistance) ->Attribute(AZ::Edit::Attributes::Suffix, " m") ->Attribute(AZ::Edit::Attributes::Step, 0.1f) ->Attribute(AZ::Edit::Attributes::Max, &CameraComponentConfig::GetFarClipDistance) @@ -150,6 +149,11 @@ namespace Camera } } + void CameraComponentController::SetShouldActivateFunction(AZStd::function shouldActivateFunction) + { + m_shouldActivateFn = shouldActivateFunction; + } + void CameraComponentController::Reflect(AZ::ReflectContext* context) { CameraComponentConfig::Reflect(context); @@ -202,36 +206,6 @@ namespace Camera { m_entityId = entityId; - if ((!m_viewSystem)||(!m_system)) - { - // perform first-time init - if (gEnv) - { - m_system = gEnv->pSystem; - } - if (m_system) - { - // Initialize local view. - m_viewSystem = m_system->GetIViewSystem(); - if (!m_viewSystem) - { - AZ_Error("CameraComponent", m_viewSystem != nullptr, "The CameraComponent shouldn't be used without a local view system"); - } - } - } - - if (m_viewSystem) - { - if (m_view == nullptr) - { - m_view = m_viewSystem->CreateView(); - - AZ::Entity* entity = nullptr; - AZ::ComponentApplicationBus::BroadcastResult(entity, &AZ::ComponentApplicationRequests::FindEntity, m_entityId); - m_view->LinkTo(entity); - } - } - auto atomViewportRequests = AZ::Interface::Get(); if (atomViewportRequests) { @@ -270,9 +244,8 @@ namespace Camera CameraBus::Handler::BusConnect(); CameraNotificationBus::Broadcast(&CameraNotificationBus::Events::OnCameraAdded, m_entityId); - // Activate our camera if we're running from the launcher or Editor game mode - // Otherwise, let the Editor keep managing the active camera - if (m_config.m_makeActiveViewOnActivation && (!gEnv || !gEnv->IsEditor() || gEnv->IsEditorGameMode())) + // Only activate if we're configured to do so, and our activation call back indicates that we should + if (m_config.m_makeActiveViewOnActivation && (!m_shouldActivateFn || m_shouldActivateFn())) { MakeActiveView(); } @@ -284,20 +257,6 @@ namespace Camera CameraBus::Handler::BusDisconnect(); AZ::TransformNotificationBus::Handler::BusDisconnect(m_entityId); CameraRequestBus::Handler::BusDisconnect(m_entityId); - if (m_viewSystem) - { - if (m_view != nullptr && m_viewSystem->GetViewId(m_view) != 0) - { - m_view->Unlink(); - } - if (m_viewSystem->GetActiveView() == m_view) - { - m_viewSystem->SetActiveView(m_prevViewId); - } - m_viewSystem->RemoveView(m_view); - m_prevViewId = 0; - m_view = nullptr; - } auto atomViewportRequests = AZ::Interface::Get(); if (atomViewportRequests) @@ -429,13 +388,6 @@ namespace Camera return; } - // Set Legacy Cry view, if it exists - if (m_viewSystem) - { - m_prevViewId = AZ::u32(m_viewSystem->GetActiveViewId()); - m_viewSystem->SetActiveView(m_view); - } - // Set Atom camera, if it exists if (m_atomCamera) { @@ -461,12 +413,6 @@ namespace Camera return; } - if (m_view) - { - CCamera& camera = m_view->GetCamera(); - camera.SetMatrix(AZTransformToLYTransform(world.GetOrthogonalized())); - } - if (m_atomCamera) { m_updatingTransformFromEntity = true; @@ -495,25 +441,15 @@ namespace Camera void CameraComponentController::UpdateCamera() { - if (m_view) - { - auto viewParams = *m_view->GetCurrentParams(); - viewParams.fov = AZ::DegToRad(m_config.m_fov); - viewParams.nearplane = m_config.m_nearClipDistance; - viewParams.farplane = m_config.m_farClipDistance; - m_view->SetCurrentParams(viewParams); - } - if (auto viewportContext = GetViewportContext()) { AZ::Matrix4x4 viewToClipMatrix; - float aspectRatio = m_view ? m_view->GetCamera().GetPixelAspectRatio() : 1.f; if (!m_atomAuxGeom) { SetupAtomAuxGeom(viewportContext); } auto windowSize = viewportContext->GetViewportSize(); - aspectRatio = aznumeric_cast(windowSize.m_width) / aznumeric_cast(windowSize.m_height); + const float aspectRatio = aznumeric_cast(windowSize.m_width) / aznumeric_cast(windowSize.m_height); // This assumes a reversed depth buffer, in line with other LY Atom integration if (m_config.m_orthographic) diff --git a/Gems/Camera/Code/Source/CameraComponentController.h b/Gems/Camera/Code/Source/CameraComponentController.h index 923da65618..5eca6b1711 100644 --- a/Gems/Camera/Code/Source/CameraComponentController.h +++ b/Gems/Camera/Code/Source/CameraComponentController.h @@ -16,15 +16,12 @@ #include #include -#include -#include -#include - namespace Camera { static constexpr float DefaultFoV = 75.0f; static constexpr float MinFoV = std::numeric_limits::epsilon(); static constexpr float MaxFoV = AZ::RadToDeg(AZ::Constants::Pi); + static constexpr float MinimumNearPlaneDistance = 0.001f; static constexpr float DefaultNearPlaneDistance = 0.2f; static constexpr float DefaultFarClipPlaneDistance = 1024.0f; static constexpr float DefaultFrustumDimension = 256.f; @@ -69,6 +66,10 @@ namespace Camera CameraComponentController() = default; explicit CameraComponentController(const CameraComponentConfig& config); + //! Defines a callback for determining whether this camera should push itself to the top of the Atom camera stack. + //! Used by the Editor to disable undesirable camera changes in edit mode. + void SetShouldActivateFunction(AZStd::function shouldActivateFunction); + // Controller interface static void Reflect(AZ::ReflectContext* context); static void GetRequiredServices(AZ::ComponentDescriptor::DependencyArrayType& required); @@ -134,10 +135,6 @@ namespace Camera bool m_updatingTransformFromEntity = false; bool m_isActiveView = false; - // Cry view integration - IView* m_view = nullptr; - AZ::u32 m_prevViewId = 0; - IViewSystem* m_viewSystem = nullptr; - ISystem* m_system = nullptr; + AZStd::function m_shouldActivateFn; }; } // namespace Camera diff --git a/Gems/Camera/Code/Source/CameraEditorSystemComponent.cpp b/Gems/Camera/Code/Source/CameraEditorSystemComponent.cpp index bf3083bf59..00a147c17a 100644 --- a/Gems/Camera/Code/Source/CameraEditorSystemComponent.cpp +++ b/Gems/Camera/Code/Source/CameraEditorSystemComponent.cpp @@ -21,17 +21,12 @@ #include #include -#include -#include -#include -#include -#include - -#include -#include #include #include "ViewportCameraSelectorWindow.h" +#include +#include + namespace Camera { void CameraEditorSystemComponent::Reflect(AZ::ReflectContext* context) @@ -72,15 +67,6 @@ namespace Camera void CameraEditorSystemComponent::PopulateEditorGlobalContextMenu(QMenu* menu, const AZ::Vector2&, int flags) { - IEditor* editor; - AzToolsFramework::EditorRequests::Bus::BroadcastResult(editor, &AzToolsFramework::EditorRequests::GetEditor); - - CGameEngine* gameEngine = editor->GetGameEngine(); - if (!gameEngine || !gameEngine->IsLevelLoaded()) - { - return; - } - if (!(flags & AzToolsFramework::EditorEvents::eECMF_HIDE_ENTITY_CREATION)) { QAction* action = menu->addAction(QObject::tr("Create camera entity from view")); @@ -90,9 +76,6 @@ namespace Camera void CameraEditorSystemComponent::CreateCameraEntityFromViewport() { - IEditor* editor = nullptr; - AzToolsFramework::EditorRequests::Bus::BroadcastResult(editor, &AzToolsFramework::EditorRequests::GetEditor); - AzFramework::CameraState cameraState{}; AZ::EBusReduceResult> aggregator; Camera::EditorCameraRequestBus::BroadcastResult( diff --git a/Gems/Camera/Code/Source/CameraGem.cpp b/Gems/Camera/Code/Source/CameraGem.cpp index 7efb09a59c..99f270e71b 100644 --- a/Gems/Camera/Code/Source/CameraGem.cpp +++ b/Gems/Camera/Code/Source/CameraGem.cpp @@ -7,7 +7,6 @@ */ #include -#include #include "CameraComponent.h" #include "CameraSystemComponent.h" @@ -22,13 +21,13 @@ namespace Camera { class CameraModule - : public CryHooksModule + : public AZ::Module { public: AZ_RTTI(CameraModule, "{C2E72B0D-BCEF-452A-9BFA-03833015258C}", AZ::Module); CameraModule() - : CryHooksModule() + : AZ::Module() { m_descriptors.insert(m_descriptors.end(), { Camera::CameraComponent::CreateDescriptor(), diff --git a/Gems/Camera/Code/Source/EditorCameraComponent.cpp b/Gems/Camera/Code/Source/EditorCameraComponent.cpp index 4ebec334ec..3ac60cbff8 100644 --- a/Gems/Camera/Code/Source/EditorCameraComponent.cpp +++ b/Gems/Camera/Code/Source/EditorCameraComponent.cpp @@ -12,10 +12,9 @@ #include "EditorCameraComponent.h" #include "ViewportCameraSelectorWindow.h" -#include -#include #include #include +#include #include #include @@ -33,6 +32,14 @@ namespace Camera CameraComponentConfig controllerConfig = m_controller.GetConfiguration(); controllerConfig.m_editorEntityId = GetEntityId().operator AZ::u64(); m_controller.SetConfiguration(controllerConfig); + // Only allow our camera to activate with the component if we're currently in game mode. + m_controller.SetShouldActivateFunction([]() + { + bool isInGameMode = true; + AzToolsFramework::EditorEntityContextRequestBus::BroadcastResult( + isInGameMode, &AzToolsFramework::EditorEntityContextRequestBus::Events::IsEditorRunningGame); + return isInGameMode; + }); // Call base class activate, which in turn calls Activate on our controller. EditorCameraComponentBase::Activate(); diff --git a/Gems/Camera/Code/Source/EditorCameraComponent.h b/Gems/Camera/Code/Source/EditorCameraComponent.h index 02b9d591d0..0cb130e7a0 100644 --- a/Gems/Camera/Code/Source/EditorCameraComponent.h +++ b/Gems/Camera/Code/Source/EditorCameraComponent.h @@ -21,8 +21,6 @@ #include #include "CameraComponent.h" #include "CameraComponentController.h" -#include -#include #include diff --git a/Gems/Camera/Code/Source/ViewportCameraSelectorWindow.cpp b/Gems/Camera/Code/Source/ViewportCameraSelectorWindow.cpp index 7a8d6be020..dc091db9e5 100644 --- a/Gems/Camera/Code/Source/ViewportCameraSelectorWindow.cpp +++ b/Gems/Camera/Code/Source/ViewportCameraSelectorWindow.cpp @@ -7,17 +7,14 @@ */ #include "ViewportCameraSelectorWindow.h" #include "ViewportCameraSelectorWindow_Internals.h" -#include #include #include #include #include #include #include -#include -#include -#include #include +#include namespace Qt { @@ -308,7 +305,7 @@ namespace Camera void RegisterViewportCameraSelectorWindow() { - QtViewOptions viewOptions; + AzToolsFramework::ViewPaneOptions viewOptions; viewOptions.isPreview = true; viewOptions.showInMenu = true; viewOptions.preferedDockingArea = Qt::DockWidgetArea::LeftDockWidgetArea; diff --git a/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/AnimGraphCommands.cpp b/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/AnimGraphCommands.cpp index dbc25d7a60..bd5a14f772 100644 --- a/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/AnimGraphCommands.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/AnimGraphCommands.cpp @@ -715,12 +715,15 @@ namespace CommandSystem // restore the workspace dirty flag GetCommandManager()->SetWorkspaceDirtyFlag(m_oldWorkspaceDirtyFlag); - AZStd::string resultString; - GetCommandManager()->ExecuteCommandInsideCommand("Unselect -animGraphIndex SELECT_ALL", resultString); + MCore::CommandGroup commandGroup; + commandGroup.AddCommandString("RecorderClear"); + commandGroup.AddCommandString("Unselect -animGraphIndex SELECT_ALL"); if (animGraph) { - GetCommandManager()->ExecuteCommandInsideCommand(AZStd::string::format("Select -animGraphID %d", animGraph->GetID()), resultString); + commandGroup.AddCommandString(AZStd::string::format("Select -animGraphID %d", animGraph->GetID())); } + AZStd::string resultString; + GetCommandManager()->ExecuteCommandGroupInsideCommand(commandGroup, resultString); return true; } diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/Actor.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/Actor.cpp index 94a56cc0d5..3e592113b1 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/Actor.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/Actor.cpp @@ -1245,7 +1245,7 @@ namespace EMotionFX } else { - SetMotionExtractionNodeIndex(MCORE_INVALIDINDEX32); + SetMotionExtractionNodeIndex(InvalidIndex); } } diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/Recorder.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/Recorder.cpp index 085d164a94..54fb130ad3 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/Recorder.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/Recorder.cpp @@ -1421,17 +1421,16 @@ namespace EMotionFX // extract sorted active items void Recorder::ExtractNodeHistoryItems(const ActorInstanceData& actorInstanceData, float timeValue, bool sort, EValueType valueType, AZStd::vector* outItems, AZStd::vector* outMap) const { - // clear the map array + // Reinit the item array. const size_t maxIndex = CalcMaxNodeHistoryTrackIndex(actorInstanceData); outItems->resize(maxIndex + 1); for (size_t i = 0; i <= maxIndex; ++i) { - ExtractedNodeHistoryItem item; - item.m_trackIndex = i; - item.m_value = 0.0f; + ExtractedNodeHistoryItem& item = (*outItems)[i]; + item.m_nodeHistoryItem = nullptr; + item.m_trackIndex = i; item.m_keyTrackSampleTime = 0.0f; - item.m_nodeHistoryItem = nullptr; - outItems->emplace(AZStd::next(begin(*outItems), i), AZStd::move(item)); + item.m_value = 0.0f; } // find all node history items @@ -1440,7 +1439,7 @@ namespace EMotionFX { if (curItem->m_startTime <= timeValue && curItem->m_endTime > timeValue) { - ExtractedNodeHistoryItem item; + ExtractedNodeHistoryItem& item = (*outItems)[curItem->m_trackIndex]; item.m_trackIndex = curItem->m_trackIndex; item.m_keyTrackSampleTime = timeValue - curItem->m_startTime; item.m_nodeHistoryItem = curItem; @@ -1463,8 +1462,6 @@ namespace EMotionFX MCORE_ASSERT(false); // unsupported mode item.m_value = curItem->m_globalWeights.GetValueAtTime(item.m_keyTrackSampleTime, nullptr, nullptr, m_recordSettings.m_interpolate); } - - outItems->emplace(AZStd::next(begin(*outItems), curItem->m_trackIndex), item); } } @@ -1472,7 +1469,7 @@ namespace EMotionFX outMap->resize(maxIndex + 1); for (size_t i = 0; i <= maxIndex; ++i) { - outMap->emplace(AZStd::next(begin(*outMap), i), i); + (*outMap)[i] = i; } // sort if desired @@ -1482,7 +1479,7 @@ namespace EMotionFX for (size_t i = 0; i <= maxIndex; ++i) { - outMap->emplace(AZStd::next(begin(*outMap), outItems->at(i).m_trackIndex), i); + (*outMap)[outItems->at(i).m_trackIndex] = i; } } } diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/Recorder.h b/Gems/EMotionFX/Code/EMotionFX/Source/Recorder.h index fe87d36ea1..c486427159 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/Recorder.h +++ b/Gems/EMotionFX/Code/EMotionFX/Source/Recorder.h @@ -168,10 +168,10 @@ namespace EMotionFX struct EMFX_API ExtractedNodeHistoryItem { - NodeHistoryItem* m_nodeHistoryItem; - size_t m_trackIndex; - float m_value; - float m_keyTrackSampleTime; + NodeHistoryItem* m_nodeHistoryItem = nullptr; + size_t m_trackIndex = 0; + float m_value = 0.0f; + float m_keyTrackSampleTime = 0.0f; friend bool operator< (const ExtractedNodeHistoryItem& a, const ExtractedNodeHistoryItem& b) { return (a.m_value > b.m_value); } friend bool operator==(const ExtractedNodeHistoryItem& a, const ExtractedNodeHistoryItem& b) { return (a.m_value == b.m_value); } diff --git a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/AnimGraph/ParameterWindow.cpp b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/AnimGraph/ParameterWindow.cpp index 3f3c7c1c7d..c8ce48fe18 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/AnimGraph/ParameterWindow.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/AnimGraph/ParameterWindow.cpp @@ -1461,10 +1461,15 @@ namespace EMStudio // show the create window auto createWindow = new ParameterCreateRenameWindow("Create Group", "Please enter the group name:", uniqueGroupName.c_str(), "", invalidNames, this); - connect(createWindow, &QDialog::finished, this, [this, createWindow]() + connect(createWindow, &QDialog::finished, this, [this, createWindow](int resultCode) { createWindow->deleteLater(); + if (resultCode == QDialog::Rejected) + { + return; + } + AZStd::string command = AZStd::string::format("AnimGraphAddGroupParameter -animGraphID %i -name \"%s\"", m_animGraph->GetID(), createWindow->GetName().c_str()); const EMotionFX::GroupParameter* parentGroup = nullptr; const EMotionFX::Parameter* selectedParameter = GetSingleSelectedParameter(); diff --git a/Gems/EMotionFX/Code/MCore/Source/MCoreCommandManager.h b/Gems/EMotionFX/Code/MCore/Source/MCoreCommandManager.h index d59639dee5..495fdcde07 100644 --- a/Gems/EMotionFX/Code/MCore/Source/MCoreCommandManager.h +++ b/Gems/EMotionFX/Code/MCore/Source/MCoreCommandManager.h @@ -40,7 +40,7 @@ namespace MCore CommandHistoryEntry() : m_commandGroup(nullptr) , m_executedCommand(nullptr) - , m_parameters(nullptr) {} + {} /** * Extended Constructor. diff --git a/Gems/EMotionFX/Code/Source/Editor/ActorJointBrowseEdit.cpp b/Gems/EMotionFX/Code/Source/Editor/ActorJointBrowseEdit.cpp index 41253a513e..b1f8733bfe 100644 --- a/Gems/EMotionFX/Code/Source/Editor/ActorJointBrowseEdit.cpp +++ b/Gems/EMotionFX/Code/Source/Editor/ActorJointBrowseEdit.cpp @@ -66,6 +66,7 @@ namespace EMStudio m_jointSelectionWindow = new NodeSelectionWindow(this, m_singleJointSelection); connect(m_jointSelectionWindow, &NodeSelectionWindow::rejected, this, &ActorJointBrowseEdit::OnSelectionRejected); connect(m_jointSelectionWindow->GetNodeHierarchyWidget()->GetTreeWidget(), &QTreeWidget::itemSelectionChanged, this, &ActorJointBrowseEdit::OnSelectionChanged); + connect(m_jointSelectionWindow->GetNodeHierarchyWidget(), &NodeHierarchyWidget::OnSelectionDone, this, &ActorJointBrowseEdit::OnSelectionDone); NodeSelectionWindow::connect(m_jointSelectionWindow, &QDialog::finished, [=]([[maybe_unused]] int resultCode) { diff --git a/Gems/LandscapeCanvas/Code/Source/Editor/MainWindow.cpp b/Gems/LandscapeCanvas/Code/Source/Editor/MainWindow.cpp index 836eec682e..4574b938f6 100644 --- a/Gems/LandscapeCanvas/Code/Source/Editor/MainWindow.cpp +++ b/Gems/LandscapeCanvas/Code/Source/Editor/MainWindow.cpp @@ -2512,6 +2512,26 @@ namespace LandscapeCanvasEditor { // See comment above in OnPrefabInstancePropagationBegin m_prefabPropagationInProgress = false; + + // After prefab propagation is complete, the entity tied to one of our open + // graphs might have been deleted (e.g. if a prefab was created from that entity). + // Any open graphs tied to an entity that no longer exists will need to be closed. + // We need to close them in a separate iterator because the CloseEditor API will + // end up modifying m_dockWidgetsByEntity. + AZStd::vector dockWidgetsToDelete; + for (auto [entityId, dockWidgetId] : m_dockWidgetsByEntity) + { + AZ::Entity* entity = nullptr; + AZ::ComponentApplicationBus::BroadcastResult(entity, &AZ::ComponentApplicationRequests::FindEntity, entityId); + if (!entity) + { + dockWidgetsToDelete.push_back(dockWidgetId); + } + } + for (auto dockWidgetId : dockWidgetsToDelete) + { + CloseEditor(dockWidgetId); + } } void MainWindow::OnCryEditorEndCreate() diff --git a/Gems/LmbrCentral/Code/CMakeLists.txt b/Gems/LmbrCentral/Code/CMakeLists.txt index 00176ae2c2..b047a9f65e 100644 --- a/Gems/LmbrCentral/Code/CMakeLists.txt +++ b/Gems/LmbrCentral/Code/CMakeLists.txt @@ -114,6 +114,16 @@ endif() # Tests ################################################################################ if(PAL_TRAIT_BUILD_TESTS_SUPPORTED) + ly_add_target( + NAME LmbrCentral.Mocks HEADERONLY + NAMESPACE Gem + FILES_CMAKE + lmbrcentral_mocks_files.cmake + INCLUDE_DIRECTORIES + INTERFACE + Mocks + ) + ly_add_target( NAME LmbrCentral.Tests ${PAL_TRAIT_TEST_TARGET_TYPE} NAMESPACE Gem @@ -131,6 +141,7 @@ if(PAL_TRAIT_BUILD_TESTS_SUPPORTED) Legacy::CryCommon AZ::AzFramework Gem::LmbrCentral.Static + Gem::LmbrCentral.Mocks ) ly_add_googletest( NAME Gem::LmbrCentral.Tests diff --git a/Gems/LmbrCentral/Code/Mocks/LmbrCentral/Shape/MockShapes.h b/Gems/LmbrCentral/Code/Mocks/LmbrCentral/Shape/MockShapes.h new file mode 100644 index 0000000000..20be74dd90 --- /dev/null +++ b/Gems/LmbrCentral/Code/Mocks/LmbrCentral/Shape/MockShapes.h @@ -0,0 +1,60 @@ +/* + * Copyright (c) Contributors to the Open 3D Engine Project. + * For complete copyright and license terms please see the LICENSE at the root of this distribution. + * + * SPDX-License-Identifier: Apache-2.0 OR MIT + * + */ +#pragma once + +#include + +#include +#include +#include + +namespace UnitTest +{ + class MockBoxShapeComponentRequests + : public LmbrCentral::BoxShapeComponentRequestsBus::Handler + { + public: + MockBoxShapeComponentRequests(AZ::EntityId entityId) + { + LmbrCentral::BoxShapeComponentRequestsBus::Handler::BusConnect(entityId); + } + + ~MockBoxShapeComponentRequests() + { + LmbrCentral::BoxShapeComponentRequestsBus::Handler::BusDisconnect(); + } + + MOCK_METHOD0(GetBoxConfiguration, LmbrCentral::BoxShapeConfig()); + MOCK_METHOD0(GetBoxDimensions, AZ::Vector3()); + MOCK_METHOD1(SetBoxDimensions, void(const AZ::Vector3& newDimensions)); + }; + + class MockShapeComponentRequests + : public LmbrCentral::ShapeComponentRequestsBus::Handler + { + public: + MockShapeComponentRequests(AZ::EntityId entityId) + { + LmbrCentral::ShapeComponentRequestsBus::Handler::BusConnect(entityId); + } + + ~MockShapeComponentRequests() + { + LmbrCentral::ShapeComponentRequestsBus::Handler::BusDisconnect(); + } + + MOCK_METHOD0(GetShapeType, AZ::Crc32()); + MOCK_METHOD0(GetEncompassingAabb, AZ::Aabb()); + MOCK_METHOD2(GetTransformAndLocalBounds, void(AZ::Transform& transform, AZ::Aabb& bounds)); + MOCK_METHOD1(IsPointInside, bool(const AZ::Vector3& point)); + MOCK_METHOD1(DistanceSquaredFromPoint, float(const AZ::Vector3& point)); + MOCK_METHOD1(GenerateRandomPointInside, AZ::Vector3(AZ::RandomDistributionType randomDistribution)); + MOCK_METHOD3(IntersectRay, bool(const AZ::Vector3& src, const AZ::Vector3& dir, float& distance)); + }; +} + diff --git a/Gems/LmbrCentral/Code/Source/Editor/EditorCommentComponent.cpp b/Gems/LmbrCentral/Code/Source/Editor/EditorCommentComponent.cpp index 7eb0db1832..97f8dc60a2 100644 --- a/Gems/LmbrCentral/Code/Source/Editor/EditorCommentComponent.cpp +++ b/Gems/LmbrCentral/Code/Source/Editor/EditorCommentComponent.cpp @@ -30,7 +30,7 @@ namespace LmbrCentral ->ClassElement(AZ::Edit::ClassElements::EditorData, "") ->Attribute(AZ::Edit::Attributes::Category, "Editor") ->Attribute(AZ::Edit::Attributes::Icon, "Icons/Components/Comment.svg") - ->Attribute(AZ::Edit::Attributes::ViewportIcon, "Icons/Components/Viewport/Comment.png") + ->Attribute(AZ::Edit::Attributes::ViewportIcon, "Icons/Components/Viewport/Comment.svg") ->Attribute(AZ::Edit::Attributes::AppearsInAddComponentMenu, AZStd::vector({ AZ_CRC("Level", 0x9aeacc13), AZ_CRC("Game", 0x232b318c), AZ_CRC("Layer", 0xe4db211a) })) ->Attribute(AZ::Edit::Attributes::AutoExpand, true) ->Attribute(AZ::Edit::Attributes::HelpPageURL, "https://o3de.org/docs/user-guide/components/reference/comment/") diff --git a/Gems/LmbrCentral/Code/Tests/LmbrCentralTest.cpp b/Gems/LmbrCentral/Code/Tests/LmbrCentralTest.cpp index 40217ff9bc..f36978f22d 100644 --- a/Gems/LmbrCentral/Code/Tests/LmbrCentralTest.cpp +++ b/Gems/LmbrCentral/Code/Tests/LmbrCentralTest.cpp @@ -8,4 +8,7 @@ #include +// Include any public mocks here to ensure they get compiled as a part of the test project. +#include + AZ_UNIT_TEST_HOOK(DEFAULT_UNIT_TEST_ENV); diff --git a/Gems/LmbrCentral/Code/lmbrcentral_mocks_files.cmake b/Gems/LmbrCentral/Code/lmbrcentral_mocks_files.cmake new file mode 100644 index 0000000000..c3a5cca3f8 --- /dev/null +++ b/Gems/LmbrCentral/Code/lmbrcentral_mocks_files.cmake @@ -0,0 +1,11 @@ +# +# Copyright (c) Contributors to the Open 3D Engine Project. +# For complete copyright and license terms please see the LICENSE at the root of this distribution. +# +# SPDX-License-Identifier: Apache-2.0 OR MIT +# +# + +set(FILES + Mocks/LmbrCentral/Shape/MockShapes.h +) diff --git a/Gems/LyShine/Code/Editor/Animation/Controls/UiSplineCtrlEx.cpp b/Gems/LyShine/Code/Editor/Animation/Controls/UiSplineCtrlEx.cpp index 94a4c77593..60109fc49c 100644 --- a/Gems/LyShine/Code/Editor/Animation/Controls/UiSplineCtrlEx.cpp +++ b/Gems/LyShine/Code/Editor/Animation/Controls/UiSplineCtrlEx.cpp @@ -78,7 +78,7 @@ protected: m_splineEntries.resize(m_splineEntries.size() + 1); SplineEntry& entry = m_splineEntries.back(); ISplineSet* pSplineSet = (pCtrl ? pCtrl->m_pSplineSet : 0); - entry.id = (pSplineSet ? pSplineSet->GetIDFromSpline(pSpline) : 0); + entry.id = (pSplineSet ? pSplineSet->GetIDFromSpline(pSpline) : AZStd::string{}); entry.pSpline = pSpline; const int numKeys = pSpline->GetKeyCount(); diff --git a/Gems/Multiplayer/Code/CMakeLists.txt b/Gems/Multiplayer/Code/CMakeLists.txt index e8b38c8799..49b404fb1c 100644 --- a/Gems/Multiplayer/Code/CMakeLists.txt +++ b/Gems/Multiplayer/Code/CMakeLists.txt @@ -25,6 +25,9 @@ ly_add_target( AZ::AzCore AZ::AzFramework AZ::AzNetworking + PRIVATE + Gem::EMotionFXStaticLib + Gem::PhysX.Static AUTOGEN_RULES *.AutoPackets.xml,AutoPackets_Header.jinja,$path/$fileprefix.AutoPackets.h *.AutoPackets.xml,AutoPackets_Inline.jinja,$path/$fileprefix.AutoPackets.inl diff --git a/Gems/Multiplayer/Code/Include/Multiplayer/Components/NetBindComponent.h b/Gems/Multiplayer/Code/Include/Multiplayer/Components/NetBindComponent.h index 65bac09726..d09de1ad0d 100644 --- a/Gems/Multiplayer/Code/Include/Multiplayer/Components/NetBindComponent.h +++ b/Gems/Multiplayer/Code/Include/Multiplayer/Components/NetBindComponent.h @@ -35,7 +35,7 @@ namespace Multiplayer using EntityMigrationStartEvent = AZ::Event; using EntityMigrationEndEvent = AZ::Event<>; using EntityServerMigrationEvent = AZ::Event; - using EntityPreRenderEvent = AZ::Event; + using EntityPreRenderEvent = AZ::Event; using EntityCorrectionEvent = AZ::Event<>; //! @class NetBindComponent @@ -118,7 +118,7 @@ namespace Multiplayer void NotifyMigrationStart(ClientInputId migratedInputId); void NotifyMigrationEnd(); void NotifyServerMigration(HostId hostId, AzNetworking::ConnectionId connectionId); - void NotifyPreRender(float deltaTime, float blendFactor); + void NotifyPreRender(float deltaTime); void NotifyCorrection(); void AddEntityStopEventHandler(EntityStopEvent::Handler& eventHandler); diff --git a/Gems/Multiplayer/Code/Include/Multiplayer/Components/NetworkCharacterComponent.h b/Gems/Multiplayer/Code/Include/Multiplayer/Components/NetworkCharacterComponent.h new file mode 100644 index 0000000000..478c925299 --- /dev/null +++ b/Gems/Multiplayer/Code/Include/Multiplayer/Components/NetworkCharacterComponent.h @@ -0,0 +1,82 @@ +/* + * Copyright (c) Contributors to the Open 3D Engine Project. + * For complete copyright and license terms please see the LICENSE at the root of this distribution. + * + * SPDX-License-Identifier: Apache-2.0 OR MIT + * + */ + +#pragma once + +#include +#include +#include + +namespace Physics +{ + class Character; +} + +namespace Multiplayer +{ + //! NetworkCharacterComponent + //! Provides multiplayer support for game-play player characters. + class NetworkCharacterComponent + : public NetworkCharacterComponentBase + , private PhysX::CharacterGameplayRequestBus::Handler + { + friend class NetworkCharacterComponentController; + + public: + AZ_MULTIPLAYER_COMPONENT(Multiplayer::NetworkCharacterComponent, s_networkCharacterComponentConcreteUuid, Multiplayer::NetworkCharacterComponentBase) + + static void Reflect(AZ::ReflectContext* context); + + NetworkCharacterComponent(); + + static void GetIncompatibleServices(AZ::ComponentDescriptor::DependencyArrayType& incompatible) + { + incompatible.push_back(AZ_CRC_CE("NetworkRigidBodyService")); + } + + // AZ::Component + void OnInit() override {} + void OnActivate(Multiplayer::EntityIsMigrating entityIsMigrating) override; + void OnDeactivate(Multiplayer::EntityIsMigrating entityIsMigrating) override; + + private: + void OnTranslationChangedEvent(const AZ::Vector3& translation); + void OnSyncRewind(); + + // CharacterGameplayRequestBus + bool IsOnGround() const override; + float GetGravityMultiplier() const override { return {}; } + void SetGravityMultiplier([[maybe_unused]] float gravityMultiplier) override {} + AZ::Vector3 GetFallingVelocity() const override { return {}; } + void SetFallingVelocity([[maybe_unused]] const AZ::Vector3& fallingVelocity) override {} + + Physics::Character* m_physicsCharacter = nullptr; + Multiplayer::EntitySyncRewindEvent::Handler m_syncRewindHandler = Multiplayer::EntitySyncRewindEvent::Handler([this]() { OnSyncRewind(); }); + AZ::Event::Handler m_translationEventHandler; + }; + + //! NetworkCharacterComponentController + //! This is the network controller for NetworkCharacterComponent. + //! Class provides the ability to move characters in physical space while keeping the network in-sync. + class NetworkCharacterComponentController + : public NetworkCharacterComponentControllerBase + { + public: + NetworkCharacterComponentController(NetworkCharacterComponent& parent); + + // NetworkCharacterComponentControllerBase + void OnActivate(Multiplayer::EntityIsMigrating entityIsMigrating) override; + void OnDeactivate(Multiplayer::EntityIsMigrating entityIsMigrating) override; + + //! TryMoveWithVelocity + //! Will move this character entity kinematically through physical world while also ensuring the network stays in-sync. + //! Velocity will be applied over delta-time to determine the movement amount. + //! Returns this entity's world-space position after the move. + AZ::Vector3 TryMoveWithVelocity(const AZ::Vector3& velocity, float deltaTime); + }; +} diff --git a/Gems/Multiplayer/Code/Include/Multiplayer/Components/NetworkHitVolumesComponent.h b/Gems/Multiplayer/Code/Include/Multiplayer/Components/NetworkHitVolumesComponent.h new file mode 100644 index 0000000000..215359f209 --- /dev/null +++ b/Gems/Multiplayer/Code/Include/Multiplayer/Components/NetworkHitVolumesComponent.h @@ -0,0 +1,90 @@ +/* + * Copyright (c) Contributors to the Open 3D Engine Project. + * For complete copyright and license terms please see the LICENSE at the root of this distribution. + * + * SPDX-License-Identifier: Apache-2.0 OR MIT + * + */ + +#pragma once + +#include +#include +#include +#include + +namespace Physics +{ + class CharacterRequests; + class CharacterHitDetectionConfiguration; +} + +namespace Multiplayer +{ + class NetworkHitVolumesComponent + : public NetworkHitVolumesComponentBase + , private EMotionFX::Integration::ActorComponentNotificationBus::Handler + { + public: + struct AnimatedHitVolume final + { + AnimatedHitVolume + ( + AzNetworking::ConnectionId connectionId, + Physics::CharacterRequests* character, + const char* hitVolumeName, + const Physics::ColliderConfiguration* colliderConfig, + const Physics::ShapeConfiguration* shapeConfig, + const uint32_t jointIndex + ); + + ~AnimatedHitVolume() = default; + + void UpdateTransform(const AZ::Transform& transform); + void SyncToCurrentTransform(); + + Multiplayer::RewindableObject m_transform; + AZStd::shared_ptr m_physicsShape; + + // Cached so we don't have to do subsequent lookups by name + const Physics::ColliderConfiguration* m_colliderConfig = nullptr; + const Physics::ShapeConfiguration* m_shapeConfig = nullptr; + AZ::Transform m_colliderOffSetTransform; + const AZ::u32 m_jointIndex = 0; + }; + + AZ_MULTIPLAYER_COMPONENT(Multiplayer::NetworkHitVolumesComponent, s_networkHitVolumesComponentConcreteUuid, Multiplayer::NetworkHitVolumesComponentBase); + + static void Reflect(AZ::ReflectContext* context); + + NetworkHitVolumesComponent(); + + void OnInit() override; + void OnActivate(Multiplayer::EntityIsMigrating entityIsMigrating) override; + void OnDeactivate(Multiplayer::EntityIsMigrating entityIsMigrating) override; + + private: + void OnPreRender(float deltaTime); + void OnTransformUpdate(const AZ::Transform& transform); + void OnSyncRewind(); + + void CreateHitVolumes(); + void DestroyHitVolumes(); + + //! ActorComponentNotificationBus::Handler + //! @{ + void OnActorInstanceCreated(EMotionFX::ActorInstance* actorInstance) override; + void OnActorInstanceDestroyed(EMotionFX::ActorInstance* actorInstance) override; + //! @} + + Physics::CharacterRequests* m_physicsCharacter = nullptr; + EMotionFX::Integration::ActorComponentRequests* m_actorComponent = nullptr; + const Physics::CharacterColliderConfiguration* m_hitDetectionConfig = nullptr; + + AZStd::vector m_animatedHitVolumes; + + Multiplayer::EntitySyncRewindEvent::Handler m_syncRewindHandler; + Multiplayer::EntityPreRenderEvent::Handler m_preRenderHandler; + AZ::TransformChangedEvent::Handler m_transformChangedHandler; + }; +} diff --git a/Gems/Multiplayer/Code/Include/Multiplayer/Components/NetworkRigidBodyComponent.h b/Gems/Multiplayer/Code/Include/Multiplayer/Components/NetworkRigidBodyComponent.h new file mode 100644 index 0000000000..19379fc959 --- /dev/null +++ b/Gems/Multiplayer/Code/Include/Multiplayer/Components/NetworkRigidBodyComponent.h @@ -0,0 +1,68 @@ +/* + * Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. + * + * SPDX-License-Identifier: Apache-2.0 OR MIT + * + */ +#pragma once + +#include +#include +#include + +namespace Physics +{ + class RigidBodyRequests; +} + +namespace Multiplayer +{ + //! Bus for requests to the network rigid body component. + class NetworkRigidBodyRequests : public AZ::ComponentBus + { + }; + using NetworkRigidBodyRequestBus = AZ::EBus; + + class NetworkRigidBodyComponent final + : public NetworkRigidBodyComponentBase + , private NetworkRigidBodyRequestBus::Handler + { + friend class NetworkRigidBodyComponentController; + + public: + AZ_MULTIPLAYER_COMPONENT( + Multiplayer::NetworkRigidBodyComponent, s_networkRigidBodyComponentConcreteUuid, Multiplayer::NetworkRigidBodyComponentBase); + + static void Reflect(AZ::ReflectContext* context); + static void GetProvidedServices(AZ::ComponentDescriptor::DependencyArrayType& provided); + static void GetRequiredServices(AZ::ComponentDescriptor::DependencyArrayType& required); + static void GetDependentServices(AZ::ComponentDescriptor::DependencyArrayType& dependent); + + NetworkRigidBodyComponent(); + + void OnInit() override; + void OnActivate(Multiplayer::EntityIsMigrating entityIsMigrating) override; + void OnDeactivate(Multiplayer::EntityIsMigrating entityIsMigrating) override; + + private: + void OnTransformUpdate(const AZ::Transform& worldTm); + void OnSyncRewind(); + + Multiplayer::EntitySyncRewindEvent::Handler m_syncRewindHandler; + AZ::TransformChangedEvent::Handler m_transformChangedHandler; + Physics::RigidBodyRequests* m_physicsRigidBodyComponent = nullptr; + Multiplayer::RewindableObject m_transform; + }; + + class NetworkRigidBodyComponentController + : public NetworkRigidBodyComponentControllerBase + { + public: + NetworkRigidBodyComponentController(NetworkRigidBodyComponent& parent); + + void OnActivate(Multiplayer::EntityIsMigrating entityIsMigrating) override; + void OnDeactivate(Multiplayer::EntityIsMigrating entityIsMigrating) override; + + void HandleSendApplyImpulse(AzNetworking::IConnection* invokingConnection, const AZ::Vector3& impulse, const AZ::Vector3& worldPoint) override; + }; +} // namespace Multiplayer diff --git a/Gems/Multiplayer/Code/Include/Multiplayer/Components/NetworkTransformComponent.h b/Gems/Multiplayer/Code/Include/Multiplayer/Components/NetworkTransformComponent.h index 914aeaadd3..a018279a79 100644 --- a/Gems/Multiplayer/Code/Include/Multiplayer/Components/NetworkTransformComponent.h +++ b/Gems/Multiplayer/Code/Include/Multiplayer/Components/NetworkTransformComponent.h @@ -29,24 +29,9 @@ namespace Multiplayer void OnDeactivate(Multiplayer::EntityIsMigrating entityIsMigrating) override; private: - void OnPreRender(float deltaTime, float blendFactor); + void OnPreRender(float deltaTime); void OnCorrection(); - void OnRotationChangedEvent(const AZ::Quaternion& rotation); - void OnTranslationChangedEvent(const AZ::Vector3& translation); - void OnScaleChangedEvent(float scale); - void OnResetCountChangedEvent(); - - void UpdateTargetHostFrameId(); - - AZ::Transform m_previousTransform = AZ::Transform::CreateIdentity(); - AZ::Transform m_targetTransform = AZ::Transform::CreateIdentity(); - - AZ::Event::Handler m_rotationEventHandler; - AZ::Event::Handler m_translationEventHandler; - AZ::Event::Handler m_scaleEventHandler; - AZ::Event::Handler m_resetCountEventHandler; - EntityPreRenderEvent::Handler m_entityPreRenderEventHandler; EntityCorrectionEvent::Handler m_entityCorrectionEventHandler; diff --git a/Gems/Multiplayer/Code/Include/Multiplayer/IMultiplayer.h b/Gems/Multiplayer/Code/Include/Multiplayer/IMultiplayer.h index 4f714068db..e32b6188eb 100644 --- a/Gems/Multiplayer/Code/Include/Multiplayer/IMultiplayer.h +++ b/Gems/Multiplayer/Code/Include/Multiplayer/IMultiplayer.h @@ -193,15 +193,13 @@ namespace Multiplayer m_previousHostFrameId = time->GetHostFrameId(); m_previousHostTimeMs = time->GetHostTimeMs(); m_previousRewindConnectionId = time->GetRewindingConnectionId(); - time->AlterTime(frameId, timeMs, connectionId); m_previousBlendFactor = time->GetHostBlendFactor(); - time->AlterBlendFactor(blendFactor); + time->AlterTime(frameId, timeMs, blendFactor, connectionId); } inline ~ScopedAlterTime() { INetworkTime* time = GetNetworkTime(); - time->AlterTime(m_previousHostFrameId, m_previousHostTimeMs, m_previousRewindConnectionId); - time->AlterBlendFactor(m_previousBlendFactor); + time->AlterTime(m_previousHostFrameId, m_previousHostTimeMs, m_previousBlendFactor, m_previousRewindConnectionId); } private: HostFrameId m_previousHostFrameId = InvalidHostFrameId; diff --git a/Gems/Multiplayer/Code/Include/Multiplayer/NetworkTime/INetworkTime.h b/Gems/Multiplayer/Code/Include/Multiplayer/NetworkTime/INetworkTime.h index ae47aa8373..c12cbb660b 100644 --- a/Gems/Multiplayer/Code/Include/Multiplayer/NetworkTime/INetworkTime.h +++ b/Gems/Multiplayer/Code/Include/Multiplayer/NetworkTime/INetworkTime.h @@ -52,12 +52,6 @@ namespace Multiplayer //! @return the ConnectionId of the connection requesting the rewind operation virtual AzNetworking::ConnectionId GetRewindingConnectionId() const = 0; - //! Get the controlling connection that may be currently altering global game time. - //! Note this abstraction is required at a relatively high level to allow for 'don't rewind the shooter' semantics - //! @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; - //! Forcibly sets the current network time to the provided frameId and game time in milliseconds. //! @param frameId the new HostFrameId to use //! @param timeMs the new HostTimeMs to use @@ -66,12 +60,9 @@ namespace Multiplayer //! 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 blendFactor the factor used to blend between values at the current and previous HostFrameId //! @param rewindConnectionId the rewinding ConnectionId - virtual void AlterTime(HostFrameId frameId, AZ::TimeMs timeMs, AzNetworking::ConnectionId rewindConnectionId) = 0; - - //! Alters the current Host blend factor. Used to drive interpolation in rewound states. - //! @param blendFactor the blend factor to use - virtual void AlterBlendFactor(float blendFactor) = 0; + virtual void AlterTime(HostFrameId frameId, AZ::TimeMs timeMs, float blendFactor, AzNetworking::ConnectionId rewindConnectionId) = 0; //! Syncs all entities contained within a volume to the current rewind state. //! @param rewindVolume the volume to rewind entities within (needed for physics entities) diff --git a/Gems/Multiplayer/Code/Include/Multiplayer/NetworkTime/RewindableObject.h b/Gems/Multiplayer/Code/Include/Multiplayer/NetworkTime/RewindableObject.h index a8af564c15..152f6f47a7 100644 --- a/Gems/Multiplayer/Code/Include/Multiplayer/NetworkTime/RewindableObject.h +++ b/Gems/Multiplayer/Code/Include/Multiplayer/NetworkTime/RewindableObject.h @@ -60,7 +60,7 @@ namespace Multiplayer //! @return value in const base type form const BASE_TYPE& Get() const; - //! Const base type retriever for one host frame behind Get(). Only intended for use in SyncRewind contexts. + //! Const base type retriever for one host frame behind Get() when contextually appropriate, otherwise identical to Get(). //! @return value in const base type form const BASE_TYPE& GetPrevious() const; @@ -86,9 +86,13 @@ namespace Multiplayer private: //! Returns what the appropriate current time is for this rewindable property. - //! @return the appropriate current time is for this rewindable property + //! @return the appropriate current time for this rewindable property HostFrameId GetCurrentTimeForProperty() const; + //! Returns what the appropriate previous time is for this rewindable property. + //! @return the appropriate previous time for this rewindable property + HostFrameId GetPreviousTimeForProperty() 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 diff --git a/Gems/Multiplayer/Code/Include/Multiplayer/NetworkTime/RewindableObject.inl b/Gems/Multiplayer/Code/Include/Multiplayer/NetworkTime/RewindableObject.inl index b0c9bc0c46..9183a1e9da 100644 --- a/Gems/Multiplayer/Code/Include/Multiplayer/NetworkTime/RewindableObject.inl +++ b/Gems/Multiplayer/Code/Include/Multiplayer/NetworkTime/RewindableObject.inl @@ -69,7 +69,7 @@ namespace Multiplayer template inline const BASE_TYPE& RewindableObject::GetPrevious() const { - return GetValueForTime(GetCurrentTimeForProperty() - HostFrameId(1)); + return GetValueForTime(GetPreviousTimeForProperty()); } template @@ -118,7 +118,22 @@ namespace Multiplayer inline HostFrameId RewindableObject::GetCurrentTimeForProperty() const { INetworkTime* networkTime = Multiplayer::GetNetworkTime(); - return networkTime->GetHostFrameIdForRewindingConnection(m_owningConnectionId); + if (networkTime->IsTimeRewound() && (m_owningConnectionId == networkTime->GetRewindingConnectionId())) + { + return networkTime->GetUnalteredHostFrameId(); + } + return networkTime->GetHostFrameId(); + } + + template + inline HostFrameId RewindableObject::GetPreviousTimeForProperty() const + { + INetworkTime* networkTime = Multiplayer::GetNetworkTime(); + if (networkTime->IsTimeRewound() && (m_owningConnectionId == networkTime->GetRewindingConnectionId())) + { + return networkTime->GetUnalteredHostFrameId(); + } + return networkTime->GetHostFrameId() - HostFrameId(1); } template diff --git a/Gems/Multiplayer/Code/Source/AutoGen/AutoComponentTypes_Source.jinja b/Gems/Multiplayer/Code/Source/AutoGen/AutoComponentTypes_Source.jinja index 7bb4bdcc2c..c551c8bc20 100644 --- a/Gems/Multiplayer/Code/Source/AutoGen/AutoComponentTypes_Source.jinja +++ b/Gems/Multiplayer/Code/Source/AutoGen/AutoComponentTypes_Source.jinja @@ -14,7 +14,7 @@ {% set Namespace = dataFiles[0].attrib['Namespace'] %} {% for Component in dataFiles %} {% if Component.attrib['Namespace'] != Namespace %} -#error "mismatched component namespaces detected in declared multiplayer components, expected {{ Namespace }} but found {{ Component.attrib['Namespace'] }}" +#error "mismatched component namespaces detected in declared multiplayer components, expected {{ Namespace }} but {{ Component.attrib['Name'] }} is using {{ Component.attrib['Namespace'] }} namespace." {% endif %} {% endfor %} namespace {{ Namespace }} diff --git a/Gems/Multiplayer/Code/Source/AutoGen/AutoComponent_Header.jinja b/Gems/Multiplayer/Code/Source/AutoGen/AutoComponent_Header.jinja index 0f62da11f3..41f0fa1b02 100644 --- a/Gems/Multiplayer/Code/Source/AutoGen/AutoComponent_Header.jinja +++ b/Gems/Multiplayer/Code/Source/AutoGen/AutoComponent_Header.jinja @@ -7,21 +7,21 @@ {% macro DeclareNetworkPropertyGetter(Property) %} {% set PropertyName = UpperFirst(Property.attrib['Name']) %} {% if Property.attrib['Container'] == 'Array' %} -{% if Property.attrib['IsRewindable']|booleanTrue %} +{% if Property.attrib['IsRewindable']|booleanTrue %} const RewindableArray<{{ Property.attrib['Type'] }}, {{ Property.attrib['Count'] }}>& Get{{ PropertyName }}Array() const; -{% else %} +{% else %} const AZStd::array<{{ Property.attrib['Type'] }}, {{ Property.attrib['Count'] }}>& Get{{ PropertyName }}Array() const; -{% endif %} +{% endif %} const {{ Property.attrib['Type'] }}& Get{{ PropertyName }}(int32_t index) const; {% if Property.attrib['GenerateEventBindings']|booleanTrue %} void {{ PropertyName }}AddEvent(AZ::Event::Handler& handler); {% endif %} {% elif Property.attrib['Container'] == 'Vector' %} -{% if Property.attrib['IsRewindable']|booleanTrue %} +{% if Property.attrib['IsRewindable']|booleanTrue %} const RewindableFixedVector<{{ Property.attrib['Type'] }}, {{ Property.attrib['Count'] }}>& Get{{ PropertyName }}Vector() const; -{% else %} +{% else %} const AZStd::fixed_vector<{{ Property.attrib['Type'] }}, {{ Property.attrib['Count'] }}>& Get{{ PropertyName }}Vector() const; -{% endif %} +{% endif %} const {{ Property.attrib['Type'] }}& Get{{ PropertyName }}(int32_t index) const; const {{ Property.attrib['Type'] }}& {{ PropertyName }}GetBack() const; uint32_t {{ PropertyName }}GetSize() const; @@ -31,6 +31,9 @@ void {{ PropertyName }}SizeChangedAddEvent(AZ::Event::Handler& handler {% endif %} {% else %} const {{ Property.attrib['Type'] }}& Get{{ PropertyName }}() const; +{% if Property.attrib['IsRewindable']|booleanTrue %} +const {{ Property.attrib['Type'] }}& Get{{ PropertyName }}Previous() const; +{% endif %} {% if Property.attrib['GenerateEventBindings']|booleanTrue %} void {{ PropertyName }}AddEvent(AZ::Event<{{ Property.attrib['Type'] }}>::Handler& handler); {% endif %} diff --git a/Gems/Multiplayer/Code/Source/AutoGen/AutoComponent_Source.jinja b/Gems/Multiplayer/Code/Source/AutoGen/AutoComponent_Source.jinja index e57e8dad2f..eb4b81ea96 100644 --- a/Gems/Multiplayer/Code/Source/AutoGen/AutoComponent_Source.jinja +++ b/Gems/Multiplayer/Code/Source/AutoGen/AutoComponent_Source.jinja @@ -3,11 +3,11 @@ {% macro LowerFirst(text) %}{{ text[0] | lower}}{{ text[1:] }}{% endmacro %} {% macro DefineNetworkPropertyGet(ClassName, Property, Prefix = '') %} {% if Property.attrib['Container'] == 'Array' %} -{% if Property.attrib['IsRewindable']|booleanTrue %} +{% if Property.attrib['IsRewindable']|booleanTrue %} const RewindableArray<{{ Property.attrib['Type'] }}, {{ Property.attrib['Count'] }}>& {{ ClassName }}::Get{{ UpperFirst(Property.attrib['Name']) }}Array() const -{% else %} +{% else %} const AZStd::array<{{ Property.attrib['Type'] }}, {{ Property.attrib['Count'] }}>& {{ ClassName }}::Get{{ UpperFirst(Property.attrib['Name']) }}Array() const -{% endif %} +{% endif %} { return {{ Prefix }}m_{{ LowerFirst(Property.attrib['Name']) }}; } @@ -25,11 +25,11 @@ void {{ ClassName }}::{{ UpperFirst(Property.attrib['Name']) }}AddEvent(AZ::Even {% endif %} {% elif Property.attrib['Container'] == 'Vector' %} -{% if Property.attrib['IsRewindable']|booleanTrue %} +{% if Property.attrib['IsRewindable']|booleanTrue %} const RewindableFixedVector<{{ Property.attrib['Type'] }}, {{ Property.attrib['Count'] }}>& {{ ClassName }}::Get{{ UpperFirst(Property.attrib['Name']) }}Vector() const -{% else %} +{% else %} const AZStd::fixed_vector<{{ Property.attrib['Type'] }}, {{ Property.attrib['Count'] }}>& {{ ClassName }}::Get{{ UpperFirst(Property.attrib['Name']) }}Vector() const -{% endif %} +{% endif %} { return {{ Prefix }}m_{{ LowerFirst(Property.attrib['Name']) }}; } @@ -68,7 +68,12 @@ const {{ Property.attrib['Type'] }}& {{ ClassName }}::Get{{ UpperFirst(Property. { return {{ Prefix }}m_{{ LowerFirst(Property.attrib['Name']) }}; } - +{% if Property.attrib['IsRewindable']|booleanTrue %} +const {{ Property.attrib['Type'] }}& {{ ClassName }}::Get{{ UpperFirst(Property.attrib['Name']) }}Previous() const +{ + return {{ Prefix }}m_{{ LowerFirst(Property.attrib['Name']) }}.GetPrevious(); +} +{% endif %} {% if Property.attrib['GenerateEventBindings']|booleanTrue %} void {{ ClassName }}::{{ UpperFirst(Property.attrib['Name']) }}AddEvent(AZ::Event<{{ Property.attrib['Type'] }}>::Handler& handler) { diff --git a/Gems/Multiplayer/Code/Source/AutoGen/Multiplayer.AutoPackets.xml b/Gems/Multiplayer/Code/Source/AutoGen/Multiplayer.AutoPackets.xml index 203750d761..c553bc5351 100644 --- a/Gems/Multiplayer/Code/Source/AutoGen/Multiplayer.AutoPackets.xml +++ b/Gems/Multiplayer/Code/Source/AutoGen/Multiplayer.AutoPackets.xml @@ -32,11 +32,11 @@ - + - + diff --git a/Gems/Multiplayer/Code/Source/AutoGen/NetworkCharacterComponent.AutoComponent.xml b/Gems/Multiplayer/Code/Source/AutoGen/NetworkCharacterComponent.AutoComponent.xml new file mode 100644 index 0000000000..83e15800e0 --- /dev/null +++ b/Gems/Multiplayer/Code/Source/AutoGen/NetworkCharacterComponent.AutoComponent.xml @@ -0,0 +1,12 @@ + + + + + + diff --git a/Gems/Multiplayer/Code/Source/AutoGen/NetworkHitVolumesComponent.AutoComponent.xml b/Gems/Multiplayer/Code/Source/AutoGen/NetworkHitVolumesComponent.AutoComponent.xml new file mode 100644 index 0000000000..d3c31a5bc0 --- /dev/null +++ b/Gems/Multiplayer/Code/Source/AutoGen/NetworkHitVolumesComponent.AutoComponent.xml @@ -0,0 +1,12 @@ + + + + + + diff --git a/Gems/Multiplayer/Code/Source/AutoGen/NetworkRigidBodyComponent.AutoComponent.xml b/Gems/Multiplayer/Code/Source/AutoGen/NetworkRigidBodyComponent.AutoComponent.xml new file mode 100644 index 0000000000..b6cdfca9c2 --- /dev/null +++ b/Gems/Multiplayer/Code/Source/AutoGen/NetworkRigidBodyComponent.AutoComponent.xml @@ -0,0 +1,18 @@ + + + + + + + + + + + + diff --git a/Gems/Multiplayer/Code/Source/AutoGen/NetworkTransformComponent.AutoComponent.xml b/Gems/Multiplayer/Code/Source/AutoGen/NetworkTransformComponent.AutoComponent.xml index cec005cc26..8ab2e61e5e 100644 --- a/Gems/Multiplayer/Code/Source/AutoGen/NetworkTransformComponent.AutoComponent.xml +++ b/Gems/Multiplayer/Code/Source/AutoGen/NetworkTransformComponent.AutoComponent.xml @@ -12,9 +12,9 @@ - + - + diff --git a/Gems/Multiplayer/Code/Source/Components/LocalPredictionPlayerInputComponent.cpp b/Gems/Multiplayer/Code/Source/Components/LocalPredictionPlayerInputComponent.cpp index 418bea79dd..c5f9b265f9 100644 --- a/Gems/Multiplayer/Code/Source/Components/LocalPredictionPlayerInputComponent.cpp +++ b/Gems/Multiplayer/Code/Source/Components/LocalPredictionPlayerInputComponent.cpp @@ -185,12 +185,9 @@ namespace Multiplayer // Discard move input events, client may be speed hacking if (m_clientBankedTime < sv_MaxBankTimeWindowSec) { - // Client blends from previous frame to target so here we subtract blend factor to get to that state - const float blendFactor = AZStd::min(AZStd::max(0.f, input.GetHostBlendFactor()), 1.0f); - const AZ::TimeMs blendMs = AZ::TimeMs(static_cast(static_cast(cl_InputRateMs)) * (1.0f - blendFactor)); m_clientBankedTime = AZStd::min(m_clientBankedTime + clientInputRateSec, (double)sv_MaxBankTimeWindowSec); // clamp to boundary { - ScopedAlterTime scopedTime(input.GetHostFrameId(), input.GetHostTimeMs() - blendMs, input.GetHostBlendFactor(), invokingConnection->GetConnectionId()); + ScopedAlterTime scopedTime(input.GetHostFrameId(), input.GetHostTimeMs(), input.GetHostBlendFactor(), invokingConnection->GetConnectionId()); GetNetBindComponent()->ProcessInput(input, static_cast(clientInputRateSec)); } @@ -436,10 +433,13 @@ namespace Multiplayer NetworkInputArray inputArray(GetEntityHandle()); NetworkInput& input = inputArray[0]; + const float blendFactor = AZStd::min(AZStd::max(0.f, multiplayer->GetCurrentBlendFactor()), 1.0f); + const AZ::TimeMs blendMs = AZ::TimeMs(static_cast(static_cast(cl_InputRateMs)) * (1.0f - blendFactor)); input.SetClientInputId(m_clientInputId); input.SetHostFrameId(networkTime->GetHostFrameId()); - input.SetHostTimeMs(multiplayer->GetCurrentHostTimeMs()); + // Account for the client blending from previous frame to current + input.SetHostTimeMs(multiplayer->GetCurrentHostTimeMs() - blendMs); input.SetHostBlendFactor(multiplayer->GetCurrentBlendFactor()); // Allow components to form the input for this frame diff --git a/Gems/Multiplayer/Code/Source/Components/NetBindComponent.cpp b/Gems/Multiplayer/Code/Source/Components/NetBindComponent.cpp index 43577525c0..634cac74b2 100644 --- a/Gems/Multiplayer/Code/Source/Components/NetBindComponent.cpp +++ b/Gems/Multiplayer/Code/Source/Components/NetBindComponent.cpp @@ -405,9 +405,9 @@ namespace Multiplayer m_entityServerMigrationEvent.Signal(m_netEntityHandle, hostId, connectionId); } - void NetBindComponent::NotifyPreRender(float deltaTime, float blendFactor) + void NetBindComponent::NotifyPreRender(float deltaTime) { - m_entityPreRenderEvent.Signal(deltaTime, blendFactor); + m_entityPreRenderEvent.Signal(deltaTime); } void NetBindComponent::NotifyCorrection() diff --git a/Gems/Multiplayer/Code/Source/Components/NetworkCharacterComponent.cpp b/Gems/Multiplayer/Code/Source/Components/NetworkCharacterComponent.cpp new file mode 100644 index 0000000000..b14fc8761f --- /dev/null +++ b/Gems/Multiplayer/Code/Source/Components/NetworkCharacterComponent.cpp @@ -0,0 +1,209 @@ +/* + * Copyright (c) Contributors to the Open 3D Engine Project. + * For complete copyright and license terms please see the LICENSE at the root of this distribution. + * + * SPDX-License-Identifier: Apache-2.0 OR MIT + * + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace Multiplayer +{ + + bool CollisionLayerBasedControllerFilter(const physx::PxController& controllerA, const physx::PxController& controllerB) + { + PHYSX_SCENE_READ_LOCK(controllerA.getActor()->getScene()); + physx::PxRigidDynamic* actorA = controllerA.getActor(); + physx::PxRigidDynamic* actorB = controllerB.getActor(); + + if (actorA && actorA->getNbShapes() > 0 && actorB && actorB->getNbShapes() > 0) + { + physx::PxShape* shapeA = nullptr; + actorA->getShapes(&shapeA, 1, 0); + physx::PxFilterData filterDataA = shapeA->getSimulationFilterData(); + physx::PxShape* shapeB = nullptr; + actorB->getShapes(&shapeB, 1, 0); + physx::PxFilterData filterDataB = shapeB->getSimulationFilterData(); + return PhysX::Utils::Collision::ShouldCollide(filterDataA, filterDataB); + } + + return true; + } + + physx::PxQueryHitType::Enum CollisionLayerBasedObjectPreFilter( + const physx::PxFilterData& filterData, + const physx::PxShape* shape, + const physx::PxRigidActor* actor, + [[maybe_unused]] physx::PxHitFlags& queryFlags) + { + // non-kinematic dynamic bodies should not impede the movement of the character + if (actor->getConcreteType() == physx::PxConcreteType::eRIGID_DYNAMIC) + { + const physx::PxRigidDynamic* rigidDynamic = static_cast(actor); + + bool isKinematic = (rigidDynamic->getRigidBodyFlags() & physx::PxRigidBodyFlag::eKINEMATIC); + if (isKinematic) + { + const PhysX::ActorData* actorData = PhysX::Utils::GetUserData(rigidDynamic); + if (actorData) + { + const AZ::EntityId entityId = actorData->GetEntityId(); + + if (Multiplayer::NetworkRigidBodyRequestBus::FindFirstHandler(entityId) != nullptr) + { + // Network rigid bodies are kinematic on the client but dynamic on the server, + // hence filtering treats these actors as dynamic to support client prediction and avoid desyncs + isKinematic = false; + } + } + } + + if (!isKinematic) + { + return physx::PxQueryHitType::eNONE; + } + } + + // all other cases should be determined by collision filters + if (PhysX::Utils::Collision::ShouldCollide(filterData, shape->getSimulationFilterData())) + { + return physx::PxQueryHitType::eBLOCK; + } + + return physx::PxQueryHitType::eNONE; + } + + void NetworkCharacterComponent::NetworkCharacterComponent::Reflect(AZ::ReflectContext* context) + { + AZ::SerializeContext* serializeContext = azrtti_cast(context); + if (serializeContext) + { + serializeContext->Class() + ->Version(1); + } + NetworkCharacterComponentBase::Reflect(context); + } + + NetworkCharacterComponent::NetworkCharacterComponent() + : m_translationEventHandler([this](const AZ::Vector3& translation) { OnTranslationChangedEvent(translation); }) + { + } + + void NetworkCharacterComponent::OnActivate([[maybe_unused]] Multiplayer::EntityIsMigrating entityIsMigrating) + { + Physics::CharacterRequests* characterRequests = Physics::CharacterRequestBus::FindFirstHandler(GetEntityId()); + m_physicsCharacter = (characterRequests != nullptr) ? characterRequests->GetCharacter() : nullptr; + GetNetBindComponent()->AddEntitySyncRewindEventHandler(m_syncRewindHandler); + + if (m_physicsCharacter) + { + auto controller = static_cast(m_physicsCharacter); + controller->SetFilterFlags(physx::PxQueryFlag::eSTATIC | physx::PxQueryFlag::eDYNAMIC | physx::PxQueryFlag::ePREFILTER); + if (auto callbackManager = controller->GetCallbackManager()) + { + callbackManager->SetControllerFilter(CollisionLayerBasedControllerFilter); + callbackManager->SetObjectPreFilter(CollisionLayerBasedObjectPreFilter); + } + } + + if (!HasController()) + { + GetNetworkTransformComponent()->TranslationAddEvent(m_translationEventHandler); + } + } + + void NetworkCharacterComponent::OnDeactivate([[maybe_unused]] Multiplayer::EntityIsMigrating entityIsMigrating) + { + ; + } + + void NetworkCharacterComponent::OnTranslationChangedEvent([[maybe_unused]] const AZ::Vector3& translation) + { + OnSyncRewind(); + } + + void NetworkCharacterComponent::OnSyncRewind() + { + if (m_physicsCharacter == nullptr) + { + return; + } + + const AZ::Vector3 currPosition = m_physicsCharacter->GetBasePosition(); + if (!currPosition.IsClose(GetNetworkTransformComponent()->GetTranslation())) + { + uint32_t frameId = static_cast(Multiplayer::GetNetworkTime()->GetHostFrameId()); + m_physicsCharacter->SetFrameId(frameId); + //m_physicsCharacter->SetBasePosition(GetNetworkTransformComponent()->GetTranslation()); + } + } + + bool NetworkCharacterComponent::IsOnGround() const + { + auto pxController = static_cast(m_physicsCharacter->GetNativePointer()); + if (!pxController) + { + return true; + } + + physx::PxControllerState state; + pxController->getState(state); + return state.touchedActor != nullptr || (state.collisionFlags & physx::PxControllerCollisionFlag::eCOLLISION_DOWN) != 0; + } + + NetworkCharacterComponentController::NetworkCharacterComponentController(NetworkCharacterComponent& parent) + : NetworkCharacterComponentControllerBase(parent) + { + ; + } + + void NetworkCharacterComponentController::OnActivate([[maybe_unused]] Multiplayer::EntityIsMigrating entityIsMigrating) + { + ; + } + + void NetworkCharacterComponentController::OnDeactivate([[maybe_unused]] Multiplayer::EntityIsMigrating entityIsMigrating) + { + ; + } + + AZ::Vector3 NetworkCharacterComponentController::TryMoveWithVelocity(const AZ::Vector3& velocity, [[maybe_unused]] float deltaTime) + { + // Ensure any entities that we might interact with are properly synchronized to their rewind state + if (IsAuthority()) + { + const AZ::Aabb entityStartBounds = AZ::Interface::Get()->GetEntityLocalBoundsUnion(GetEntity()->GetId()); + const AZ::Aabb entityFinalBounds = entityStartBounds.GetTranslated(velocity); + AZ::Aabb entitySweptBounds = entityStartBounds; + entitySweptBounds.AddAabb(entityFinalBounds); + Multiplayer::GetNetworkTime()->SyncEntitiesToRewindState(entitySweptBounds); + } + + if ((GetParent().m_physicsCharacter == nullptr) || (velocity.GetLengthSq() <= 0.0f)) + { + return GetEntity()->GetTransform()->GetWorldTranslation(); + } + GetParent().m_physicsCharacter->AddVelocity(velocity); + GetParent().m_physicsCharacter->ApplyRequestedVelocity(deltaTime); + GetEntity()->GetTransform()->SetWorldTranslation(GetParent().m_physicsCharacter->GetBasePosition()); + AZLOG + ( + NET_Movement, + "Moved to position %f x %f x %f", + GetParent().m_physicsCharacter->GetBasePosition().GetX(), + GetParent().m_physicsCharacter->GetBasePosition().GetY(), + GetParent().m_physicsCharacter->GetBasePosition().GetZ() + ); + return GetEntity()->GetTransform()->GetWorldTranslation(); + } +} diff --git a/Gems/Multiplayer/Code/Source/Components/NetworkHitVolumesComponent.cpp b/Gems/Multiplayer/Code/Source/Components/NetworkHitVolumesComponent.cpp new file mode 100644 index 0000000000..c14bb643e1 --- /dev/null +++ b/Gems/Multiplayer/Code/Source/Components/NetworkHitVolumesComponent.cpp @@ -0,0 +1,221 @@ +/* + * Copyright (c) Contributors to the Open 3D Engine Project. + * For complete copyright and license terms please see the LICENSE at the root of this distribution. + * + * SPDX-License-Identifier: Apache-2.0 OR MIT + * + */ + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace Multiplayer +{ + AZ_CVAR(bool, bg_DrawArticulatedHitVolumes, false, nullptr, AZ::ConsoleFunctorFlags::Null, "Enables debug draw of articulated hit volumes"); + AZ_CVAR(float, bg_DrawDebugHitVolumeLifetime, 0.0f, nullptr, AZ::ConsoleFunctorFlags::Null, "The lifetime for hit volume draw-debug shapes"); + + AZ_CVAR(float, bg_RewindPositionTolerance, 0.0001f, nullptr, AZ::ConsoleFunctorFlags::Null, "Don't sync the physx entity if the square of delta position is less than this value"); + AZ_CVAR(float, bg_RewindOrientationTolerance, 0.001f, nullptr, AZ::ConsoleFunctorFlags::Null, "Don't sync the physx entity if the square of delta orientation is less than this value"); + + NetworkHitVolumesComponent::AnimatedHitVolume::AnimatedHitVolume + ( + AzNetworking::ConnectionId connectionId, + Physics::CharacterRequests* character, + const char* hitVolumeName, + const Physics::ColliderConfiguration* colliderConfig, + const Physics::ShapeConfiguration* shapeConfig, + const uint32_t jointIndex + ) + : m_colliderConfig(colliderConfig) + , m_shapeConfig(shapeConfig) + , m_jointIndex(jointIndex) + { + m_transform.SetOwningConnectionId(connectionId); + + m_colliderOffSetTransform = AZ::Transform::CreateFromQuaternionAndTranslation(m_colliderConfig->m_rotation, m_colliderConfig->m_position); + + if (m_colliderConfig->m_isExclusive) + { + Physics::SystemRequestBus::BroadcastResult(m_physicsShape, &Physics::SystemRequests::CreateShape, *m_colliderConfig, *m_shapeConfig); + } + else + { + Physics::ColliderConfiguration colliderConfiguration = *m_colliderConfig; + colliderConfiguration.m_isExclusive = true; + colliderConfiguration.m_isSimulated = false; + colliderConfiguration.m_isInSceneQueries = true; + Physics::SystemRequestBus::BroadcastResult(m_physicsShape, &Physics::SystemRequests::CreateShape, colliderConfiguration, *m_shapeConfig); + } + + if (m_physicsShape) + { + m_physicsShape->SetName(hitVolumeName); + character->GetCharacter()->AttachShape(m_physicsShape); + } + } + + void NetworkHitVolumesComponent::AnimatedHitVolume::UpdateTransform(const AZ::Transform& transform) + { + m_transform = transform; + m_physicsShape->SetLocalPose(transform.GetTranslation(), transform.GetRotation()); + } + + void NetworkHitVolumesComponent::AnimatedHitVolume::SyncToCurrentTransform() + { + AZ::Transform rewoundTransform; + const AZ::Transform& targetTransform = m_transform.Get(); + const float blendFactor = Multiplayer::GetNetworkTime()->GetHostBlendFactor(); + if (blendFactor < 1.f) + { + // If a blend factor was supplied, interpolate the transform appropriately + const AZ::Transform& previousTransform = m_transform.GetPrevious(); + rewoundTransform.SetRotation(previousTransform.GetRotation().Slerp(targetTransform.GetRotation(), blendFactor)); + rewoundTransform.SetTranslation(previousTransform.GetTranslation().Lerp(targetTransform.GetTranslation(), blendFactor)); + rewoundTransform.SetUniformScale(AZ::Lerp(previousTransform.GetUniformScale(), targetTransform.GetUniformScale(), blendFactor)); + } + else + { + rewoundTransform = m_transform.Get(); + } + + const AZ::Transform physicsTransform = AZ::Transform::CreateFromQuaternionAndTranslation(m_physicsShape->GetLocalPose().second, m_physicsShape->GetLocalPose().first); + + // Don't call SetLocalPose unless the transforms are actually different + const AZ::Vector3 positionDelta = physicsTransform.GetTranslation() - rewoundTransform.GetTranslation(); + const AZ::Quaternion orientationDelta = physicsTransform.GetRotation() - rewoundTransform.GetRotation(); + + if ((positionDelta.GetLengthSq() >= bg_RewindPositionTolerance) || (orientationDelta.GetLengthSq() >= bg_RewindOrientationTolerance)) + { + m_physicsShape->SetLocalPose(rewoundTransform.GetTranslation(), rewoundTransform.GetRotation()); + } + } + + void NetworkHitVolumesComponent::NetworkHitVolumesComponent::Reflect(AZ::ReflectContext* context) + { + AZ::SerializeContext* serializeContext = azrtti_cast(context); + if (serializeContext) + { + serializeContext->Class() + ->Version(1); + } + NetworkHitVolumesComponentBase::Reflect(context); + } + + NetworkHitVolumesComponent::NetworkHitVolumesComponent() + : m_syncRewindHandler([this]() { OnSyncRewind(); }) + , m_preRenderHandler([this](float deltaTime) { OnPreRender(deltaTime); }) + , m_transformChangedHandler([this](const AZ::Transform&, const AZ::Transform& worldTm) { OnTransformUpdate(worldTm); }) + { + ; + } + + void NetworkHitVolumesComponent::OnInit() + { + ; + } + + void NetworkHitVolumesComponent::OnActivate([[maybe_unused]] Multiplayer::EntityIsMigrating entityIsMigrating) + { + EMotionFX::Integration::ActorComponentNotificationBus::Handler::BusConnect(GetEntityId()); + GetNetBindComponent()->AddEntitySyncRewindEventHandler(m_syncRewindHandler); + m_physicsCharacter = Physics::CharacterRequestBus::FindFirstHandler(GetEntityId()); + GetTransformComponent()->BindTransformChangedEventHandler(m_transformChangedHandler); + OnTransformUpdate(GetTransformComponent()->GetWorldTM()); + } + + void NetworkHitVolumesComponent::OnDeactivate([[maybe_unused]] Multiplayer::EntityIsMigrating entityIsMigrating) + { + DestroyHitVolumes(); + EMotionFX::Integration::ActorComponentNotificationBus::Handler::BusDisconnect(); + } + + void NetworkHitVolumesComponent::OnPreRender([[maybe_unused]] float deltaTime) + { + if (m_animatedHitVolumes.size() <= 0) + { + CreateHitVolumes(); + } + + AZ::Vector3 position, scale; + AZ::Quaternion rotation; + for (AnimatedHitVolume& hitVolume : m_animatedHitVolumes) + { + m_actorComponent->GetJointTransformComponents(hitVolume.m_jointIndex, EMotionFX::Integration::Space::ModelSpace, position, rotation, scale); + hitVolume.UpdateTransform(AZ::Transform::CreateFromQuaternionAndTranslation(rotation, position) * hitVolume.m_colliderOffSetTransform); + } + } + + void NetworkHitVolumesComponent::OnTransformUpdate([[maybe_unused]] const AZ::Transform& transform) + { + OnSyncRewind(); + } + + void NetworkHitVolumesComponent::OnSyncRewind() + { + if (m_physicsCharacter && m_physicsCharacter->GetCharacter()) + { + uint32_t frameId = static_cast(Multiplayer::GetNetworkTime()->GetHostFrameId()); + m_physicsCharacter->GetCharacter()->SetFrameId(frameId); + } + + for (AnimatedHitVolume& hitVolume : m_animatedHitVolumes) + { + hitVolume.SyncToCurrentTransform(); + } + } + + void NetworkHitVolumesComponent::CreateHitVolumes() + { + if (m_physicsCharacter == nullptr || m_actorComponent == nullptr) + { + return; + } + + const Physics::AnimationConfiguration* physicsConfig = m_actorComponent->GetPhysicsConfig(); + if (physicsConfig == nullptr) + { + return; + } + + m_hitDetectionConfig = &physicsConfig->m_hitDetectionConfig; + const AzNetworking::ConnectionId owningConnectionId = GetNetBindComponent()->GetOwningConnectionId(); + + m_animatedHitVolumes.reserve(m_hitDetectionConfig->m_nodes.size()); + for (const Physics::CharacterColliderNodeConfiguration& nodeConfig : m_hitDetectionConfig->m_nodes) + { + const AZStd::size_t jointIndex = m_actorComponent->GetJointIndexByName(nodeConfig.m_name.c_str()); + if (jointIndex == EMotionFX::Integration::ActorComponentRequests::s_invalidJointIndex) + { + continue; + } + + for (const AzPhysics::ShapeColliderPair& coliderPair : nodeConfig.m_shapes) + { + const Physics::ColliderConfiguration* colliderConfig = coliderPair.first.get(); + Physics::ShapeConfiguration* shapeConfig = coliderPair.second.get(); + m_animatedHitVolumes.emplace_back(owningConnectionId, m_physicsCharacter, nodeConfig.m_name.c_str(), colliderConfig, shapeConfig, aznumeric_cast(jointIndex)); + } + } + } + + void NetworkHitVolumesComponent::DestroyHitVolumes() + { + m_animatedHitVolumes.clear(); + } + + void NetworkHitVolumesComponent::OnActorInstanceCreated([[maybe_unused]] EMotionFX::ActorInstance* actorInstance) + { + m_actorComponent = EMotionFX::Integration::ActorComponentRequestBus::FindFirstHandler(GetEntity()->GetId()); + } + + void NetworkHitVolumesComponent::OnActorInstanceDestroyed([[maybe_unused]] EMotionFX::ActorInstance* actorInstance) + { + m_actorComponent = nullptr; + } +} diff --git a/Gems/Multiplayer/Code/Source/Components/NetworkRigidBodyComponent.cpp b/Gems/Multiplayer/Code/Source/Components/NetworkRigidBodyComponent.cpp new file mode 100644 index 0000000000..bcf855d834 --- /dev/null +++ b/Gems/Multiplayer/Code/Source/Components/NetworkRigidBodyComponent.cpp @@ -0,0 +1,147 @@ +/* + * Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. + * + * SPDX-License-Identifier: Apache-2.0 OR MIT + * + */ + +#include +#include +#include +#include + +namespace Multiplayer +{ + AZ_CVAR_EXTERNED(float, bg_RewindPositionTolerance); + AZ_CVAR_EXTERNED(float, bg_RewindOrientationTolerance); + + void NetworkRigidBodyComponent::NetworkRigidBodyComponent::Reflect(AZ::ReflectContext* context) + { + AZ::SerializeContext* serializeContext = azrtti_cast(context); + if (serializeContext) + { + serializeContext->Class()->Version(1); + } + NetworkRigidBodyComponentBase::Reflect(context); + } + + void NetworkRigidBodyComponent::GetProvidedServices(AZ::ComponentDescriptor::DependencyArrayType& provided) + { + provided.push_back(AZ_CRC_CE("NetworkRigidBodyService")); + } + + void NetworkRigidBodyComponent::GetRequiredServices(AZ::ComponentDescriptor::DependencyArrayType& required) + { + required.push_back(AZ_CRC_CE("PhysXRigidBodyService")); + } + + void NetworkRigidBodyComponent::GetDependentServices(AZ::ComponentDescriptor::DependencyArrayType& dependent) + { + dependent.push_back(AZ_CRC_CE("TransformService")); + dependent.push_back(AZ_CRC_CE("PhysXRigidBodyService")); + } + + NetworkRigidBodyComponent::NetworkRigidBodyComponent() + : m_syncRewindHandler([this](){ OnSyncRewind(); }) + , m_transformChangedHandler([this]([[maybe_unused]] const AZ::Transform& localTm, const AZ::Transform& worldTm){ OnTransformUpdate(worldTm); }) + { + } + + void NetworkRigidBodyComponent::OnInit() + { + } + + void NetworkRigidBodyComponent::OnActivate([[maybe_unused]] Multiplayer::EntityIsMigrating entityIsMigrating) + { + NetworkRigidBodyRequestBus::Handler::BusConnect(GetEntityId()); + + GetNetBindComponent()->AddEntitySyncRewindEventHandler(m_syncRewindHandler); + GetEntity()->FindComponent()->BindTransformChangedEventHandler(m_transformChangedHandler); + + m_physicsRigidBodyComponent = + Physics::RigidBodyRequestBus::FindFirstHandler(GetEntity()->GetId()); + AZ_Assert(m_physicsRigidBodyComponent, "PhysX Rigid Body Component is required on entity %s", GetEntity()->GetName().c_str()); + + if (!HasController()) + { + m_physicsRigidBodyComponent->SetKinematic(true); + } + } + + void NetworkRigidBodyComponent::OnDeactivate([[maybe_unused]] Multiplayer::EntityIsMigrating entityIsMigrating) + { + NetworkRigidBodyRequestBus::Handler::BusDisconnect(); + } + + void NetworkRigidBodyComponent::OnTransformUpdate(const AZ::Transform& worldTm) + { + m_transform = worldTm; + + if (!HasController()) + { + m_physicsRigidBodyComponent->SetKinematicTarget(worldTm); + } + } + + void NetworkRigidBodyComponent::OnSyncRewind() + { + uint32_t frameId = static_cast(Multiplayer::GetNetworkTime()->GetHostFrameId()); + + AzPhysics::RigidBody* rigidBody = m_physicsRigidBodyComponent->GetRigidBody(); + rigidBody->SetFrameId(frameId); + + AZ::Transform rewoundTransform; + const AZ::Transform& targetTransform = m_transform.Get(); + const float blendFactor = Multiplayer::GetNetworkTime()->GetHostBlendFactor(); + if (blendFactor < 1.f) + { + // If a blend factor was supplied, interpolate the transform appropriately + const AZ::Transform& previousTransform = m_transform.GetPrevious(); + rewoundTransform.SetRotation(previousTransform.GetRotation().Slerp(targetTransform.GetRotation(), blendFactor)); + rewoundTransform.SetTranslation(previousTransform.GetTranslation().Lerp(targetTransform.GetTranslation(), blendFactor)); + rewoundTransform.SetUniformScale(AZ::Lerp(previousTransform.GetUniformScale(), targetTransform.GetUniformScale(), blendFactor)); + } + else + { + rewoundTransform = m_transform.Get(); + } + const AZ::Transform& physicsTransform = rigidBody->GetTransform(); + + // Don't call SetLocalPose unless the transforms are actually different + const AZ::Vector3 positionDelta = physicsTransform.GetTranslation() - rewoundTransform.GetTranslation(); + const AZ::Quaternion orientationDelta = physicsTransform.GetRotation() - rewoundTransform.GetRotation(); + + if ((positionDelta.GetLengthSq() >= bg_RewindPositionTolerance) || + (orientationDelta.GetLengthSq() >= bg_RewindOrientationTolerance)) + { + rigidBody->SetTransform(rewoundTransform); + } + } + + NetworkRigidBodyComponentController::NetworkRigidBodyComponentController(NetworkRigidBodyComponent& parent) + : NetworkRigidBodyComponentControllerBase(parent) + { + ; + } + + void NetworkRigidBodyComponentController::OnActivate([[maybe_unused]] Multiplayer::EntityIsMigrating entityIsMigrating) + { + ; + } + + void NetworkRigidBodyComponentController::OnDeactivate([[maybe_unused]] Multiplayer::EntityIsMigrating entityIsMigrating) + { + ; + } + + void NetworkRigidBodyComponentController::HandleSendApplyImpulse + ( + [[maybe_unused]] AzNetworking::IConnection* invokingConnection, + const AZ::Vector3& impulse, + const AZ::Vector3& worldPoint + ) + { + AzPhysics::RigidBody* rigidBody = GetParent().m_physicsRigidBodyComponent->GetRigidBody(); + rigidBody->ApplyLinearImpulseAtWorldPoint(impulse, worldPoint); + } +} // namespace Multiplayer diff --git a/Gems/Multiplayer/Code/Source/Components/NetworkTransformComponent.cpp b/Gems/Multiplayer/Code/Source/Components/NetworkTransformComponent.cpp index fa08794c4d..1d9fee16e0 100644 --- a/Gems/Multiplayer/Code/Source/Components/NetworkTransformComponent.cpp +++ b/Gems/Multiplayer/Code/Source/Components/NetworkTransformComponent.cpp @@ -26,11 +26,7 @@ namespace Multiplayer } NetworkTransformComponent::NetworkTransformComponent() - : m_rotationEventHandler([this](const AZ::Quaternion& rotation) { OnRotationChangedEvent(rotation); }) - , m_translationEventHandler([this](const AZ::Vector3& translation) { OnTranslationChangedEvent(translation); }) - , m_scaleEventHandler([this](float scale) { OnScaleChangedEvent(scale); }) - , m_resetCountEventHandler([this](const uint8_t&) { OnResetCountChangedEvent(); }) - , m_entityPreRenderEventHandler([this](float deltaTime, float blendFactor) { OnPreRender(deltaTime, blendFactor); }) + : m_entityPreRenderEventHandler([this](float deltaTime) { OnPreRender(deltaTime); }) , m_entityCorrectionEventHandler([this]() { OnCorrection(); }) { ; @@ -43,15 +39,8 @@ namespace Multiplayer void NetworkTransformComponent::OnActivate([[maybe_unused]] Multiplayer::EntityIsMigrating entityIsMigrating) { - RotationAddEvent(m_rotationEventHandler); - TranslationAddEvent(m_translationEventHandler); - ScaleAddEvent(m_scaleEventHandler); - ResetCountAddEvent(m_resetCountEventHandler); GetNetBindComponent()->AddEntityPreRenderEventHandler(m_entityPreRenderEventHandler); GetNetBindComponent()->AddEntityCorrectionEventHandler(m_entityCorrectionEventHandler); - - // When coming into relevance, reset all blending factors so we don't interpolate to our start position - OnResetCountChangedEvent(); } void NetworkTransformComponent::OnDeactivate([[maybe_unused]] Multiplayer::EntityIsMigrating entityIsMigrating) @@ -59,59 +48,31 @@ namespace Multiplayer ; } - void NetworkTransformComponent::OnRotationChangedEvent(const AZ::Quaternion& rotation) - { - m_previousTransform.SetRotation(m_targetTransform.GetRotation()); - m_targetTransform.SetRotation(rotation); - UpdateTargetHostFrameId(); - } - - void NetworkTransformComponent::OnTranslationChangedEvent(const AZ::Vector3& translation) - { - m_previousTransform.SetTranslation(m_targetTransform.GetTranslation()); - m_targetTransform.SetTranslation(translation); - UpdateTargetHostFrameId(); - } - - void NetworkTransformComponent::OnScaleChangedEvent(float scale) - { - m_previousTransform.SetUniformScale(m_targetTransform.GetUniformScale()); - m_targetTransform.SetUniformScale(scale); - UpdateTargetHostFrameId(); - } - - void NetworkTransformComponent::OnResetCountChangedEvent() - { - m_targetTransform.SetRotation(GetRotation()); - m_targetTransform.SetTranslation(GetTranslation()); - m_targetTransform.SetUniformScale(GetScale()); - m_previousTransform = m_targetTransform; - } - - void NetworkTransformComponent::UpdateTargetHostFrameId() - { - HostFrameId currentHostFrameId = Multiplayer::GetNetworkTime()->GetHostFrameId(); - if (currentHostFrameId > m_targetHostFrameId) - { - m_targetHostFrameId = currentHostFrameId; - } - } - - void NetworkTransformComponent::OnPreRender([[maybe_unused]] float deltaTime, float blendFactor) + void NetworkTransformComponent::OnPreRender([[maybe_unused]] float deltaTime) { if (!HasController()) { AZ::Transform blendTransform; - if (Multiplayer::GetNetworkTime() && Multiplayer::GetNetworkTime()->GetHostFrameId() > m_targetHostFrameId) + blendTransform.SetRotation(GetRotation()); + blendTransform.SetTranslation(GetTranslation()); + blendTransform.SetUniformScale(GetScale()); + + const float blendFactor = GetMultiplayer()->GetCurrentBlendFactor(); + if (!AZ::IsClose(blendFactor, 1.0f)) { - m_previousTransform = m_targetTransform; - blendTransform = m_targetTransform; - } - else - { - blendTransform.SetRotation(m_previousTransform.GetRotation().Slerp(m_targetTransform.GetRotation(), blendFactor)); - blendTransform.SetTranslation(m_previousTransform.GetTranslation().Lerp(m_targetTransform.GetTranslation(), blendFactor)); - blendTransform.SetUniformScale(AZ::Lerp(m_previousTransform.GetUniformScale(), m_targetTransform.GetUniformScale(), blendFactor)); + AZ::Transform blendTransformPrevious; + blendTransformPrevious.SetRotation(GetRotationPrevious()); + blendTransformPrevious.SetTranslation(GetTranslationPrevious()); + blendTransformPrevious.SetUniformScale(GetScalePrevious()); + + if (!blendTransform.IsClose(blendTransformPrevious)) + { + blendTransform.SetRotation(blendTransformPrevious.GetRotation().Slerp(blendTransform.GetRotation(), blendFactor)); + blendTransform.SetTranslation( + blendTransformPrevious.GetTranslation().Lerp(blendTransform.GetTranslation(), blendFactor)); + blendTransform.SetUniformScale( + AZ::Lerp(blendTransformPrevious.GetUniformScale(), blendTransform.GetUniformScale(), blendFactor)); + } } if (!GetTransformComponent()->GetWorldTM().IsClose(blendTransform)) @@ -124,12 +85,15 @@ namespace Multiplayer void NetworkTransformComponent::OnCorrection() { // Snap to latest - OnResetCountChangedEvent(); + AZ::Transform targetTransform; + targetTransform.SetRotation(GetRotation()); + targetTransform.SetTranslation(GetTranslation()); + targetTransform.SetUniformScale(GetScale()); // Hard set the entities transform - if (!GetTransformComponent()->GetWorldTM().IsClose(m_targetTransform)) + if (!GetTransformComponent()->GetWorldTM().IsClose(targetTransform)) { - GetTransformComponent()->SetWorldTM(m_targetTransform); + GetTransformComponent()->SetWorldTM(targetTransform); } } diff --git a/Gems/Multiplayer/Code/Source/MultiplayerSystemComponent.cpp b/Gems/Multiplayer/Code/Source/MultiplayerSystemComponent.cpp index 24f865194f..e66eb8d3a3 100644 --- a/Gems/Multiplayer/Code/Source/MultiplayerSystemComponent.cpp +++ b/Gems/Multiplayer/Code/Source/MultiplayerSystemComponent.cpp @@ -922,7 +922,7 @@ namespace Multiplayer for (NetBindComponent* netBindComponent : gatheredEntities) { - netBindComponent->NotifyPreRender(deltaTime, m_renderBlendFactor); + netBindComponent->NotifyPreRender(deltaTime); } } else @@ -934,7 +934,7 @@ namespace Multiplayer NetBindComponent* netBindComponent = entity->FindComponent(); if (netBindComponent != nullptr) { - netBindComponent->NotifyPreRender(deltaTime, m_renderBlendFactor); + netBindComponent->NotifyPreRender(deltaTime); } } } diff --git a/Gems/Multiplayer/Code/Source/NetworkEntity/NetworkEntityManager.cpp b/Gems/Multiplayer/Code/Source/NetworkEntity/NetworkEntityManager.cpp index 69d2726c65..f981966ae1 100644 --- a/Gems/Multiplayer/Code/Source/NetworkEntity/NetworkEntityManager.cpp +++ b/Gems/Multiplayer/Code/Source/NetworkEntity/NetworkEntityManager.cpp @@ -281,8 +281,6 @@ namespace Multiplayer void NetworkEntityManager::RemoveEntities() { - //RewindableObjectState::ClearRewoundEntities(); - AZStd::vector removeList; removeList.swap(m_removeList); for (NetEntityId entityId : removeList) diff --git a/Gems/Multiplayer/Code/Source/NetworkTime/NetworkTime.cpp b/Gems/Multiplayer/Code/Source/NetworkTime/NetworkTime.cpp index db8d6bd2f7..b37f485ff4 100644 --- a/Gems/Multiplayer/Code/Source/NetworkTime/NetworkTime.cpp +++ b/Gems/Multiplayer/Code/Source/NetworkTime/NetworkTime.cpp @@ -65,11 +65,6 @@ namespace Multiplayer return m_rewindingConnectionId; } - HostFrameId NetworkTime::GetHostFrameIdForRewindingConnection(AzNetworking::ConnectionId rewindConnectionId) const - { - return (IsTimeRewound() && (rewindConnectionId == m_rewindingConnectionId)) ? m_unalteredFrameId : m_hostFrameId; - } - void NetworkTime::ForceSetTime(HostFrameId frameId, AZ::TimeMs timeMs) { AZ_Assert(!IsTimeRewound(), "Forcibly setting network time is unsupported under a rewound time scope"); @@ -79,20 +74,23 @@ namespace Multiplayer m_rewindingConnectionId = AzNetworking::InvalidConnectionId; } - void NetworkTime::AlterTime(HostFrameId frameId, AZ::TimeMs timeMs, AzNetworking::ConnectionId rewindConnectionId) + void NetworkTime::AlterTime(HostFrameId frameId, AZ::TimeMs timeMs, float blendFactor, AzNetworking::ConnectionId rewindConnectionId) { m_hostFrameId = frameId; m_hostTimeMs = timeMs; - m_rewindingConnectionId = rewindConnectionId; - } - - void NetworkTime::AlterBlendFactor(float blendFactor) - { m_hostBlendFactor = blendFactor; + m_rewindingConnectionId = rewindConnectionId; } void NetworkTime::SyncEntitiesToRewindState(const AZ::Aabb& rewindVolume) { + if (!IsTimeRewound()) + { + // If we're not inside a rewind scope then reset any rewound state and exit + ClearRewoundEntities(); + return; + } + // Since the vis system doesn't support rewound queries, first query with an expanded volume to catch any fast moving entities const AZ::Aabb expandedVolume = rewindVolume.GetExpanded(AZ::Vector3(sv_RewindVolumeExtrudeDistance)); @@ -114,8 +112,15 @@ namespace Multiplayer if (networkTransform != nullptr) { - // We're not presently factoring in interpolated position here - const AZ::Vector3 rewindCenter = networkTransform->GetTranslation(); // Get the rewound position + // Get the rewound position for target host frame ID plus the one preceding it for potential lerp + AZ::Vector3 rewindCenter = networkTransform->GetTranslation(); + const AZ::Vector3 rewindCenterPrevious = networkTransform->GetTranslationPrevious(); + const float blendFactor = GetNetworkTime()->GetHostBlendFactor(); + if (!AZ::IsClose(blendFactor, 1.0f) && !rewindCenter.IsClose(rewindCenterPrevious)) + { + // If we have a blend factor, lerp the translation for accuracy + rewindCenter = rewindCenterPrevious.Lerp(rewindCenter, blendFactor); + } const AZ::Vector3 rewindOffset = rewindCenter - currentCenter; // Compute offset between rewound and current positions const AZ::Aabb rewoundAabb = currentBounds.GetTranslated(rewindOffset); // Apply offset to the entity aabb diff --git a/Gems/Multiplayer/Code/Source/NetworkTime/NetworkTime.h b/Gems/Multiplayer/Code/Source/NetworkTime/NetworkTime.h index 0278ddd2b0..2bcf019623 100644 --- a/Gems/Multiplayer/Code/Source/NetworkTime/NetworkTime.h +++ b/Gems/Multiplayer/Code/Source/NetworkTime/NetworkTime.h @@ -32,10 +32,8 @@ namespace Multiplayer AZ::TimeMs GetHostTimeMs() const override; float GetHostBlendFactor() const override; AzNetworking::ConnectionId GetRewindingConnectionId() const override; - HostFrameId GetHostFrameIdForRewindingConnection(AzNetworking::ConnectionId rewindConnectionId) const override; void ForceSetTime(HostFrameId frameId, AZ::TimeMs timeMs) override; - void AlterTime(HostFrameId frameId, AZ::TimeMs timeMs, AzNetworking::ConnectionId rewindConnectionId) override; - void AlterBlendFactor(float blendFactor) override; + void AlterTime(HostFrameId frameId, AZ::TimeMs timeMs, float blendFactor, AzNetworking::ConnectionId rewindConnectionId) override; void SyncEntitiesToRewindState(const AZ::Aabb& rewindVolume) override; void ClearRewoundEntities() override; //! @} diff --git a/Gems/Multiplayer/Code/Tests/RewindableObjectTests.cpp b/Gems/Multiplayer/Code/Tests/RewindableObjectTests.cpp index b8d60a94e8..04de971f0d 100644 --- a/Gems/Multiplayer/Code/Tests/RewindableObjectTests.cpp +++ b/Gems/Multiplayer/Code/Tests/RewindableObjectTests.cpp @@ -57,6 +57,35 @@ namespace UnitTest } } + TEST_F(RewindableObjectTests, CurrentPreviousTests) + { + Multiplayer::RewindableObject test(0); + + for (uint32_t i = 0; i < RewindableBufferFrames; ++i) + { + test = i; + EXPECT_EQ(i, test); + Multiplayer::GetNetworkTime()->IncrementHostFrameId(); + } + + { + // Test that Get/GetPrevious return different value when not on the owning connection + Multiplayer::ScopedAlterTime time(static_cast(RewindableBufferFrames - 1), AZ::TimeMs{ 0 }, 1.f, AzNetworking::InvalidConnectionId); + EXPECT_EQ(RewindableBufferFrames - 1, test.Get()); + EXPECT_EQ(RewindableBufferFrames - 2, test.GetPrevious()); + } + + // Test that Get/GetPrevious return the unaltered frame on the owning conection + Multiplayer::GetNetworkTime()->AlterTime(static_cast(RewindableBufferFrames - 1), AZ::TimeMs{ 0 }, 1.f, AzNetworking::ConnectionId(0)); + { + Multiplayer::ScopedAlterTime time(static_cast(RewindableBufferFrames - 1), AZ::TimeMs{ 0 }, 1.f, AzNetworking::ConnectionId(0)); + test.SetOwningConnectionId(AzNetworking::ConnectionId(0)); + EXPECT_EQ(RewindableBufferFrames - 1, test.Get()); + EXPECT_EQ(RewindableBufferFrames - 1, test.GetPrevious()); + } + Multiplayer::GetNetworkTime()->AlterTime(static_cast(RewindableBufferFrames), AZ::TimeMs(0), 1.f, AzNetworking::InvalidConnectionId); + } + TEST_F(RewindableObjectTests, OverflowTests) { Multiplayer::RewindableObject test(0); diff --git a/Gems/Multiplayer/Code/multiplayer_files.cmake b/Gems/Multiplayer/Code/multiplayer_files.cmake index 0b2adb1530..54311a0abc 100644 --- a/Gems/Multiplayer/Code/multiplayer_files.cmake +++ b/Gems/Multiplayer/Code/multiplayer_files.cmake @@ -18,6 +18,9 @@ set(FILES Include/Multiplayer/Components/MultiplayerController.h Include/Multiplayer/Components/MultiplayerComponentRegistry.h Include/Multiplayer/Components/NetBindComponent.h + Include/Multiplayer/Components/NetworkCharacterComponent.h + Include/Multiplayer/Components/NetworkHitVolumesComponent.h + Include/Multiplayer/Components/NetworkRigidBodyComponent.h Include/Multiplayer/Components/NetworkTransformComponent.h Include/Multiplayer/ConnectionData/IConnectionData.h Include/Multiplayer/EntityDomains/IEntityDomain.h @@ -51,12 +54,18 @@ set(FILES Source/AutoGen/LocalPredictionPlayerInputComponent.AutoComponent.xml Source/AutoGen/Multiplayer.AutoPackets.xml Source/AutoGen/MultiplayerEditor.AutoPackets.xml + Source/AutoGen/NetworkCharacterComponent.AutoComponent.xml + Source/AutoGen/NetworkHitVolumesComponent.AutoComponent.xml + Source/AutoGen/NetworkRigidBodyComponent.AutoComponent.xml Source/AutoGen/NetworkTransformComponent.AutoComponent.xml Source/Components/LocalPredictionPlayerInputComponent.cpp Source/Components/MultiplayerComponent.cpp Source/Components/MultiplayerController.cpp Source/Components/MultiplayerComponentRegistry.cpp Source/Components/NetBindComponent.cpp + Source/Components/NetworkCharacterComponent.cpp + Source/Components/NetworkHitVolumesComponent.cpp + Source/Components/NetworkRigidBodyComponent.cpp Source/Components/NetworkTransformComponent.cpp Source/ConnectionData/ClientToServerConnectionData.cpp Source/ConnectionData/ClientToServerConnectionData.h diff --git a/Gems/PhysX/Code/Include/PhysX/EditorColliderComponentRequestBus.h b/Gems/PhysX/Code/Include/PhysX/EditorColliderComponentRequestBus.h index 2cfb48effa..20b02b7098 100644 --- a/Gems/PhysX/Code/Include/PhysX/EditorColliderComponentRequestBus.h +++ b/Gems/PhysX/Code/Include/PhysX/EditorColliderComponentRequestBus.h @@ -82,4 +82,18 @@ namespace PhysX }; using EditorColliderComponentRequestBus = AZ::EBus; + + /// + /// This is a Bus in order to communicate the status of the meshes of the collider and avoid dependencies with the rigidbody + /// + class EditorColliderValidationRequests : public AZ::ComponentBus + { + public: + /// Checks if the the mesh in the collider is correct with the current state of the Rigidbody! + virtual void ValidateRigidBodyMeshGeometryType() = 0; + }; + + using EditorColliderValidationRequestBus = AZ::EBus; } + + diff --git a/Gems/PhysX/Code/Source/EditorColliderComponent.cpp b/Gems/PhysX/Code/Source/EditorColliderComponent.cpp index 4aa240eaae..566903d84a 100644 --- a/Gems/PhysX/Code/Source/EditorColliderComponent.cpp +++ b/Gems/PhysX/Code/Source/EditorColliderComponent.cpp @@ -118,11 +118,10 @@ namespace PhysX AZ::u32 EditorProxyShapeConfig::OnShapeTypeChanged() { - //reset the physics asset if the shape type was Physics Asset - if (m_shapeType != Physics::ShapeType::PhysicsAsset && - m_lastShapeType == Physics::ShapeType::PhysicsAsset) + // reset the physics asset if the shape type was Physics Asset + if (m_shapeType != Physics::ShapeType::PhysicsAsset && m_lastShapeType == Physics::ShapeType::PhysicsAsset) { - //clean up any reference to a physics assets, and re-initialize to an empty Pipeline::MeshAsset asset. + // clean up any reference to a physics assets, and re-initialize to an empty Pipeline::MeshAsset asset. m_physicsAsset.m_pxAsset.Reset(); m_physicsAsset.m_pxAsset = AZ::Data::Asset(AZ::Data::AssetLoadBehavior::QueueLoad); @@ -212,6 +211,7 @@ namespace PhysX ->DataElement(AZ::Edit::UIHandlers::Default, &EditorColliderComponent::m_shapeConfiguration, "Shape Configuration", "Configuration of the shape") ->Attribute(AZ::Edit::Attributes::Visibility, AZ::Edit::PropertyVisibility::ShowChildrenOnly) ->Attribute(AZ::Edit::Attributes::ChangeNotify, &EditorColliderComponent::OnConfigurationChanged) + ->Attribute(AZ::Edit::Attributes::RemoveNotify, &EditorColliderComponent::ValidateRigidBodyMeshGeometryType) ->DataElement(AZ::Edit::UIHandlers::Default, &EditorColliderComponent::m_componentModeDelegate, "Component Mode", "Collider Component Mode") ->Attribute(AZ::Edit::Attributes::Visibility, AZ::Edit::PropertyVisibility::ShowChildrenOnly) ->DataElement(AZ::Edit::UIHandlers::Default, &EditorColliderComponent::m_colliderDebugDraw, @@ -383,6 +383,7 @@ namespace PhysX ColliderShapeRequestBus::Handler::BusConnect(GetEntityId()); AZ::Render::MeshComponentNotificationBus::Handler::BusConnect(GetEntityId()); EditorColliderComponentRequestBus::Handler::BusConnect(AZ::EntityComponentIdPair(GetEntityId(), GetId())); + EditorColliderValidationRequestBus::Handler::BusConnect(GetEntityId()); m_nonUniformScaleChangedHandler = AZ::NonUniformScaleChangedEvent::Handler( [this](const AZ::Vector3& scale) {OnNonUniformScaleChanged(scale); }); AZ::NonUniformScaleRequestBus::Event(GetEntityId(), &AZ::NonUniformScaleRequests::RegisterScaleChangedEvent, @@ -427,6 +428,7 @@ namespace PhysX m_colliderDebugDraw.Disconnect(); AZ::Data::AssetBus::MultiHandler::BusDisconnect(); m_nonUniformScaleChangedHandler.Disconnect(); + EditorColliderValidationRequestBus::Handler::BusDisconnect(); EditorColliderComponentRequestBus::Handler::BusDisconnect(); AZ::Render::MeshComponentNotificationBus::Handler::BusDisconnect(); ColliderShapeRequestBus::Handler::BusDisconnect(); @@ -466,6 +468,7 @@ namespace PhysX UpdateShapeConfigurationScale(); CreateStaticEditorCollider(); + ValidateRigidBodyMeshGeometryType(); m_colliderDebugDraw.ClearCachedGeometry(); @@ -768,15 +771,16 @@ namespace PhysX { m_componentWarnings.clear(); m_configuration.m_materialSelection.SetMaterialSlots(Physics::MaterialSelection::SlotsArray()); + AzToolsFramework::ToolsApplicationEvents::Bus::Broadcast( + &AzToolsFramework::ToolsApplicationEvents::InvalidatePropertyDisplay, AzToolsFramework::Refresh_EntireTree); } - AzToolsFramework::ToolsApplicationEvents::Bus::Broadcast(&AzToolsFramework::ToolsApplicationEvents::InvalidatePropertyDisplay, AzToolsFramework::Refresh_EntireTree); } void EditorColliderComponent::ValidateRigidBodyMeshGeometryType() { const PhysX::EditorRigidBodyComponent* entityRigidbody = m_entity->FindComponent(); - if (m_shapeConfiguration.m_physicsAsset.m_configuration.GetShapeType() == Physics::ShapeType::PhysicsAsset && entityRigidbody) + if (m_shapeConfiguration.m_physicsAsset.m_pxAsset && (m_shapeConfiguration.m_shapeType == Physics::ShapeType::PhysicsAsset) && entityRigidbody) { AZStd::vector> shapes; Utils::GetShapesFromAsset(m_shapeConfiguration.m_physicsAsset.m_configuration, m_configuration, m_hasNonUniformScale, @@ -784,17 +788,32 @@ namespace PhysX if (shapes.empty()) { + m_componentWarnings.clear(); + AzToolsFramework::ToolsApplicationEvents::Bus::Broadcast( + &AzToolsFramework::ToolsApplicationEvents::InvalidatePropertyDisplay, AzToolsFramework::Refresh_EntireTree); return; } - //We grab the first shape to check if it is a triangle mesh. - auto shape = AZStd::rtti_pointer_cast(shapes[0]); + //We check if the shapes are triangle meshes, if any mesh is a triangle mesh we activate the warning. + bool shapeIsTriangleMesh = false; - if (shape && - shape->GetPxShape()->getGeometryType() == physx::PxGeometryType::eTRIANGLEMESH && - entityRigidbody->GetRigidBody() && - entityRigidbody->GetRigidBody()->IsKinematic() == false) + for (const auto& shape : shapes) { + auto current_shape = AZStd::rtti_pointer_cast(shape); + if (current_shape && + current_shape->GetPxShape()->getGeometryType() == physx::PxGeometryType::eTRIANGLEMESH && + entityRigidbody->GetRigidBody() && + entityRigidbody->GetRigidBody()->IsKinematic() == false) + { + shapeIsTriangleMesh = true; + break; + } + } + + if (shapeIsTriangleMesh) + { + m_componentWarnings.clear(); + AZStd::string assetPath = m_shapeConfiguration.m_physicsAsset.m_configuration.m_asset.GetHint().c_str(); const size_t lastSlash = assetPath.rfind('/'); if (lastSlash != AZStd::string::npos) @@ -816,6 +835,10 @@ namespace PhysX { m_componentWarnings.clear(); } + + AzToolsFramework::ToolsApplicationEvents::Bus::Broadcast( + &AzToolsFramework::ToolsApplicationEvents::InvalidatePropertyDisplay, AzToolsFramework::Refresh_EntireTree); + } void EditorColliderComponent::OnAssetReloaded(AZ::Data::Asset asset) diff --git a/Gems/PhysX/Code/Source/EditorColliderComponent.h b/Gems/PhysX/Code/Source/EditorColliderComponent.h index 1331fd08b6..773dd0a9b8 100644 --- a/Gems/PhysX/Code/Source/EditorColliderComponent.h +++ b/Gems/PhysX/Code/Source/EditorColliderComponent.h @@ -58,8 +58,8 @@ namespace PhysX //! Proxy container for only displaying a specific shape configuration depending on the shapeType selected. struct EditorProxyShapeConfig { - AZ_CLASS_ALLOCATOR(PhysX::EditorProxyShapeConfig, AZ::SystemAllocator, 0); - AZ_RTTI(PhysX::EditorProxyShapeConfig, "{531FB42A-42A9-4234-89BA-FD349EF83D0C}"); + AZ_CLASS_ALLOCATOR(EditorProxyShapeConfig, AZ::SystemAllocator, 0); + AZ_RTTI(EditorProxyShapeConfig, "{531FB42A-42A9-4234-89BA-FD349EF83D0C}"); static void Reflect(AZ::ReflectContext* context); EditorProxyShapeConfig() = default; @@ -106,6 +106,7 @@ namespace PhysX , private PhysX::ColliderShapeRequestBus::Handler , private AZ::Render::MeshComponentNotificationBus::Handler , private PhysX::EditorColliderComponentRequestBus::Handler + , private PhysX::EditorColliderValidationRequestBus::Handler , private AzPhysics::SimulatedBodyComponentRequestsBus::Handler { public: @@ -197,6 +198,9 @@ namespace PhysX void SetAssetScale(const AZ::Vector3& scale) override; AZ::Vector3 GetAssetScale() override; + // PhysX::EditorColliderValidationRequestBus overrides ... + void ValidateRigidBodyMeshGeometryType() override; + AZ::Transform GetColliderLocalTransform() const; EditorProxyShapeConfig m_shapeConfiguration; @@ -223,8 +227,6 @@ namespace PhysX void BuildDebugDrawMesh() const; - void ValidateRigidBodyMeshGeometryType(); - AZ::ComponentDescriptor::StringWarningArray GetComponentWarnings() const { return m_componentWarnings; }; using ComponentModeDelegate = AzToolsFramework::ComponentModeFramework::ComponentModeDelegate; diff --git a/Gems/PhysX/Code/Source/EditorRigidBodyComponent.cpp b/Gems/PhysX/Code/Source/EditorRigidBodyComponent.cpp index ce812a9f31..447c2755c6 100644 --- a/Gems/PhysX/Code/Source/EditorRigidBodyComponent.cpp +++ b/Gems/PhysX/Code/Source/EditorRigidBodyComponent.cpp @@ -286,6 +286,9 @@ namespace PhysX } CreateEditorWorldRigidBody(); + PhysX::EditorColliderValidationRequestBus::Event( + GetEntityId(), &PhysX::EditorColliderValidationRequestBus::Events::ValidateRigidBodyMeshGeometryType); + AzPhysics::SimulatedBodyComponentRequestsBus::Handler::BusConnect(GetEntityId()); } diff --git a/Gems/SaveData/Code/Source/Platform/Android/SaveData_SystemComponent_Android.cpp b/Gems/SaveData/Code/Source/Platform/Android/SaveData_SystemComponent_Android.cpp index 26760ca002..cf083e26ca 100644 --- a/Gems/SaveData/Code/Source/Platform/Android/SaveData_SystemComponent_Android.cpp +++ b/Gems/SaveData/Code/Source/Platform/Android/SaveData_SystemComponent_Android.cpp @@ -59,7 +59,7 @@ namespace SaveData //////////////////////////////////////////////////////////////////////////////////////////// //! The absolute path to the application's save data dircetory. - AZStd::string m_saveDataDircetoryPathAbsolute = nullptr; + AZStd::string m_saveDataDircetoryPathAbsolute; }; //////////////////////////////////////////////////////////////////////////////////////////////// diff --git a/Gems/SaveData/Code/Source/Platform/Common/Apple/SaveData_SystemComponent_Apple.mm b/Gems/SaveData/Code/Source/Platform/Common/Apple/SaveData_SystemComponent_Apple.mm index 882723de13..e4c1f8a0d8 100644 --- a/Gems/SaveData/Code/Source/Platform/Common/Apple/SaveData_SystemComponent_Apple.mm +++ b/Gems/SaveData/Code/Source/Platform/Common/Apple/SaveData_SystemComponent_Apple.mm @@ -60,7 +60,7 @@ namespace SaveData //////////////////////////////////////////////////////////////////////////////////////////// //! The absolute path to the application's save data dircetory. - AZStd::string m_saveDataDircetoryPathAbsolute = nullptr; + AZStd::string m_saveDataDircetoryPathAbsolute; }; //////////////////////////////////////////////////////////////////////////////////////////////// diff --git a/Gems/SaveData/Code/Source/Platform/Windows/SaveData_SystemComponent_Windows.cpp b/Gems/SaveData/Code/Source/Platform/Windows/SaveData_SystemComponent_Windows.cpp index 2e473cfea7..4c182ecd17 100644 --- a/Gems/SaveData/Code/Source/Platform/Windows/SaveData_SystemComponent_Windows.cpp +++ b/Gems/SaveData/Code/Source/Platform/Windows/SaveData_SystemComponent_Windows.cpp @@ -62,7 +62,7 @@ namespace SaveData //////////////////////////////////////////////////////////////////////////////////////////// //! The absolute path to the application's save data dircetory. - AZStd::string m_saveDataDircetoryPathAbsolute = nullptr; + AZStd::string m_saveDataDircetoryPathAbsolute; }; //////////////////////////////////////////////////////////////////////////////////////////////// diff --git a/Gems/ScriptCanvas/Code/Editor/View/Widgets/NodePalette/NodePaletteModel.cpp b/Gems/ScriptCanvas/Code/Editor/View/Widgets/NodePalette/NodePaletteModel.cpp index 390dbaf0fb..b29992f9b1 100644 --- a/Gems/ScriptCanvas/Code/Editor/View/Widgets/NodePalette/NodePaletteModel.cpp +++ b/Gems/ScriptCanvas/Code/Editor/View/Widgets/NodePalette/NodePaletteModel.cpp @@ -1322,7 +1322,7 @@ namespace ScriptCanvasEditor if (seperator == AZStd::string_view::npos) { - categoryTrail = nullptr; + categoryTrail = {}; } else { diff --git a/Gems/ScriptCanvasDeveloper/Code/Editor/Include/ScriptCanvasDeveloperEditor/EditorAutomation/EditorAutomationStates/CreateElementsStates.h b/Gems/ScriptCanvasDeveloper/Code/Editor/Include/ScriptCanvasDeveloperEditor/EditorAutomation/EditorAutomationStates/CreateElementsStates.h index 156933063f..58779e91f6 100644 --- a/Gems/ScriptCanvasDeveloper/Code/Editor/Include/ScriptCanvasDeveloperEditor/EditorAutomation/EditorAutomationStates/CreateElementsStates.h +++ b/Gems/ScriptCanvasDeveloper/Code/Editor/Include/ScriptCanvasDeveloperEditor/EditorAutomation/EditorAutomationStates/CreateElementsStates.h @@ -131,7 +131,7 @@ namespace ScriptCanvasDeveloper QString m_nodeName; - AutomationStateModelId m_endpointId = nullptr; + AutomationStateModelId m_endpointId; AutomationStateModelId m_scenePointId; AutomationStateModelId m_nodeOutputId; diff --git a/Gems/Terrain/Code/CMakeLists.txt b/Gems/Terrain/Code/CMakeLists.txt index 0feacdaf71..fc07294dab 100644 --- a/Gems/Terrain/Code/CMakeLists.txt +++ b/Gems/Terrain/Code/CMakeLists.txt @@ -83,6 +83,15 @@ endif() ################################################################################ # See if globally, tests are supported if(PAL_TRAIT_BUILD_TESTS_SUPPORTED) + ly_add_target( + NAME Terrain.Mocks HEADERONLY + NAMESPACE Gem + FILES_CMAKE + terrain_mocks_files.cmake + INCLUDE_DIRECTORIES + INTERFACE + Mocks + ) ly_add_target( NAME Terrain.Tests ${PAL_TRAIT_TEST_TARGET_TYPE} NAMESPACE Gem @@ -97,6 +106,8 @@ if(PAL_TRAIT_BUILD_TESTS_SUPPORTED) PRIVATE AZ::AzTest AZ::AzFramework + Gem::LmbrCentral.Mocks + Gem::Terrain.Mocks Gem::Terrain.Static ) @@ -120,6 +131,8 @@ if(PAL_TRAIT_BUILD_TESTS_SUPPORTED) BUILD_DEPENDENCIES PRIVATE AZ::AzTest + Gem::LmbrCentral.Mocks + Gem::Terrain.Mocks Gem::Terrain.Editor ) diff --git a/Gems/Terrain/Code/Tests/TerrainMocks.h b/Gems/Terrain/Code/Mocks/Terrain/MockTerrain.h similarity index 57% rename from Gems/Terrain/Code/Tests/TerrainMocks.h rename to Gems/Terrain/Code/Mocks/Terrain/MockTerrain.h index 03a2eccf1d..ea0413be9a 100644 --- a/Gems/Terrain/Code/Tests/TerrainMocks.h +++ b/Gems/Terrain/Code/Mocks/Terrain/MockTerrain.h @@ -11,59 +11,9 @@ #include #include -#include namespace UnitTest { - static const AZ::Uuid BoxShapeComponentTypeId = "{5EDF4B9E-0D3D-40B8-8C91-5142BCFC30A6}"; - - class MockBoxShapeComponent - : public AZ::Component - { - public: - AZ_COMPONENT(MockBoxShapeComponent, BoxShapeComponentTypeId) - static void Reflect([[maybe_unused]] AZ::ReflectContext* context) - { - } - - void Activate() override - { - } - - void Deactivate() override - { - } - - bool ReadInConfig([[maybe_unused]] const AZ::ComponentConfig* baseConfig) override - { - return true; - } - - bool WriteOutConfig([[maybe_unused]] AZ::ComponentConfig* outBaseConfig) const override - { - return true; - } - - private: - static void GetProvidedServices([[maybe_unused]] AZ::ComponentDescriptor::DependencyArrayType& provided) - { - provided.push_back(AZ_CRC("ShapeService", 0xe86aa5fe)); - provided.push_back(AZ_CRC("BoxShapeService", 0x946a0032)); - provided.push_back(AZ_CRC_CE("AxisAlignedBoxShapeService")); - } - - static void GetIncompatibleServices([[maybe_unused]] AZ::ComponentDescriptor::DependencyArrayType& incompatible) - { - } - - static void GetRequiredServices([[maybe_unused]] AZ::ComponentDescriptor::DependencyArrayType& required) - { - } - - static void GetDependentServices([[maybe_unused]] AZ::ComponentDescriptor::DependencyArrayType& dependent) - { - } - }; class MockTerrainSystemService : private Terrain::TerrainSystemServiceRequestBus::Handler { @@ -106,4 +56,40 @@ namespace UnitTest MOCK_METHOD2(OnTerrainDataChanged, void(const AZ::Aabb& dirtyRegion, TerrainDataChangedMask dataChangedMask)); }; + class MockTerrainAreaHeightRequests : public Terrain::TerrainAreaHeightRequestBus::Handler + { + public: + MockTerrainAreaHeightRequests(AZ::EntityId entityId) + { + Terrain::TerrainAreaHeightRequestBus::Handler::BusConnect(entityId); + } + + ~MockTerrainAreaHeightRequests() + { + Terrain::TerrainAreaHeightRequestBus::Handler::BusDisconnect(); + } + + MOCK_METHOD3(GetHeight, void( + const AZ::Vector3& inPosition, + AZ::Vector3& outPosition, + bool& terrainExists)); + + }; + + class MockTerrainSpawnerRequests : public Terrain::TerrainSpawnerRequestBus::Handler + { + public: + MockTerrainSpawnerRequests(AZ::EntityId entityId) + { + Terrain::TerrainSpawnerRequestBus::Handler::BusConnect(entityId); + } + + ~MockTerrainSpawnerRequests() + { + Terrain::TerrainSpawnerRequestBus::Handler::BusDisconnect(); + } + + MOCK_METHOD2(GetPriority, void(AZ::u32& outLayer, AZ::u32& outPriority)); + MOCK_METHOD0(GetUseGroundPlane, bool()); + }; } diff --git a/Gems/Terrain/Code/Source/Components/TerrainHeightGradientListComponent.cpp b/Gems/Terrain/Code/Source/Components/TerrainHeightGradientListComponent.cpp index 4d0cb6576d..4ea16018d1 100644 --- a/Gems/Terrain/Code/Source/Components/TerrainHeightGradientListComponent.cpp +++ b/Gems/Terrain/Code/Source/Components/TerrainHeightGradientListComponent.cpp @@ -142,11 +142,15 @@ namespace Terrain return false; } - float TerrainHeightGradientListComponent::GetHeight(float x, float y) + void TerrainHeightGradientListComponent::GetHeight( + const AZ::Vector3& inPosition, + AZ::Vector3& outPosition, + bool& terrainExists) { float maxSample = 0.0f; + terrainExists = false; - GradientSignal::GradientSampleParams params(AZ::Vector3(x, y, 0.0f)); + GradientSignal::GradientSampleParams params(AZ::Vector3(inPosition.GetX(), inPosition.GetY(), 0.0f)); // Right now, when the list contains multiple entries, we will use the highest point from each gradient. // This is needed in part because gradients don't really have world bounds, so they exist everywhere but generally have a value @@ -155,49 +159,20 @@ namespace Terrain // make this list a prioritized list from top to bottom for any points that overlap. for (auto& gradientId : m_configuration.m_gradientEntities) { + // If gradients ever provide bounds, or if we add a value threshold in this component, it would be possible for terrain + // to *not* exist at a specific point. + terrainExists = true; + float sample = 0.0f; - GradientSignal::GradientRequestBus::EventResult(sample, gradientId, &GradientSignal::GradientRequestBus::Events::GetValue, params); + GradientSignal::GradientRequestBus::EventResult( + sample, gradientId, &GradientSignal::GradientRequestBus::Events::GetValue, params); maxSample = AZ::GetMax(maxSample, sample); } const float height = AZ::Lerp(m_cachedShapeBounds.GetMin().GetZ(), m_cachedShapeBounds.GetMax().GetZ(), maxSample); - - return AZ::GetClamp(height, m_cachedMinWorldHeight, m_cachedMaxWorldHeight); + outPosition.SetZ(AZ::GetClamp(height, m_cachedMinWorldHeight, m_cachedMaxWorldHeight)); } - void TerrainHeightGradientListComponent::GetHeight( - const AZ::Vector3& inPosition, - AZ::Vector3& outPosition, - [[maybe_unused]] AzFramework::Terrain::TerrainDataRequests::Sampler sampleFilter = - AzFramework::Terrain::TerrainDataRequests::Sampler::DEFAULT) - { - const float height = GetHeight(inPosition.GetX(), inPosition.GetY()); - outPosition.SetZ(height); - } - - void TerrainHeightGradientListComponent::GetNormal( - const AZ::Vector3& inPosition, - AZ::Vector3& outNormal, - [[maybe_unused]] AzFramework::Terrain::TerrainDataRequests::Sampler sampleFilter = - AzFramework::Terrain::TerrainDataRequests::Sampler::DEFAULT) - { - const float x = inPosition.GetX(); - const float y = inPosition.GetY(); - - if ((x >= m_cachedShapeBounds.GetMin().GetX()) && (x <= m_cachedShapeBounds.GetMax().GetX()) && - (y >= m_cachedShapeBounds.GetMin().GetY()) && (y <= m_cachedShapeBounds.GetMax().GetY())) - { - AZ::Vector2 fRange = (m_cachedHeightQueryResolution / 2.0f) + AZ::Vector2(0.05f); - - AZ::Vector3 v1(x - fRange.GetX(), y - fRange.GetY(), GetHeight(x - fRange.GetX(), y - fRange.GetY())); - AZ::Vector3 v2(x - fRange.GetX(), y + fRange.GetY(), GetHeight(x - fRange.GetX(), y + fRange.GetY())); - AZ::Vector3 v3(x + fRange.GetX(), y - fRange.GetY(), GetHeight(x + fRange.GetX(), y - fRange.GetY())); - AZ::Vector3 v4(x + fRange.GetX(), y + fRange.GetY(), GetHeight(x + fRange.GetX(), y + fRange.GetY())); - outNormal = (v3 - v2).Cross(v4 - v1).GetNormalized(); - } - } - - void TerrainHeightGradientListComponent::OnCompositionChanged() { RefreshMinMaxHeights(); diff --git a/Gems/Terrain/Code/Source/Components/TerrainHeightGradientListComponent.h b/Gems/Terrain/Code/Source/Components/TerrainHeightGradientListComponent.h index 509f003afa..6c3fd7b820 100644 --- a/Gems/Terrain/Code/Source/Components/TerrainHeightGradientListComponent.h +++ b/Gems/Terrain/Code/Source/Components/TerrainHeightGradientListComponent.h @@ -64,14 +64,7 @@ namespace Terrain TerrainHeightGradientListComponent() = default; ~TerrainHeightGradientListComponent() = default; - void GetHeight( - const AZ::Vector3& inPosition, - AZ::Vector3& outPosition, - AzFramework::Terrain::TerrainDataRequests::Sampler sampleFilter) override; - void GetNormal( - const AZ::Vector3& inPosition, - AZ::Vector3& outNormal, - AzFramework::Terrain::TerrainDataRequests::Sampler sampleFilter) override; + void GetHeight(const AZ::Vector3& inPosition, AZ::Vector3& outPosition, bool& terrainExists) override; ////////////////////////////////////////////////////////////////////////// // AZ::Component interface implementation @@ -91,11 +84,7 @@ namespace Terrain private: TerrainHeightGradientListConfig m_configuration; - /////////////////////////////////////////// - void GetNormalSynchronous(float x, float y, AZ::Vector3& normal); - void RefreshMinMaxHeights(); - float GetHeight(float x, float y); float m_cachedMinWorldHeight{ 0.0f }; float m_cachedMaxWorldHeight{ 0.0f }; diff --git a/Gems/Terrain/Code/Source/Components/TerrainWorldDebuggerComponent.cpp b/Gems/Terrain/Code/Source/Components/TerrainWorldDebuggerComponent.cpp index 89ffa6364f..7233d08281 100644 --- a/Gems/Terrain/Code/Source/Components/TerrainWorldDebuggerComponent.cpp +++ b/Gems/Terrain/Code/Source/Components/TerrainWorldDebuggerComponent.cpp @@ -285,13 +285,13 @@ namespace Terrain AzFramework::Terrain::TerrainDataRequestBus::BroadcastResult( z00, &AzFramework::Terrain::TerrainDataRequests::GetHeightFromFloats, x, y, - AzFramework::Terrain::TerrainDataRequests::Sampler::DEFAULT, &terrainExists); + AzFramework::Terrain::TerrainDataRequests::Sampler::EXACT, &terrainExists); AzFramework::Terrain::TerrainDataRequestBus::BroadcastResult( z01, &AzFramework::Terrain::TerrainDataRequests::GetHeightFromFloats, x, y1, - AzFramework::Terrain::TerrainDataRequests::Sampler::DEFAULT, &terrainExists); + AzFramework::Terrain::TerrainDataRequests::Sampler::EXACT, &terrainExists); AzFramework::Terrain::TerrainDataRequestBus::BroadcastResult( z10, &AzFramework::Terrain::TerrainDataRequests::GetHeightFromFloats, x1, y, - AzFramework::Terrain::TerrainDataRequests::Sampler::DEFAULT, &terrainExists); + AzFramework::Terrain::TerrainDataRequests::Sampler::EXACT, &terrainExists); sector.m_lineVertices.push_back(AZ::Vector3(x, y, z00)); sector.m_lineVertices.push_back(AZ::Vector3(x1, y, z10)); diff --git a/Gems/Terrain/Code/Source/TerrainSystem/TerrainSystem.cpp b/Gems/Terrain/Code/Source/TerrainSystem/TerrainSystem.cpp index 674af376e4..5ec6af6f37 100644 --- a/Gems/Terrain/Code/Source/TerrainSystem/TerrainSystem.cpp +++ b/Gems/Terrain/Code/Source/TerrainSystem/TerrainSystem.cpp @@ -152,27 +152,69 @@ AZ::Vector2 TerrainSystem::GetTerrainHeightQueryResolution() const return m_currentSettings.m_heightQueryResolution; } +void TerrainSystem::ClampPosition(float x, float y, AZ::Vector2& outPosition, AZ::Vector2& normalizedDelta) const +{ + // Given an input position, clamp the values to our terrain grid, where it will always go to the terrain grid point + // at a lower value, whether positive or negative. Ex: 3.3 -> 3, -3.3 -> -4 + // Also, return the normalized delta as a value of [0-1) describing what fraction of a grid point the value moved. + + // Scale the position by the query resolution, so that integer values represent exact steps on the grid, + // and fractional values are the amount in-between each grid point, in the range [0-1). + AZ::Vector2 normalizedPosition = AZ::Vector2(x, y) / m_currentSettings.m_heightQueryResolution; + normalizedDelta = AZ::Vector2( + normalizedPosition.GetX() - floor(normalizedPosition.GetX()), normalizedPosition.GetY() - floor(normalizedPosition.GetY())); + + // Remove the fractional part, then scale back down into world space. + outPosition = (normalizedPosition - normalizedDelta) * m_currentSettings.m_heightQueryResolution; +} + float TerrainSystem::GetHeightSynchronous(float x, float y, Sampler sampler, bool* terrainExistsPtr) const { bool terrainExists = false; - - AZ::Vector3 inPosition((float)x, (float)y, m_currentSettings.m_worldBounds.GetMin().GetZ()); - AZ::Vector3 outPosition((float)x, (float)y, m_currentSettings.m_worldBounds.GetMin().GetZ()); + float height = m_currentSettings.m_worldBounds.GetMin().GetZ(); AZStd::shared_lock lock(m_areaMutex); - for (auto& [areaId, areaBounds] : m_registeredAreas) + switch (sampler) { - inPosition.SetZ(areaBounds.GetMin().GetZ()); - if (areaBounds.Contains(inPosition)) + // Get the value at the requested location, using the terrain grid to bilinear filter between sample grid points. + case AzFramework::Terrain::TerrainDataRequests::Sampler::BILINEAR: { - Terrain::TerrainAreaHeightRequestBus::Event( - areaId, &Terrain::TerrainAreaHeightRequestBus::Events::GetHeight, inPosition, outPosition, sampler); + // pos0 contains one corner of our grid square, pos1 contains the opposite corner, and normalizedDelta is the fractional + // amount the position exists between those corners. + // Ex: (3.3, 4.4) would have a pos0 of (3, 4), a pos1 of (4, 5), and a delta of (0.3, 0.4). + AZ::Vector2 normalizedDelta; + AZ::Vector2 pos0; + ClampPosition(x, y, pos0, normalizedDelta); + const AZ::Vector2 pos1 = pos0 + m_currentSettings.m_heightQueryResolution; - terrainExists = true; - - break; + const float heightX0Y0 = GetTerrainAreaHeight(pos0.GetX(), pos0.GetY(), terrainExists); + const float heightX1Y0 = GetTerrainAreaHeight(pos1.GetX(), pos0.GetY(), terrainExists); + const float heightX0Y1 = GetTerrainAreaHeight(pos0.GetX(), pos1.GetY(), terrainExists); + const float heightX1Y1 = GetTerrainAreaHeight(pos1.GetX(), pos1.GetY(), terrainExists); + const float heightXY0 = AZ::Lerp(heightX0Y0, heightX1Y0, normalizedDelta.GetX()); + const float heightXY1 = AZ::Lerp(heightX0Y1, heightX1Y1, normalizedDelta.GetX()); + height = AZ::Lerp(heightXY0, heightXY1, normalizedDelta.GetY()); } + break; + + //! Clamp the input point to the terrain sample grid, then get the height at the given grid location. + case AzFramework::Terrain::TerrainDataRequests::Sampler::CLAMP: + { + AZ::Vector2 normalizedDelta; + AZ::Vector2 clampedPosition; + ClampPosition(x, y, clampedPosition, normalizedDelta); + + height = GetTerrainAreaHeight(clampedPosition.GetX(), clampedPosition.GetY(), terrainExists); + } + break; + + //! Directly get the value at the location, regardless of terrain sample grid density. + case AzFramework::Terrain::TerrainDataRequests::Sampler::EXACT: + [[fallthrough]]; + default: + height = GetTerrainAreaHeight(x, y, terrainExists); + break; } if (terrainExistsPtr) @@ -181,7 +223,30 @@ float TerrainSystem::GetHeightSynchronous(float x, float y, Sampler sampler, boo } return AZ::GetClamp( - outPosition.GetZ(), m_currentSettings.m_worldBounds.GetMin().GetZ(), m_currentSettings.m_worldBounds.GetMax().GetZ()); + height, m_currentSettings.m_worldBounds.GetMin().GetZ(), m_currentSettings.m_worldBounds.GetMax().GetZ()); +} + +float TerrainSystem::GetTerrainAreaHeight(float x, float y, bool& terrainExists) const +{ + AZ::Vector3 inPosition((float)x, (float)y, m_currentSettings.m_worldBounds.GetMin().GetZ()); + float height = m_currentSettings.m_worldBounds.GetMin().GetZ(); + + AZStd::shared_lock lock(m_areaMutex); + + for (auto& [areaId, areaBounds] : m_registeredAreas) + { + inPosition.SetZ(areaBounds.GetMin().GetZ()); + if (areaBounds.Contains(inPosition)) + { + AZ::Vector3 outPosition; + Terrain::TerrainAreaHeightRequestBus::Event( + areaId, &Terrain::TerrainAreaHeightRequestBus::Events::GetHeight, inPosition, outPosition, terrainExists); + height = outPosition.GetZ(); + break; + } + } + + return height; } float TerrainSystem::GetHeight(AZ::Vector3 position, Sampler sampler, bool* terrainExistsPtr) const @@ -203,24 +268,24 @@ bool TerrainSystem::GetIsHoleFromFloats(float x, float y, Sampler sampler) const AZ::Vector3 TerrainSystem::GetNormalSynchronous(float x, float y, Sampler sampler, bool* terrainExistsPtr) const { - bool terrainExists = false; - - AZ::Vector3 inPosition((float)x, (float)y, m_currentSettings.m_worldBounds.GetMin().GetZ()); - AZ::Vector3 outNormal = AZ::Vector3::CreateAxisZ(); - AZStd::shared_lock lock(m_areaMutex); - for (auto& [areaId, areaBounds] : m_registeredAreas) - { - inPosition.SetZ(areaBounds.GetMin().GetZ()); - if (areaBounds.Contains(inPosition)) - { - Terrain::TerrainAreaHeightRequestBus::Event( - areaId, &Terrain::TerrainAreaHeightRequestBus::Events::GetNormal, inPosition, outNormal, sampler); - terrainExists = true; - break; - } - } + bool terrainExists = false; + + AZ::Vector3 outNormal = AZ::Vector3::CreateAxisZ(); + + const AZ::Vector2 range = (m_currentSettings.m_heightQueryResolution / 2.0f); + const AZ::Vector2 left (x - range.GetX(), y); + const AZ::Vector2 right(x + range.GetX(), y); + const AZ::Vector2 up (x, y - range.GetY()); + const AZ::Vector2 down (x, y + range.GetY()); + + AZ::Vector3 v1(up.GetX(), up.GetY(), GetHeightSynchronous(up.GetX(), up.GetY(), sampler, &terrainExists)); + AZ::Vector3 v2(left.GetX(), left.GetY(), GetHeightSynchronous(left.GetX(), left.GetY(), sampler, &terrainExists)); + AZ::Vector3 v3(right.GetX(), right.GetY(), GetHeightSynchronous(right.GetX(), right.GetY(), sampler, &terrainExists)); + AZ::Vector3 v4(down.GetX(), down.GetY(), GetHeightSynchronous(down.GetX(), down.GetY(), sampler, &terrainExists)); + + outNormal = (v3 - v2).Cross(v4 - v1).GetNormalized(); if (terrainExistsPtr) { @@ -469,43 +534,30 @@ void TerrainSystem::OnTick(float /*deltaTime*/, AZ::ScriptTimePoint /*time*/) { for (uint32_t x = 0; x < width; x++) { - // Find the first terrain layer that covers this position. This will be the highest priority, so others can be ignored. - for (auto& [areaId, areaBounds] : m_registeredAreas) - { - AZ::Vector3 inPosition( - (x * m_currentSettings.m_heightQueryResolution.GetX()) + m_currentSettings.m_worldBounds.GetMin().GetX(), - (y * m_currentSettings.m_heightQueryResolution.GetY()) + m_currentSettings.m_worldBounds.GetMin().GetY(), - areaBounds.GetMin().GetZ()); + bool terrainExists; + float terrainHeight = GetTerrainAreaHeight( + (x * m_currentSettings.m_heightQueryResolution.GetX()) + m_currentSettings.m_worldBounds.GetMin().GetX(), + (y * m_currentSettings.m_heightQueryResolution.GetY()) + m_currentSettings.m_worldBounds.GetMin().GetY(), + terrainExists); - if (!areaBounds.Contains(inPosition)) - { - continue; - } - - AZ::Vector3 outPosition; - const AzFramework::Terrain::TerrainDataRequestBus::Events::Sampler sampleFilter = - AzFramework::Terrain::TerrainDataRequestBus::Events::Sampler::DEFAULT; - - Terrain::TerrainAreaHeightRequestBus::Event( - areaId, &Terrain::TerrainAreaHeightRequestBus::Events::GetHeight, inPosition, outPosition, sampleFilter); - - pixels[(y * width) + x] = (outPosition.GetZ() - m_currentSettings.m_worldBounds.GetMin().GetZ()) / - m_currentSettings.m_worldBounds.GetExtents().GetZ(); - - break; - } + pixels[(y * width) + x] = + (terrainHeight - m_currentSettings.m_worldBounds.GetMin().GetZ()) / + m_currentSettings.m_worldBounds.GetExtents().GetZ(); } } - - const AZ::RPI::Scene* scene = AZ::RPI::RPISystemInterface::Get()->GetDefaultScene().get(); - auto terrainFeatureProcessor = scene->GetFeatureProcessor(); - - AZ_Assert(terrainFeatureProcessor, "Unable to find a TerrainFeatureProcessor."); - if (terrainFeatureProcessor) + if (auto rpi = AZ::RPI::RPISystemInterface::Get(); rpi) { - terrainFeatureProcessor->UpdateTerrainData( - transform, m_currentSettings.m_worldBounds, m_currentSettings.m_heightQueryResolution.GetX(), width, height, pixels); + if (auto defaultScene = rpi->GetDefaultScene(); defaultScene) + { + const AZ::RPI::Scene* scene = defaultScene.get(); + if (auto terrainFeatureProcessor = scene->GetFeatureProcessor(); terrainFeatureProcessor) + { + terrainFeatureProcessor->UpdateTerrainData( + transform, m_currentSettings.m_worldBounds, m_currentSettings.m_heightQueryResolution.GetX(), width, height, + pixels); + } + } } } diff --git a/Gems/Terrain/Code/Source/TerrainSystem/TerrainSystem.h b/Gems/Terrain/Code/Source/TerrainSystem/TerrainSystem.h index c52165da6b..a9240e02a6 100644 --- a/Gems/Terrain/Code/Source/TerrainSystem/TerrainSystem.h +++ b/Gems/Terrain/Code/Source/TerrainSystem/TerrainSystem.h @@ -94,8 +94,11 @@ namespace Terrain float x, float y, Sampler sampleFilter = Sampler::BILINEAR, bool* terrainExistsPtr = nullptr) const override; private: + void ClampPosition(float x, float y, AZ::Vector2& outPosition, AZ::Vector2& normalizedDelta) const; + float GetHeightSynchronous(float x, float y, Sampler sampler, bool* terrainExistsPtr) const; - AZ::Vector3 GetNormalSynchronous(float x, float y, Sampler sampler, bool* terrainExistsPtr) const; + float GetTerrainAreaHeight(float x, float y, bool& terrainExists) const; + AZ::Vector3 GetNormalSynchronous(float x, float y, Sampler sampler, bool* terrainExistsPtr) const; // AZ::TickBus::Handler overrides ... void OnTick(float deltaTime, AZ::ScriptTimePoint time) override; diff --git a/Gems/Terrain/Code/Source/TerrainSystem/TerrainSystemBus.h b/Gems/Terrain/Code/Source/TerrainSystem/TerrainSystemBus.h index 1ba63a8f84..cda6d65a1e 100644 --- a/Gems/Terrain/Code/Source/TerrainSystem/TerrainSystemBus.h +++ b/Gems/Terrain/Code/Source/TerrainSystem/TerrainSystemBus.h @@ -65,27 +65,8 @@ namespace Terrain virtual ~TerrainAreaHeightRequests() = default; - enum SurfacePointDataMask - { - POSITION = 0x01, - NORMAL = 0x02, - SURFACE_WEIGHTS = 0x04, - - DEFAULT = POSITION | NORMAL | SURFACE_WEIGHTS - }; - // Synchronous single input location. The Vector3 input position versions are defined to ignore the input Z value. - - virtual void GetHeight( - const AZ::Vector3& inPosition, - AZ::Vector3& outPosition, - AzFramework::Terrain::TerrainDataRequests::Sampler sampleFilter = - AzFramework::Terrain::TerrainDataRequests::Sampler::DEFAULT) = 0; - virtual void GetNormal( - const AZ::Vector3& inPosition, - AZ::Vector3& outNormal, - AzFramework::Terrain::TerrainDataRequests::Sampler sampleFilter = - AzFramework::Terrain::TerrainDataRequests::Sampler::DEFAULT) = 0; + virtual void GetHeight(const AZ::Vector3& inPosition, AZ::Vector3& outPosition, bool& terrainExists) = 0; }; using TerrainAreaHeightRequestBus = AZ::EBus; diff --git a/Gems/Terrain/Code/Tests/LayerSpawnerTests.cpp b/Gems/Terrain/Code/Tests/LayerSpawnerTests.cpp index f0533322c8..ee4b18e2fb 100644 --- a/Gems/Terrain/Code/Tests/LayerSpawnerTests.cpp +++ b/Gems/Terrain/Code/Tests/LayerSpawnerTests.cpp @@ -15,7 +15,12 @@ #include #include -#include +#include +#include + +using ::testing::NiceMock; +using ::testing::AtLeast; +using ::testing::_; using ::testing::NiceMock; using ::testing::AtLeast; @@ -29,7 +34,7 @@ protected: AZStd::unique_ptr m_entity; Terrain::TerrainLayerSpawnerComponent* m_layerSpawnerComponent; - UnitTest::MockBoxShapeComponent* m_shapeComponent; + UnitTest::MockAxisAlignedBoxShapeComponent* m_shapeComponent; AZStd::unique_ptr> m_terrainSystem; void SetUp() override @@ -67,7 +72,7 @@ protected: m_layerSpawnerComponent = m_entity->CreateComponent(config); m_app.RegisterComponentDescriptor(m_layerSpawnerComponent->CreateDescriptor()); - m_shapeComponent = m_entity->CreateComponent(); + m_shapeComponent = m_entity->CreateComponent(); m_app.RegisterComponentDescriptor(m_shapeComponent->CreateDescriptor()); ASSERT_TRUE(m_layerSpawnerComponent); diff --git a/Gems/Terrain/Code/Tests/MockAxisAlignedBoxShapeComponent.h b/Gems/Terrain/Code/Tests/MockAxisAlignedBoxShapeComponent.h new file mode 100644 index 0000000000..aeaaa609c4 --- /dev/null +++ b/Gems/Terrain/Code/Tests/MockAxisAlignedBoxShapeComponent.h @@ -0,0 +1,45 @@ +/* + * Copyright (c) Contributors to the Open 3D Engine Project. + * For complete copyright and license terms please see the LICENSE at the root of this distribution. + * + * SPDX-License-Identifier: Apache-2.0 OR MIT + * + */ +#pragma once + +#include + +#include +#include +#include +#include + +namespace UnitTest +{ + class MockAxisAlignedBoxShapeComponent + : public AZ::Component + { + public: + AZ_COMPONENT(MockAxisAlignedBoxShapeComponent, "{77CBEED3-FAA3-4BC7-85A9-1A2BFC37BC2A}"); + + static void Reflect([[maybe_unused]] AZ::ReflectContext* context) + { + } + + void Activate() override + { + } + + void Deactivate() override + { + } + + private: + static void GetProvidedServices(AZ::ComponentDescriptor::DependencyArrayType& provided) + { + provided.push_back(AZ_CRC_CE("ShapeService")); + provided.push_back(AZ_CRC_CE("BoxShapeService")); + provided.push_back(AZ_CRC_CE("AxisAlignedBoxShapeService")); + } + }; +} diff --git a/Gems/Terrain/Code/Tests/TerrainSystemTest.cpp b/Gems/Terrain/Code/Tests/TerrainSystemTest.cpp index 3e557c66a6..91a9744f0b 100644 --- a/Gems/Terrain/Code/Tests/TerrainSystemTest.cpp +++ b/Gems/Terrain/Code/Tests/TerrainSystemTest.cpp @@ -9,20 +9,23 @@ #include #include -#include - #include -#include + +#include +#include +#include + +#include +#include using ::testing::AtLeast; using ::testing::NiceMock; +using ::testing::Return; class TerrainSystemTest : public ::testing::Test { protected: AZ::ComponentApplication m_app; - - AZStd::unique_ptr m_entity; AZStd::unique_ptr m_terrainSystem; void SetUp() override @@ -41,28 +44,46 @@ protected: m_app.Destroy(); } - void CreateEntity() + AZStd::unique_ptr CreateEntity() { - m_entity = AZStd::make_unique(); - m_entity->Init(); - - ASSERT_TRUE(m_entity); + return AZStd::make_unique(); } - void ResetEntity() + void ActivateEntity(AZ::Entity* entity) { - m_entity->Deactivate(); - m_entity->Reset(); + entity->Init(); + EXPECT_EQ(AZ::Entity::State::Init, entity->GetState()); + + entity->Activate(); + EXPECT_EQ(AZ::Entity::State::Active, entity->GetState()); + } + + template + AZ::Component* CreateComponent(AZ::Entity* entity, const Configuration& config) + { + m_app.RegisterComponentDescriptor(Component::CreateDescriptor()); + return entity->CreateComponent(config); + } + + template + AZ::Component* CreateComponent(AZ::Entity* entity) + { + m_app.RegisterComponentDescriptor(Component::CreateDescriptor()); + return entity->CreateComponent(); } }; TEST_F(TerrainSystemTest, TrivialCreateDestroy) { + // Trivially verify that the terrain system can successfully be constructed and destructed without errors. + m_terrainSystem = AZStd::make_unique(); } TEST_F(TerrainSystemTest, TrivialActivateDeactivate) { + // Verify that the terrain system can be activated and deactivated without errors. + m_terrainSystem = AZStd::make_unique(); m_terrainSystem->Activate(); m_terrainSystem->Deactivate(); @@ -70,6 +91,8 @@ TEST_F(TerrainSystemTest, TrivialActivateDeactivate) TEST_F(TerrainSystemTest, CreateEventsCalledOnActivation) { + // Verify that when the terrain system is activated, the OnTerrainDataCreate* ebus notifications are generated. + NiceMock mockTerrainListener; EXPECT_CALL(mockTerrainListener, OnTerrainDataCreateBegin()).Times(AtLeast(1)); EXPECT_CALL(mockTerrainListener, OnTerrainDataCreateEnd()).Times(AtLeast(1)); @@ -80,6 +103,8 @@ TEST_F(TerrainSystemTest, CreateEventsCalledOnActivation) TEST_F(TerrainSystemTest, DestroyEventsCalledOnDeactivation) { + // Verify that when the terrain system is deactivated, the OnTerrainDataDestroy* ebus notifications are generated. + NiceMock mockTerrainListener; EXPECT_CALL(mockTerrainListener, OnTerrainDataDestroyBegin()).Times(AtLeast(1)); EXPECT_CALL(mockTerrainListener, OnTerrainDataDestroyEnd()).Times(AtLeast(1)); @@ -89,4 +114,115 @@ TEST_F(TerrainSystemTest, DestroyEventsCalledOnDeactivation) m_terrainSystem->Deactivate(); } +TEST_F(TerrainSystemTest, TerrainDoesNotExistWhenNoTerrainLayerSpawnersAreRegistered) +{ + // For the terrain system, terrain should only exist where terrain layer spawners are present. + + // Verify that in the active terrain system, if there are no terrain layer spawners, any arbitrary point + // will return false for terrainExists, returns a height equal to the min world bounds of the terrain system, and returns + // a normal facing up the Z axis. + + // Create the terrain system and give it one tick to fully initialize itself. + m_terrainSystem = AZStd::make_unique(); + m_terrainSystem->Activate(); + AZ::TickBus::Broadcast(&AZ::TickBus::Events::OnTick, 0.f, AZ::ScriptTimePoint{}); + + AZ::Aabb worldBounds = m_terrainSystem->GetTerrainAabb(); + + // Loop through several points within the world bounds, including on the edges, and verify that they all return false for + // terrainExists with default heights and normals. + for (float y = worldBounds.GetMin().GetY(); y <= worldBounds.GetMax().GetY(); y += (worldBounds.GetExtents().GetY() / 4.0f)) + { + for (float x = worldBounds.GetMin().GetX(); x <= worldBounds.GetMax().GetX(); x += (worldBounds.GetExtents().GetX() / 4.0f)) + { + AZ::Vector3 position(x, y, 0.0f); + bool terrainExists = true; + float height = m_terrainSystem->GetHeight(position, AzFramework::Terrain::TerrainDataRequests::Sampler::EXACT, &terrainExists); + EXPECT_FALSE(terrainExists); + EXPECT_EQ(height, worldBounds.GetMin().GetZ()); + + terrainExists = true; + AZ::Vector3 normal = m_terrainSystem->GetNormal( + position, AzFramework::Terrain::TerrainDataRequests::Sampler::EXACT, &terrainExists); + EXPECT_FALSE(terrainExists); + EXPECT_EQ(normal, AZ::Vector3::CreateAxisZ()); + + bool isHole = m_terrainSystem->GetIsHoleFromFloats( + position.GetX(), position.GetY(), AzFramework::Terrain::TerrainDataRequests::Sampler::EXACT); + EXPECT_TRUE(isHole); + } + } +} + +TEST_F(TerrainSystemTest, TerrainExistsOnlyWithinTerrainLayerSpawnerBounds) +{ + // Verify that the presence of a TerrainLayerSpawner causes terrain to exist in (and *only* in) the box where the TerrainLayerSpawner + // is defined. + + // The terrain system should only query Heights from the TerrainAreaHeightRequest bus within the + // TerrainLayerSpawner region, and so those values should only get returned from GetHeight for queries inside that region. + + // Create the base entity with a mock Box Shape and a Terrain Layer Spawner. + auto entity = CreateEntity(); + CreateComponent(entity.get()); + CreateComponent(entity.get()); + + // Set up the box shape to return a box from (0,0,5) to (10, 10, 15) + AZ::Aabb spawnerBox = AZ::Aabb::CreateFromMinMaxValues(0.0f, 0.0f, 5.0f, 10.0f, 10.0f, 15.0f); + NiceMock boxShapeRequests(entity->GetId()); + NiceMock shapeRequests(entity->GetId()); + ON_CALL(shapeRequests, GetEncompassingAabb).WillByDefault(Return(spawnerBox)); + + // Set up a mock height provider that always returns 5.0 and a normal of Y-up. + const float spawnerHeight = 5.0f; + NiceMock terrainAreaHeightRequests(entity->GetId()); + ON_CALL(terrainAreaHeightRequests, GetHeight) + .WillByDefault( + [spawnerHeight](const AZ::Vector3& inPosition, AZ::Vector3& outPosition, bool& terrainExists) + { + outPosition = inPosition; + outPosition.SetZ(spawnerHeight); + terrainExists = true; + }); + + ActivateEntity(entity.get()); + + // Verify that terrain exists within the layer spawner bounds, and doesn't exist outside of it. + + // Create the terrain system and give it one tick to fully initialize itself. + m_terrainSystem = AZStd::make_unique(); + m_terrainSystem->Activate(); + AZ::TickBus::Broadcast(&AZ::TickBus::Events::OnTick, 0.f, AZ::ScriptTimePoint{}); + + // Create a box that's twice as big as the layer spawner box. Loop through it and verify that points within the layer box contain + // terrain and the expected height & normal values, and points outside the layer box don't contain terrain. + const AZ::Aabb encompassingBox = + AZ::Aabb::CreateFromMinMax(spawnerBox.GetMin() - (spawnerBox.GetExtents() / 2.0f), + spawnerBox.GetMax() + (spawnerBox.GetExtents() / 2.0f)); + + for (float y = encompassingBox.GetMin().GetY(); y < encompassingBox.GetMax().GetY(); y += 1.0f) + { + for (float x = encompassingBox.GetMin().GetX(); x < encompassingBox.GetMax().GetX(); x += 1.0f) + { + AZ::Vector3 position(x, y, 0.0f); + bool heightQueryTerrainExists = false; + float height = + m_terrainSystem->GetHeight(position, AzFramework::Terrain::TerrainDataRequests::Sampler::EXACT, &heightQueryTerrainExists); + bool isHole = m_terrainSystem->GetIsHoleFromFloats( + position.GetX(), position.GetY(), AzFramework::Terrain::TerrainDataRequests::Sampler::EXACT); + + if (spawnerBox.Contains(AZ::Vector3(position.GetX(), position.GetY(), spawnerBox.GetMin().GetZ()))) + { + EXPECT_TRUE(heightQueryTerrainExists); + EXPECT_FALSE(isHole); + EXPECT_EQ(height, spawnerHeight); + } + else + { + EXPECT_FALSE(heightQueryTerrainExists); + EXPECT_TRUE(isHole); + } + } + } +} diff --git a/Gems/Terrain/Code/terrain_mocks_files.cmake b/Gems/Terrain/Code/terrain_mocks_files.cmake new file mode 100644 index 0000000000..2aedd1c5d8 --- /dev/null +++ b/Gems/Terrain/Code/terrain_mocks_files.cmake @@ -0,0 +1,11 @@ +# +# Copyright (c) Contributors to the Open 3D Engine Project. +# For complete copyright and license terms please see the LICENSE at the root of this distribution. +# +# SPDX-License-Identifier: Apache-2.0 OR MIT +# +# + +set(FILES + Mocks/Terrain/MockTerrain.h +) diff --git a/Gems/Terrain/Code/terrain_tests_files.cmake b/Gems/Terrain/Code/terrain_tests_files.cmake index 6d1cf97fd9..3ce1d05003 100644 --- a/Gems/Terrain/Code/terrain_tests_files.cmake +++ b/Gems/Terrain/Code/terrain_tests_files.cmake @@ -7,8 +7,8 @@ # set(FILES - Tests/TerrainMocks.h Tests/TerrainTest.cpp Tests/TerrainSystemTest.cpp Tests/LayerSpawnerTests.cpp + Tests/MockAxisAlignedBoxShapeComponent.h ) diff --git a/cmake/3rdParty.cmake b/cmake/3rdParty.cmake index f70ed1aa02..4b7f929279 100644 --- a/cmake/3rdParty.cmake +++ b/cmake/3rdParty.cmake @@ -6,6 +6,17 @@ # # +define_property(TARGET PROPERTY LY_SYSTEM_LIBRARY + BRIEF_DOCS "Defines a 3rdParty library as a system library" + FULL_DOCS [[ + Property which is set on third party targets that should be considered + as provided by the system. Such targets are excluded from the runtime + dependencies considerations, and are not distributed as part of the + O3DE SDK package. Instead, users of the SDK are expected to install + such a third party library themselves. + ]] +) + # Do not overcomplicate searching for the 3rdParty path, if it is not easy to find, # the user should define it. @@ -79,9 +90,10 @@ endfunction() # "fileA\nMy/Output/Subfolder/lib" # "fileB\nMy/Output/Subfolder/bin" # +# \arg:SYSTEM If specified, the library is considered a system library, and is not copied to the build output directory function(ly_add_external_target) - set(options) + set(options SYSTEM) set(oneValueArgs NAME VERSION 3RDPARTY_DIRECTORY PACKAGE 3RDPARTY_ROOT_DIRECTORY OUTPUT_SUBDIRECTORY) set(multiValueArgs HEADER_CHECK COMPILE_DEFINITIONS INCLUDE_DIRECTORIES BUILD_DEPENDENCIES RUNTIME_DEPENDENCIES) @@ -300,6 +312,10 @@ function(ly_add_external_target) ) endif() + if(ly_add_external_target_SYSTEM) + set_target_properties(3rdParty::${NAME_WITH_NAMESPACE} PROPERTIES LY_SYSTEM_LIBRARY TRUE) + endif() + endif() endfunction() @@ -327,4 +343,4 @@ if(NOT INSTALLED_ENGINE) ly_include_cmake_file_list(cmake/3rdParty/cmake_files.cmake) ly_get_absolute_pal_filename(pal_3rdparty_dir ${CMAKE_CURRENT_SOURCE_DIR}/cmake/3rdParty/Platform/${PAL_PLATFORM_NAME}) ly_include_cmake_file_list(${pal_3rdparty_dir}/cmake_${PAL_PLATFORM_NAME_LOWERCASE}_files.cmake) -endif() \ No newline at end of file +endif() diff --git a/cmake/3rdParty/FindX11.cmake b/cmake/3rdParty/FindX11.cmake new file mode 100644 index 0000000000..98cc57e40e --- /dev/null +++ b/cmake/3rdParty/FindX11.cmake @@ -0,0 +1,29 @@ +# +# Copyright (c) Contributors to the Open 3D Engine Project. +# For complete copyright and license terms please see the LICENSE at the root of this distribution. +# +# SPDX-License-Identifier: Apache-2.0 OR MIT +# +# + +# Open a new scope so we can make changes to CMAKE_MODULE_PATH, and restore it +# when we're done +function(FindX11) + # O3DE's FindX11.cmake is a wrapper for the one that CMake provides. Remove + # our current directory from CMAKE_MODULE_PATH to avoid recursive includes + list(REMOVE_ITEM CMAKE_MODULE_PATH ${CMAKE_CURRENT_LIST_DIR}) + + find_package(X11 COMPONENTS ${X11_FIND_COMPONENTS} QUIET) + + foreach(component IN LISTS X11_FIND_COMPONENTS) + ly_add_external_target( + SYSTEM + PACKAGE X11 + NAME ${component} + VERSION "" + BUILD_DEPENDENCIES + X11::${component} + ) + endforeach() +endfunction() +FindX11() diff --git a/cmake/3rdParty/Platform/Linux/BuiltInPackages_linux.cmake b/cmake/3rdParty/Platform/Linux/BuiltInPackages_linux.cmake index 429665f04a..816ef6db30 100644 --- a/cmake/3rdParty/Platform/Linux/BuiltInPackages_linux.cmake +++ b/cmake/3rdParty/Platform/Linux/BuiltInPackages_linux.cmake @@ -9,7 +9,6 @@ # shared by other platforms: ly_associate_package(PACKAGE_NAME ilmbase-2.3.0-rev4-multiplatform TARGETS ilmbase PACKAGE_HASH 97547fdf1fbc4d81b8ccf382261f8c25514ed3b3c4f8fd493f0a4fa873bba348) ly_associate_package(PACKAGE_NAME assimp-5.0.1-rev11-multiplatform TARGETS assimplib PACKAGE_HASH 1a9113788b893ef4a2ee63ac01eb71b981a92894a5a51175703fa225f5804dec) -ly_associate_package(PACKAGE_NAME ASTCEncoder-2017_11_14-rev2-multiplatform TARGETS ASTCEncoder PACKAGE_HASH c240ffc12083ee39a5ce9dc241de44d116e513e1e3e4cc1d05305e7aa3bdc326) ly_associate_package(PACKAGE_NAME md5-2.0-multiplatform TARGETS md5 PACKAGE_HASH 29e52ad22c78051551f78a40c2709594f0378762ae03b417adca3f4b700affdf) ly_associate_package(PACKAGE_NAME RapidJSON-1.1.0-rev1-multiplatform TARGETS RapidJSON PACKAGE_HASH 2f5e26ecf86c3b7a262753e7da69ac59928e78e9534361f3d00c1ad5879e4023) ly_associate_package(PACKAGE_NAME RapidXML-1.13-rev1-multiplatform TARGETS RapidXML PACKAGE_HASH 4b7b5651e47cfd019b6b295cc17bb147b65e53073eaab4a0c0d20a37ab74a246) @@ -44,5 +43,6 @@ ly_associate_package(PACKAGE_NAME SPIRVCross-2021.04.29-rev1-linux ly_associate_package(PACKAGE_NAME azslc-1.7.23-rev2-linux TARGETS azslc PACKAGE_HASH 1ba84d8321a566d35a1e9aa7400211ba8e6d1c11c08e4be3c93e6e74b8f7aef1) ly_associate_package(PACKAGE_NAME zlib-1.2.11-rev2-linux TARGETS zlib PACKAGE_HASH 16f3b9e11cda525efb62144f354c1cfc30a5def9eff020dbe49cb00ee7d8234f) ly_associate_package(PACKAGE_NAME squish-ccr-deb557d-rev1-linux TARGETS squish-ccr PACKAGE_HASH 85fecafbddc6a41a27c5f59ed4a5dfb123a94cb4666782cf26e63c0a4724c530) +ly_associate_package(PACKAGE_NAME astc-encoder-3.2-rev1-linux TARGETS astc-encoder PACKAGE_HASH 2ba97a06474d609945f0ab4419af1f6bbffdd294ca6b869f5fcebec75c573c0f) ly_associate_package(PACKAGE_NAME ISPCTexComp-36b80aa-rev1-linux TARGETS ISPCTexComp PACKAGE_HASH 065fd12abe4247dde247330313763cf816c3375c221da030bdec35024947f259) ly_associate_package(PACKAGE_NAME lz4-1.9.3-vcpkg-rev4-linux TARGETS lz4 PACKAGE_HASH 5de3dbd3e2a3537c6555d759b3c5bb98e5456cf85c74ff6d046f809b7087290d) diff --git a/cmake/3rdParty/Platform/Mac/BuiltInPackages_mac.cmake b/cmake/3rdParty/Platform/Mac/BuiltInPackages_mac.cmake index 4900a9d77e..58cafdd4b8 100644 --- a/cmake/3rdParty/Platform/Mac/BuiltInPackages_mac.cmake +++ b/cmake/3rdParty/Platform/Mac/BuiltInPackages_mac.cmake @@ -9,7 +9,6 @@ # shared by other platforms: ly_associate_package(PACKAGE_NAME ilmbase-2.3.0-rev4-multiplatform TARGETS ilmbase PACKAGE_HASH 97547fdf1fbc4d81b8ccf382261f8c25514ed3b3c4f8fd493f0a4fa873bba348) ly_associate_package(PACKAGE_NAME assimp-5.0.1-rev11-multiplatform TARGETS assimplib PACKAGE_HASH 1a9113788b893ef4a2ee63ac01eb71b981a92894a5a51175703fa225f5804dec) -ly_associate_package(PACKAGE_NAME ASTCEncoder-2017_11_14-rev2-multiplatform TARGETS ASTCEncoder PACKAGE_HASH c240ffc12083ee39a5ce9dc241de44d116e513e1e3e4cc1d05305e7aa3bdc326) ly_associate_package(PACKAGE_NAME md5-2.0-multiplatform TARGETS md5 PACKAGE_HASH 29e52ad22c78051551f78a40c2709594f0378762ae03b417adca3f4b700affdf) ly_associate_package(PACKAGE_NAME RapidJSON-1.1.0-rev1-multiplatform TARGETS RapidJSON PACKAGE_HASH 2f5e26ecf86c3b7a262753e7da69ac59928e78e9534361f3d00c1ad5879e4023) ly_associate_package(PACKAGE_NAME RapidXML-1.13-rev1-multiplatform TARGETS RapidXML PACKAGE_HASH 4b7b5651e47cfd019b6b295cc17bb147b65e53073eaab4a0c0d20a37ab74a246) @@ -42,6 +41,7 @@ ly_associate_package(PACKAGE_NAME qt-5.15.2-rev5-mac ly_associate_package(PACKAGE_NAME libsamplerate-0.2.1-rev2-mac TARGETS libsamplerate PACKAGE_HASH b912af40c0ac197af9c43d85004395ba92a6a859a24b7eacd920fed5854a97fe) ly_associate_package(PACKAGE_NAME zlib-1.2.11-rev2-mac TARGETS zlib PACKAGE_HASH 21714e8a6de4f2523ee92a7f52d51fbee29c5f37ced334e00dc3c029115b472e) ly_associate_package(PACKAGE_NAME squish-ccr-deb557d-rev1-mac TARGETS squish-ccr PACKAGE_HASH 155bfbfa17c19a9cd2ef025de14c5db598f4290045d5b0d83ab58cb345089a77) +ly_associate_package(PACKAGE_NAME astc-encoder-3.2-rev1-mac TARGETS astc-encoder PACKAGE_HASH 96f6ea8c3e45ec7fe525230c7c53ca665c8300d8e28456cc19bb3159ce6f8dcc) ly_associate_package(PACKAGE_NAME ISPCTexComp-36b80aa-rev1-mac TARGETS ISPCTexComp PACKAGE_HASH 8a4e93277b8face6ea2fd57c6d017bdb55643ed3d6387110bc5f6b3b884dd169) ly_associate_package(PACKAGE_NAME lz4-1.9.3-vcpkg-rev4-mac TARGETS lz4 PACKAGE_HASH 891ff630bf34f7ab1d8eaee2ea0a8f1fca89dbdc63fca41ee592703dd488a73b) diff --git a/cmake/3rdParty/Platform/Windows/BuiltInPackages_windows.cmake b/cmake/3rdParty/Platform/Windows/BuiltInPackages_windows.cmake index 3855b7d712..d02fefc0e9 100644 --- a/cmake/3rdParty/Platform/Windows/BuiltInPackages_windows.cmake +++ b/cmake/3rdParty/Platform/Windows/BuiltInPackages_windows.cmake @@ -9,7 +9,6 @@ # shared by other platforms: ly_associate_package(PACKAGE_NAME ilmbase-2.3.0-rev4-multiplatform TARGETS ilmbase PACKAGE_HASH 97547fdf1fbc4d81b8ccf382261f8c25514ed3b3c4f8fd493f0a4fa873bba348) ly_associate_package(PACKAGE_NAME assimp-5.0.1-rev11-multiplatform TARGETS assimplib PACKAGE_HASH 1a9113788b893ef4a2ee63ac01eb71b981a92894a5a51175703fa225f5804dec) -ly_associate_package(PACKAGE_NAME ASTCEncoder-2017_11_14-rev2-multiplatform TARGETS ASTCEncoder PACKAGE_HASH c240ffc12083ee39a5ce9dc241de44d116e513e1e3e4cc1d05305e7aa3bdc326) ly_associate_package(PACKAGE_NAME md5-2.0-multiplatform TARGETS md5 PACKAGE_HASH 29e52ad22c78051551f78a40c2709594f0378762ae03b417adca3f4b700affdf) ly_associate_package(PACKAGE_NAME RapidJSON-1.1.0-rev1-multiplatform TARGETS RapidJSON PACKAGE_HASH 2f5e26ecf86c3b7a262753e7da69ac59928e78e9534361f3d00c1ad5879e4023) ly_associate_package(PACKAGE_NAME RapidXML-1.13-rev1-multiplatform TARGETS RapidXML PACKAGE_HASH 4b7b5651e47cfd019b6b295cc17bb147b65e53073eaab4a0c0d20a37ab74a246) @@ -49,5 +48,6 @@ ly_associate_package(PACKAGE_NAME OpenSSL-1.1.1b-rev2-windows ly_associate_package(PACKAGE_NAME Crashpad-0.8.0-rev1-windows TARGETS Crashpad PACKAGE_HASH d162aa3070147bc0130a44caab02c5fe58606910252caf7f90472bd48d4e31e2) ly_associate_package(PACKAGE_NAME zlib-1.2.11-rev2-windows TARGETS zlib PACKAGE_HASH 9afab1d67641ed8bef2fb38fc53942da47f2ab339d9e77d3d20704a48af2da0b) ly_associate_package(PACKAGE_NAME squish-ccr-deb557d-rev1-windows TARGETS squish-ccr PACKAGE_HASH 5c3d9fa491e488ccaf802304ad23b932268a2b2846e383f088779962af2bfa84) +ly_associate_package(PACKAGE_NAME astc-encoder-3.2-rev1-windows TARGETS astc-encoder PACKAGE_HASH 3addc6fc1a7eb0d6b7f3d530e962af967e6d92b3825ef485da243346357cf78e) ly_associate_package(PACKAGE_NAME ISPCTexComp-36b80aa-rev1-windows TARGETS ISPCTexComp PACKAGE_HASH b6fa6ea28a2808a9a5524c72c37789c525925e435770f2d94eb2d387360fa2d0) ly_associate_package(PACKAGE_NAME lz4-1.9.3-vcpkg-rev4-windows TARGETS lz4 PACKAGE_HASH 4ea457b833cd8cfaf8e8e06ed6df601d3e6783b606bdbc44a677f77e19e0db16) diff --git a/cmake/AzAutoGen.py b/cmake/AzAutoGen.py index 51c46b53d8..19b9711325 100755 --- a/cmake/AzAutoGen.py +++ b/cmake/AzAutoGen.py @@ -71,10 +71,10 @@ def SearchPaths(filename, paths=[]): return None def ComputeOutputPath(inputFiles, projectDir, outputDir): - commonInputPath = os.path.commonprefix(inputFiles) # If we've globbed many source files, this finds the common prefix + commonInputPath = os.path.commonpath(inputFiles) # If we've globbed many source files, this finds the common path if os.path.isfile(commonInputPath): # If the commonInputPath resolves to an actual file, slice off the filename commonInputPath = os.path.dirname(commonInputPath) - commonPath = os.path.commonprefix([commonInputPath, projectDir]) # Finds the common path between the data source files and our project directory (//depot/dev/Code/Framework/AzCore/) + commonPath = os.path.commonpath([commonInputPath, projectDir]) # Finds the common path between the data source files and our project directory (//depot/dev/Code/Framework/AzCore/) inputRelativePath = os.path.relpath(commonInputPath, commonPath) # Computes the relative path for the project source directory (Code/Framework/AzCore/AutoGen/) return os.path.join(outputDir, inputRelativePath) # Returns a suitable output directory (//depot/dev/Generated/Code/Framework/AzCore/AutoGen/) diff --git a/cmake/Install.cmake b/cmake/Install.cmake index 6f50c78fd7..adcd28fa37 100644 --- a/cmake/Install.cmake +++ b/cmake/Install.cmake @@ -152,3 +152,20 @@ function(ly_install_run_code CODE) ) endfunction() + +#! ly_install_run_script: specifies path to script to be added to the install process (will run at install time) +# +# \notes: +# - refer to cmake's install(SCRIPT documentation for more information +# +function(ly_install_run_script SCRIPT) + + if(NOT LY_INSTALL_ENABLED) + return() + endif() + + install(SCRIPT ${SCRIPT} + COMPONENT ${CMAKE_INSTALL_DEFAULT_COMPONENT_NAME} # use the default for the time being + ) + +endfunction() \ No newline at end of file diff --git a/cmake/LYPython.cmake b/cmake/LYPython.cmake index eeb9f97a55..a8095fbc95 100644 --- a/cmake/LYPython.cmake +++ b/cmake/LYPython.cmake @@ -21,14 +21,17 @@ include(cmake/LySet.cmake) # CMAKE_HOST_SYSTEM_NAME is "Windows", "Darwin", or "Linux" in our cases.. if (${CMAKE_HOST_SYSTEM_NAME} STREQUAL "Linux" ) ly_set(LY_PYTHON_VERSION 3.7.10) + ly_set(LY_PYTHON_VERSION_MAJOR_MINOR 3.7) ly_set(LY_PYTHON_PACKAGE_NAME python-3.7.10-rev2-linux) ly_set(LY_PYTHON_PACKAGE_HASH 6b9cf455e6190ec38836194f4454bb9db6bfc6890b4baff185cc5520aa822f05) elseif (${CMAKE_HOST_SYSTEM_NAME} STREQUAL "Darwin" ) ly_set(LY_PYTHON_VERSION 3.7.10) + ly_set(LY_PYTHON_VERSION_MAJOR_MINOR 3.7) ly_set(LY_PYTHON_PACKAGE_NAME python-3.7.10-rev1-darwin) ly_set(LY_PYTHON_PACKAGE_HASH 3f65801894e4e44b5faa84dd85ef80ecd772dcf728cdd2d668a6e75978a32695) elseif (${CMAKE_HOST_SYSTEM_NAME} STREQUAL "Windows" ) ly_set(LY_PYTHON_VERSION 3.7.10) + ly_set(LY_PYTHON_VERSION_MAJOR_MINOR 3.7) ly_set(LY_PYTHON_PACKAGE_NAME python-3.7.10-rev2-windows) ly_set(LY_PYTHON_PACKAGE_HASH 06d97488a2dbabe832ecfa832a42d3e8a7163ba95e975f032727331b0f49d280) endif() diff --git a/cmake/LYWrappers.cmake b/cmake/LYWrappers.cmake index 8e5633b5e6..d388b03b75 100644 --- a/cmake/LYWrappers.cmake +++ b/cmake/LYWrappers.cmake @@ -477,11 +477,23 @@ function(ly_parse_third_party_dependencies ly_THIRD_PARTY_LIBRARIES) if(${dependency_namespace} STREQUAL "3rdParty") if (NOT TARGET ${dependency}) list(GET dependency_list 1 dependency_package) + list(LENGTH dependency_list dependency_list_length) ly_download_associated_package(${dependency_package}) - find_package(${dependency_package} REQUIRED MODULE) + if (dependency_list_length GREATER 2) + # There's an optional interface specified + list(GET dependency_list 2 component) + list(APPEND packages_with_components ${dependency_package}) + list(APPEND ${dependency_package}_components ${component}) + else() + find_package(${dependency_package} REQUIRED MODULE) + endif() endif() endif() endforeach() + + foreach(dependency IN LISTS packages_with_components) + find_package(${dependency} REQUIRED MODULE COMPONENTS ${${dependency}_components}) + endforeach() endfunction() #! ly_configure_target_platform_properties: Configures any platform specific properties on target diff --git a/cmake/Platform/Common/Install_common.cmake b/cmake/Platform/Common/Install_common.cmake index ab34446922..224d6ccffc 100644 --- a/cmake/Platform/Common/Install_common.cmake +++ b/cmake/Platform/Common/Install_common.cmake @@ -21,15 +21,21 @@ define_property(TARGET PROPERTY LY_INSTALL_GENERATE_RUN_TARGET ly_set(CMAKE_INSTALL_DEFAULT_COMPONENT_NAME Core) -cmake_path(RELATIVE_PATH CMAKE_RUNTIME_OUTPUT_DIRECTORY BASE_DIRECTORY ${CMAKE_BINARY_DIR} OUTPUT_VARIABLE runtime_output_directory) -cmake_path(RELATIVE_PATH CMAKE_LIBRARY_OUTPUT_DIRECTORY BASE_DIRECTORY ${CMAKE_BINARY_DIR} OUTPUT_VARIABLE library_output_directory) - if(LY_MONOLITHIC_GAME) set(LY_BUILD_PERMUTATION Monolithic) else() set(LY_BUILD_PERMUTATION Default) endif() +cmake_path(RELATIVE_PATH CMAKE_RUNTIME_OUTPUT_DIRECTORY BASE_DIRECTORY ${CMAKE_BINARY_DIR} OUTPUT_VARIABLE runtime_output_directory) +cmake_path(RELATIVE_PATH CMAKE_LIBRARY_OUTPUT_DIRECTORY BASE_DIRECTORY ${CMAKE_BINARY_DIR} OUTPUT_VARIABLE library_output_directory) +# Get the output folders, archive is always the same, but runtime/library can be in subfolders defined per target +cmake_path(RELATIVE_PATH CMAKE_ARCHIVE_OUTPUT_DIRECTORY BASE_DIRECTORY ${CMAKE_BINARY_DIR} OUTPUT_VARIABLE archive_output_directory) + +cmake_path(APPEND archive_output_directory "${PAL_PLATFORM_NAME}/$/${LY_BUILD_PERMUTATION}") +cmake_path(APPEND library_output_directory "${PAL_PLATFORM_NAME}/$/${LY_BUILD_PERMUTATION}") +cmake_path(APPEND runtime_output_directory "${PAL_PLATFORM_NAME}/$/${LY_BUILD_PERMUTATION}") + #! ly_setup_target: Setup the data needed to re-create the cmake target commands for a single target function(ly_setup_target OUTPUT_CONFIGURED_TARGET ALIAS_TARGET_NAME absolute_target_source_dir) # De-alias target name @@ -78,9 +84,6 @@ function(ly_setup_target OUTPUT_CONFIGURED_TARGET ALIAS_TARGET_NAME absolute_tar endforeach() endif() - # Get the output folders, archive is always the same, but runtime/library can be in subfolders defined per target - cmake_path(RELATIVE_PATH CMAKE_ARCHIVE_OUTPUT_DIRECTORY BASE_DIRECTORY ${CMAKE_BINARY_DIR} OUTPUT_VARIABLE archive_output_directory) - get_target_property(target_runtime_output_directory ${TARGET_NAME} RUNTIME_OUTPUT_DIRECTORY) if(target_runtime_output_directory) cmake_path(RELATIVE_PATH target_runtime_output_directory BASE_DIRECTORY ${CMAKE_RUNTIME_OUTPUT_DIRECTORY} OUTPUT_VARIABLE target_runtime_output_subdirectory) @@ -91,10 +94,6 @@ function(ly_setup_target OUTPUT_CONFIGURED_TARGET ALIAS_TARGET_NAME absolute_tar cmake_path(RELATIVE_PATH target_library_output_directory BASE_DIRECTORY ${CMAKE_LIBRARY_OUTPUT_DIRECTORY} OUTPUT_VARIABLE target_library_output_subdirectory) endif() - cmake_path(APPEND archive_output_directory "${PAL_PLATFORM_NAME}/$/${LY_BUILD_PERMUTATION}") - cmake_path(APPEND library_output_directory "${PAL_PLATFORM_NAME}/$/${LY_BUILD_PERMUTATION}") - cmake_path(APPEND runtime_output_directory "${PAL_PLATFORM_NAME}/$/${LY_BUILD_PERMUTATION}") - if(COMMAND ly_install_target_override) # Mac needs special handling because of a cmake issue ly_install_target_override(TARGET ${TARGET_NAME} @@ -378,6 +377,10 @@ function(ly_setup_o3de_install) COMPONENT ${CMAKE_INSTALL_DEFAULT_COMPONENT_NAME} ) + if(COMMAND ly_post_install_steps) + ly_post_install_steps() + endif() + endfunction() #! ly_setup_cmake_install: install the "cmake" folder @@ -537,7 +540,7 @@ endfunction()" # of baking the path. This is needed so `cmake --install --prefix ` works regardless of the CMAKE_INSTALL_PREFIX # used to generate the solution. # CMAKE_INSTALL_PREFIX is still used when building the INSTALL target - set(install_output_folder "\${CMAKE_INSTALL_PREFIX}/${runtime_output_directory}/${PAL_PLATFORM_NAME}/$/${LY_BUILD_PERMUTATION}") + set(install_output_folder "\${CMAKE_INSTALL_PREFIX}/${runtime_output_directory}") set(target_file_dir "${install_output_folder}/${target_runtime_output_subdirectory}") ly_get_runtime_dependencies(runtime_dependencies ${target}) foreach(runtime_dependency ${runtime_dependencies}) diff --git a/cmake/Platform/Common/RuntimeDependencies_common.cmake b/cmake/Platform/Common/RuntimeDependencies_common.cmake index 95d91da7f7..60e55453f8 100644 --- a/cmake/Platform/Common/RuntimeDependencies_common.cmake +++ b/cmake/Platform/Common/RuntimeDependencies_common.cmake @@ -70,12 +70,23 @@ function(ly_get_runtime_dependencies ly_RUNTIME_DEPENDENCIES ly_TARGET) # link dependencies are not runtime dependencies (we dont have anything to copy) however, we need to traverse # them since them or some dependency downstream could have something to copy over - foreach(link_dependency ${link_dependencies}) - if(NOT ${link_dependency} MATCHES "^::@") # Skip wraping produced when targets are not created in the same directory (https://cmake.org/cmake/help/latest/prop_tgt/LINK_LIBRARIES.html) - unset(dependencies) - ly_get_runtime_dependencies(dependencies ${link_dependency}) - list(APPEND all_runtime_dependencies ${dependencies}) + foreach(link_dependency IN LISTS link_dependencies) + if(${link_dependency} MATCHES "^::@") + # Skip wraping produced when targets are not created in the same directory + # (https://cmake.org/cmake/help/latest/prop_tgt/LINK_LIBRARIES.html) + continue() endif() + + if(TARGET ${link_dependency} AND link_dependency MATCHES "^3rdParty::") + get_target_property(is_system_library ${link_dependency} LY_SYSTEM_LIBRARY) + if(is_system_library) + continue() + endif() + endif() + + unset(dependencies) + ly_get_runtime_dependencies(dependencies ${link_dependency}) + list(APPEND all_runtime_dependencies ${dependencies}) endforeach() # For manual dependencies, we want to copy over the dependency and traverse them diff --git a/cmake/Platform/Linux/PAL_linux.cmake b/cmake/Platform/Linux/PAL_linux.cmake index c088163dca..e74adb287e 100644 --- a/cmake/Platform/Linux/PAL_linux.cmake +++ b/cmake/Platform/Linux/PAL_linux.cmake @@ -35,7 +35,7 @@ else() endif() # Set the default asset type for deployment -set(LY_ASSET_DEPLOY_ASSET_TYPE "pc" CACHE STRING "Set the asset type for deployment.") +set(LY_ASSET_DEPLOY_ASSET_TYPE "linux" CACHE STRING "Set the asset type for deployment.") # Set the python cmd tool ly_set(LY_PYTHON_CMD ${CMAKE_CURRENT_SOURCE_DIR}/python/python.sh) diff --git a/cmake/Platform/Mac/Configurations_mac.cmake b/cmake/Platform/Mac/Configurations_mac.cmake index 33a58dbbda..b1c50b751d 100644 --- a/cmake/Platform/Mac/Configurations_mac.cmake +++ b/cmake/Platform/Mac/Configurations_mac.cmake @@ -29,9 +29,7 @@ else() endif() # Signing -# The "-o linker-signed" flag is required as a work-around for the following CMake issue: -# https://gitlab.kitware.com/cmake/cmake/-/issues/21854 -ly_set(CMAKE_XCODE_ATTRIBUTE_OTHER_CODE_SIGN_FLAGS "--deep -o linker-signed") +ly_set(CMAKE_XCODE_ATTRIBUTE_OTHER_CODE_SIGN_FLAGS "--deep") # Generate scheme files for Xcode ly_set(CMAKE_XCODE_GENERATE_SCHEME TRUE) diff --git a/cmake/Platform/Mac/InstallUtils_mac.cmake.in b/cmake/Platform/Mac/InstallUtils_mac.cmake.in new file mode 100644 index 0000000000..de6d9ddf65 --- /dev/null +++ b/cmake/Platform/Mac/InstallUtils_mac.cmake.in @@ -0,0 +1,168 @@ +# +# Copyright (c) Contributors to the Open 3D Engine Project. +# For complete copyright and license terms please see the LICENSE at the root of this distribution. +# +# SPDX-License-Identifier: Apache-2.0 OR MIT +# +# + +function(fixup_qt_framework lib_name framework_path) + + file(REMOVE_RECURSE + ${framework_path}/Headers + ${framework_path}/Resources + ${framework_path}/${lib_name} + ${framework_path}/Versions/Current + ${framework_path}/Versions/5/Headers + ) + + execute_process(COMMAND ${CMAKE_COMMAND} -E create_symlink 5 Current + WORKING_DIRECTORY ${framework_path}/Versions + ) + execute_process(COMMAND ${CMAKE_COMMAND} -E create_symlink Versions/Current/${lib_name} ${lib_name} + WORKING_DIRECTORY ${framework_path} + ) + execute_process(COMMAND ${CMAKE_COMMAND} -E create_symlink Versions/Current/Resources Resources + WORKING_DIRECTORY ${framework_path} + ) + +endfunction() + +function(fixup_python_framework framework_path) + + file(REMOVE_RECURSE + ${framework_path}/Versions/Current + ${framework_path}/Versions/@LY_PYTHON_VERSION_MAJOR_MINOR@/Headers + ${framework_path}/Versions/@LY_PYTHON_VERSION_MAJOR_MINOR@/lib/Python + ${framework_path}/Versions/@LY_PYTHON_VERSION_MAJOR_MINOR@/lib/python@LY_PYTHON_VERSION_MAJOR_MINOR@/test + ${framework_path}/Versions/@LY_PYTHON_VERSION_MAJOR_MINOR@/lib/python@LY_PYTHON_VERSION_MAJOR_MINOR@/site-packages/scipy/io/tests + ${framework_path}/Python + ${framework_path}/Resources + ${framework_path}/Headers + ) + + file(GLOB_RECURSE exe_file_list "${framework_path}/**/*.exe") + if(exe_file_list) + file(REMOVE_RECURSE ${exe_file_list}) + endif() + execute_process(COMMAND ${CMAKE_COMMAND} -E create_symlink include/python@LY_PYTHON_VERSION_MAJOR_MINOR@m Headers + WORKING_DIRECTORY ${framework_path}/Versions/@LY_PYTHON_VERSION_MAJOR_MINOR@ + ) + execute_process(COMMAND ${CMAKE_COMMAND} -E create_symlink @LY_PYTHON_VERSION_MAJOR_MINOR@ Current + WORKING_DIRECTORY ${framework_path}/Versions/ + ) + execute_process(COMMAND ${CMAKE_COMMAND} -E create_symlink Versions/Current/Python Python + WORKING_DIRECTORY ${framework_path} + ) + execute_process(COMMAND ${CMAKE_COMMAND} -E create_symlink Versions/Current/Headers Headers + WORKING_DIRECTORY ${framework_path} + ) + execute_process(COMMAND ${CMAKE_COMMAND} -E create_symlink Versions/Current/Resources Resources + WORKING_DIRECTORY ${framework_path} + ) + file(CHMOD ${framework_path}/Versions/Current/Python + PERMISSIONS OWNER_READ OWNER_WRITE OWNER_EXECUTE GROUP_READ GROUP_WRITE GROUP_EXECUTE WORLD_READ WORLD_EXECUTE + ) + +endfunction() + +function(codesign_file file entitlement_file) + + if (NOT @LY_ENABLE_HARDENED_RUNTIME@) + return() + endif() + + if(EXISTS ${entitlement_file}) + + execute_process(COMMAND "/usr/bin/codesign" "--force" "--sign" "@LY_CODE_SIGN_IDENTITY@" "--deep" "-o" "runtime" "--timestamp" "--entitlements" "${entitlement_file}" "${file}" + TIMEOUT 300 + OUTPUT_VARIABLE codesign_out + RESULT_VARIABLE codesign_ret + ) + else() + execute_process(COMMAND "/usr/bin/codesign" "--force" "--sign" "@LY_CODE_SIGN_IDENTITY@" "--deep" "-o" "runtime" "--timestamp" "${file}" + TIMEOUT 300 + OUTPUT_VARIABLE codesign_out + RESULT_VARIABLE codesign_ret + ) + endif() + + if(NOT ${codesign_ret} EQUAL "0") + message(FATAL_ERROR "Codesign operation for ${file_path} returned ${codesign_ret} with message ${codesign_out}") + endif() + +endfunction() + +function(codesign_python_framework_binaries framework_path) + + if (NOT @LY_ENABLE_HARDENED_RUNTIME@) + return() + endif() + + # The codesign "--deep" flag will only codesign binaries in folders with specific names. + # We need to codesign all the binaries that the "--deep" flag will miss. + file(GLOB_RECURSE files + LIST_DIRECTORIES false + "${framework_path}/Versions/@LY_PYTHON_VERSION_MAJOR_MINOR@/bin/**" + "${framework_path}/Versions/@LY_PYTHON_VERSION_MAJOR_MINOR@/lib/**" + "${framework_path}/Versions/@LY_PYTHON_VERSION_MAJOR_MINOR@/Resources/**") + + foreach(file ${files}) + if(NOT EXISTS ${file}) + file(REMOVE ${file}) + continue() + endif() + cmake_path(SET path_var "${file}") + cmake_path(GET path_var EXTENSION LAST_ONLY extension) + set(should_codesign FALSE) + set(extension_skip_list ".dylib" ".so" ".7m") + if (NOT extension) + set(should_codesign TRUE) + elseif(extension IN_LIST extension_skip_list) + set(should_codesign TRUE) + endif() + if(${should_codesign}) + codesign_file("${file}" "@LY_ROOT_FOLDER@/python/Platform/Mac/PythonEntitlements.plist") + endif() + endforeach() + +endfunction() + +function(ly_copy source_file target_directory) + + if("${source_file}" MATCHES "\\.[Ff]ramework[^\\.]") + + # fixup origin to copy the whole Framework folder + string(REGEX REPLACE "(.*\\.[Ff]ramework).*" "\\1" source_file "${source_file}") + + endif() + get_filename_component(target_filename "${source_file}" NAME) + file(COPY "${source_file}" DESTINATION "${target_directory}" FILE_PERMISSIONS @LY_COPY_PERMISSIONS@ FOLLOW_SYMLINK_CHAIN) + + # Our Qt and Python frameworks aren't in the correct bundle format to be codesigned. + if("${target_filename}" MATCHES "(Qt[^.]+)\\.[Ff]ramework") + fixup_qt_framework(${CMAKE_MATCH_1} "${target_directory}/${target_filename}") + # For some Qt frameworks(QtCore), signing the bundle doesn't work because of bundle + # format issues(despite the fixes above). But once we've patched the framework above, there's + # only one executable that we need to sign so we can do it directly. + set(target_filename "${target_filename}/Versions/5/${CMAKE_MATCH_1}") + elseif("${target_filename}" MATCHES "Python.framework") + fixup_python_framework("${target_directory}/${target_filename}") + codesign_python_framework_binaries("${target_directory}/${target_filename}") + endif() + codesign_file("${target_directory}/${target_filename}" "none") + +endfunction() + +function(ly_download_and_codesign_sdk_python) + execute_process(COMMAND ${CMAKE_COMMAND} -DPAL_PLATFORM_NAME=Mac -DLY_3RDPARTY_PATH=${CMAKE_INSTALL_PREFIX}/python -P ${CMAKE_INSTALL_PREFIX}/python/get_python.cmake) + fixup_python_framework(${CMAKE_INSTALL_PREFIX}/python/runtime/@LY_PYTHON_PACKAGE_NAME@/Python.framework) + codesign_python_framework_binaries(${CMAKE_INSTALL_PREFIX}/python/runtime/@LY_PYTHON_PACKAGE_NAME@/Python.framework) + codesign_file(${CMAKE_INSTALL_PREFIX}/python/runtime/@LY_PYTHON_PACKAGE_NAME@/Python.framework @LY_ROOT_FOLDER@/python/Platform/Mac/PythonEntitlements.plist) +endfunction() + +function(ly_codesign_sdk) + codesign_file(${LY_INSTALL_PATH_ORIGINAL}/O3DE_SDK.app "none") +endfunction() + + diff --git a/cmake/Platform/Mac/Install_mac.cmake b/cmake/Platform/Mac/Install_mac.cmake index 8f07b1bfde..bdc2300131 100644 --- a/cmake/Platform/Mac/Install_mac.cmake +++ b/cmake/Platform/Mac/Install_mac.cmake @@ -6,6 +6,8 @@ # # +include(cmake/Platform/Common/Install_common.cmake) + # This is used to generate a setreg file which will be placed inside the bundle # for targets that request it(eg. AssetProcessor/Editor). This is the relative path # to the bundle from the installed engine's root. This will be used to compute the @@ -16,7 +18,7 @@ set(installed_binaries_path_template [[ "AzCore": { "Runtime": { "FilePaths": { - "InstalledBinariesFolder": "bin/Mac/$" + "InstalledBinariesFolder": "@runtime_output_directory@" } } } @@ -24,15 +26,20 @@ set(installed_binaries_path_template [[ }]] ) -unset(target_conf_dir) -foreach(conf IN LISTS CMAKE_CONFIGURATION_TYPES) - string(TOUPPER ${conf} UCONF) - string(APPEND target_conf_dir $<$:${CMAKE_RUNTIME_OUTPUT_DIRECTORY_${UCONF}}>) -endforeach() +# This setreg file will be used by all of our installed app bundles to locate installed +# runtime dependencies. It contains the path to binary install directory relative to +# the installed engine root. +string(CONFIGURE "${installed_binaries_path_template}" configured_setreg_file) +file(GENERATE + OUTPUT ${CMAKE_BINARY_DIR}/runtime_install/$/BinariesInstallPath.setreg + CONTENT "${configured_setreg_file}" +) -set(installed_binaries_setreg_path ${target_conf_dir}/Registry/installed_binaries_path.setreg) - -file(GENERATE OUTPUT ${installed_binaries_setreg_path} CONTENT ${installed_binaries_path_template}) +# ly_install_run_script isn't defined yet so we use install(SCRIPT) directly. +# This needs to be done here because it needs to update the install prefix +# before cmake does anything else in the install process. +configure_file(${LY_ROOT_FOLDER}/cmake/Platform/Mac/PreInstallSteps_mac.cmake.in ${CMAKE_BINARY_DIR}/runtime_install/PreInstallSteps_mac.cmake @ONLY) +install(SCRIPT ${CMAKE_BINARY_DIR}/runtime_install/PreInstallSteps_mac.cmake COMPONENT ${CMAKE_INSTALL_DEFAULT_COMPONENT_NAME}) #! ly_install_target_override: Mac specific target installation function(ly_install_target_override) @@ -70,33 +77,62 @@ function(ly_install_target_override) COMPONENT ${CMAKE_INSTALL_DEFAULT_COMPONENT_NAME} ) + set(install_relative_binaries_path "${ly_platform_install_target_RUNTIME_DIR}/${ly_platform_install_target_RUNTIME_SUBDIR}") + if (${is_bundle}) set_property(TARGET ${ly_platform_install_target_TARGET} PROPERTY RESOURCE ${cached_resources_dir}) + set(runtime_output_filename "$.app") + else() + set(runtime_output_filename "$") + endif() + + get_target_property(target_type ${ly_platform_install_target_TARGET} TYPE) + if(target_type IN_LIST LY_TARGET_TYPES_WITH_RUNTIME_OUTPUTS) + get_target_property(entitlement_file ${ly_platform_install_target_TARGET} ENTITLEMENT_FILE_PATH) + if (NOT entitlement_file) + set(entitlement_file "none") + endif() + + ly_file_read(${LY_ROOT_FOLDER}/cmake/Platform/Mac/runtime_install_mac.cmake.in template_file) + string(CONFIGURE "${template_file}" configured_template_file @ONLY) + file(GENERATE + OUTPUT ${CMAKE_BINARY_DIR}/runtime_install/$/${ly_platform_install_target_TARGET}.cmake + CONTENT "${configured_template_file}" + ) endif() -endfunction() - -#! ly_install_add_install_path_setreg: Adds the install path setreg file as a dependency -function(ly_install_add_install_path_setreg NAME) - set_property(TARGET ${NAME} APPEND PROPERTY INTERFACE_LY_TARGET_FILES "${installed_binaries_setreg_path}\nRegistry") endfunction() #! ly_install_code_function_override: Mac specific copy function to handle frameworks function(ly_install_code_function_override) - install(CODE -"function(ly_copy source_file target_directory) - if(\"\${source_file}\" MATCHES \"\\\\.[Ff]ramework[^\\\\.]\") - - # fixup origin to copy the whole Framework folder - string(REGEX REPLACE \"(.*\\\\.[Ff]ramework).*\" \"\\\\1\" source_file \"\${source_file}\") - get_filename_component(target_filename \"\${source_file}\" NAME) - - endif() - file(COPY \"\${source_file}\" DESTINATION \"\${target_directory}\" FILE_PERMISSIONS ${LY_COPY_PERMISSIONS}) -endfunction()" - COMPONENT ${CMAKE_INSTALL_DEFAULT_COMPONENT_NAME} - ) + configure_file(${LY_ROOT_FOLDER}/cmake/Platform/Mac/InstallUtils_mac.cmake.in ${CMAKE_BINARY_DIR}/runtime_install/InstallUtils_mac.cmake @ONLY) + ly_install_run_script(${CMAKE_BINARY_DIR}/runtime_install/InstallUtils_mac.cmake) + +endfunction() + +#! ly_post_install_steps: Any additional platform specific post install steps +function(ly_post_install_steps) + + # On Mac, after CMake is done installing, the code signatures on all our built binaries will be invalid. + # We need to now codesign each dynamic library, executable, and app bundle. It's specific to each target + # because there could potentially be different entitlements for different targets. + get_property(all_targets GLOBAL PROPERTY LY_ALL_TARGETS) + foreach(alias_target IN LISTS all_targets) + ly_de_alias_target(${alias_target} target) + # Exclude targets that dont produce runtime outputs + get_target_property(target_type ${target} TYPE) + if(NOT target_type IN_LIST LY_TARGET_TYPES_WITH_RUNTIME_OUTPUTS) + continue() + endif() + + ly_install_run_script(${CMAKE_BINARY_DIR}/runtime_install/$/${target}.cmake) + endforeach() + + ly_install_run_code(" + ly_download_and_codesign_sdk_python() + ly_codesign_sdk() + set(CMAKE_INSTALL_PREFIX ${LY_INSTALL_PATH_ORIGINAL}) + ") endfunction() -include(cmake/Platform/Common/Install_common.cmake) diff --git a/cmake/Platform/Mac/LYWrappers_mac.cmake b/cmake/Platform/Mac/LYWrappers_mac.cmake index 578f6fe041..245d3bb7c1 100644 --- a/cmake/Platform/Mac/LYWrappers_mac.cmake +++ b/cmake/Platform/Mac/LYWrappers_mac.cmake @@ -6,6 +6,16 @@ # # +set(LY_ENABLE_HARDENED_RUNTIME OFF CACHE BOOL "Enable hardened runtime capability for Mac builds. This should be ON when building the engine for notarization/distribution.") + +define_property(TARGET PROPERTY ENTITLEMENT_FILE_PATH + BRIEF_DOCS "Path to the entitlement file" + FULL_DOCS [[ + On MacOS, entitlements are used to grant certain privileges + to applications at runtime. Use this propery to specify the + path to a .plist file containing entitlements. + ]] +) function(ly_apply_platform_properties target) @@ -14,6 +24,18 @@ function(ly_apply_platform_properties target) INSTALL_RPATH "@executable_path/;@executable_path/../Frameworks" ) + get_property(is_imported TARGET ${target} PROPERTY IMPORTED) + if((NOT is_imported) AND (LY_ENABLE_HARDENED_RUNTIME)) + get_property(target_type TARGET ${target} PROPERTY TYPE) + set(runtime_types_list "MODULE_LIBRARY" "SHARED_LIBRARY" "EXECUTABLE") + if (target_type IN_LIST runtime_types_list) + set_target_properties(${target} PROPERTIES + XCODE_ATTRIBUTE_ENABLE_HARDENED_RUNTIME YES + XCODE_ATTRIBUTE_CODE_SIGN_INJECT_BASE_ENTITLEMENTS NO + ) + endif() + endif() + endfunction() diff --git a/cmake/Platform/Mac/PAL_mac.cmake b/cmake/Platform/Mac/PAL_mac.cmake index b415daf44a..065b35d69c 100644 --- a/cmake/Platform/Mac/PAL_mac.cmake +++ b/cmake/Platform/Mac/PAL_mac.cmake @@ -39,3 +39,6 @@ set(LY_ASSET_DEPLOY_ASSET_TYPE "mac" CACHE STRING "Set the asset type for deploy # Set the python cmd tool ly_set(LY_PYTHON_CMD ${CMAKE_CURRENT_SOURCE_DIR}/python/python.sh) + +# Only x86_64 is currently supported on Mac +ly_set(CMAKE_OSX_ARCHITECTURES "x86_64") diff --git a/cmake/Platform/Mac/PreInstallSteps_mac.cmake.in b/cmake/Platform/Mac/PreInstallSteps_mac.cmake.in new file mode 100644 index 0000000000..5033aadd6e --- /dev/null +++ b/cmake/Platform/Mac/PreInstallSteps_mac.cmake.in @@ -0,0 +1,39 @@ +# +# Copyright (c) Contributors to the Open 3D Engine Project. +# For complete copyright and license terms please see the LICENSE at the root of this distribution. +# +# SPDX-License-Identifier: Apache-2.0 OR MIT +# +# + +cmake_minimum_required(VERSION 3.20) + +# The O3DE SDK will be shipped as an app bundle. So we create an O3DE_SDK.app directory +# and install SDK into the app's Contents/Engine directory. +set(LY_INSTALL_PATH_ORIGINAL ${CMAKE_INSTALL_PREFIX}) + +file(INSTALL @LY_ROOT_FOLDER@/Code/Tools/BundleLauncher/info.plist + DESTINATION ${CMAKE_INSTALL_PREFIX}/O3DE_SDK.app/Contents +) + +# This SDK launcher will install python site-packages and then launch the ProjectManager +# when a user double clicks on the SDK from Finder. We're only going to need one version +# of the SDK launcher regardless of what configs of the engine are installed. +if (EXISTS @CMAKE_BINARY_DIR@/bin/profile/O3DE_SDK) + set(sdk_launcher_config profile) +elseif (EXISTS @CMAKE_BINARY_DIR@/bin/debug/O3DE_SDK) + set(sdk_launcher_config debug) +elseif (EXISTS @CMAKE_BINARY_DIR@/bin/release/O3DE_SDK) + set(sdk_launcher_config release) +endif() +file(INSTALL @CMAKE_BINARY_DIR@/bin/${sdk_launcher_config}/O3DE_SDK + DESTINATION ${CMAKE_INSTALL_PREFIX}/O3DE_SDK.app/Contents/MacOS + USE_SOURCE_PERMISSIONS +) +file(INSTALL @CMAKE_BINARY_DIR@/runtime_install/${sdk_launcher_config}/BinariesInstallPath.setreg + DESTINATION ${CMAKE_INSTALL_PREFIX}/O3DE_SDK.app/Contents/MacOS/Registry +) + +# We need to update the CMAKE_INSTALL_PREFIX so that the engine is installed inside the app bundle. +file(MAKE_DIRECTORY ${CMAKE_INSTALL_PREFIX}/O3DE_SDK.app/Contents/Engine) +set(CMAKE_INSTALL_PREFIX ${CMAKE_INSTALL_PREFIX}/O3DE_SDK.app/Contents/Engine) \ No newline at end of file diff --git a/cmake/Platform/Mac/runtime_dependencies_mac.cmake.in b/cmake/Platform/Mac/runtime_dependencies_mac.cmake.in index d65578f82a..11551f608f 100644 --- a/cmake/Platform/Mac/runtime_dependencies_mac.cmake.in +++ b/cmake/Platform/Mac/runtime_dependencies_mac.cmake.in @@ -73,8 +73,8 @@ function(ly_copy source_file target_directory) return() endif() - # fixup the destination so it ends up in Contents/Plugins - string(REGEX REPLACE "(.*\\.app/Contents)/MacOS" "\\1/plugins" target_directory "${target_directory}") + # fixup the destination so it ends up in Contents/PlugIns + string(REGEX REPLACE "(.*\\.app/Contents)/MacOS" "\\1/PlugIns" target_directory "${target_directory}") set(local_plugin_dirs ${plugin_dirs}) list(APPEND local_plugin_dirs "${target_directory}") @@ -212,7 +212,6 @@ if(@target_file_dir@ MATCHES ".app/Contents/MacOS") file(REMOVE_RECURSE ${remove_file_list}) endif() - endif() else() # Non-bundle case diff --git a/cmake/Platform/Mac/runtime_install_mac.cmake.in b/cmake/Platform/Mac/runtime_install_mac.cmake.in new file mode 100644 index 0000000000..65b1ede77b --- /dev/null +++ b/cmake/Platform/Mac/runtime_install_mac.cmake.in @@ -0,0 +1,34 @@ +# +# Copyright (c) Contributors to the Open 3D Engine Project. +# For complete copyright and license terms please see the LICENSE at the root of this distribution. +# +# SPDX-License-Identifier: Apache-2.0 OR MIT +# +# + +cmake_path(SET file_path "${CMAKE_INSTALL_PREFIX}/@install_relative_binaries_path@/@runtime_output_filename@") +cmake_path(GET file_path EXTENSION LAST_ONLY file_ext) + +if(file_ext STREQUAL .app) + + file(INSTALL @CMAKE_BINARY_DIR@/runtime_install/$/BinariesInstallPath.setreg + DESTINATION ${file_path}/Contents/MacOS/Registry + ) + + if(EXISTS "${file_path}/Contents/Frameworks/Python.framework") + codesign_python_framework_binaries("${file_path}/Contents/Frameworks/Python.framework") + endif() + +else() + + find_program(LY_INSTALL_NAME_TOOL install_name_tool) + if (NOT LY_INSTALL_NAME_TOOL) + message(FATAL_ERROR "Unable to locate 'install_name_tool'") + endif() + + execute_process(COMMAND + ${LY_INSTALL_NAME_TOOL} -add_rpath @loader_path ${file_path}) + +endif() + +codesign_file("${file_path}" "@entitlement_file@") diff --git a/cmake/Projects.cmake b/cmake/Projects.cmake index 85104e72f6..0ef6da0c20 100644 --- a/cmake/Projects.cmake +++ b/cmake/Projects.cmake @@ -147,14 +147,24 @@ foreach(project ${LY_PROJECTS}) cmake_path(RELATIVE_PATH CMAKE_RUNTIME_OUTPUT_DIRECTORY BASE_DIRECTORY ${CMAKE_BINARY_DIR} OUTPUT_VARIABLE runtime_output_directory) set(install_engine_pak_template [=[ if("${CMAKE_INSTALL_CONFIG_NAME}" MATCHES "^([Rr][Ee][Ll][Ee][Aa][Ss][Ee])$") - set(install_output_folder "${CMAKE_INSTALL_PREFIX}/@runtime_output_directory@/@PAL_PLATFORM_NAME@/${CMAKE_INSTALL_CONFIG_NAME}") - message(STATUS "Generating ${install_output_folder}/Engine.pak from @full_directory_path@/Cache") + set(install_output_folder "${CMAKE_INSTALL_PREFIX}/@runtime_output_directory@/@PAL_PLATFORM_NAME@/${CMAKE_INSTALL_CONFIG_NAME}/@LY_BUILD_PERMUTATION@") + if(NOT DEFINED LY_ASSET_DEPLOY_ASSET_TYPE) + set(LY_ASSET_DEPLOY_ASSET_TYPE @LY_ASSET_DEPLOY_ASSET_TYPE@) + endif() + message(STATUS "Generating ${install_output_folder}/Engine.pak from @full_directory_path@/Cache/${LY_ASSET_DEPLOY_ASSET_TYPE}") file(MAKE_DIRECTORY "${install_output_folder}") - file(ARCHIVE_CREATE OUTPUT "${install_output_folder}/Engine.pak" - PATHS "@full_directory_path@/Cache" - FORMAT zip - ) - message(STATUS "${install_output_folder}/Engine.pak generated") + cmake_path(SET cache_product_path "@full_directory_path@/Cache/${LY_ASSET_DEPLOY_ASSET_TYPE}") + file(GLOB product_assets "${cache_product_path}/*") + if(product_assets) + execute_process( + COMMAND ${CMAKE_COMMAND} -E tar "cf" "${install_output_folder}/Engine.pak" --format=zip -- ${product_assets} + WORKING_DIRECTORY "${cache_product_path}" + RESULT_VARIABLE archive_creation_result + ) + if(archive_creation_result EQUAL 0) + message(STATUS "${install_output_folder}/Engine.pak generated") + endif() + endif() endif() ]=]) string(CONFIGURE "${install_engine_pak_template}" install_engine_pak_code @ONLY) diff --git a/python/Platform/Mac/PythonEntitlements.plist b/python/Platform/Mac/PythonEntitlements.plist new file mode 100644 index 0000000000..ed4892befa --- /dev/null +++ b/python/Platform/Mac/PythonEntitlements.plist @@ -0,0 +1,10 @@ + + + + + com.apple.security.cs.disable-library-validation + + com.apple.security.cs.allow-unsigned-executable-memory + + + diff --git a/python/get_python.sh b/python/get_python.sh index 248a0790fc..e8d35a311e 100755 --- a/python/get_python.sh +++ b/python/get_python.sh @@ -30,7 +30,8 @@ cd $DIR python_exitcode=$? if [ $python_exitcode == 0 ]; then echo get_python.sh: Python is already downloaded: $(./python.sh --version) - $DIR/pip.sh install -r $DIR/requirements.txt --quiet --disable-pip-version-check + $DIR/pip.sh install -r $DIR/requirements.txt --disable-pip-version-check --no-warn-script-location + $DIR/pip.sh install -e $DIR/../scripts/o3de --no-deps --disable-pip-version-check --no-warn-script-location exit 0 fi if [[ "$OSTYPE" = *"darwin"* ]]; @@ -73,5 +74,6 @@ if [ $retVal -ne 0 ]; then fi echo installing via pip... -$DIR/pip.sh install -r $DIR/requirements.txt --disable-pip-version-check +$DIR/pip.sh install -r $DIR/requirements.txt --disable-pip-version-check --no-warn-script-location +$DIR/pip.sh install -e $DIR/../scripts/o3de --no-deps --disable-pip-version-check --no-warn-script-location exit $? diff --git a/scripts/build/Platform/Windows/build_config.json b/scripts/build/Platform/Windows/build_config.json index 02bd01038a..3848e6f980 100644 --- a/scripts/build/Platform/Windows/build_config.json +++ b/scripts/build/Platform/Windows/build_config.json @@ -360,7 +360,7 @@ "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 -DLY_VERSION_ENGINE_NAME=o3de-sdk -DLY_INSTALLER_WIX_ROOT=\"!WIX! \"", - "EXTRA_CMAKE_OPTIONS": "-DLY_INSTALLER_AUTO_GEN_TAG=ON -DLY_INSTALLER_DOWNLOAD_URL=https://dkb1uj4hs9ikv.cloudfront.net -DLY_INSTALLER_LICENSE_URL=https://www.o3debinaries.org/license -DLY_INSTALLER_3RD_PARTY_LICENSE_URL=https://dkb1uj4hs9ikv.cloudfront.net/SPDX-Licenses.txt", + "EXTRA_CMAKE_OPTIONS": "-DLY_INSTALLER_AUTO_GEN_TAG=ON -DLY_INSTALLER_DOWNLOAD_URL=https://www.o3debinaries.org -DLY_INSTALLER_LICENSE_URL=https://www.o3debinaries.org/license", "CPACK_BUCKET": "spectra-prism-staging-us-west-2", "CMAKE_LY_PROJECTS": "", "CMAKE_TARGET": "ALL_BUILD", diff --git a/scripts/build/build_node/Platform/Linux/package-list.ubuntu-focal.txt b/scripts/build/build_node/Platform/Linux/package-list.ubuntu-focal.txt index 21c4755a2e..2cbbe58b38 100644 --- a/scripts/build/build_node/Platform/Linux/package-list.ubuntu-focal.txt +++ b/scripts/build/build_node/Platform/Linux/package-list.ubuntu-focal.txt @@ -13,6 +13,8 @@ libxcb-xinput0 # For Qt plugins at runtime libfontconfig1-dev # For Qt plugins at runtime libcurl4-openssl-dev # For HttpRequestor libsdl2-dev # for WWise/Audio -libxkbcommon-dev +libxcb-xkb-dev # For xcb keyboard input +libxkbcommon-x11-dev # For xcb keyboard input +libxkbcommon-dev # For xcb keyboard input zlib1g-dev mesa-common-dev
Material Slot %1
Entity %1
Material Slot %1
Material %1