diff --git a/AutomatedTesting/Gem/PythonTests/AWS/Windows/client_auth/aws_client_auth_automation_test.py b/AutomatedTesting/Gem/PythonTests/AWS/Windows/client_auth/aws_client_auth_automation_test.py index 198fb934d9..077a068a18 100644 --- a/AutomatedTesting/Gem/PythonTests/AWS/Windows/client_auth/aws_client_auth_automation_test.py +++ b/AutomatedTesting/Gem/PythonTests/AWS/Windows/client_auth/aws_client_auth_automation_test.py @@ -12,6 +12,7 @@ import pytest import ly_test_tools.log.log_monitor from AWS.common import constants +from AWS.common.resource_mappings import AWS_RESOURCE_MAPPINGS_ACCOUNT_ID_KEY # fixture imports from assetpipeline.ap_fixtures.asset_processor_fixture import asset_processor @@ -70,6 +71,41 @@ class TestAWSClientAuthWindows(object): halt_on_unexpected=True, ) assert result, 'Anonymous credentials fetched successfully.' + + @pytest.mark.parametrize('level', ['AWS/ClientAuth']) + def test_anonymous_credentials_no_global_accountid(self, + level: str, + launcher: pytest.fixture, + resource_mappings: pytest.fixture, + workspace: pytest.fixture, + asset_processor: pytest.fixture + ): + """ + Test to verify AWS Cognito Identity pool anonymous authorization. + + Setup: Updates resource mapping file using existing CloudFormation stacks. + Tests: Getting credentials when no credentials are configured + Verification: Log monitor looks for success credentials log. + """ + # Remove top-level account ID from resource mappings + resource_mappings.clear_select_keys([AWS_RESOURCE_MAPPINGS_ACCOUNT_ID_KEY]) + + asset_processor.start() + asset_processor.wait_for_idle() + + file_to_monitor = os.path.join(launcher.workspace.paths.project_log(), constants.GAME_LOG_NAME) + log_monitor = ly_test_tools.log.log_monitor.LogMonitor(launcher=launcher, log_file_path=file_to_monitor) + + launcher.args = ['+LoadLevel', level] + launcher.args.extend(['-rhi=null']) + + with launcher.start(launch_ap=False): + result = log_monitor.monitor_log_for_lines( + expected_lines=['(Script) - Success anonymous credentials'], + unexpected_lines=['(Script) - Fail anonymous credentials'], + halt_on_unexpected=True, + ) + assert result, 'Anonymous credentials fetched successfully.' def test_password_signin_credentials(self, launcher: pytest.fixture, diff --git a/AutomatedTesting/Gem/PythonTests/EditorPythonTestTools/editor_python_test_tools/hydra_editor_utils.py b/AutomatedTesting/Gem/PythonTests/EditorPythonTestTools/editor_python_test_tools/hydra_editor_utils.py index 985e32ede5..19aa6e9d3c 100644 --- a/AutomatedTesting/Gem/PythonTests/EditorPythonTestTools/editor_python_test_tools/hydra_editor_utils.py +++ b/AutomatedTesting/Gem/PythonTests/EditorPythonTestTools/editor_python_test_tools/hydra_editor_utils.py @@ -57,6 +57,10 @@ def add_level_component(component_name): level_component_list, entity.EntityType().Level) level_component_outcome = editor.EditorLevelComponentAPIBus(bus.Broadcast, 'AddComponentsOfType', [level_component_type_ids_list[0]]) + if not level_component_outcome.IsSuccess(): + print('Failed to add {} level component'.format(component_name)) + return None + level_component = level_component_outcome.GetValue()[0] return level_component diff --git a/AutomatedTesting/Gem/PythonTests/PythonAssetBuilder/AssetBuilder_test_case.py b/AutomatedTesting/Gem/PythonTests/PythonAssetBuilder/AssetBuilder_test_case.py index 8d418222ce..112fd013bf 100644 --- a/AutomatedTesting/Gem/PythonTests/PythonAssetBuilder/AssetBuilder_test_case.py +++ b/AutomatedTesting/Gem/PythonTests/PythonAssetBuilder/AssetBuilder_test_case.py @@ -8,42 +8,54 @@ import azlmbr.bus import azlmbr.asset import azlmbr.editor import azlmbr.math -import azlmbr.legacy.general -def raise_and_stop(msg): - print (msg) +print('Starting mock asset tests') +handler = azlmbr.editor.EditorEventBusHandler() + +def on_notify_editor_initialized(args): + # These tests are meant to check that the test_asset.mock source asset turned into + # a test_asset.mock_asset product asset via the Python asset builder system + mockAssetType = azlmbr.math.Uuid_CreateString('{9274AD17-3212-4651-9F3B-7DCCB080E467}', 0) + mockAssetPath = 'gem/pythontests/pythonassetbuilder/test_asset.mock_asset' + assetId = azlmbr.asset.AssetCatalogRequestBus(azlmbr.bus.Broadcast, 'GetAssetIdByPath', mockAssetPath, mockAssetType, False) + if (assetId.is_valid() is False): + print(f'Mock AssetId is not valid! Got {assetId.to_string()} instead') + else: + print(f'Mock AssetId is valid!') + + assetIdString = assetId.to_string() + if (assetIdString.endswith(':528cca58') is False): + print(f'Mock AssetId {assetIdString} has unexpected sub-id for {mockAssetPath}!') + else: + print(f'Mock AssetId has expected sub-id for {mockAssetPath}!') + + print ('Mock asset exists') + + # These tests detect if the geom_group.fbx file turns into a number of azmodel product assets + def test_azmodel_product(generatedModelAssetPath): + azModelAssetType = azlmbr.math.Uuid_CreateString('{2C7477B6-69C5-45BE-8163-BCD6A275B6D8}', 0) + assetId = azlmbr.asset.AssetCatalogRequestBus(azlmbr.bus.Broadcast, 'GetAssetIdByPath', generatedModelAssetPath, azModelAssetType, False) + assetIdString = assetId.to_string() + if (assetId.is_valid()): + print(f'AssetId found for asset ({generatedModelAssetPath}) found') + else: + print(f'Asset at path {generatedModelAssetPath} has unexpected asset ID ({assetIdString})!') + + test_azmodel_product('gem/pythontests/pythonassetbuilder/geom_group_fbx_cube_100cm_z_positive_1.azmodel') + test_azmodel_product('gem/pythontests/pythonassetbuilder/geom_group_fbx_cube_100cm_z_negative_1.azmodel') + test_azmodel_product('gem/pythontests/pythonassetbuilder/geom_group_fbx_cube_100cm_y_positive_1.azmodel') + test_azmodel_product('gem/pythontests/pythonassetbuilder/geom_group_fbx_cube_100cm_y_negative_1.azmodel') + test_azmodel_product('gem/pythontests/pythonassetbuilder/geom_group_fbx_cube_100cm_x_positive_1.azmodel') + test_azmodel_product('gem/pythontests/pythonassetbuilder/geom_group_fbx_cube_100cm_x_negative_1.azmodel') + test_azmodel_product('gem/pythontests/pythonassetbuilder/geom_group_fbx_cube_100cm_center_1.azmodel') + + # clear up notification handler + global handler + handler.disconnect() + handler = None + + print('Finished mock asset tests') azlmbr.editor.EditorToolsApplicationRequestBus(azlmbr.bus.Broadcast, 'ExitNoPrompt') -# These tests are meant to check that the test_asset.mock source asset turned into -# a test_asset.mock_asset product asset via the Python asset builder system -mockAssetType = azlmbr.math.Uuid_CreateString('{9274AD17-3212-4651-9F3B-7DCCB080E467}', 0) -mockAssetPath = 'gem/pythontests/pythonassetbuilder/test_asset.mock_asset' -assetId = azlmbr.asset.AssetCatalogRequestBus(azlmbr.bus.Broadcast, 'GetAssetIdByPath', mockAssetPath, mockAssetType, False) -if (assetId.is_valid() is False): - raise_and_stop(f'Mock AssetId is not valid! Got {assetId.to_string()} instead') - -assetIdString = assetId.to_string() -if (assetIdString.endswith(':528cca58') is False): - raise_and_stop(f'Mock AssetId {assetIdString} has unexpected sub-id for {mockAssetPath}!') - -print ('Mock asset exists') - -# These tests detect if the geom_group.fbx file turns into a number of azmodel product assets -def test_azmodel_product(generatedModelAssetPath): - azModelAssetType = azlmbr.math.Uuid_CreateString('{2C7477B6-69C5-45BE-8163-BCD6A275B6D8}', 0) - assetId = azlmbr.asset.AssetCatalogRequestBus(azlmbr.bus.Broadcast, 'GetAssetIdByPath', generatedModelAssetPath, azModelAssetType, False) - assetIdString = assetId.to_string() - if (assetId.is_valid()): - print(f'AssetId found for asset ({generatedModelAssetPath}) found') - else: - raise_and_stop(f'Asset at path {generatedModelAssetPath} has unexpected asset ID ({assetIdString})!') - -test_azmodel_product('gem/pythontests/pythonassetbuilder/geom_group_fbx_cube_100cm_z_positive_1.azmodel') -test_azmodel_product('gem/pythontests/pythonassetbuilder/geom_group_fbx_cube_100cm_z_negative_1.azmodel') -test_azmodel_product('gem/pythontests/pythonassetbuilder/geom_group_fbx_cube_100cm_y_positive_1.azmodel') -test_azmodel_product('gem/pythontests/pythonassetbuilder/geom_group_fbx_cube_100cm_y_negative_1.azmodel') -test_azmodel_product('gem/pythontests/pythonassetbuilder/geom_group_fbx_cube_100cm_x_positive_1.azmodel') -test_azmodel_product('gem/pythontests/pythonassetbuilder/geom_group_fbx_cube_100cm_x_negative_1.azmodel') -test_azmodel_product('gem/pythontests/pythonassetbuilder/geom_group_fbx_cube_100cm_center_1.azmodel') - -azlmbr.editor.EditorToolsApplicationRequestBus(azlmbr.bus.Broadcast, 'ExitNoPrompt') +handler.connect() +handler.add_callback('NotifyEditorInitialized', on_notify_editor_initialized) diff --git a/AutomatedTesting/Gem/PythonTests/Terrain/EditorScripts/TerrainPhysicsCollider_ChangesSizeWithAxisAlignedBoxShapeChanges.py b/AutomatedTesting/Gem/PythonTests/Terrain/EditorScripts/TerrainPhysicsCollider_ChangesSizeWithAxisAlignedBoxShapeChanges.py index aba506ea20..f4c2a19884 100644 --- a/AutomatedTesting/Gem/PythonTests/Terrain/EditorScripts/TerrainPhysicsCollider_ChangesSizeWithAxisAlignedBoxShapeChanges.py +++ b/AutomatedTesting/Gem/PythonTests/Terrain/EditorScripts/TerrainPhysicsCollider_ChangesSizeWithAxisAlignedBoxShapeChanges.py @@ -12,13 +12,12 @@ class Tests(): add_terrain_collider = ("Terrain Physics Heightfield Collider component added", "Failed to add a Terrain Physics Heightfield Collider component") box_dimensions_changed = ("Aabb dimensions changed successfully", "Failed change Aabb dimensions") configuration_changed = ("Terrain size changed successfully", "Failed terrain size change") - no_errors_and_warnings_found = ("No errors and warnings found", "Found errors and warnings") #fmt: on def TerrainPhysicsCollider_ChangesSizeWithAxisAlignedBoxShapeChanges(): """ Summary: - Test aspects of the TerrainHeightGradientList through the BehaviorContext and the Property Tree. + Test aspects of the Terrain Physics Heightfield Collider through the BehaviorContext and the Property Tree. Test Steps: Expected Behavior: diff --git a/AutomatedTesting/Gem/PythonTests/Terrain/EditorScripts/Terrain_SupportsPhysics.py b/AutomatedTesting/Gem/PythonTests/Terrain/EditorScripts/Terrain_SupportsPhysics.py new file mode 100644 index 0000000000..e68b0932c2 --- /dev/null +++ b/AutomatedTesting/Gem/PythonTests/Terrain/EditorScripts/Terrain_SupportsPhysics.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(): + create_terrain_spawner_entity = ("Terrain_spawner_entity created successfully", "Failed to create terrain_spawner_entity") + create_height_provider_entity = ("Height_provider_entity created successfully", "Failed to create height_provider_entity") + create_test_ball = ("Ball created successfully", "Failed to create Ball") + box_dimensions_changed = ("Aabb dimensions changed successfully", "Failed change Aabb dimensions") + shape_changed = ("Shape changed successfully", "Failed Shape change") + entity_added = ("Entity added successfully", "Failed Entity add") + frequency_changed = ("Frequency changed successfully", "Failed Frequency change") + shape_set = ("Shape set to Sphere successfully", "Failed to set Sphere shape") + test_collision = ("Ball collided with terrain", "Ball failed to collide with terrain") + no_errors_and_warnings_found = ("No errors and warnings found", "Found errors and warnings") +#fmt: on + +def Terrain_SupportsPhysics(): + """ + Summary: + Test aspects of the TerrainHeightGradientList through the BehaviorContext and the Property Tree. + + Test Steps: + Expected Behavior: + The Editor is stable there are no warnings or errors. + + Test Steps: + 1) Load the base level + 2) Create 2 test entities, one parent at 512.0, 512.0, 50.0 and one child at the default position and add the required components + 2a) Create a ball at 600.0, 600.0, 46.0 - This position is not too high over the heightfield so will collide in a reasonable time + 3) Start the Tracer to catch any errors and warnings + 4) Change the Axis Aligned Box Shape dimensions + 5) Set the Vegetation Shape reference to TestEntity1 + 6) Set the FastNoise gradient frequency to 0.01 + 7) Set the Gradient List to TestEntity2 + 8) Set the PhysX Collider to Sphere mode + 9) Disable and Enable the Terrain Gradient List so that it is recognised + 10) Enter game mode and test if the ball hits the heightfield within 3 seconds + 11) Verify there are no errors and warnings in the logs + + + :return: None + """ + + from editor_python_test_tools.editor_entity_utils import EditorEntity + from editor_python_test_tools.utils import TestHelper as helper, Report + from editor_python_test_tools.utils import Report, Tracer + import editor_python_test_tools.hydra_editor_utils as hydra + import azlmbr.math as azmath + import azlmbr.legacy.general as general + import azlmbr.bus as bus + import azlmbr.editor as editor + import math + + SET_BOX_X_SIZE = 1024.0 + SET_BOX_Y_SIZE = 1024.0 + SET_BOX_Z_SIZE = 100.0 + + helper.init_idle() + + # 1) Load the level + helper.open_level("", "Base") + helper.wait_for_condition(lambda: general.get_current_level_name() == "Base", 2.0) + + #1a) Load the level components + hydra.add_level_component("Terrain World") + hydra.add_level_component("Terrain World Renderer") + + # 2) Create 2 test entities, one parent at 512.0, 512.0, 50.0 and one child at the default position and add the required components + entity1_components_to_add = ["Axis Aligned Box Shape", "Terrain Layer Spawner", "Terrain Height Gradient List", "Terrain Physics Heightfield Collider", "PhysX Heightfield Collider"] + entity2_components_to_add = ["Vegetation Reference Shape", "Gradient Transform Modifier", "FastNoise Gradient"] + ball_components_to_add = ["Sphere Shape", "PhysX Collider", "PhysX Rigid Body"] + terrain_spawner_entity = hydra.Entity("TestEntity1") + terrain_spawner_entity.create_entity(azmath.Vector3(512.0, 512.0, 50.0), entity1_components_to_add) + Report.result(Tests.create_terrain_spawner_entity, terrain_spawner_entity.id.IsValid()) + height_provider_entity = hydra.Entity("TestEntity2") + height_provider_entity.create_entity(azmath.Vector3(0.0, 0.0, 0.0), entity2_components_to_add,terrain_spawner_entity.id) + Report.result(Tests.create_height_provider_entity, height_provider_entity.id.IsValid()) + # 2a) Create a ball at 600.0, 600.0, 46.0 - This position is not too high over the heightfield so will collide in a reasonable time + ball = hydra.Entity("Ball") + ball.create_entity(azmath.Vector3(600.0, 600.0, 46.0), ball_components_to_add) + Report.result(Tests.create_test_ball, ball.id.IsValid()) + # Give everything a chance to finish initializing. + general.idle_wait_frames(1) + + # 3) Start the Tracer to catch any errors and warnings + with Tracer() as section_tracer: + # 4) Change the Axis Aligned Box Shape dimensions + box_dimensions = azmath.Vector3(SET_BOX_X_SIZE, SET_BOX_Y_SIZE, SET_BOX_Z_SIZE) + terrain_spawner_entity.get_set_test(0, "Axis Aligned Box Shape|Box Configuration|Dimensions", box_dimensions) + box_shape_dimensions = hydra.get_component_property_value(terrain_spawner_entity.components[0], "Axis Aligned Box Shape|Box Configuration|Dimensions") + Report.result(Tests.box_dimensions_changed, box_dimensions == box_shape_dimensions) + + # 5) Set the Vegetaion Shape reference to TestEntity1 + height_provider_entity.get_set_test(0, "Configuration|Shape Entity Id", terrain_spawner_entity.id) + entityId = hydra.get_component_property_value(height_provider_entity.components[0], "Configuration|Shape Entity Id") + Report.result(Tests.shape_changed, entityId == terrain_spawner_entity.id) + + # 6) Set the FastNoise Gradient frequency to 0.01 + Frequency = 0.01 + height_provider_entity.get_set_test(2, "Configuration|Frequency", Frequency) + FrequencyVal = hydra.get_component_property_value(height_provider_entity.components[2], "Configuration|Frequency") + Report.result(Tests.frequency_changed, math.isclose(Frequency, FrequencyVal, abs_tol = 0.00001)) + + # 7) Set the Gradient List to TestEntity2 + propertyTree = hydra.get_property_tree(terrain_spawner_entity.components[2]) + propertyTree.add_container_item("Configuration|Gradient Entities", 0, height_provider_entity.id) + checkID = propertyTree.get_container_item("Configuration|Gradient Entities", 0) + Report.result(Tests.entity_added, checkID.GetValue() == height_provider_entity.id) + + # 8) Set the PhysX Collider to Sphere mode + shape = 0 + hydra.get_set_test(ball, 1, "Shape Configuration|Shape", shape) + setShape = hydra.get_component_property_value(ball.components[1], "Shape Configuration|Shape") + Report.result(Tests.shape_set, shape == setShape) + + # 9) Disable and Enable the Terrain Gradient List so that it is recognised + editor.EditorComponentAPIBus(bus.Broadcast, 'EnableComponents', [terrain_spawner_entity.components[2]]) + + general.enter_game_mode() + + general.idle_wait_frames(1) + + # 10) Enter game mode and test if the ball hits the heightfield within 3 seconds + TIMEOUT = 3.0 + + class Collider: + id = general.find_game_entity("Ball") + touched_ground = False + + terrain_id = general.find_game_entity("TestEntity1") + + def on_collision_begin(args): + other_id = args[0] + if other_id.Equal(terrain_id): + Report.info("Touched ground") + Collider.touched_ground = True + + handler = azlmbr.physics.CollisionNotificationBusHandler() + handler.connect(Collider.id) + handler.add_callback("OnCollisionBegin", on_collision_begin) + + helper.wait_for_condition(lambda: Collider.touched_ground, TIMEOUT) + Report.result(Tests.test_collision, Collider.touched_ground) + + general.exit_game_mode() + + # 11) Verify there are no errors and warnings in the logs + helper.wait_for_condition(lambda: section_tracer.has_errors or section_tracer.has_asserts, 1.0) + for error_info in section_tracer.errors: + Report.info(f"Error: {error_info.filename} {error_info.function} | {error_info.message}") + for assert_info in section_tracer.asserts: + Report.info(f"Assert: {assert_info.filename} {assert_info.function} | {assert_info.message}") + + +if __name__ == "__main__": + + from editor_python_test_tools.utils import Report + Report.start_test(Terrain_SupportsPhysics) + diff --git a/AutomatedTesting/Gem/PythonTests/Terrain/TestSuite_Main.py b/AutomatedTesting/Gem/PythonTests/Terrain/TestSuite_Main.py index 620d84d7db..c5eec74c08 100644 --- a/AutomatedTesting/Gem/PythonTests/Terrain/TestSuite_Main.py +++ b/AutomatedTesting/Gem/PythonTests/Terrain/TestSuite_Main.py @@ -13,13 +13,15 @@ import os import sys from ly_test_tools import LAUNCHERS -from ly_test_tools.o3de.editor_test import EditorTestSuite, EditorSingleTest +from ly_test_tools.o3de.editor_test import EditorTestSuite, EditorSharedTest @pytest.mark.SUITE_main @pytest.mark.parametrize("launcher_platform", ['windows_editor']) @pytest.mark.parametrize("project", ["AutomatedTesting"]) class TestAutomation(EditorTestSuite): - #global_extra_cmdline_args=["--regset=/Amazon/Preferences/EnablePrefabSystem=true"] - class test_AxisAlignedBoxShape_ConfigurationWorks(EditorSingleTest): + class test_AxisAlignedBoxShape_ConfigurationWorks(EditorSharedTest): from .EditorScripts import TerrainPhysicsCollider_ChangesSizeWithAxisAlignedBoxShapeChanges as test_module + + class test_Terrain_SupportsPhysics(EditorSharedTest): + from .EditorScripts import Terrain_SupportsPhysics as test_module diff --git a/AutomatedTesting/Gem/PythonTests/editor/EditorScripts/AssetBrowser_SearchFiltering.py b/AutomatedTesting/Gem/PythonTests/editor/EditorScripts/AssetBrowser_SearchFiltering.py index 33c48c7a77..7366faafdc 100644 --- a/AutomatedTesting/Gem/PythonTests/editor/EditorScripts/AssetBrowser_SearchFiltering.py +++ b/AutomatedTesting/Gem/PythonTests/editor/EditorScripts/AssetBrowser_SearchFiltering.py @@ -62,7 +62,7 @@ def AssetBrowser_SearchFiltering(): from editor_python_test_tools.utils import Report from editor_python_test_tools.utils import TestHelper as helper - def verify_files_appeared(model, allowed_asset_extentions, parent_index=QtCore.QModelIndex()): + def verify_files_appeared(model, allowed_asset_extensions, parent_index=QtCore.QModelIndex()): indexes = [parent_index] while len(indexes) > 0: parent_index = indexes.pop(0) @@ -71,7 +71,7 @@ def AssetBrowser_SearchFiltering(): cur_data = cur_index.data(Qt.DisplayRole) if ( "." in cur_data - and (cur_data.lower().split(".")[-1] not in allowed_asset_extentions) + and (cur_data.lower().split(".")[-1] not in allowed_asset_extensions) and not cur_data[-1] == ")" ): Report.info(f"Incorrect file found: {cur_data}") @@ -94,16 +94,21 @@ def AssetBrowser_SearchFiltering(): Report.info("Asset Browser is already open") editor_window = pyside_utils.get_editor_main_window() app = QtWidgets.QApplication.instance() - - # 3) Type the name of an asset in the search bar and make sure only one asset is filtered in Asset browser + + # 3) Type the name of an asset in the search bar and make sure it is filtered to and selectable asset_browser = editor_window.findChild(QtWidgets.QDockWidget, "Asset Browser") search_bar = asset_browser.findChild(QtWidgets.QLineEdit, "textSearch") search_bar.setText("cedar.fbx") asset_browser_tree = asset_browser.findChild(QtWidgets.QTreeView, "m_assetBrowserTreeViewWidget") - model_index = pyside_utils.find_child_by_pattern(asset_browser_tree, "cedar.fbx") - pyside_utils.item_view_index_mouse_click(asset_browser_tree, model_index) + asset_browser_table = asset_browser.findChild(QtWidgets.QTreeView, "m_assetBrowserTableViewWidget") + found = await pyside_utils.wait_for_condition(lambda: pyside_utils.find_child_by_pattern(asset_browser_table, "cedar.fbx"), 5.0) + if found: + model_index = pyside_utils.find_child_by_pattern(asset_browser_table, "cedar.fbx") + else: + Report.result(Tests.asset_filtered, found) + pyside_utils.item_view_index_mouse_click(asset_browser_table, model_index) is_filtered = await pyside_utils.wait_for_condition( - lambda: asset_browser_tree.indexBelow(asset_browser_tree.currentIndex()) == QtCore.QModelIndex(), 5.0) + lambda: asset_browser_table.currentIndex() == model_index, 5.0) Report.result(Tests.asset_filtered, is_filtered) # 4) Click the "X" in the search bar. diff --git a/AutomatedTesting/Gem/PythonTests/editor/EditorScripts/AssetBrowser_TreeNavigation.py b/AutomatedTesting/Gem/PythonTests/editor/EditorScripts/AssetBrowser_TreeNavigation.py index b4f0dc7f6c..ecc77778cc 100644 --- a/AutomatedTesting/Gem/PythonTests/editor/EditorScripts/AssetBrowser_TreeNavigation.py +++ b/AutomatedTesting/Gem/PythonTests/editor/EditorScripts/AssetBrowser_TreeNavigation.py @@ -84,8 +84,8 @@ def AssetBrowser_TreeNavigation(): # 3) Collapse all files initially main_window = editor_window.findChild(QtWidgets.QMainWindow) - asset_browser = pyside_utils.find_child_by_hierarchy(main_window, ..., "Asset Browser") - tree = pyside_utils.find_child_by_hierarchy(asset_browser, ..., "m_assetBrowserTreeViewWidget") + asset_browser = pyside_utils.find_child_by_pattern(main_window, text="Asset Browser", type=QtWidgets.QDockWidget) + tree = pyside_utils.find_child_by_pattern(asset_browser, "m_assetBrowserTreeViewWidget") scroll_area = tree.findChild(QtWidgets.QWidget, "qt_scrollarea_vcontainer") scroll_bar = scroll_area.findChild(QtWidgets.QScrollBar) tree.collapseAll() diff --git a/AutomatedTesting/Gem/PythonTests/editor/TestSuite_Main_Optimized.py b/AutomatedTesting/Gem/PythonTests/editor/TestSuite_Main_Optimized.py index afc52f962d..820e4bd2aa 100644 --- a/AutomatedTesting/Gem/PythonTests/editor/TestSuite_Main_Optimized.py +++ b/AutomatedTesting/Gem/PythonTests/editor/TestSuite_Main_Optimized.py @@ -43,7 +43,6 @@ class TestAutomationNoAutoTestMode(EditorTestSuite): class test_InputBindings_Add_Remove_Input_Events(EditorSharedTest): from .EditorScripts import InputBindings_Add_Remove_Input_Events as test_module - @pytest.mark.skip(reason="Crashes Editor: ATOM-15493") class test_AssetPicker_UI_UX(EditorSharedTest): from .EditorScripts import AssetPicker_UI_UX as test_module @@ -60,7 +59,6 @@ class TestAutomationAutoTestMode(EditorTestSuite): class test_AssetBrowser_TreeNavigation(EditorSharedTest): from .EditorScripts import AssetBrowser_TreeNavigation as test_module - @pytest.mark.skip(reason="Crashes Editor: ATOM-15493") class test_AssetBrowser_SearchFiltering(EditorSharedTest): from .EditorScripts import AssetBrowser_SearchFiltering as test_module @@ -74,6 +72,5 @@ class TestAutomationAutoTestMode(EditorTestSuite): class test_Menus_FileMenuOptions_Work(EditorSharedTest): from .EditorScripts import Menus_FileMenuOptions as test_module - class test_BasicEditorWorkflows_ExistingLevel_EntityComponentCRUD(EditorSharedTest): from .EditorScripts import BasicEditorWorkflows_ExistingLevel_EntityComponentCRUD as test_module diff --git a/AutomatedTesting/Gem/PythonTests/editor/TestSuite_Periodic.py b/AutomatedTesting/Gem/PythonTests/editor/TestSuite_Periodic.py index 398b64bc87..f131a1c8bc 100644 --- a/AutomatedTesting/Gem/PythonTests/editor/TestSuite_Periodic.py +++ b/AutomatedTesting/Gem/PythonTests/editor/TestSuite_Periodic.py @@ -34,12 +34,10 @@ class TestAutomation(TestAutomationBase): from .EditorScripts import AssetBrowser_TreeNavigation as test_module self._run_test(request, workspace, editor, test_module, batch_mode=False) - @pytest.mark.skip(reason="Crashes Editor: ATOM-15493") def test_AssetBrowser_SearchFiltering(self, request, workspace, editor, launcher_platform): from .EditorScripts import AssetBrowser_SearchFiltering as test_module self._run_test(request, workspace, editor, test_module, batch_mode=False) - @pytest.mark.skip(reason="Crashes Editor: ATOM-15493") def test_AssetPicker_UI_UX(self, request, workspace, editor, launcher_platform): from .EditorScripts import AssetPicker_UI_UX as test_module self._run_test(request, workspace, editor, test_module, autotest_mode=False, batch_mode=False) diff --git a/AutomatedTesting/Levels/Base/Base.prefab b/AutomatedTesting/Levels/Base/Base.prefab index 98495663b7..7765fe488e 100644 --- a/AutomatedTesting/Levels/Base/Base.prefab +++ b/AutomatedTesting/Levels/Base/Base.prefab @@ -1,52 +1,61 @@ { "ContainerEntity": { - "Id": "ContainerEntity", - "Name": "Base", + "Id": "Entity_[1146574390643]", + "Name": "Level", "Components": { - "Component_[10182366347512475253]": { - "$type": "EditorPrefabComponent", - "Id": 10182366347512475253 + "Component_[10641544592923449938]": { + "$type": "EditorInspectorComponent", + "Id": 10641544592923449938 }, - "Component_[12917798267488243668]": { - "$type": "EditorPendingCompositionComponent", - "Id": 12917798267488243668 - }, - "Component_[3261249813163778338]": { + "Component_[12039882709170782873]": { "$type": "EditorOnlyEntityComponent", - "Id": 3261249813163778338 + "Id": 12039882709170782873 }, - "Component_[3837204912784440039]": { - "$type": "EditorDisabledCompositionComponent", - "Id": 3837204912784440039 + "Component_[12265484671603697631]": { + "$type": "EditorPendingCompositionComponent", + "Id": 12265484671603697631 }, - "Component_[4272963378099646759]": { + "Component_[14126657869720434043]": { + "$type": "EditorEntitySortComponent", + "Id": 14126657869720434043, + "ChildEntityOrderEntryArray": [ + { + "EntityId": "" + }, + { + "EntityId": "", + "SortIndex": 1 + } + ] + }, + "Component_[15230859088967841193]": { "$type": "{27F1E1A1-8D9D-4C3B-BD3A-AFB9762449C0} TransformComponent", - "Id": 4272963378099646759, + "Id": 15230859088967841193, "Parent Entity": "" }, - "Component_[4848458548047175816]": { - "$type": "EditorVisibilityComponent", - "Id": 4848458548047175816 + "Component_[16239496886950819870]": { + "$type": "EditorDisabledCompositionComponent", + "Id": 16239496886950819870 }, - "Component_[5787060997243919943]": { - "$type": "EditorInspectorComponent", - "Id": 5787060997243919943 - }, - "Component_[7804170251266531779]": { - "$type": "EditorLockComponent", - "Id": 7804170251266531779 - }, - "Component_[7874177159288365422]": { - "$type": "EditorEntitySortComponent", - "Id": 7874177159288365422 - }, - "Component_[8018146290632383969]": { + "Component_[5688118765544765547]": { "$type": "EditorEntityIconComponent", - "Id": 8018146290632383969 + "Id": 5688118765544765547 }, - "Component_[8452360690590857075]": { + "Component_[6545738857812235305]": { "$type": "SelectionComponent", - "Id": 8452360690590857075 + "Id": 6545738857812235305 + }, + "Component_[7247035804068349658]": { + "$type": "EditorPrefabComponent", + "Id": 7247035804068349658 + }, + "Component_[9307224322037797205]": { + "$type": "EditorLockComponent", + "Id": 9307224322037797205 + }, + "Component_[9562516168917670048]": { + "$type": "EditorVisibilityComponent", + "Id": 9562516168917670048 } } } diff --git a/Code/Editor/2DViewport.cpp b/Code/Editor/2DViewport.cpp index ed810aea29..4d0609907f 100644 --- a/Code/Editor/2DViewport.cpp +++ b/Code/Editor/2DViewport.cpp @@ -234,7 +234,7 @@ void Q2DViewport::UpdateContent(int flags) } ////////////////////////////////////////////////////////////////////////// -void Q2DViewport::OnRButtonDown(Qt::KeyboardModifiers modifiers, const QPoint& point) +void Q2DViewport::OnRButtonDown([[maybe_unused]] Qt::KeyboardModifiers modifiers, const QPoint& point) { if (GetIEditor()->IsInGameMode()) { @@ -246,9 +246,6 @@ void Q2DViewport::OnRButtonDown(Qt::KeyboardModifiers modifiers, const QPoint& p setFocus(); } - // Check Edit Tool. - MouseCallback(eMouseRDown, point, modifiers); - SetCurrentCursor(STD_CURSOR_MOVE, QString()); // Save the mouse down position @@ -273,17 +270,8 @@ void Q2DViewport::OnRButtonUp([[maybe_unused]] Qt::KeyboardModifiers modifiers, } ////////////////////////////////////////////////////////////////////////// -void Q2DViewport::OnMButtonDown(Qt::KeyboardModifiers modifiers, const QPoint& point) +void Q2DViewport::OnMButtonDown([[maybe_unused]] Qt::KeyboardModifiers modifiers, const QPoint& point) { - //////////////////////////////////////////////////////////////////////// - // User pressed the middle mouse button - //////////////////////////////////////////////////////////////////////// - // Check Edit Tool. - if (MouseCallback(eMouseMDown, point, modifiers)) - { - return; - } - // Save the mouse down position m_RMouseDownPos = point; @@ -300,14 +288,8 @@ void Q2DViewport::OnMButtonDown(Qt::KeyboardModifiers modifiers, const QPoint& p } ////////////////////////////////////////////////////////////////////////// -void Q2DViewport::OnMButtonUp(Qt::KeyboardModifiers modifiers, const QPoint& point) +void Q2DViewport::OnMButtonUp([[maybe_unused]] Qt::KeyboardModifiers modifiers, [[maybe_unused]] const QPoint& point) { - // Check Edit Tool. - if (MouseCallback(eMouseMUp, point, modifiers)) - { - return; - } - SetViewMode(NothingMode); ReleaseMouse(); @@ -547,13 +529,6 @@ QPoint Q2DViewport::WorldToView(const Vec3& wp) const QPoint p = QPoint(static_cast(sp.x), static_cast(sp.y)); return p; } -////////////////////////////////////////////////////////////////////////// -QPoint Q2DViewport::WorldToViewParticleEditor(const Vec3& wp, [[maybe_unused]] int width, [[maybe_unused]] int height) const //Eric@conffx implement for the children class of IDisplayViewport -{ - Vec3 sp = m_screenTM.TransformPoint(wp); - QPoint p = QPoint(static_cast(sp.x), static_cast(sp.y)); - return p; -} ////////////////////////////////////////////////////////////////////////// Vec3 Q2DViewport::ViewToWorld(const QPoint& vp, [[maybe_unused]] bool* collideWithTerrain, [[maybe_unused]] bool onlyTerrain, [[maybe_unused]] bool bSkipVegetation, [[maybe_unused]] bool bTestRenderMesh, [[maybe_unused]] bool* collideWithObject) const diff --git a/Code/Editor/2DViewport.h b/Code/Editor/2DViewport.h index cee07ca6cd..e89f4aed34 100644 --- a/Code/Editor/2DViewport.h +++ b/Code/Editor/2DViewport.h @@ -50,8 +50,6 @@ public: //! Map world space position to viewport position. QPoint WorldToView(const Vec3& wp) const override; - QPoint WorldToViewParticleEditor(const Vec3& wp, int width, int height) const override; //Eric@conffx - //! Map viewport position to world space position. Vec3 ViewToWorld(const QPoint& vp, bool* collideWithTerrain = nullptr, bool onlyTerrain = false, bool bSkipVegetation = false, bool bTestRenderMesh = false, bool* collideWithObject = nullptr) const override; //! Map viewport position to world space ray from camera. diff --git a/Code/Editor/ActionManager.cpp b/Code/Editor/ActionManager.cpp index ff74a2c208..4cc64a532e 100644 --- a/Code/Editor/ActionManager.cpp +++ b/Code/Editor/ActionManager.cpp @@ -152,15 +152,6 @@ ActionManager::ActionWrapper& ActionManager::ActionWrapper::SetMenu(DynamicMenu* return *this; } -ActionManager::ActionWrapper& ActionManager::ActionWrapper::SetApplyHoverEffect() -{ - // Our standard toolbar icons, when hovered on, get a white color effect. - // But for this to work we need .pngs that look good with this effect, so this only works with the standard toolbars - // and looks very ugly for other toolbars, including toolbars loaded from XML (which just show a white rectangle) - m_action->setProperty("IconHasHoverEffect", true); - return *this; -} - ActionManager::ActionWrapper& ActionManager::ActionWrapper::SetReserved() { m_action->setProperty("Reserved", true); diff --git a/Code/Editor/ActionManager.h b/Code/Editor/ActionManager.h index 8879bdc1fb..58504f860c 100644 --- a/Code/Editor/ActionManager.h +++ b/Code/Editor/ActionManager.h @@ -151,7 +151,6 @@ public: } ActionWrapper& SetMenu(DynamicMenu* menu); - ActionWrapper& SetApplyHoverEffect(); operator QAction*() const { return m_action; diff --git a/Code/Editor/EditorModularViewportCameraComposer.cpp b/Code/Editor/EditorModularViewportCameraComposer.cpp index 72fd37605a..f145adf72f 100644 --- a/Code/Editor/EditorModularViewportCameraComposer.cpp +++ b/Code/Editor/EditorModularViewportCameraComposer.cpp @@ -145,6 +145,15 @@ namespace SandboxEditor } }; + const auto trackingTransform = [viewportId = m_viewportId] + { + bool tracking = false; + AtomToolsFramework::ModularViewportCameraControllerRequestBus::EventResult( + tracking, viewportId, &AtomToolsFramework::ModularViewportCameraControllerRequestBus::Events::IsTrackingTransform); + + return tracking; + }; + m_firstPersonRotateCamera = AZStd::make_shared(SandboxEditor::CameraFreeLookChannelId()); m_firstPersonRotateCamera->m_rotateSpeedFn = [] @@ -152,6 +161,11 @@ namespace SandboxEditor return SandboxEditor::CameraRotateSpeed(); }; + m_firstPersonRotateCamera->m_constrainPitch = [trackingTransform] + { + return !trackingTransform(); + }; + // default behavior is to hide the cursor but this can be disabled (useful for remote desktop) // note: See CaptureCursorLook in the Settings Registry m_firstPersonRotateCamera->SetActivationBeganFn(hideCursor); @@ -255,6 +269,11 @@ namespace SandboxEditor return SandboxEditor::CameraOrbitYawRotationInverted(); }; + m_orbitRotateCamera->m_constrainPitch = [trackingTransform] + { + return !trackingTransform(); + }; + m_orbitTranslateCamera = AZStd::make_shared( translateCameraInputChannelIds, AzFramework::LookTranslation, AzFramework::TranslateOffsetOrbit); @@ -337,12 +356,12 @@ namespace SandboxEditor AZ::TransformBus::EventResult(worldFromLocal, viewEntityId, &AZ::TransformBus::Events::GetWorldTM); AtomToolsFramework::ModularViewportCameraControllerRequestBus::Event( - m_viewportId, &AtomToolsFramework::ModularViewportCameraControllerRequestBus::Events::SetReferenceFrame, worldFromLocal); + m_viewportId, &AtomToolsFramework::ModularViewportCameraControllerRequestBus::Events::StartTrackingTransform, worldFromLocal); } else { AtomToolsFramework::ModularViewportCameraControllerRequestBus::Event( - m_viewportId, &AtomToolsFramework::ModularViewportCameraControllerRequestBus::Events::ClearReferenceFrame); + m_viewportId, &AtomToolsFramework::ModularViewportCameraControllerRequestBus::Events::StopTrackingTransform); } } diff --git a/Code/Editor/EditorViewportWidget.cpp b/Code/Editor/EditorViewportWidget.cpp index 3a2053f328..132729466c 100644 --- a/Code/Editor/EditorViewportWidget.cpp +++ b/Code/Editor/EditorViewportWidget.cpp @@ -298,13 +298,9 @@ AzToolsFramework::ViewportInteraction::MousePick EditorViewportWidget::BuildMous { AzToolsFramework::ViewportInteraction::MousePick mousePick; mousePick.m_screenCoordinates = AzToolsFramework::ViewportInteraction::ScreenPointFromQPoint(point); - if (const auto& ray = m_renderViewport->ViewportScreenToWorldRay(mousePick.m_screenCoordinates); - ray.has_value()) - { - mousePick.m_rayOrigin = ray.value().origin; - mousePick.m_rayDirection = ray.value().direction; - } - + const auto[origin, direction] = m_renderViewport->ViewportScreenToWorldRay(mousePick.m_screenCoordinates); + mousePick.m_rayOrigin = origin; + mousePick.m_rayDirection = direction; return mousePick; } @@ -895,23 +891,6 @@ AZ::Vector3 EditorViewportWidget::PickTerrain(const AzFramework::ScreenPoint& po return LYVec3ToAZVec3(ViewToWorld(AzToolsFramework::ViewportInteraction::QPointFromScreenPoint(point), nullptr, true)); } -AZ::EntityId EditorViewportWidget::PickEntity(const AzFramework::ScreenPoint& point) -{ - AZ::EntityId entityId; - HitContext hitInfo; - hitInfo.view = this; - if (HitTest(AzToolsFramework::ViewportInteraction::QPointFromScreenPoint(point), hitInfo)) - { - if (hitInfo.object && (hitInfo.object->GetType() == OBJTYPE_AZENTITY)) - { - auto entityObject = static_cast(hitInfo.object); - entityId = entityObject->GetAssociatedEntityId(); - } - } - - return entityId; -} - float EditorViewportWidget::TerrainHeight(const AZ::Vector2& position) { return GetIEditor()->GetTerrainElevation(position.GetX(), position.GetY()); @@ -1636,16 +1615,15 @@ void EditorViewportWidget::RenderSelectedRegion() Vec3 EditorViewportWidget::WorldToView3D(const Vec3& wp, [[maybe_unused]] int nFlags) const { Vec3 out(0, 0, 0); - float x, y, z; + float x, y; - ProjectToScreen(wp.x, wp.y, wp.z, &x, &y, &z); - if (_finite(x) && _finite(y) && _finite(z)) + ProjectToScreen(wp.x, wp.y, wp.z, &x, &y); + if (_finite(x) && _finite(y)) { out.x = (x / 100) * m_rcClient.width(); out.y = (y / 100) * m_rcClient.height(); out.x /= static_cast(QHighDpiScaling::factor(windowHandle()->screen())); out.y /= static_cast(QHighDpiScaling::factor(windowHandle()->screen())); - out.z = z; } return out; } @@ -1655,24 +1633,6 @@ QPoint EditorViewportWidget::WorldToView(const Vec3& wp) const { return AzToolsFramework::ViewportInteraction::QPointFromScreenPoint(m_renderViewport->ViewportWorldToScreen(LYVec3ToAZVec3(wp))); } -////////////////////////////////////////////////////////////////////////// -QPoint EditorViewportWidget::WorldToViewParticleEditor(const Vec3& wp, int width, int height) const -{ - QPoint p; - float x, y, z; - - ProjectToScreen(wp.x, wp.y, wp.z, &x, &y, &z); - if (_finite(x) || _finite(y)) - { - p.rx() = static_cast((x / 100) * width); - p.ry() = static_cast((y / 100) * height); - } - else - { - QPoint(0, 0); - } - return p; -} ////////////////////////////////////////////////////////////////////////// Vec3 EditorViewportWidget::ViewToWorld( @@ -1688,20 +1648,16 @@ Vec3 EditorViewportWidget::ViewToWorld( AZ_UNUSED(collideWithObject); auto ray = m_renderViewport->ViewportScreenToWorldRay(AzToolsFramework::ViewportInteraction::ScreenPointFromQPoint(vp)); - if (!ray.has_value()) - { - return Vec3(0, 0, 0); - } const float maxDistance = 10000.f; - Vec3 v = AZVec3ToLYVec3(ray.value().direction) * maxDistance; + Vec3 v = AZVec3ToLYVec3(ray.direction) * maxDistance; if (!_finite(v.x) || !_finite(v.y) || !_finite(v.z)) { return Vec3(0, 0, 0); } - Vec3 colp = AZVec3ToLYVec3(ray.value().origin) + 0.002f * v; + Vec3 colp = AZVec3ToLYVec3(ray.origin) + 0.002f * v; return colp; } @@ -1740,21 +1696,19 @@ bool EditorViewportWidget::RayRenderMeshIntersection(IRenderMesh* pRenderMesh, c return bRes;*/ } -void EditorViewportWidget::UnProjectFromScreen(float sx, float sy, float sz, float* px, float* py, float* pz) const +void EditorViewportWidget::UnProjectFromScreen(float sx, float sy, float* px, float* py, float* pz) const { - AZ::Vector3 wp; - wp = m_renderViewport->ViewportScreenToWorld(AzFramework::ScreenPoint{(int)sx, m_rcClient.bottom() - ((int)sy)}, sz).value_or(wp); + const AZ::Vector3 wp = m_renderViewport->ViewportScreenToWorld(AzFramework::ScreenPoint{(int)sx, m_rcClient.bottom() - ((int)sy)}); *px = wp.GetX(); *py = wp.GetY(); *pz = wp.GetZ(); } -void EditorViewportWidget::ProjectToScreen(float ptx, float pty, float ptz, float* sx, float* sy, float* sz) const +void EditorViewportWidget::ProjectToScreen(float ptx, float pty, float ptz, float* sx, float* sy) const { AzFramework::ScreenPoint screenPosition = m_renderViewport->ViewportWorldToScreen(AZ::Vector3{ptx, pty, ptz}); *sx = static_cast(screenPosition.m_x); *sy = static_cast(screenPosition.m_y); - *sz = 0.f; } ////////////////////////////////////////////////////////////////////////// @@ -1764,32 +1718,22 @@ void EditorViewportWidget::ViewToWorldRay(const QPoint& vp, Vec3& raySrc, Vec3& Vec3 pos0, pos1; float wx, wy, wz; - UnProjectFromScreen(static_cast(vp.x()), static_cast(rc.bottom() - vp.y()), 0.0f, &wx, &wy, &wz); - if (!_finite(wx) || !_finite(wy) || !_finite(wz)) - { - return; - } - if (fabs(wx) > 1000000 || fabs(wy) > 1000000 || fabs(wz) > 1000000) - { - return; - } - pos0(wx, wy, wz); - UnProjectFromScreen(static_cast(vp.x()), static_cast(rc.bottom() - vp.y()), 1.0f, &wx, &wy, &wz); - if (!_finite(wx) || !_finite(wy) || !_finite(wz)) - { - return; - } - if (fabs(wx) > 1000000 || fabs(wy) > 1000000 || fabs(wz) > 1000000) - { - return; - } - pos1(wx, wy, wz); + UnProjectFromScreen(static_cast(vp.x()), static_cast(rc.bottom() - vp.y()), &wx, &wy, &wz); - Vec3 v = (pos1 - pos0); - v = v.GetNormalized(); + if (!_finite(wx) || !_finite(wy) || !_finite(wz)) + { + return; + } + + if (fabs(wx) > 1000000 || fabs(wy) > 1000000 || fabs(wz) > 1000000) + { + return; + } + + pos0(wx, wy, wz); raySrc = pos0; - rayDir = v; + rayDir = (pos0 - AZVec3ToLYVec3(m_renderViewport->GetCameraState().m_position)).GetNormalized(); } ////////////////////////////////////////////////////////////////////////// @@ -2338,10 +2282,10 @@ void* EditorViewportWidget::GetSystemCursorConstraintWindow() const return systemCursorConstrained ? renderOverlayHWND() : nullptr; } -void EditorViewportWidget::BuildDragDropContext(AzQtComponents::ViewportDragContext& context, const QPoint& pt) +void EditorViewportWidget::BuildDragDropContext( + AzQtComponents::ViewportDragContext& context, const AzFramework::ViewportId viewportId, const QPoint& point) { - const auto scaledPoint = WidgetToViewport(pt); - QtViewport::BuildDragDropContext(context, scaledPoint); + QtViewport::BuildDragDropContext(context, viewportId, point); } void EditorViewportWidget::RestoreViewportAfterGameMode() diff --git a/Code/Editor/EditorViewportWidget.h b/Code/Editor/EditorViewportWidget.h index b63eb66de2..0101f2ffef 100644 --- a/Code/Editor/EditorViewportWidget.h +++ b/Code/Editor/EditorViewportWidget.h @@ -165,7 +165,6 @@ private: Qt::MouseButtons buttons, Qt::KeyboardModifiers modifiers, const QPoint& point) override; void SetViewportId(int id) override; QPoint WorldToView(const Vec3& wp) const override; - QPoint WorldToViewParticleEditor(const Vec3& wp, int width, int height) const override; Vec3 WorldToView3D(const Vec3& wp, int nFlags = 0) const override; Vec3 ViewToWorld(const QPoint& vp, bool* collideWithTerrain = nullptr, bool onlyTerrain = false, bool bSkipVegetation = false, bool bTestRenderMesh = false, bool* collideWithObject = nullptr) const override; void ViewToWorldRay(const QPoint& vp, Vec3& raySrc, Vec3& rayDir) const override; @@ -206,7 +205,6 @@ private: void* GetSystemCursorConstraintWindow() const override; // AzToolsFramework::MainEditorViewportInteractionRequestBus overrides ... - AZ::EntityId PickEntity(const AzFramework::ScreenPoint& point) override; AZ::Vector3 PickTerrain(const AzFramework::ScreenPoint& point) override; float TerrainHeight(const AZ::Vector2& position) override; bool ShowingWorldSpace() override; @@ -273,7 +271,8 @@ private: bool CheckRespondToInput() const; - void BuildDragDropContext(AzQtComponents::ViewportDragContext& context, const QPoint& pt) override; + void BuildDragDropContext( + AzQtComponents::ViewportDragContext& context, AzFramework::ViewportId viewportId, const QPoint& point) override; void SetAsActiveViewport(); void PushDisableRendering(); @@ -304,8 +303,8 @@ private: const DisplayContext& GetDisplayContext() const { return m_displayContext; } CBaseObject* GetCameraObject() const; - void UnProjectFromScreen(float sx, float sy, float sz, float* px, float* py, float* pz) const; - void ProjectToScreen(float ptx, float pty, float ptz, float* sx, float* sy, float* sz) const; + void UnProjectFromScreen(float sx, float sy, float* px, float* py, float* pz) const; + void ProjectToScreen(float ptx, float pty, float ptz, float* sx, float* sy) const; AZ::RPI::ViewPtr GetCurrentAtomView() const; diff --git a/Code/Editor/Include/IDisplayViewport.h b/Code/Editor/Include/IDisplayViewport.h index df17c9cb13..132c62804c 100644 --- a/Code/Editor/Include/IDisplayViewport.h +++ b/Code/Editor/Include/IDisplayViewport.h @@ -45,7 +45,6 @@ struct IDisplayViewport virtual const Matrix34& GetViewTM() const = 0; virtual const Matrix34& GetScreenTM() const = 0; virtual QPoint WorldToView(const Vec3& worldPoint) const = 0; - virtual QPoint WorldToViewParticleEditor(const Vec3& worldPoint, int width, int height) const = 0; virtual Vec3 WorldToView3D(const Vec3& worldPoint, int flags = 0) const = 0; virtual Vec3 ViewToWorld(const QPoint& vp, bool* collideWithTerrain = nullptr, bool onlyTerrain = false, bool bSkipVegetation = false, bool bTestRenderMesh = false, bool* collideWithObject = nullptr) const = 0; virtual void ViewToWorldRay(const QPoint& vp, Vec3& raySrc, Vec3& rayDir) const = 0; diff --git a/Code/Editor/Lib/Tests/Camera/test_EditorCamera.cpp b/Code/Editor/Lib/Tests/Camera/test_EditorCamera.cpp index 637b9c44c5..dd7698a82e 100644 --- a/Code/Editor/Lib/Tests/Camera/test_EditorCamera.cpp +++ b/Code/Editor/Lib/Tests/Camera/test_EditorCamera.cpp @@ -27,7 +27,9 @@ namespace UnitTest AZ::Entity* m_entity = nullptr; AZ::ComponentDescriptor* m_transformComponent = nullptr; - static const AzFramework::ViewportId TestViewportId; + static inline constexpr AzFramework::ViewportId TestViewportId = 2345; + static inline constexpr float HalfInterpolateToTransformDuration = + AtomToolsFramework::ModularViewportCameraControllerRequests::InterpolateToTransformDuration * 0.5f; void SetUp() override { @@ -76,8 +78,6 @@ namespace UnitTest } }; - const AzFramework::ViewportId EditorCameraFixture::TestViewportId = AzFramework::ViewportId(1337); - TEST_F(EditorCameraFixture, ModularViewportCameraControllerReferenceFrameUpdatedWhenViewportEntityisChanged) { // Given @@ -91,8 +91,8 @@ namespace UnitTest &Camera::EditorCameraNotificationBus::Events::OnViewportViewEntityChanged, m_entity->GetId()); // ensure the viewport updates after the viewport view entity change - const float deltaTime = 1.0f / 60.0f; - m_controllerList->UpdateViewport({ TestViewportId, AzFramework::FloatSeconds(deltaTime), AZ::ScriptTimePoint() }); + // note: do a large step to ensure smoothing finishes (e.g. not 1.0f/60.0f) + m_controllerList->UpdateViewport({ TestViewportId, AzFramework::FloatSeconds(2.0f), AZ::ScriptTimePoint() }); // retrieve updated camera transform const AZ::Transform cameraTransform = m_cameraViewportContextView->GetCameraTransform(); @@ -102,61 +102,40 @@ namespace UnitTest EXPECT_THAT(cameraTransform, IsClose(entityTransform)); } - TEST_F(EditorCameraFixture, ReferenceFrameRemainsIdentityAfterExternalCameraTransformChangeWhenNotSet) + TEST_F(EditorCameraFixture, TrackingTransformIsTrueAfterTransformIsTracked) { - // Given - m_cameraViewportContextView->SetCameraTransform(AZ::Transform::CreateTranslation(AZ::Vector3(10.0f, 20.0f, 30.0f))); + // Given/When + const AZ::Transform referenceFrame = AZ::Transform::CreateFromQuaternionAndTranslation( + AZ::Quaternion::CreateRotationX(AZ::DegToRad(90.0f)), AZ::Vector3(1.0f, 2.0f, 3.0f)); + AtomToolsFramework::ModularViewportCameraControllerRequestBus::Event( + TestViewportId, &AtomToolsFramework::ModularViewportCameraControllerRequestBus::Events::StartTrackingTransform, referenceFrame); - // When - AZ::Transform referenceFrame = AZ::Transform::CreateTranslation(AZ::Vector3(1.0f, 2.0f, 3.0f)); + bool trackingTransform = false; AtomToolsFramework::ModularViewportCameraControllerRequestBus::EventResult( - referenceFrame, TestViewportId, &AtomToolsFramework::ModularViewportCameraControllerRequestBus::Events::GetReferenceFrame); + trackingTransform, TestViewportId, &AtomToolsFramework::ModularViewportCameraControllerRequestBus::Events::IsTrackingTransform); // Then - // reference frame is still the identity - EXPECT_THAT(referenceFrame, IsClose(AZ::Transform::CreateIdentity())); + EXPECT_THAT(trackingTransform, ::testing::IsTrue()); } - TEST_F(EditorCameraFixture, ExternalCameraTransformChangeWhenReferenceFrameIsSetUpdatesReferenceFrame) + TEST_F(EditorCameraFixture, TrackingTransformIsFalseAfterTransformIsStoppedBeingTracked) { // Given const AZ::Transform referenceFrame = AZ::Transform::CreateFromQuaternionAndTranslation( AZ::Quaternion::CreateRotationX(AZ::DegToRad(90.0f)), AZ::Vector3(1.0f, 2.0f, 3.0f)); AtomToolsFramework::ModularViewportCameraControllerRequestBus::Event( - TestViewportId, &AtomToolsFramework::ModularViewportCameraControllerRequestBus::Events::SetReferenceFrame, referenceFrame); - - const AZ::Transform nextTransform = AZ::Transform::CreateTranslation(AZ::Vector3(10.0f, 20.0f, 30.0f)); - m_cameraViewportContextView->SetCameraTransform(nextTransform); - - // When - AZ::Transform currentReferenceFrame = AZ::Transform::CreateTranslation(AZ::Vector3(1.0f, 2.0f, 3.0f)); - AtomToolsFramework::ModularViewportCameraControllerRequestBus::EventResult( - currentReferenceFrame, TestViewportId, - &AtomToolsFramework::ModularViewportCameraControllerRequestBus::Events::GetReferenceFrame); - - // Then - EXPECT_THAT(currentReferenceFrame, IsClose(nextTransform)); - } - - TEST_F(EditorCameraFixture, ReferenceFrameReturnedToIdentityAfterClear) - { - // Given - const AZ::Transform referenceFrame = AZ::Transform::CreateFromQuaternionAndTranslation( - AZ::Quaternion::CreateRotationX(AZ::DegToRad(90.0f)), AZ::Vector3(1.0f, 2.0f, 3.0f)); - AtomToolsFramework::ModularViewportCameraControllerRequestBus::Event( - TestViewportId, &AtomToolsFramework::ModularViewportCameraControllerRequestBus::Events::SetReferenceFrame, referenceFrame); + TestViewportId, &AtomToolsFramework::ModularViewportCameraControllerRequestBus::Events::StartTrackingTransform, referenceFrame); // When AtomToolsFramework::ModularViewportCameraControllerRequestBus::Event( - TestViewportId, &AtomToolsFramework::ModularViewportCameraControllerRequestBus::Events::ClearReferenceFrame); - - AZ::Transform currentReferenceFrame = AZ::Transform::CreateTranslation(AZ::Vector3(1.0f, 2.0f, 3.0f)); - AtomToolsFramework::ModularViewportCameraControllerRequestBus::EventResult( - currentReferenceFrame, TestViewportId, - &AtomToolsFramework::ModularViewportCameraControllerRequestBus::Events::GetReferenceFrame); + TestViewportId, &AtomToolsFramework::ModularViewportCameraControllerRequestBus::Events::StopTrackingTransform); // Then - EXPECT_THAT(currentReferenceFrame, IsClose(AZ::Transform::CreateIdentity())); + bool trackingTransform = false; + AtomToolsFramework::ModularViewportCameraControllerRequestBus::EventResult( + trackingTransform, TestViewportId, &AtomToolsFramework::ModularViewportCameraControllerRequestBus::Events::IsTrackingTransform); + + EXPECT_THAT(trackingTransform, ::testing::IsFalse()); } TEST_F(EditorCameraFixture, InterpolateToTransform) @@ -169,8 +148,10 @@ namespace UnitTest transformToInterpolateTo); // simulate interpolation - m_controllerList->UpdateViewport({ TestViewportId, AzFramework::FloatSeconds(0.5f), AZ::ScriptTimePoint() }); - m_controllerList->UpdateViewport({ TestViewportId, AzFramework::FloatSeconds(0.5f), AZ::ScriptTimePoint() }); + m_controllerList->UpdateViewport( + { TestViewportId, AzFramework::FloatSeconds(HalfInterpolateToTransformDuration), AZ::ScriptTimePoint() }); + m_controllerList->UpdateViewport( + { TestViewportId, AzFramework::FloatSeconds(HalfInterpolateToTransformDuration), AZ::ScriptTimePoint() }); const auto finalTransform = m_cameraViewportContextView->GetCameraTransform(); @@ -184,7 +165,7 @@ namespace UnitTest const AZ::Transform referenceFrame = AZ::Transform::CreateFromQuaternionAndTranslation( AZ::Quaternion::CreateRotationX(AZ::DegToRad(90.0f)), AZ::Vector3(1.0f, 2.0f, 3.0f)); AtomToolsFramework::ModularViewportCameraControllerRequestBus::Event( - TestViewportId, &AtomToolsFramework::ModularViewportCameraControllerRequestBus::Events::SetReferenceFrame, referenceFrame); + TestViewportId, &AtomToolsFramework::ModularViewportCameraControllerRequestBus::Events::StartTrackingTransform, referenceFrame); AZ::Transform transformToInterpolateTo = AZ::Transform::CreateFromQuaternionAndTranslation( AZ::Quaternion::CreateRotationZ(AZ::DegToRad(90.0f)), AZ::Vector3(20.0f, 40.0f, 60.0f)); @@ -195,18 +176,85 @@ namespace UnitTest transformToInterpolateTo); // simulate interpolation - m_controllerList->UpdateViewport({ TestViewportId, AzFramework::FloatSeconds(0.5f), AZ::ScriptTimePoint() }); - m_controllerList->UpdateViewport({ TestViewportId, AzFramework::FloatSeconds(0.5f), AZ::ScriptTimePoint() }); - - AZ::Transform currentReferenceFrame = AZ::Transform::CreateTranslation(AZ::Vector3(1.0f, 2.0f, 3.0f)); - AtomToolsFramework::ModularViewportCameraControllerRequestBus::EventResult( - currentReferenceFrame, TestViewportId, - &AtomToolsFramework::ModularViewportCameraControllerRequestBus::Events::GetReferenceFrame); + m_controllerList->UpdateViewport( + { TestViewportId, AzFramework::FloatSeconds(HalfInterpolateToTransformDuration), AZ::ScriptTimePoint() }); + m_controllerList->UpdateViewport( + { TestViewportId, AzFramework::FloatSeconds(HalfInterpolateToTransformDuration), AZ::ScriptTimePoint() }); const auto finalTransform = m_cameraViewportContextView->GetCameraTransform(); // Then EXPECT_THAT(finalTransform, IsClose(transformToInterpolateTo)); - EXPECT_THAT(currentReferenceFrame, IsClose(AZ::Transform::CreateIdentity())); + } + + TEST_F(EditorCameraFixture, BeginningCameraInterpolationReturnsTrue) + { + // Given/When + bool interpolationBegan = false; + AtomToolsFramework::ModularViewportCameraControllerRequestBus::EventResult( + interpolationBegan, TestViewportId, + &AtomToolsFramework::ModularViewportCameraControllerRequestBus::Events::InterpolateToTransform, + AZ::Transform::CreateTranslation(AZ::Vector3(10.0f, 10.0f, 10.0f))); + + // Then + EXPECT_THAT(interpolationBegan, ::testing::IsTrue()); + } + + TEST_F(EditorCameraFixture, CameraInterpolationDoesNotBeginDuringAnExistingInterpolation) + { + // Given/When + bool initialInterpolationBegan = false; + AtomToolsFramework::ModularViewportCameraControllerRequestBus::EventResult( + initialInterpolationBegan, TestViewportId, + &AtomToolsFramework::ModularViewportCameraControllerRequestBus::Events::InterpolateToTransform, + AZ::Transform::CreateTranslation(AZ::Vector3(10.0f, 10.0f, 10.0f))); + + m_controllerList->UpdateViewport( + { TestViewportId, AzFramework::FloatSeconds(HalfInterpolateToTransformDuration), AZ::ScriptTimePoint() }); + + bool nextInterpolationBegan = true; + AtomToolsFramework::ModularViewportCameraControllerRequestBus::EventResult( + nextInterpolationBegan, TestViewportId, + &AtomToolsFramework::ModularViewportCameraControllerRequestBus::Events::InterpolateToTransform, + AZ::Transform::CreateTranslation(AZ::Vector3(10.0f, 10.0f, 10.0f))); + + bool interpolating = false; + AtomToolsFramework::ModularViewportCameraControllerRequestBus::EventResult( + interpolating, TestViewportId, &AtomToolsFramework::ModularViewportCameraControllerRequestBus::Events::IsInterpolating); + + // Then + EXPECT_THAT(initialInterpolationBegan, ::testing::IsTrue()); + EXPECT_THAT(nextInterpolationBegan, ::testing::IsFalse()); + EXPECT_THAT(interpolating, ::testing::IsTrue()); + } + + TEST_F(EditorCameraFixture, CameraInterpolationCanBeginAfterAnInterpolationCompletes) + { + // Given/When + bool initialInterpolationBegan = false; + AtomToolsFramework::ModularViewportCameraControllerRequestBus::EventResult( + initialInterpolationBegan, TestViewportId, + &AtomToolsFramework::ModularViewportCameraControllerRequestBus::Events::InterpolateToTransform, + AZ::Transform::CreateTranslation(AZ::Vector3(10.0f, 10.0f, 10.0f))); + + m_controllerList->UpdateViewport( + { TestViewportId, + AzFramework::FloatSeconds(AtomToolsFramework::ModularViewportCameraControllerRequests::InterpolateToTransformDuration + 0.5f), + AZ::ScriptTimePoint() }); + + bool interpolating = true; + AtomToolsFramework::ModularViewportCameraControllerRequestBus::EventResult( + interpolating, TestViewportId, &AtomToolsFramework::ModularViewportCameraControllerRequestBus::Events::IsInterpolating); + + bool nextInterpolationBegan = false; + AtomToolsFramework::ModularViewportCameraControllerRequestBus::EventResult( + nextInterpolationBegan, TestViewportId, + &AtomToolsFramework::ModularViewportCameraControllerRequestBus::Events::InterpolateToTransform, + AZ::Transform::CreateTranslation(AZ::Vector3(10.0f, 10.0f, 10.0f))); + + // Then + EXPECT_THAT(initialInterpolationBegan, ::testing::IsTrue()); + EXPECT_THAT(interpolating, ::testing::IsFalse()); + EXPECT_THAT(nextInterpolationBegan, ::testing::IsTrue()); } } // namespace UnitTest diff --git a/Code/Editor/Lib/Tests/test_ModularViewportCameraController.cpp b/Code/Editor/Lib/Tests/test_ModularViewportCameraController.cpp index 275df11784..656440f16e 100644 --- a/Code/Editor/Lib/Tests/test_ModularViewportCameraController.cpp +++ b/Code/Editor/Lib/Tests/test_ModularViewportCameraController.cpp @@ -74,7 +74,7 @@ namespace UnitTest class ModularViewportCameraControllerFixture : public AllocatorsTestFixture { public: - static const AzFramework::ViewportId TestViewportId; + static inline constexpr AzFramework::ViewportId TestViewportId = 1234; void SetUp() override { @@ -146,6 +146,17 @@ namespace UnitTest controller->SetCameraPropsBuilderCallback( [](AzFramework::CameraProps& cameraProps) { + // note: rotateSmoothness is also used for roll (not related to camera input directly) + cameraProps.m_rotateSmoothnessFn = [] + { + return 5.0f; + }; + + cameraProps.m_translateSmoothnessFn = [] + { + return 5.0f; + }; + cameraProps.m_rotateSmoothingEnabledFn = [] { return false; @@ -209,8 +220,6 @@ namespace UnitTest AZStd::unique_ptr m_editorModularViewportCameraComposer; }; - const AzFramework::ViewportId ModularViewportCameraControllerFixture::TestViewportId = AzFramework::ViewportId(0); - TEST_F(ModularViewportCameraControllerFixture, MouseMovementDoesNotAccumulateExcessiveDriftInModularViewportCameraWithVaryingDeltaTime) { SandboxEditor::SetCameraCaptureCursorForLook(false); @@ -380,6 +389,7 @@ namespace UnitTest m_controllerList->UpdateViewport({ TestViewportId, AzFramework::FloatSeconds(deltaTime), AZ::ScriptTimePoint() }); QTest::mouseRelease(m_rootWidget.get(), Qt::MouseButton::RightButton, Qt::NoModifier, start + mouseDelta); + m_controllerList->UpdateViewport({ TestViewportId, AzFramework::FloatSeconds(deltaTime), AZ::ScriptTimePoint() }); // update the position of the widget const auto offset = QPoint(500, 500); diff --git a/Code/Editor/Lib/Tests/test_ViewportManipulatorController.cpp b/Code/Editor/Lib/Tests/test_ViewportManipulatorController.cpp index 63e59ea940..81dcae9129 100644 --- a/Code/Editor/Lib/Tests/test_ViewportManipulatorController.cpp +++ b/Code/Editor/Lib/Tests/test_ViewportManipulatorController.cpp @@ -12,6 +12,7 @@ #include #include #include +#include namespace UnitTest { @@ -77,14 +78,15 @@ namespace UnitTest class ViewportManipulatorControllerFixture : public AllocatorsTestFixture { public: - static const AzFramework::ViewportId TestViewportId; + static inline constexpr AzFramework::ViewportId TestViewportId = 1234; + static inline const QSize WidgetSize = QSize(1920, 1080); void SetUp() override { AllocatorsTestFixture::SetUp(); m_rootWidget = AZStd::make_unique(); - m_rootWidget->setFixedSize(QSize(100, 100)); + m_rootWidget->setFixedSize(WidgetSize); QApplication::setActiveWindow(m_rootWidget.get()); m_controllerList = AZStd::make_shared(); @@ -111,8 +113,6 @@ namespace UnitTest AZStd::unique_ptr m_inputChannelMapper; }; - const AzFramework::ViewportId ViewportManipulatorControllerFixture::TestViewportId = AzFramework::ViewportId(0); - TEST_F(ViewportManipulatorControllerFixture, AnEventIsNotPropagatedToTheViewportWhenAManipulatorHandlesItFirst) { // forward input events to our controller list @@ -227,4 +227,74 @@ namespace UnitTest // the key was released (cleared) EXPECT_TRUE(endedEvent); } + + TEST_F(ViewportManipulatorControllerFixture, DoubleClickIsNotRegisteredIfMouseDeltaHasMovedMoreThanDeadzoneInClickInterval) + { + AzFramework::NativeWindowHandle nativeWindowHandle = nullptr; + + // forward input events to our controller list + QObject::connect( + m_inputChannelMapper.get(), &AzToolsFramework::QtEventToAzInputMapper::InputChannelUpdated, m_rootWidget.get(), + [this, nativeWindowHandle](const AzFramework::InputChannel* inputChannel, [[maybe_unused]] QEvent* event) + { + m_controllerList->HandleInputChannelEvent( + AzFramework::ViewportControllerInputEvent{ TestViewportId, nativeWindowHandle, *inputChannel }); + }); + + ::testing::NiceMock mockWindowRequests; + mockWindowRequests.Connect(nativeWindowHandle); + + using ::testing::Return; + // note: WindowRequests is used internally by ViewportManipulatorController + ON_CALL(mockWindowRequests, GetClientAreaSize()) + .WillByDefault(Return(AzFramework::WindowSize(WidgetSize.width(), WidgetSize.height()))); + + EditorInteractionViewportSelectionFake editorInteractionViewportFake; + editorInteractionViewportFake.m_internalHandleMouseManipulatorInteraction = [](const MouseInteractionEvent&) + { + // report the event was not handled (manipulator was not interacted with) + return false; + }; + + bool doubleClickDetected = false; + editorInteractionViewportFake.m_internalHandleMouseViewportInteraction = + [&doubleClickDetected](const MouseInteractionEvent& mouseInteractionEvent) + { + // ensure no double click event is detected with the given inputs below + if (mouseInteractionEvent.m_mouseEvent == AzToolsFramework::ViewportInteraction::MouseEvent::DoubleClick) + { + doubleClickDetected = true; + } + + return true; + }; + + editorInteractionViewportFake.Connect(); + + m_controllerList->Add(AZStd::make_shared()); + + // simulate a click, move, click + MouseMove(m_rootWidget.get(), QPoint(0, 0), QPoint(10, 10)); + MousePressAndMove(m_rootWidget.get(), QPoint(10, 10), QPoint(0, 0), Qt::MouseButton::LeftButton); + QTest::mouseRelease(m_rootWidget.get(), Qt::MouseButton::LeftButton, Qt::KeyboardModifier::NoModifier, QPoint(10, 10)); + MouseMove(m_rootWidget.get(), QPoint(10, 10), QPoint(20, 20)); + MousePressAndMove(m_rootWidget.get(), QPoint(20, 20), QPoint(0, 0), Qt::MouseButton::LeftButton); + QTest::mouseRelease(m_rootWidget.get(), Qt::MouseButton::LeftButton, Qt::KeyboardModifier::NoModifier, QPoint(20, 20)); + + // ensure no double click was detected + EXPECT_FALSE(doubleClickDetected); + + // simulate double click (sanity check it still is detected correctly with no movement) + MouseMove(m_rootWidget.get(), QPoint(0, 0), QPoint(10, 10)); + MousePressAndMove(m_rootWidget.get(), QPoint(10, 10), QPoint(0, 0), Qt::MouseButton::LeftButton); + QTest::mouseRelease(m_rootWidget.get(), Qt::MouseButton::LeftButton, Qt::KeyboardModifier::NoModifier, QPoint(10, 10)); + MousePressAndMove(m_rootWidget.get(), QPoint(10, 10), QPoint(0, 0), Qt::MouseButton::LeftButton); + QTest::mouseRelease(m_rootWidget.get(), Qt::MouseButton::LeftButton, Qt::KeyboardModifier::NoModifier, QPoint(10, 10)); + + // ensure a double click was detected + EXPECT_TRUE(doubleClickDetected); + + mockWindowRequests.Disconnect(); + editorInteractionViewportFake.Disconnect(); + } } // namespace UnitTest diff --git a/Code/Editor/MainWindow.cpp b/Code/Editor/MainWindow.cpp index 14ba902b15..f6744ec2d2 100644 --- a/Code/Editor/MainWindow.cpp +++ b/Code/Editor/MainWindow.cpp @@ -519,7 +519,7 @@ MainWindow* MainWindow::instance() void MainWindow::closeEvent(QCloseEvent* event) { - gSettings.Save(); + gSettings.Save(true); AzFramework::SystemCursorState currentCursorState; bool isInGameMode = false; @@ -708,14 +708,10 @@ void MainWindow::InitActions() .SetShortcut(QKeySequence::Undo) .SetReserved() .SetStatusTip(tr("Undo last operation")) - //.SetMenu(new QMenu("FIXME")) - .SetApplyHoverEffect() .RegisterUpdateCallback(cryEdit, &CCryEditApp::OnUpdateUndo); am->AddAction(ID_REDO, tr("&Redo")) .SetShortcut(AzQtComponents::RedoKeySequence) .SetReserved() - //.SetMenu(new QMenu("FIXME")) - .SetApplyHoverEffect() .SetStatusTip(tr("Redo last undo operation")) .RegisterUpdateCallback(cryEdit, &CCryEditApp::OnUpdateRedo); @@ -731,7 +727,6 @@ void MainWindow::InitActions() // Modify actions am->AddAction(AzToolsFramework::EditModeMove, tr("Move")) .SetIcon(Style::icon("Move")) - .SetApplyHoverEffect() .SetShortcut(tr("1")) .SetToolTip(tr("Move (1)")) .SetCheckable(true) @@ -757,7 +752,6 @@ void MainWindow::InitActions() }); am->AddAction(AzToolsFramework::EditModeRotate, tr("Rotate")) .SetIcon(Style::icon("Translate")) - .SetApplyHoverEffect() .SetShortcut(tr("2")) .SetToolTip(tr("Rotate (2)")) .SetCheckable(true) @@ -783,7 +777,6 @@ void MainWindow::InitActions() }); am->AddAction(AzToolsFramework::EditModeScale, tr("Scale")) .SetIcon(Style::icon("Scale")) - .SetApplyHoverEffect() .SetShortcut(tr("3")) .SetToolTip(tr("Scale (3)")) .SetCheckable(true) @@ -808,7 +801,6 @@ void MainWindow::InitActions() am->AddAction(AzToolsFramework::SnapToGrid, tr("Snap to grid")) .SetIcon(Style::icon("Grid")) - .SetApplyHoverEffect() .SetShortcut(tr("G")) .SetToolTip(tr("Snap to grid (G)")) .SetStatusTip(tr("Toggles snap to grid")) @@ -821,7 +813,6 @@ void MainWindow::InitActions() am->AddAction(AzToolsFramework::SnapAngle, tr("Snap angle")) .SetIcon(Style::icon("Angle")) - .SetApplyHoverEffect() .SetStatusTip(tr("Snap angle")) .SetCheckable(true) .RegisterUpdateCallback([](QAction* action) { @@ -961,7 +952,6 @@ void MainWindow::InitActions() .SetShortcut(tr("Ctrl+P")) .SetToolTip(tr("Simulate (Ctrl+P)")) .SetStatusTip(tr("Enable processing of Physics and AI.")) - .SetApplyHoverEffect() .SetCheckable(true) .RegisterUpdateCallback(cryEdit, &CCryEditApp::OnSwitchPhysicsUpdate); am->AddAction(ID_GAME_SYNCPLAYER, tr("Move Player and Camera Separately")).SetCheckable(true) @@ -1051,8 +1041,7 @@ void MainWindow::InitActions() // Editors Toolbar actions am->AddAction(ID_OPEN_ASSET_BROWSER, tr("Asset browser")) - .SetToolTip(tr("Open Asset Browser")) - .SetApplyHoverEffect(); + .SetToolTip(tr("Open Asset Browser")); AZ::EBusReduceResult> emfxEnabled(false); using AnimationRequestBus = AzToolsFramework::EditorAnimationSystemRequestsBus; @@ -1062,8 +1051,7 @@ void MainWindow::InitActions() { QAction* action = am->AddAction(ID_OPEN_EMOTIONFX_EDITOR, tr("Animation Editor")) .SetToolTip(tr("Open Animation Editor")) - .SetIcon(QIcon(":/EMotionFX/EMFX_icon_32x32.png")) - .SetApplyHoverEffect(); + .SetIcon(QIcon(":/EMotionFX/EMFX_icon_32x32.png")); QObject::connect(action, &QAction::triggered, this, []() { QtViewPaneManager::instance()->OpenPane(LyViewPane::AnimationEditor); }); @@ -1071,12 +1059,10 @@ void MainWindow::InitActions() am->AddAction(ID_OPEN_AUDIO_CONTROLS_BROWSER, tr("Audio Controls Editor")) .SetToolTip(tr("Open Audio Controls Editor")) - .SetIcon(Style::icon("Audio")) - .SetApplyHoverEffect(); + .SetIcon(Style::icon("Audio")); am->AddAction(ID_OPEN_UICANVASEDITOR, tr(LyViewPane::UiEditor)) - .SetToolTip(tr("Open UI Editor")) - .SetApplyHoverEffect(); + .SetToolTip(tr("Open UI Editor")); // Edit Mode Toolbar Actions am->AddAction(IDC_SELECTION_MASK, tr("Selected Object Types")); @@ -1089,12 +1075,10 @@ void MainWindow::InitActions() // Object Toolbar Actions am->AddAction(ID_GOTO_SELECTED, tr("Go to selected object")) .SetIcon(Style::icon("select_object")) - .SetApplyHoverEffect() .Connect(&QAction::triggered, this, &MainWindow::OnGotoSelected); // Misc Toolbar Actions - am->AddAction(ID_OPEN_SUBSTANCE_EDITOR, tr("Open Substance Editor")) - .SetApplyHoverEffect(); + am->AddAction(ID_OPEN_SUBSTANCE_EDITOR, tr("Open Substance Editor")); } void MainWindow::InitToolActionHandlers() diff --git a/Code/Editor/Plugins/ComponentEntityEditorPlugin/SandboxIntegration.cpp b/Code/Editor/Plugins/ComponentEntityEditorPlugin/SandboxIntegration.cpp index 82d9f9ede2..64bd943d63 100644 --- a/Code/Editor/Plugins/ComponentEntityEditorPlugin/SandboxIntegration.cpp +++ b/Code/Editor/Plugins/ComponentEntityEditorPlugin/SandboxIntegration.cpp @@ -10,7 +10,6 @@ #include #include #include -#include #include #include #include @@ -57,6 +56,7 @@ #include #include #include +#include #include #include @@ -1394,13 +1394,13 @@ void SandboxIntegrationManager::ContextMenu_NewEntity() { AZ::Vector3 worldPosition = AZ::Vector3::CreateZero(); - CViewport* view = GetIEditor()->GetViewManager()->GetGameViewport(); // If we don't have a viewport active to aid in placement, the object // will be created at the origin. - if (view) + if (CViewport* view = GetIEditor()->GetViewManager()->GetGameViewport()) { - const QPoint viewPoint(static_cast(m_contextMenuViewPoint.GetX()), static_cast(m_contextMenuViewPoint.GetY())); - worldPosition = view->GetHitLocation(viewPoint); + worldPosition = AzToolsFramework::FindClosestPickIntersection( + view->GetViewportId(), AzFramework::ScreenPointFromVector2(m_contextMenuViewPoint), AzToolsFramework::EditorPickRayLength, + GetDefaultEntityPlacementDistance()); } CreateNewEntityAtPosition(worldPosition); @@ -1675,6 +1675,12 @@ void SandboxIntegrationManager::GoToEntitiesInViewports(const AzToolsFramework:: if (auto viewportContext = viewportContextManager->GetViewportContextById(viewIndex)) { const AZ::Transform cameraTransform = viewportContext->GetCameraTransform(); + // do not attempt to interpolate to where we currently are + if (cameraTransform.GetTranslation().IsClose(center)) + { + continue; + } + const AZ::Vector3 forward = (center - cameraTransform.GetTranslation()).GetNormalized(); // move camera 25% further back than required diff --git a/Code/Editor/Settings.cpp b/Code/Editor/Settings.cpp index 147ed0c0b8..acb48c3545 100644 --- a/Code/Editor/Settings.cpp +++ b/Code/Editor/Settings.cpp @@ -471,7 +471,7 @@ void SEditorSettings::LoadValue(const char* sSection, const char* sKey, ESystemC } ////////////////////////////////////////////////////////////////////////// -void SEditorSettings::Save() +void SEditorSettings::Save(bool isEditorClosing) { QString strStringPlaceholder; @@ -638,14 +638,16 @@ void SEditorSettings::Save() // --- Settings Registry values // Prefab System UI - AzFramework::ApplicationRequests::Bus::Broadcast( - &AzFramework::ApplicationRequests::SetPrefabSystemEnabled, prefabSystem); + AzFramework::ApplicationRequests::Bus::Broadcast(&AzFramework::ApplicationRequests::SetPrefabSystemEnabled, prefabSystem); AzToolsFramework::Prefab::PrefabLoaderInterface* prefabLoaderInterface = AZ::Interface::Get(); prefabLoaderInterface->SetSaveAllPrefabsPreference(levelSaveSettings.saveAllPrefabsPreference); - SaveSettingsRegistryFile(); + if (!isEditorClosing) + { + SaveSettingsRegistryFile(); + } } ////////////////////////////////////////////////////////////////////////// diff --git a/Code/Editor/Settings.h b/Code/Editor/Settings.h index f4a6dabde8..9276d9b715 100644 --- a/Code/Editor/Settings.h +++ b/Code/Editor/Settings.h @@ -267,7 +267,7 @@ struct SANDBOX_API SEditorSettings AZ_POP_DISABLE_DLL_EXPORT_BASECLASS_WARNING SEditorSettings(); ~SEditorSettings() = default; - void Save(); + void Save(bool isEditorClosing = false); void Load(); void LoadCloudSettings(); diff --git a/Code/Editor/Viewport.cpp b/Code/Editor/Viewport.cpp index 37c46f07dd..5a64982350 100644 --- a/Code/Editor/Viewport.cpp +++ b/Code/Editor/Viewport.cpp @@ -14,14 +14,19 @@ // Qt #include +// AzCore +#include + // AzQtComponents #include #include #include #include +#include // Editor +#include "Editor/Plugins/ComponentEntityEditorPlugin/SandboxIntegration.h" #include "ViewManager.h" #include "Include/ITransformManipulator.h" #include "Include/HitContext.h" @@ -32,22 +37,35 @@ #include "GameEngine.h" #include "Settings.h" - #ifdef LoadCursor #undef LoadCursor #endif +AZ_CVAR( + float, + ed_defaultEntityPlacementDistance, + 10.0f, + nullptr, + AZ::ConsoleFunctorFlags::Null, + "The default distance to place an entity from the camera if no intersection is found"); + +float GetDefaultEntityPlacementDistance() +{ + return ed_defaultEntityPlacementDistance; +} + ////////////////////////////////////////////////////////////////////// // Viewport drag and drop support ////////////////////////////////////////////////////////////////////// -void QtViewport::BuildDragDropContext(AzQtComponents::ViewportDragContext& context, const QPoint& pt) +void QtViewport::BuildDragDropContext( + AzQtComponents::ViewportDragContext& context, const AzFramework::ViewportId viewportId, const QPoint& point) { - context.m_hitLocation = AZ::Vector3::CreateZero(); - context.m_hitLocation = GetHitLocation(pt); + context.m_hitLocation = AzToolsFramework::FindClosestPickIntersection( + viewportId, AzToolsFramework::ViewportInteraction::ScreenPointFromQPoint(point), AzToolsFramework::EditorPickRayLength, + GetDefaultEntityPlacementDistance()); } - void QtViewport::dragEnterEvent(QDragEnterEvent* event) { if (!GetIEditor()->GetGameEngine()->IsLevelLoaded()) @@ -66,7 +84,7 @@ void QtViewport::dragEnterEvent(QDragEnterEvent* event) // new bus-based way of doing it (install a listener!) using namespace AzQtComponents; ViewportDragContext context; - BuildDragDropContext(context, event->pos()); + BuildDragDropContext(context, GetViewportId(), event->pos()); DragAndDropEventsBus::Event(DragAndDropContexts::EditorViewport, &DragAndDropEvents::DragEnter, event, context); } } @@ -89,7 +107,7 @@ void QtViewport::dragMoveEvent(QDragMoveEvent* event) // new bus-based way of doing it (install a listener!) using namespace AzQtComponents; ViewportDragContext context; - BuildDragDropContext(context, event->pos()); + BuildDragDropContext(context, GetViewportId(), event->pos()); DragAndDropEventsBus::Event(DragAndDropContexts::EditorViewport, &DragAndDropEvents::DragMove, event, context); } } @@ -112,7 +130,7 @@ void QtViewport::dropEvent(QDropEvent* event) { // new bus-based way of doing it (install a listener!) ViewportDragContext context; - BuildDragDropContext(context, event->pos()); + BuildDragDropContext(context, GetViewportId(), event->pos()); DragAndDropEventsBus::Event(DragAndDropContexts::EditorViewport, &DragAndDropEvents::Drop, event, context); } } @@ -340,13 +358,6 @@ void QtViewport::resizeEvent(QResizeEvent* event) Update(); } -////////////////////////////////////////////////////////////////////////// -void QtViewport::leaveEvent(QEvent* event) -{ - QWidget::leaveEvent(event); - MouseCallback(eMouseLeave, QPoint(), Qt::KeyboardModifiers(), Qt::MouseButtons()); -} - ////////////////////////////////////////////////////////////////////////// void QtViewport::paintEvent([[maybe_unused]] QPaintEvent* event) { @@ -581,63 +592,7 @@ void QtViewport::keyReleaseEvent(QKeyEvent* event) OnKeyUp(nativeKey, 1, event->nativeModifiers()); } -////////////////////////////////////////////////////////////////////////// -void QtViewport::OnLButtonDown(Qt::KeyboardModifiers modifiers, const QPoint& point) -{ - // Save the mouse down position - m_cMouseDownPos = point; - if (MouseCallback(eMouseLDown, point, modifiers)) - { - return; - } -} - -////////////////////////////////////////////////////////////////////////// -void QtViewport::OnLButtonUp(Qt::KeyboardModifiers modifiers, const QPoint& point) -{ - // Check Edit Tool. - MouseCallback(eMouseLUp, point, modifiers); -} -////////////////////////////////////////////////////////////////////////// -void QtViewport::OnRButtonDown(Qt::KeyboardModifiers modifiers, const QPoint& point) -{ - MouseCallback(eMouseRDown, point, modifiers); -} - -////////////////////////////////////////////////////////////////////////// -void QtViewport::OnRButtonUp(Qt::KeyboardModifiers modifiers, const QPoint& point) -{ - MouseCallback(eMouseRUp, point, modifiers); -} - -////////////////////////////////////////////////////////////////////////// -void QtViewport::OnMButtonDown(Qt::KeyboardModifiers modifiers, const QPoint& point) -{ - // Check Edit Tool. - MouseCallback(eMouseMDown, point, modifiers); -} - -////////////////////////////////////////////////////////////////////////// -void QtViewport::OnMButtonUp(Qt::KeyboardModifiers modifiers, const QPoint& point) -{ - // Move the viewer to the mouse location. - // Check Edit Tool. - MouseCallback(eMouseMUp, point, modifiers); -} - -////////////////////////////////////////////////////////////////////////// -void QtViewport::OnMButtonDblClk(Qt::KeyboardModifiers modifiers, const QPoint& point) -{ - MouseCallback(eMouseMDblClick, point, modifiers); -} - - -////////////////////////////////////////////////////////////////////////// -void QtViewport::OnMouseMove(Qt::KeyboardModifiers modifiers, Qt::MouseButtons buttons, const QPoint& point) -{ - MouseCallback(eMouseMove, point, modifiers, buttons); -} ////////////////////////////////////////////////////////////////////////// void QtViewport::OnSetCursor() @@ -696,44 +651,6 @@ void QtViewport::OnDragSelectRectangle(const QRect& rect, bool bNormalizeRect) GetIEditor()->SetStatusText(szNewStatusText); } -////////////////////////////////////////////////////////////////////////// -void QtViewport::OnLButtonDblClk(Qt::KeyboardModifiers modifiers, const QPoint& point) -{ - if (GetIEditor()->IsInGameMode()) - { - // Ignore double clicks while in game. - return; - } - - MouseCallback(eMouseLDblClick, point, modifiers); -} - -////////////////////////////////////////////////////////////////////////// -void QtViewport::OnRButtonDblClk(Qt::KeyboardModifiers modifiers, const QPoint& point) -{ - MouseCallback(eMouseRDblClick, point, modifiers); -} - -////////////////////////////////////////////////////////////////////////// -void QtViewport::OnKeyDown([[maybe_unused]] UINT nChar, [[maybe_unused]] UINT nRepCnt, [[maybe_unused]] UINT nFlags) -{ - if (GetIEditor()->IsInGameMode()) - { - // Ignore key downs while in game. - return; - } -} - -////////////////////////////////////////////////////////////////////////// -void QtViewport::OnKeyUp([[maybe_unused]] UINT nChar, [[maybe_unused]] UINT nRepCnt, [[maybe_unused]] UINT nFlags) -{ - if (GetIEditor()->IsInGameMode()) - { - // Ignore key downs while in game. - return; - } -} - ////////////////////////////////////////////////////////////////////////// void QtViewport::SetCurrentCursor(const QCursor& hCursor, const QString& cursorString) { @@ -1119,29 +1036,6 @@ bool QtViewport::HitTest(const QPoint& point, HitContext& hitInfo) return false; } -AZ::Vector3 QtViewport::GetHitLocation(const QPoint& point) -{ - Vec3 pos = Vec3(ZERO); - HitContext hit; - if (HitTest(point, hit)) - { - pos = hit.raySrc + hit.rayDir * hit.dist; - pos = SnapToGrid(pos); - } - else - { - bool hitTerrain; - pos = ViewToWorld(point, &hitTerrain); - if (hitTerrain) - { - pos.z = GetIEditor()->GetTerrainElevation(pos.x, pos.y); - } - pos = SnapToGrid(pos); - } - - return AZ::Vector3(pos.x, pos.y, pos.z); -} - ////////////////////////////////////////////////////////////////////////// void QtViewport::SetZoomFactor(float fZoomFactor) { @@ -1315,84 +1209,6 @@ bool QtViewport::GetAdvancedSelectModeFlag() return m_bAdvancedSelectMode; } -////////////////////////////////////////////////////////////////////////// -bool QtViewport::MouseCallback(EMouseEvent event, const QPoint& point, Qt::KeyboardModifiers modifiers, Qt::MouseButtons buttons) -{ - AZ_PROFILE_FUNCTION(Editor); - - // Ignore any mouse events in game mode. - if (GetIEditor()->IsInGameMode()) - { - return true; - } - - // We must ignore mouse events when we are in the middle of an assert. - // Reason: If we have an assert called from an engine module under the editor, if we call this function, - // it may call the engine again and cause a deadlock. - // Concrete example: CryPhysics called from Trackview causing an assert, and moving the cursor over the viewport - // would cause the editor to freeze as it calls CryPhysics again for a raycast while it didn't release the lock. - if (gEnv->pSystem->IsAssertDialogVisible()) - { - return true; - } - - ////////////////////////////////////////////////////////////////////////// - // Hit test gizmo objects. - ////////////////////////////////////////////////////////////////////////// - bool bAltClick = (modifiers & Qt::AltModifier); - bool bCtrlClick = (modifiers & Qt::ControlModifier); - bool bShiftClick = (modifiers & Qt::ShiftModifier); - - int flags = (bCtrlClick ? MK_CONTROL : 0) | - (bShiftClick ? MK_SHIFT : 0) | - ((buttons& Qt::LeftButton) ? MK_LBUTTON : 0) | - ((buttons& Qt::MiddleButton) ? MK_MBUTTON : 0) | - ((buttons& Qt::RightButton) ? MK_RBUTTON : 0); - - switch (event) - { - case eMouseMove: - - if (m_nLastUpdateFrame == m_nLastMouseMoveFrame) - { - // If mouse move event generated in the same frame, ignore it. - return false; - } - m_nLastMouseMoveFrame = m_nLastUpdateFrame; - - // Skip the marker position update if anything is selected, since it is only used - // by the info bar which doesn't show the marker when there is an active selection. - // This helps a performance issue when calling ViewToWorld (which calls RayWorldIntersection) - // on every mouse movement becomes very expensive in scenes with large amounts of entities. - CSelectionGroup* selection = GetIEditor()->GetSelection(); - if (!(buttons & Qt::RightButton) /* && m_nLastUpdateFrame != m_nLastMouseMoveFrame*/ && (selection && selection->IsEmpty())) - { - //m_nLastMouseMoveFrame = m_nLastUpdateFrame; - Vec3 pos = ViewToWorld(point); - GetIEditor()->SetMarkerPosition(pos); - } - break; - } - - QPoint tempPoint(point.x(), point.y()); - - ////////////////////////////////////////////////////////////////////////// - // Handle viewport manipulators. - ////////////////////////////////////////////////////////////////////////// - if (!bAltClick) - { - ITransformManipulator* pManipulator = GetIEditor()->GetTransformManipulator(); - if (pManipulator) - { - if (pManipulator->MouseCallback(this, event, tempPoint, flags)) - { - return true; - } - } - } - - return false; -} ////////////////////////////////////////////////////////////////////////// void QtViewport::ProcessRenderLisneters(DisplayContext& rstDisplayContext) { diff --git a/Code/Editor/Viewport.h b/Code/Editor/Viewport.h index 7f8ccc4c4f..bf44b914aa 100644 --- a/Code/Editor/Viewport.h +++ b/Code/Editor/Viewport.h @@ -6,13 +6,12 @@ * */ - // Description : interface for the CViewport class. - #pragma once #if !defined(Q_MOC_RUN) +#include #include #include #include @@ -88,6 +87,9 @@ enum EStdCursor STD_CURSOR_LAST, }; +//! The default distance an entity is placed from the camera if there is no intersection +SANDBOX_API float GetDefaultEntityPlacementDistance(); + AZ_PUSH_DISABLE_DLL_EXPORT_BASECLASS_WARNING class SANDBOX_API CViewport : public IDisplayViewport @@ -201,7 +203,6 @@ public: //! Performs hit testing of 2d point in view to find which object hit. virtual bool HitTest(const QPoint& point, HitContext& hitInfo) = 0; - virtual AZ::Vector3 GetHitLocation(const QPoint& point) = 0; virtual void MakeConstructionPlane(int axis) = 0; @@ -432,7 +433,6 @@ public: //! Performs hit testing of 2d point in view to find which object hit. bool HitTest(const QPoint& point, HitContext& hitInfo) override; - AZ::Vector3 GetHitLocation(const QPoint& point) override; //! Do 2D hit testing of line in world space. // pToCameraDistance is an optional output parameter in which distance from the camera to the line is returned. @@ -522,9 +522,6 @@ protected: void setRenderOverlayVisible(bool); bool isRenderOverlayVisible() const; - // called to process mouse callback inside the viewport. - virtual bool MouseCallback(EMouseEvent event, const QPoint& point, Qt::KeyboardModifiers modifiers, Qt::MouseButtons buttons = Qt::NoButton); - void ProcessRenderLisneters(DisplayContext& rstDisplayContext); void mousePressEvent(QMouseEvent* event) override; @@ -535,29 +532,29 @@ protected: void keyPressEvent(QKeyEvent* event) override; void keyReleaseEvent(QKeyEvent* event) override; void resizeEvent(QResizeEvent* event) override; - void leaveEvent(QEvent* event) override; - void paintEvent(QPaintEvent* event) override; - virtual void OnMouseMove(Qt::KeyboardModifiers modifiers, Qt::MouseButtons buttons, const QPoint& point); - virtual void OnMouseWheel(Qt::KeyboardModifiers modifiers, short zDelta, const QPoint& pt); - virtual void OnLButtonDown(Qt::KeyboardModifiers modifiers, const QPoint& point); - virtual void OnLButtonUp(Qt::KeyboardModifiers modifiers, const QPoint& point); - virtual void OnRButtonDown(Qt::KeyboardModifiers modifiers, const QPoint& point); - virtual void OnRButtonUp(Qt::KeyboardModifiers modifiers, const QPoint& point); - virtual void OnMButtonDblClk(Qt::KeyboardModifiers modifiers, const QPoint& point); - virtual void OnMButtonDown(Qt::KeyboardModifiers modifiers, const QPoint& point); - virtual void OnMButtonUp(Qt::KeyboardModifiers modifiers, const QPoint& point); - virtual void OnLButtonDblClk(Qt::KeyboardModifiers modifiers, const QPoint& point); - virtual void OnRButtonDblClk(Qt::KeyboardModifiers modifiers, const QPoint& point); - virtual void OnKeyDown(UINT nChar, UINT nRepCnt, UINT nFlags); - virtual void OnKeyUp(UINT nChar, UINT nRepCnt, UINT nFlags); + virtual void OnMouseMove(Qt::KeyboardModifiers, Qt::MouseButtons, const QPoint&) {} + virtual void OnMouseWheel(Qt::KeyboardModifiers, short zDelta, const QPoint&); + virtual void OnLButtonDown(Qt::KeyboardModifiers, const QPoint&) {} + virtual void OnLButtonUp(Qt::KeyboardModifiers, const QPoint&) {} + virtual void OnRButtonDown(Qt::KeyboardModifiers, const QPoint&) {} + virtual void OnRButtonUp(Qt::KeyboardModifiers, const QPoint&) {} + virtual void OnMButtonDblClk(Qt::KeyboardModifiers, const QPoint&) {} + virtual void OnMButtonDown(Qt::KeyboardModifiers, const QPoint&) {} + virtual void OnMButtonUp(Qt::KeyboardModifiers, const QPoint&) {} + virtual void OnLButtonDblClk(Qt::KeyboardModifiers, const QPoint&) {} + virtual void OnRButtonDblClk(Qt::KeyboardModifiers, const QPoint&) {} + virtual void OnKeyDown([[maybe_unused]] UINT nChar, [[maybe_unused]] UINT nRepCnt, [[maybe_unused]] UINT nFlags) {} + virtual void OnKeyUp([[maybe_unused]] UINT nChar, [[maybe_unused]] UINT nRepCnt, [[maybe_unused]] UINT nFlags) {} #if defined(AZ_PLATFORM_WINDOWS) void OnRawInput(UINT wParam, HRAWINPUT lParam); #endif void OnSetCursor(); - virtual void BuildDragDropContext(AzQtComponents::ViewportDragContext& context, const QPoint& pt); + virtual void BuildDragDropContext( + AzQtComponents::ViewportDragContext& context, AzFramework::ViewportId viewportId, const QPoint& point); + void dragEnterEvent(QDragEnterEvent* event) override; void dragMoveEvent(QDragMoveEvent* event) override; void dragLeaveEvent(QDragLeaveEvent* event) override; diff --git a/Code/Editor/ViewportManipulatorController.cpp b/Code/Editor/ViewportManipulatorController.cpp index 1766945541..e46328eb65 100644 --- a/Code/Editor/ViewportManipulatorController.cpp +++ b/Code/Editor/ViewportManipulatorController.cpp @@ -8,13 +8,15 @@ #include "ViewportManipulatorController.h" +#include +#include +#include +#include +#include +#include #include #include -#include -#include -#include -#include -#include +#include #include @@ -87,8 +89,14 @@ namespace SandboxEditor } using InteractionBus = AzToolsFramework::EditorInteractionSystemViewportSelectionRequestBus; - using namespace AzToolsFramework::ViewportInteraction; using AzFramework::InputChannel; + using AzToolsFramework::ViewportInteraction::KeyboardModifier; + using AzToolsFramework::ViewportInteraction::MouseButton; + using AzToolsFramework::ViewportInteraction::MouseEvent; + using AzToolsFramework::ViewportInteraction::MouseInteraction; + using AzToolsFramework::ViewportInteraction::MouseInteractionEvent; + using AzToolsFramework::ViewportInteraction::ProjectedViewportRay; + using AzToolsFramework::ViewportInteraction::ViewportInteractionRequestBus; bool interactionHandled = false; float wheelDelta = 0.0f; @@ -117,16 +125,13 @@ namespace SandboxEditor aznumeric_cast(position->m_normalizedPosition.GetX() * windowSize.m_width), aznumeric_cast(position->m_normalizedPosition.GetY() * windowSize.m_height)); - m_mouseInteraction.m_mousePick.m_screenCoordinates = screenPoint; - AZStd::optional ray; + ProjectedViewportRay ray{}; ViewportInteractionRequestBus::EventResult( ray, GetViewportId(), &ViewportInteractionRequestBus::Events::ViewportScreenToWorldRay, screenPoint); - if (ray.has_value()) - { - m_mouseInteraction.m_mousePick.m_rayOrigin = ray.value().origin; - m_mouseInteraction.m_mousePick.m_rayDirection = ray.value().direction; - } + m_mouseInteraction.m_mousePick.m_rayOrigin = ray.origin; + m_mouseInteraction.m_mousePick.m_rayDirection = ray.direction; + m_mouseInteraction.m_mousePick.m_screenCoordinates = screenPoint; } eventType = MouseEvent::Move; @@ -152,7 +157,7 @@ namespace SandboxEditor // Only insert the double click timing once we're done processing events, to avoid a false IsDoubleClick positive if (finishedProcessingEvents) { - m_pendingDoubleClicks[mouseButton] = m_curTime; + m_pendingDoubleClicks[mouseButton] = { m_currentTime, m_mouseInteraction.m_mousePick.m_screenCoordinates }; } eventType = MouseEvent::Down; } @@ -160,8 +165,8 @@ namespace SandboxEditor else if (state == InputChannel::State::Ended) { // If we've actually logged a mouse down event, forward a mouse up event. - // This prevents corner cases like the context menu thinking it should be opened even though no one clicked in this viewport, - // due to RenderViewportWidget ensuring all controllers get InputChannel::State::Ended events. + // This prevents corner cases like the context menu thinking it should be opened even though no one clicked in this + // viewport, due to RenderViewportWidget ensuring all controllers get InputChannel::State::Ended events. if (m_mouseInteraction.m_mouseButtons.m_mouseButtons & mouseButtonValue) { // Erase the button from our state if we're done processing events. @@ -246,17 +251,22 @@ namespace SandboxEditor void ViewportManipulatorControllerInstance::UpdateViewport(const AzFramework::ViewportControllerUpdateEvent& event) { - m_curTime = event.m_time; + m_currentTime = event.m_time; } bool ViewportManipulatorControllerInstance::IsDoubleClick(AzToolsFramework::ViewportInteraction::MouseButton button) const { - auto clickIt = m_pendingDoubleClicks.find(button); - if (clickIt == m_pendingDoubleClicks.end()) + if (auto clickIt = m_pendingDoubleClicks.find(button); clickIt != m_pendingDoubleClicks.end()) { - return false; + const double doubleClickThresholdMilliseconds = qApp->doubleClickInterval(); + const bool insideTimeThreshold = + (m_currentTime.GetMilliseconds() - clickIt->second.m_time.GetMilliseconds()) < doubleClickThresholdMilliseconds; + const bool insideDistanceThreshold = + AzFramework::ScreenVectorLength(clickIt->second.m_position - m_mouseInteraction.m_mousePick.m_screenCoordinates) < + AzFramework::DefaultMouseMoveDeadZone; + return insideTimeThreshold && insideDistanceThreshold; } - const double doubleClickThresholdMilliseconds = qApp->doubleClickInterval(); - return (m_curTime.GetMilliseconds() - clickIt->second.GetMilliseconds()) < doubleClickThresholdMilliseconds; + + return false; } -} //namespace SandboxEditor +} // namespace SandboxEditor diff --git a/Code/Editor/ViewportManipulatorController.h b/Code/Editor/ViewportManipulatorController.h index d551eb3647..b9c359a544 100644 --- a/Code/Editor/ViewportManipulatorController.h +++ b/Code/Editor/ViewportManipulatorController.h @@ -39,8 +39,16 @@ namespace SandboxEditor static bool IsMouseMove(const AzFramework::InputChannel& inputChannel); static AzToolsFramework::ViewportInteraction::KeyboardModifier GetKeyboardModifier(const AzFramework::InputChannel& inputChannel); + //! Represents the time and location of a click. + struct ClickEvent + { + AZ::ScriptTimePoint m_time; + AzFramework::ScreenPoint m_position; + }; + AzToolsFramework::ViewportInteraction::MouseInteraction m_mouseInteraction; - AZStd::unordered_map m_pendingDoubleClicks; - AZ::ScriptTimePoint m_curTime; + AZStd::unordered_map m_pendingDoubleClicks; + + AZ::ScriptTimePoint m_currentTime; }; } // namespace SandboxEditor diff --git a/Code/Framework/AzFramework/AzFramework/Entity/EntityDebugDisplayBus.h b/Code/Framework/AzFramework/AzFramework/Entity/EntityDebugDisplayBus.h index 49506364f4..b81a0ab7f0 100644 --- a/Code/Framework/AzFramework/AzFramework/Entity/EntityDebugDisplayBus.h +++ b/Code/Framework/AzFramework/AzFramework/Entity/EntityDebugDisplayBus.h @@ -76,9 +76,12 @@ namespace AzFramework virtual void DrawSolidCone(const AZ::Vector3& pos, const AZ::Vector3& dir, float radius, float height, bool drawShaded = true) { (void)pos; (void)dir; (void)radius; (void)height; (void)drawShaded; } virtual void DrawWireCylinder(const AZ::Vector3& center, const AZ::Vector3& axis, float radius, float height) { (void)center; (void)axis; (void)radius; (void)height; } virtual void DrawSolidCylinder(const AZ::Vector3& center, const AZ::Vector3& axis, float radius, float height, bool drawShaded = true) { (void)center; (void)axis; (void)radius; (void)height; (void)drawShaded; } + virtual void DrawWireCylinderNoEnds(const AZ::Vector3& center, const AZ::Vector3& axis, float radius, float height) { (void)center; (void)axis; (void)radius; (void)height; } + virtual void DrawSolidCylinderNoEnds(const AZ::Vector3& center, const AZ::Vector3& axis, float radius, float height, bool drawShaded = true) { (void)center; (void)axis; (void)radius; (void)height; (void)drawShaded; } virtual void DrawWireCapsule(const AZ::Vector3& center, const AZ::Vector3& axis, float radius, float heightStraightSection) { (void)center; (void)axis; (void)radius; (void)heightStraightSection; } virtual void DrawWireSphere(const AZ::Vector3& pos, float radius) { (void)pos; (void)radius; } virtual void DrawWireSphere(const AZ::Vector3& pos, const AZ::Vector3 radius) { (void)pos; (void)radius; } + virtual void DrawWireHemisphere(const AZ::Vector3& pos, const AZ::Vector3& axis, float radius) { (void)pos; (void)axis; (void)radius; } virtual void DrawWireDisk(const AZ::Vector3& pos, const AZ::Vector3& dir, float radius) { (void)pos; (void)dir; (void)radius; } virtual void DrawBall(const AZ::Vector3& pos, float radius, bool drawShaded = true) { (void)pos; (void)radius; (void)drawShaded; } virtual void DrawDisk(const AZ::Vector3& pos, const AZ::Vector3& dir, float radius) { (void)pos; (void)dir; (void)radius; } diff --git a/Code/Framework/AzFramework/AzFramework/Viewport/CameraInput.cpp b/Code/Framework/AzFramework/AzFramework/Viewport/CameraInput.cpp index 26c9db64aa..771884ac6a 100644 --- a/Code/Framework/AzFramework/AzFramework/Viewport/CameraInput.cpp +++ b/Code/Framework/AzFramework/AzFramework/Viewport/CameraInput.cpp @@ -94,27 +94,27 @@ namespace AzFramework float y; float z; - // 2.4 Factor as RzRyRx - if (orientation.GetElement(2, 0) < 1.0f) + // 2.5 Factor as RzRxRy + if (orientation.GetElement(2, 1) < 1.0f) { - if (orientation.GetElement(2, 0) > -1.0f) + if (orientation.GetElement(2, 1) > -1.0f) { - x = AZStd::atan2(orientation.GetElement(2, 1), orientation.GetElement(2, 2)); - y = AZStd::asin(-orientation.GetElement(2, 0)); - z = AZStd::atan2(orientation.GetElement(1, 0), orientation.GetElement(0, 0)); + x = AZStd::asin(orientation.GetElement(2, 1)); + y = AZStd::atan2(-orientation.GetElement(2, 0), orientation.GetElement(2, 2)); + z = AZStd::atan2(-orientation.GetElement(0, 1), orientation.GetElement(1, 1)); } else { - x = 0.0f; - y = AZ::Constants::Pi * 0.5f; - z = -AZStd::atan2(-orientation.GetElement(2, 1), orientation.GetElement(1, 1)); + x = -AZ::Constants::Pi * 0.5f; + y = 0.0f; + z = -AZStd::atan2(orientation.GetElement(0, 2), orientation.GetElement(0, 0)); } } else { - x = 0.0f; - y = -AZ::Constants::Pi * 0.5f; - z = AZStd::atan2(-orientation.GetElement(1, 2), orientation.GetElement(1, 1)); + x = AZ::Constants::Pi * 0.5f; + y = 0.0f; + z = AZStd::atan2(orientation.GetElement(0, 2), orientation.GetElement(0, 0)); } return { x, y, z }; @@ -122,14 +122,36 @@ namespace AzFramework void UpdateCameraFromTransform(Camera& camera, const AZ::Transform& transform) { - const auto eulerAngles = AzFramework::EulerAngles(AZ::Matrix3x3::CreateFromTransform(transform)); + UpdateCameraFromTranslationAndRotation( + camera, transform.GetTranslation(), AzFramework::EulerAngles(AZ::Matrix3x3::CreateFromTransform(transform))); + } + void UpdateCameraFromTranslationAndRotation(Camera& camera, const AZ::Vector3& translation, const AZ::Vector3& eulerAngles) + { camera.m_pitch = eulerAngles.GetX(); camera.m_yaw = eulerAngles.GetZ(); - camera.m_pivot = transform.GetTranslation(); + camera.m_pivot = translation; camera.m_offset = AZ::Vector3::CreateZero(); } + float SmoothValueTime(const float smoothness, float deltaTime) + { + // note: the math for the lerp smoothing implementation for camera rotation and translation was inspired by this excellent + // article by Scott Lembcke: https://www.gamasutra.com/blogs/ScottLembcke/20180404/316046/Improved_Lerp_Smoothing.php + const float rate = AZStd::exp2(smoothness); + return AZStd::exp2(-rate * deltaTime); + } + + float SmoothValue(const float target, const float current, const float time) + { + return AZ::Lerp(target, current, time); + } + + float SmoothValue(const float target, const float current, const float smoothness, const float deltaTime) + { + return SmoothValue(target, current, SmoothValueTime(smoothness, deltaTime)); + } + bool CameraSystem::HandleEvents(const InputEvent& event) { if (const auto& cursor = AZStd::get_if(&event)) @@ -291,6 +313,11 @@ namespace AzFramework { return false; }; + + m_constrainPitch = []() constexpr + { + return true; + }; } bool RotateCameraInput::HandleEvents(const InputEvent& event, const ScreenVector& cursorDelta, [[maybe_unused]] const float scrollDelta) @@ -312,7 +339,10 @@ namespace AzFramework nextCamera.m_yaw -= float(cursorDelta.m_x) * rotateSpeed * Invert(m_invertYawFn()); nextCamera.m_yaw = WrapYawRotation(nextCamera.m_yaw); - nextCamera.m_pitch = ClampPitchRotation(nextCamera.m_pitch); + if (m_constrainPitch()) + { + nextCamera.m_pitch = ClampPitchRotation(nextCamera.m_pitch); + } return nextCamera; } @@ -726,14 +756,14 @@ namespace AzFramework Camera SmoothCamera(const Camera& currentCamera, const Camera& targetCamera, const CameraProps& cameraProps, const float deltaTime) { - const auto clamp_rotation = [](const float angle) + const auto clampRotation = [](const float angle) { return AZStd::fmod(angle + AZ::Constants::TwoPi, AZ::Constants::TwoPi); }; // keep yaw in 0 - 360 range - float targetYaw = clamp_rotation(targetCamera.m_yaw); - const float currentYaw = clamp_rotation(currentCamera.m_yaw); + float targetYaw = clampRotation(targetCamera.m_yaw); + const float currentYaw = clampRotation(currentCamera.m_yaw); // return the sign of the float input (-1, 0, 1) const auto sign = [](const float value) @@ -742,21 +772,17 @@ namespace AzFramework }; // ensure smooth transition when moving across 0 - 360 boundary - const float yawDelta = targetYaw - currentYaw; - if (AZStd::abs(yawDelta) >= AZ::Constants::Pi) + if (const float yawDelta = targetYaw - currentYaw; AZStd::abs(yawDelta) >= AZ::Constants::Pi) { targetYaw -= AZ::Constants::TwoPi * sign(yawDelta); } Camera camera; - // note: the math for the lerp smoothing implementation for camera rotation and translation was inspired by this excellent - // article by Scott Lembcke: https://www.gamasutra.com/blogs/ScottLembcke/20180404/316046/Improved_Lerp_Smoothing.php if (cameraProps.m_rotateSmoothingEnabledFn()) { - const float lookRate = AZStd::exp2(cameraProps.m_rotateSmoothnessFn()); - const float lookTime = AZStd::exp2(-lookRate * deltaTime); - camera.m_pitch = AZ::Lerp(targetCamera.m_pitch, currentCamera.m_pitch, lookTime); - camera.m_yaw = AZ::Lerp(targetYaw, currentYaw, lookTime); + const float lookTime = SmoothValueTime(cameraProps.m_rotateSmoothnessFn(), deltaTime); + camera.m_pitch = SmoothValue(targetCamera.m_pitch, currentCamera.m_pitch, lookTime); + camera.m_yaw = SmoothValue(targetYaw, currentYaw, lookTime); } else { @@ -766,8 +792,7 @@ namespace AzFramework if (cameraProps.m_translateSmoothingEnabledFn()) { - const float moveRate = AZStd::exp2(cameraProps.m_translateSmoothnessFn()); - const float moveTime = AZStd::exp2(-moveRate * deltaTime); + const float moveTime = SmoothValueTime(cameraProps.m_rotateSmoothnessFn(), deltaTime); camera.m_pivot = targetCamera.m_pivot.Lerp(currentCamera.m_pivot, moveTime); camera.m_offset = targetCamera.m_offset.Lerp(currentCamera.m_offset, moveTime); } diff --git a/Code/Framework/AzFramework/AzFramework/Viewport/CameraInput.h b/Code/Framework/AzFramework/AzFramework/Viewport/CameraInput.h index 2d02bb0b6d..4eea94cbe7 100644 --- a/Code/Framework/AzFramework/AzFramework/Viewport/CameraInput.h +++ b/Code/Framework/AzFramework/AzFramework/Viewport/CameraInput.h @@ -85,6 +85,19 @@ namespace AzFramework //! Extracts Euler angles (orientation) and translation from the transform and writes the values to the camera. void UpdateCameraFromTransform(Camera& camera, const AZ::Transform& transform); + //! Writes the translation value and Euler angles to the camera. + void UpdateCameraFromTranslationAndRotation(Camera& camera, const AZ::Vector3& translation, const AZ::Vector3& eulerAngles); + + //! Returns the time ('t') input value to use with SmoothValue. + //! Useful if it is to be reused for multiple calls to SmoothValue. + float SmoothValueTime(float smoothness, float deltaTime); + + // Smoothly interpolate a value from current to target according to a smoothing parameter. + float SmoothValue(float target, float current, float smoothness, float deltaTime); + + // Overload of SmoothValue that takes time ('t') value directly. + float SmoothValue(float target, float current, float time); + //! Generic motion type. template struct MotionEvent @@ -334,6 +347,7 @@ namespace AzFramework AZStd::function m_rotateSpeedFn; AZStd::function m_invertPitchFn; AZStd::function m_invertYawFn; + AZStd::function m_constrainPitch; private: InputChannelId m_rotateChannelId; //!< Input channel to begin the rotate camera input. diff --git a/Code/Framework/AzFramework/AzFramework/Viewport/CameraState.cpp b/Code/Framework/AzFramework/AzFramework/Viewport/CameraState.cpp index 00cbda7b34..40fb82ca97 100644 --- a/Code/Framework/AzFramework/AzFramework/Viewport/CameraState.cpp +++ b/Code/Framework/AzFramework/AzFramework/Viewport/CameraState.cpp @@ -8,18 +8,18 @@ #include "CameraState.h" -#include #include #include +#include namespace AzFramework { void SetCameraClippingVolume( - AzFramework::CameraState& cameraState, const float nearPlane, const float farPlane, const float fovRad) + AzFramework::CameraState& cameraState, const float nearPlane, const float farPlane, const float verticalFovRad) { cameraState.m_nearClip = nearPlane; cameraState.m_farClip = farPlane; - cameraState.m_fovOrZoom = fovRad; + cameraState.m_fovOrZoom = verticalFovRad; } void SetCameraTransform(CameraState& cameraState, const AZ::Transform& transform) @@ -35,20 +35,34 @@ namespace AzFramework SetCameraClippingVolume(cameraState, 0.1f, 1000.0f, AZ::DegToRad(60.0f)); } - AzFramework::CameraState CreateDefaultCamera( - const AZ::Transform& transform, const AZ::Vector2& viewportSize) + CameraState CreateCamera( + const AZ::Transform& transform, + const float nearPlane, + const float farPlane, + const float verticalFovRad, + const AZ::Vector2& viewportSize) { AzFramework::CameraState cameraState; - SetDefaultCameraClippingVolume(cameraState); SetCameraTransform(cameraState, transform); + SetCameraClippingVolume(cameraState, nearPlane, farPlane, verticalFovRad); cameraState.m_viewportSize = viewportSize; return cameraState; } - AzFramework::CameraState CreateIdentityDefaultCamera( - const AZ::Vector3& position, const AZ::Vector2& viewportSize) + AzFramework::CameraState CreateDefaultCamera(const AZ::Transform& transform, const AZ::Vector2& viewportSize) + { + AzFramework::CameraState cameraState; + + SetCameraTransform(cameraState, transform); + SetDefaultCameraClippingVolume(cameraState); + cameraState.m_viewportSize = viewportSize; + + return cameraState; + } + + AzFramework::CameraState CreateIdentityDefaultCamera(const AZ::Vector3& position, const AZ::Vector2& viewportSize) { return CreateDefaultCamera(AZ::Transform::CreateTranslation(position), viewportSize); } @@ -89,15 +103,15 @@ namespace AzFramework void CameraState::Reflect(AZ::SerializeContext& serializeContext) { - serializeContext.Class()-> - Field("Position", &CameraState::m_position)-> - Field("Forward", &CameraState::m_forward)-> - Field("Side", &CameraState::m_side)-> - Field("Up", &CameraState::m_up)-> - Field("ViewportSize", &CameraState::m_viewportSize)-> - Field("NearClip", &CameraState::m_nearClip)-> - Field("FarClip", &CameraState::m_farClip)-> - Field("FovZoom", &CameraState::m_fovOrZoom)-> - Field("Ortho", &CameraState::m_orthographic); + serializeContext.Class() + ->Field("Position", &CameraState::m_position) + ->Field("Forward", &CameraState::m_forward) + ->Field("Side", &CameraState::m_side) + ->Field("Up", &CameraState::m_up) + ->Field("ViewportSize", &CameraState::m_viewportSize) + ->Field("NearClip", &CameraState::m_nearClip) + ->Field("FarClip", &CameraState::m_farClip) + ->Field("FovZoom", &CameraState::m_fovOrZoom) + ->Field("Ortho", &CameraState::m_orthographic); } } // namespace AzFramework diff --git a/Code/Framework/AzFramework/AzFramework/Viewport/CameraState.h b/Code/Framework/AzFramework/AzFramework/Viewport/CameraState.h index e174771c3b..cefb144ec1 100644 --- a/Code/Framework/AzFramework/AzFramework/Viewport/CameraState.h +++ b/Code/Framework/AzFramework/AzFramework/Viewport/CameraState.h @@ -40,10 +40,14 @@ namespace AzFramework AZ::Vector2 m_viewportSize = AZ::Vector2::CreateZero(); //!< Dimensions of the viewport. float m_nearClip = 0.01f; //!< Near clip plane of the camera. float m_farClip = 100.0f; //!< Far clip plane of the camera. - float m_fovOrZoom = 0.0f; //!< Fov or zoom of camera depending on if it is using orthographic projection or not. + float m_fovOrZoom = 0.0f; //!< Vertical fov or zoom of camera depending on if it is using orthographic projection or not. bool m_orthographic = false; //!< Is the camera using orthographic projection or not. }; + //! Create a camera at the given transform, specifying the near and far clip planes as well as the fov with a specific viewport size. + CameraState CreateCamera( + const AZ::Transform& transform, float nearPlane, float farPlane, float verticalFovRad, const AZ::Vector2& viewportSize); + //! Create a camera at the given transform with a specific viewport size. //! @note The near/far clip planes and fov are sensible default values - please //! use SetCameraClippingVolume to override them. @@ -60,7 +64,7 @@ namespace AzFramework CameraState CreateCameraFromWorldFromViewMatrix(const AZ::Matrix4x4& worldFromView, const AZ::Vector2& viewportSize); //! Override the default near/far clipping planes and fov of the camera. - void SetCameraClippingVolume(CameraState& cameraState, float nearPlane, float farPlane, float fovRad); + void SetCameraClippingVolume(CameraState& cameraState, float nearPlane, float farPlane, float verticalFovRad); //! Override the default near/far clipping planes and fov of the camera by inferring them the specified right handed transform into clip space. void SetCameraClippingVolumeFromPerspectiveFovMatrixRH(CameraState& cameraState, const AZ::Matrix4x4& clipFromView); diff --git a/Code/Framework/AzFramework/AzFramework/Viewport/ClickDetector.cpp b/Code/Framework/AzFramework/AzFramework/Viewport/ClickDetector.cpp index 1b3645630e..294ff71974 100644 --- a/Code/Framework/AzFramework/AzFramework/Viewport/ClickDetector.cpp +++ b/Code/Framework/AzFramework/AzFramework/Viewport/ClickDetector.cpp @@ -24,11 +24,12 @@ namespace AzFramework ClickDetector::ClickOutcome ClickDetector::DetectClick(const ClickEvent clickEvent, const ScreenVector& cursorDelta) { + m_moveAccumulator += ScreenVectorLength(cursorDelta); + const auto previousDetectionState = m_detectionState; if (previousDetectionState == DetectionState::WaitingForMove) { // only allow the action to begin if the mouse has been moved a small amount - m_moveAccumulator += ScreenVectorLength(cursorDelta); if (m_moveAccumulator > m_deadZone) { m_detectionState = DetectionState::Moved; @@ -43,7 +44,7 @@ namespace AzFramework using FloatingPointSeconds = AZStd::chrono::duration; const auto diff = now - m_tryBeginTime.value(); - if (FloatingPointSeconds(diff).count() < m_doubleClickInterval) + if (FloatingPointSeconds(diff).count() < m_doubleClickInterval && m_moveAccumulator < m_deadZone) { return ClickOutcome::Nil; } diff --git a/Code/Framework/AzFramework/AzFramework/Viewport/ClickDetector.h b/Code/Framework/AzFramework/AzFramework/Viewport/ClickDetector.h index 70bdeb4619..544afe6d69 100644 --- a/Code/Framework/AzFramework/AzFramework/Viewport/ClickDetector.h +++ b/Code/Framework/AzFramework/AzFramework/Viewport/ClickDetector.h @@ -15,6 +15,10 @@ namespace AzFramework { + //! Default value to use for detecting if the mouse has moved far enough after a mouse down to no longer + //! register a click when a mouse up occurs. + inline constexpr float DefaultMouseMoveDeadZone = 2.0f; + struct ScreenVector; //! Utility class to help detect different types of mouse click (mouse down and up with @@ -66,7 +70,7 @@ namespace AzFramework }; float m_moveAccumulator = 0.0f; //!< How far the mouse has moved after mouse down. - float m_deadZone = 2.0f; //!< How far to move before a click is cancelled (when Move will fire). + float m_deadZone = DefaultMouseMoveDeadZone; //!< 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. //! Mouse down time (happens each mouse down, helps with double click handling). diff --git a/Code/Framework/AzFramework/AzFramework/Viewport/ScreenGeometry.cpp b/Code/Framework/AzFramework/AzFramework/Viewport/ScreenGeometry.cpp index e26d7cfa9b..f1c21230c7 100644 --- a/Code/Framework/AzFramework/AzFramework/Viewport/ScreenGeometry.cpp +++ b/Code/Framework/AzFramework/AzFramework/Viewport/ScreenGeometry.cpp @@ -24,6 +24,10 @@ namespace AzFramework serializeContext->Class()-> Field("X", &ScreenVector::m_x)-> Field("Y", &ScreenVector::m_y); + + serializeContext->Class()-> + Field("Width", &ScreenSize::m_width)-> + Field("Height", &ScreenSize::m_height); } } } // namespace AzFramework diff --git a/Code/Framework/AzFramework/AzFramework/Viewport/ScreenGeometry.h b/Code/Framework/AzFramework/AzFramework/Viewport/ScreenGeometry.h index 1529d760e5..7a5d7fdc62 100644 --- a/Code/Framework/AzFramework/AzFramework/Viewport/ScreenGeometry.h +++ b/Code/Framework/AzFramework/AzFramework/Viewport/ScreenGeometry.h @@ -26,7 +26,7 @@ namespace AzFramework AZ_TYPE_INFO(ScreenPoint, "{8472B6C2-527F-44FC-87F8-C226B1A57A97}"); ScreenPoint() = default; - ScreenPoint(int x, int y) + constexpr ScreenPoint(int x, int y) : m_x(x) , m_y(y) { @@ -45,7 +45,7 @@ namespace AzFramework AZ_TYPE_INFO(ScreenVector, "{1EAA2C62-8FDB-4A28-9FE3-1FA4F1418894}"); ScreenVector() = default; - ScreenVector(int x, int y) + constexpr ScreenVector(int x, int y) : m_x(x) , m_y(y) { @@ -55,6 +55,22 @@ namespace AzFramework int m_y; //!< Y screen delta. }; + //! A wrapper around a screen width and height. + struct ScreenSize + { + AZ_TYPE_INFO(ScreenSize, "{26D28916-6E8E-44B8-83F9-C44BCDA370E2}"); + ScreenSize() = default; + + constexpr ScreenSize(int width, int height) + : m_width(width) + , m_height(height) + { + } + + int m_width; //!< Screen size width. + int m_height; //!< Screen size height. + }; + void ScreenGeometryReflect(AZ::ReflectContext* context); inline const ScreenVector operator-(const ScreenPoint& lhs, const ScreenPoint& rhs) @@ -138,6 +154,16 @@ namespace AzFramework return !operator==(lhs, rhs); } + inline const bool operator==(const ScreenSize& lhs, const ScreenSize& rhs) + { + return lhs.m_width == rhs.m_width && lhs.m_height == rhs.m_height; + } + + inline const bool operator!=(const ScreenSize& lhs, const ScreenSize& rhs) + { + return !operator==(lhs, rhs); + } + inline ScreenVector& operator*=(ScreenVector& lhs, const float rhs) { lhs.m_x = aznumeric_cast(AZStd::lround(aznumeric_cast(lhs.m_x) * rhs)); @@ -152,6 +178,20 @@ namespace AzFramework return result; } + inline ScreenSize& operator*=(ScreenSize& lhs, const float rhs) + { + lhs.m_width = aznumeric_cast(AZStd::lround(aznumeric_cast(lhs.m_width) * rhs)); + lhs.m_height = aznumeric_cast(AZStd::lround(aznumeric_cast(lhs.m_height) * rhs)); + return lhs; + } + + inline const ScreenSize operator*(const ScreenSize& lhs, const float rhs) + { + ScreenSize result{ lhs }; + result *= rhs; + return result; + } + inline float ScreenVectorLength(const ScreenVector& screenVector) { return aznumeric_cast(AZStd::sqrt(screenVector.m_x * screenVector.m_x + screenVector.m_y * screenVector.m_y)); @@ -168,4 +208,28 @@ namespace AzFramework { return AZ::Vector2(aznumeric_cast(screenVector.m_x), aznumeric_cast(screenVector.m_y)); } + + //! Return an AZ::Vector2 from a ScreenSize. + inline AZ::Vector2 Vector2FromScreenSize(const ScreenSize& screenSize) + { + return AZ::Vector2(aznumeric_cast(screenSize.m_width), aznumeric_cast(screenSize.m_height)); + } + + //! Return a ScreenPoint from an AZ::Vector2. + inline ScreenPoint ScreenPointFromVector2(const AZ::Vector2& vector2) + { + return ScreenPoint(aznumeric_cast(AZStd::lround(vector2.GetX())), aznumeric_cast(AZStd::lround(vector2.GetY()))); + } + + //! Return a ScreenVector from an AZ::Vector2. + inline ScreenVector ScreenVectorFromVector2(const AZ::Vector2& vector2) + { + return ScreenVector(aznumeric_cast(AZStd::lround(vector2.GetX())), aznumeric_cast(AZStd::lround(vector2.GetY()))); + } + + //! Return a ScreenSize from an AZ::Vector2. + inline ScreenSize ScreenSizeFromVector2(const AZ::Vector2& vector2) + { + return ScreenSize(aznumeric_cast(AZStd::lround(vector2.GetX())), aznumeric_cast(AZStd::lround(vector2.GetY()))); + } } // namespace AzFramework diff --git a/Code/Framework/AzFramework/AzFramework/Viewport/ViewportScreen.cpp b/Code/Framework/AzFramework/AzFramework/Viewport/ViewportScreen.cpp index afd16a6c23..87eee53fbd 100644 --- a/Code/Framework/AzFramework/AzFramework/Viewport/ViewportScreen.cpp +++ b/Code/Framework/AzFramework/AzFramework/Viewport/ViewportScreen.cpp @@ -10,6 +10,7 @@ #include #include +#include #include #include #include @@ -112,9 +113,8 @@ namespace AzFramework const AZ::Matrix4x4& cameraProjection, const AZ::Vector2& viewportSize) { - const auto ndcNormalizedPosition = WorldToScreenNdc(worldPosition, cameraView, cameraProjection); // scale ndc position by screen dimensions to return screen position - return ScreenPointFromNdc(AZ::Vector3ToVector2(ndcNormalizedPosition), viewportSize); + return ScreenPointFromNdc(AZ::Vector3ToVector2(WorldToScreenNdc(worldPosition, cameraView, cameraProjection)), viewportSize); } ScreenPoint WorldToScreen(const AZ::Vector3& worldPosition, const CameraState& cameraState) @@ -144,9 +144,7 @@ namespace AzFramework const AZ::Matrix4x4& inverseCameraProjection, const AZ::Vector2& viewportSize) { - const auto normalizedScreenPosition = NdcFromScreenPoint(screenPosition, viewportSize); - - return ScreenNdcToWorld(normalizedScreenPosition, inverseCameraView, inverseCameraProjection); + return ScreenNdcToWorld(NdcFromScreenPoint(screenPosition, viewportSize), inverseCameraView, inverseCameraProjection); } AZ::Vector3 ScreenToWorld(const ScreenPoint& screenPosition, const CameraState& cameraState) diff --git a/Code/Framework/AzFramework/Tests/CameraInputTests.cpp b/Code/Framework/AzFramework/Tests/CameraInputTests.cpp index a89fb0bd84..005623677c 100644 --- a/Code/Framework/AzFramework/Tests/CameraInputTests.cpp +++ b/Code/Framework/AzFramework/Tests/CameraInputTests.cpp @@ -104,9 +104,10 @@ namespace UnitTest AZStd::shared_ptr m_orbitCamera; AZ::Vector3 m_pivot = AZ::Vector3::CreateZero(); - //! This is approximately Pi/2 * 1000 - this can be used to rotate the camera 90 degrees (pitch or yaw based - //! on vertical or horizontal motion) as the rotate speed function is set to be 1/1000. - inline static const int PixelMotionDelta = 1570; + // this is approximately Pi/2 * 1000 - this can be used to rotate the camera 90 degrees (pitch or yaw based + // on vertical or horizontal motion) as the rotate speed function is set to be 1/1000. + inline static const int PixelMotionDelta90Degrees = 1570; + inline static const int PixelMotionDelta135Degrees = 2356; }; TEST_F(CameraInputFixture, BeginAndEndOrbitCameraInputConsumesCorrectEvents) @@ -292,7 +293,7 @@ namespace UnitTest HandleEventAndUpdate( AzFramework::DiscreteInputEvent{ AzFramework::InputDeviceMouse::Button::Right, AzFramework::InputChannel::State::Began }); - HandleEventAndUpdate(AzFramework::HorizontalMotionEvent{ PixelMotionDelta }); + HandleEventAndUpdate(AzFramework::HorizontalMotionEvent{ PixelMotionDelta90Degrees }); const float expectedYaw = AzFramework::WrapYawRotation(-AZ::Constants::HalfPi); @@ -310,7 +311,7 @@ namespace UnitTest HandleEventAndUpdate( AzFramework::DiscreteInputEvent{ AzFramework::InputDeviceMouse::Button::Right, AzFramework::InputChannel::State::Began }); - HandleEventAndUpdate(AzFramework::VerticalMotionEvent{ PixelMotionDelta }); + HandleEventAndUpdate(AzFramework::VerticalMotionEvent{ PixelMotionDelta90Degrees }); const float expectedPitch = AzFramework::ClampPitchRotation(-AZ::Constants::HalfPi); @@ -331,7 +332,7 @@ namespace UnitTest HandleEventAndUpdate(AzFramework::DiscreteInputEvent{ m_orbitChannelId, AzFramework::InputChannel::State::Began }); HandleEventAndUpdate( AzFramework::DiscreteInputEvent{ AzFramework::InputDeviceMouse::Button::Left, AzFramework::InputChannel::State::Began }); - HandleEventAndUpdate(AzFramework::VerticalMotionEvent{ PixelMotionDelta }); + HandleEventAndUpdate(AzFramework::VerticalMotionEvent{ PixelMotionDelta90Degrees }); const auto expectedCameraEndingPosition = AZ::Vector3(0.0f, -10.0f, 10.0f); const float expectedPitch = AzFramework::ClampPitchRotation(-AZ::Constants::HalfPi); @@ -354,7 +355,7 @@ namespace UnitTest HandleEventAndUpdate(AzFramework::DiscreteInputEvent{ m_orbitChannelId, AzFramework::InputChannel::State::Began }); HandleEventAndUpdate( AzFramework::DiscreteInputEvent{ AzFramework::InputDeviceMouse::Button::Left, AzFramework::InputChannel::State::Began }); - HandleEventAndUpdate(AzFramework::HorizontalMotionEvent{ -PixelMotionDelta }); + HandleEventAndUpdate(AzFramework::HorizontalMotionEvent{ -PixelMotionDelta90Degrees }); const auto expectedCameraEndingPosition = AZ::Vector3(20.0f, -5.0f, 0.0f); const float expectedYaw = AzFramework::WrapYawRotation(AZ::Constants::HalfPi); @@ -366,4 +367,42 @@ namespace UnitTest EXPECT_THAT(m_camera.m_offset, IsClose(AZ::Vector3(5.0f, -10.0f, 0.0f))); EXPECT_THAT(m_camera.Translation(), IsCloseTolerance(expectedCameraEndingPosition, 0.01f)); } + + TEST_F(CameraInputFixture, CameraPitchCanNotBeMovedPastNinetyDegreesWhenConstrained) + { + const auto cameraStartingPosition = AZ::Vector3(15.0f, -20.0f, 0.0f); + m_targetCamera.m_pivot = cameraStartingPosition; + + HandleEventAndUpdate( + AzFramework::DiscreteInputEvent{ AzFramework::InputDeviceMouse::Button::Right, AzFramework::InputChannel::State::Began }); + // pitch by 135.0 degrees + HandleEventAndUpdate(AzFramework::VerticalMotionEvent{ -PixelMotionDelta135Degrees }); + + // clamped to 90.0 degrees + const float expectedPitch = AZ::DegToRad(90.0f); + + using ::testing::FloatNear; + EXPECT_THAT(m_camera.m_pitch, FloatNear(expectedPitch, 0.001f)); + } + + TEST_F(CameraInputFixture, CameraPitchCanBeMovedPastNinetyDegreesWhenUnconstrained) + { + m_firstPersonRotateCamera->m_constrainPitch = [] + { + return false; + }; + + const auto cameraStartingPosition = AZ::Vector3(15.0f, -20.0f, 0.0f); + m_targetCamera.m_pivot = cameraStartingPosition; + + HandleEventAndUpdate( + AzFramework::DiscreteInputEvent{ AzFramework::InputDeviceMouse::Button::Right, AzFramework::InputChannel::State::Began }); + // pitch by 135.0 degrees + HandleEventAndUpdate(AzFramework::VerticalMotionEvent{ -PixelMotionDelta135Degrees }); + + const float expectedPitch = AZ::DegToRad(135.0f); + + using ::testing::FloatNear; + EXPECT_THAT(m_camera.m_pitch, FloatNear(expectedPitch, 0.001f)); + } } // namespace UnitTest diff --git a/Code/Framework/AzFramework/Tests/CameraState.cpp b/Code/Framework/AzFramework/Tests/CameraState.cpp index 70fa8be89a..1f35d5a06c 100644 --- a/Code/Framework/AzFramework/Tests/CameraState.cpp +++ b/Code/Framework/AzFramework/Tests/CameraState.cpp @@ -11,6 +11,7 @@ #include #include #include +#include #include namespace UnitTest @@ -51,22 +52,6 @@ namespace UnitTest { }; - // Taken from Atom::MatrixUtils for testing purposes, this can be removed if MakePerspectiveFovMatrixRH makes it into AZ - static AZ::Matrix4x4 MakePerspectiveMatrixRH(float fovY, float aspectRatio, float nearClip, float farClip) - { - float sinFov, cosFov; - AZ::SinCos(0.5f * fovY, sinFov, cosFov); - float yScale = cosFov / sinFov; //cot(fovY/2) - float xScale = yScale / aspectRatio; - - AZ::Matrix4x4 out; - out.SetRow(0, xScale, 0.f, 0.f, 0.f ); - out.SetRow(1, 0.f, yScale, 0.f, 0.f ); - out.SetRow(2, 0.f, 0.f, farClip / (nearClip - farClip), nearClip*farClip / (nearClip - farClip) ); - out.SetRow(3, 0.f, 0.f, -1.f, 0.f ); - return out; - } - TEST_P(Translation, Permutation) { // Given a position @@ -176,7 +161,8 @@ namespace UnitTest { auto [fovY, aspectRatio, nearClip, farClip] = GetParam(); - AZ::Matrix4x4 clipFromView = MakePerspectiveMatrixRH(fovY, aspectRatio, nearClip, farClip); + AZ::Matrix4x4 clipFromView; + MakePerspectiveFovMatrixRH(clipFromView, fovY, aspectRatio, nearClip, farClip); AzFramework::SetCameraClippingVolumeFromPerspectiveFovMatrixRH(m_cameraState, clipFromView); diff --git a/Code/Framework/AzFramework/Tests/ClickDetectorTests.cpp b/Code/Framework/AzFramework/Tests/ClickDetectorTests.cpp index 45bac2770e..62852c9b87 100644 --- a/Code/Framework/AzFramework/Tests/ClickDetectorTests.cpp +++ b/Code/Framework/AzFramework/Tests/ClickDetectorTests.cpp @@ -144,12 +144,45 @@ namespace UnitTest { using ::testing::Eq; - const ClickDetector::ClickOutcome downOutcome = - m_clickDetector.DetectClick(ClickDetector::ClickEvent::Down, ScreenVector(0, 0)); - const ClickDetector::ClickOutcome upOutcome = - m_clickDetector.DetectClick(ClickDetector::ClickEvent::Up, ScreenVector(50, 50)); + const ClickDetector::ClickOutcome downOutcome = m_clickDetector.DetectClick(ClickDetector::ClickEvent::Down, ScreenVector(0, 0)); + const ClickDetector::ClickOutcome upOutcome = m_clickDetector.DetectClick(ClickDetector::ClickEvent::Up, ScreenVector(50, 50)); EXPECT_THAT(downOutcome, Eq(ClickDetector::ClickOutcome::Nil)); EXPECT_THAT(upOutcome, Eq(ClickDetector::ClickOutcome::Release)); } + + //! note: ClickDetector does not explicitly return double clicks but if one occurs the ClickOutcome will be Nil + TEST_F(ClickDetectorFixture, DoubleClickIsRegisteredIfMouseDeltaHasMovedLessThanDeadzoneInClickInterval) + { + using ::testing::Eq; + + const ClickDetector::ClickOutcome firstDownOutcome = + m_clickDetector.DetectClick(ClickDetector::ClickEvent::Down, ScreenVector(0, 0)); + const ClickDetector::ClickOutcome firstUpOutcome = m_clickDetector.DetectClick(ClickDetector::ClickEvent::Up, ScreenVector(0, 0)); + const ClickDetector::ClickOutcome secondDownOutcome = + m_clickDetector.DetectClick(ClickDetector::ClickEvent::Down, ScreenVector(0, 0)); + const ClickDetector::ClickOutcome secondUpOutcome = m_clickDetector.DetectClick(ClickDetector::ClickEvent::Up, ScreenVector(0, 0)); + + EXPECT_THAT(firstDownOutcome, Eq(ClickDetector::ClickOutcome::Nil)); + EXPECT_THAT(firstUpOutcome, Eq(ClickDetector::ClickOutcome::Click)); + EXPECT_THAT(secondDownOutcome, Eq(ClickDetector::ClickOutcome::Nil)); + EXPECT_THAT(secondUpOutcome, Eq(ClickDetector::ClickOutcome::Nil)); + } + + TEST_F(ClickDetectorFixture, DoubleClickIsNotRegisteredIfMouseDeltaHasMovedMoreThanDeadzoneInClickInterval) + { + using ::testing::Eq; + + const ClickDetector::ClickOutcome firstDownOutcome = + m_clickDetector.DetectClick(ClickDetector::ClickEvent::Down, ScreenVector(0, 0)); + const ClickDetector::ClickOutcome firstUpOutcome = m_clickDetector.DetectClick(ClickDetector::ClickEvent::Up, ScreenVector(0, 0)); + const ClickDetector::ClickOutcome secondDownOutcome = + m_clickDetector.DetectClick(ClickDetector::ClickEvent::Down, ScreenVector(10, 10)); + const ClickDetector::ClickOutcome secondUpOutcome = m_clickDetector.DetectClick(ClickDetector::ClickEvent::Up, ScreenVector(0, 0)); + + EXPECT_THAT(firstDownOutcome, Eq(ClickDetector::ClickOutcome::Nil)); + EXPECT_THAT(firstUpOutcome, Eq(ClickDetector::ClickOutcome::Click)); + EXPECT_THAT(secondDownOutcome, Eq(ClickDetector::ClickOutcome::Nil)); + EXPECT_THAT(secondUpOutcome, Eq(ClickDetector::ClickOutcome::Click)); + } } // namespace UnitTest diff --git a/Code/Framework/AzFramework/Tests/CursorStateTests.cpp b/Code/Framework/AzFramework/Tests/CursorStateTests.cpp index 923cd02a10..fe15580dad 100644 --- a/Code/Framework/AzFramework/Tests/CursorStateTests.cpp +++ b/Code/Framework/AzFramework/Tests/CursorStateTests.cpp @@ -8,12 +8,13 @@ #include #include +#include namespace UnitTest { using AzFramework::CursorState; - using AzFramework::ScreenVector; using AzFramework::ScreenPoint; + using AzFramework::ScreenVector; class CursorStateFixture : public ::testing::Test { diff --git a/Code/Framework/AzFramework/Tests/Utils/Printers.cpp b/Code/Framework/AzFramework/Tests/Utils/Printers.cpp new file mode 100644 index 0000000000..91c9558be7 --- /dev/null +++ b/Code/Framework/AzFramework/Tests/Utils/Printers.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 "Printers.h" + +#include + +#include +#include + +namespace AzFramework +{ + void PrintTo(const ScreenPoint& screenPoint, std::ostream* os) + { + *os << "(x: " << screenPoint.m_x << ", y: " << screenPoint.m_y << ")"; + } + + void PrintTo(const ScreenVector& screenVector, std::ostream* os) + { + *os << "(x: " << screenVector.m_x << ", y: " << screenVector.m_y << ")"; + } + + void PrintTo(const ScreenSize& screenSize, std::ostream* os) + { + *os << "(width: " << screenSize.m_width << ", height: " << screenSize.m_height << ")"; + } +} // namespace AzFramework diff --git a/Code/Framework/AzFramework/Tests/Utils/Printers.h b/Code/Framework/AzFramework/Tests/Utils/Printers.h new file mode 100644 index 0000000000..fc967eabe9 --- /dev/null +++ b/Code/Framework/AzFramework/Tests/Utils/Printers.h @@ -0,0 +1,20 @@ +/* + * 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 AzFramework +{ + struct ScreenPoint; + struct ScreenVector; + struct ScreenSize; + + void PrintTo(const ScreenPoint& screenPoint, std::ostream* os); + void PrintTo(const ScreenVector& screenVector, std::ostream* os); + void PrintTo(const ScreenSize& screenSize, std::ostream* os); +} // namespace AzFramework diff --git a/Code/Framework/AzFramework/Tests/framework_shared_tests_files.cmake b/Code/Framework/AzFramework/Tests/framework_shared_tests_files.cmake index 85c00a2e8a..9427738e67 100644 --- a/Code/Framework/AzFramework/Tests/framework_shared_tests_files.cmake +++ b/Code/Framework/AzFramework/Tests/framework_shared_tests_files.cmake @@ -11,5 +11,7 @@ set(FILES Mocks/MockWindowRequests.h Utils/Utils.h Utils/Utils.cpp + Utils/Printers.h + Utils/Printers.cpp FrameworkApplicationFixture.h ) diff --git a/Code/Framework/AzManipulatorTestFramework/Include/AzManipulatorTestFramework/ViewportInteraction.h b/Code/Framework/AzManipulatorTestFramework/Include/AzManipulatorTestFramework/ViewportInteraction.h index a8ba63500c..3c41b28851 100644 --- a/Code/Framework/AzManipulatorTestFramework/Include/AzManipulatorTestFramework/ViewportInteraction.h +++ b/Code/Framework/AzManipulatorTestFramework/Include/AzManipulatorTestFramework/ViewportInteraction.h @@ -41,8 +41,8 @@ namespace AzManipulatorTestFramework // ViewportInteractionRequestBus overrides ... AzFramework::CameraState GetCameraState() override; AzFramework::ScreenPoint ViewportWorldToScreen(const AZ::Vector3& worldPosition) override; - AZStd::optional ViewportScreenToWorld(const AzFramework::ScreenPoint& screenPosition, float depth) override; - AZStd::optional ViewportScreenToWorldRay( + AZ::Vector3 ViewportScreenToWorld(const AzFramework::ScreenPoint& screenPosition) override; + AzToolsFramework::ViewportInteraction::ProjectedViewportRay ViewportScreenToWorldRay( const AzFramework::ScreenPoint& screenPosition) override; float DeviceScalingFactor() override; diff --git a/Code/Framework/AzManipulatorTestFramework/Source/AzManipulatorTestFrameworkUtils.cpp b/Code/Framework/AzManipulatorTestFramework/Source/AzManipulatorTestFrameworkUtils.cpp index 4f1e108a14..6fbf2cb219 100644 --- a/Code/Framework/AzManipulatorTestFramework/Source/AzManipulatorTestFrameworkUtils.cpp +++ b/Code/Framework/AzManipulatorTestFramework/Source/AzManipulatorTestFrameworkUtils.cpp @@ -95,7 +95,7 @@ namespace AzManipulatorTestFramework AzToolsFramework::ViewportInteraction::MousePick mousePick; mousePick.m_screenCoordinates = screenPoint; - mousePick.m_rayOrigin = cameraState.m_position; + mousePick.m_rayOrigin = nearPlaneWorldPosition; mousePick.m_rayDirection = (nearPlaneWorldPosition - cameraState.m_position).GetNormalized(); return mousePick; diff --git a/Code/Framework/AzManipulatorTestFramework/Source/ImmediateModeActionDispatcher.cpp b/Code/Framework/AzManipulatorTestFramework/Source/ImmediateModeActionDispatcher.cpp index c122a941c4..5bfe63bd99 100644 --- a/Code/Framework/AzManipulatorTestFramework/Source/ImmediateModeActionDispatcher.cpp +++ b/Code/Framework/AzManipulatorTestFramework/Source/ImmediateModeActionDispatcher.cpp @@ -69,8 +69,6 @@ namespace AzManipulatorTestFramework void ImmediateModeActionDispatcher::CameraStateImpl(const AzFramework::CameraState& cameraState) { m_viewportManipulatorInteraction.GetViewportInteraction().SetCameraState(cameraState); - GetMouseInteractionEvent()->m_mouseInteraction.m_mousePick.m_rayOrigin = cameraState.m_position; - GetMouseInteractionEvent()->m_mouseInteraction.m_mousePick.m_rayDirection = cameraState.m_forward; } void ImmediateModeActionDispatcher::MouseLButtonDownImpl() diff --git a/Code/Framework/AzManipulatorTestFramework/Source/IndirectManipulatorViewportInteraction.cpp b/Code/Framework/AzManipulatorTestFramework/Source/IndirectManipulatorViewportInteraction.cpp index 730c106301..9bcb8986d5 100644 --- a/Code/Framework/AzManipulatorTestFramework/Source/IndirectManipulatorViewportInteraction.cpp +++ b/Code/Framework/AzManipulatorTestFramework/Source/IndirectManipulatorViewportInteraction.cpp @@ -20,7 +20,8 @@ namespace AzManipulatorTestFramework { public: IndirectCallManipulatorManager(ViewportInteractionInterface& viewportInteraction); - // ManipulatorManagerInterface ... + + // ManipulatorManagerInterface overrides ... void ConsumeMouseInteractionEvent(const MouseInteractionEvent& event) override; AzToolsFramework::ManipulatorManagerId GetId() const override; bool ManipulatorBeingInteracted() const override; diff --git a/Code/Framework/AzManipulatorTestFramework/Source/ViewportInteraction.cpp b/Code/Framework/AzManipulatorTestFramework/Source/ViewportInteraction.cpp index 269baa703d..08cae0c738 100644 --- a/Code/Framework/AzManipulatorTestFramework/Source/ViewportInteraction.cpp +++ b/Code/Framework/AzManipulatorTestFramework/Source/ViewportInteraction.cpp @@ -140,13 +140,12 @@ namespace AzManipulatorTestFramework return m_viewportId; } - AZStd::optional ViewportInteraction::ViewportScreenToWorld( - [[maybe_unused]] const AzFramework::ScreenPoint& screenPosition, [[maybe_unused]] float depth) + AZ::Vector3 ViewportInteraction::ViewportScreenToWorld([[maybe_unused]] const AzFramework::ScreenPoint& screenPosition) { - return {}; + return AZ::Vector3::CreateZero(); } - AZStd::optional ViewportInteraction::ViewportScreenToWorldRay( + AzToolsFramework::ViewportInteraction::ProjectedViewportRay ViewportInteraction::ViewportScreenToWorldRay( [[maybe_unused]] const AzFramework::ScreenPoint& screenPosition) { return {}; diff --git a/Code/Framework/AzManipulatorTestFramework/Tests/WorldSpaceBuilderTest.cpp b/Code/Framework/AzManipulatorTestFramework/Tests/WorldSpaceBuilderTest.cpp index 211c8d64ef..376c18072e 100644 --- a/Code/Framework/AzManipulatorTestFramework/Tests/WorldSpaceBuilderTest.cpp +++ b/Code/Framework/AzManipulatorTestFramework/Tests/WorldSpaceBuilderTest.cpp @@ -140,8 +140,8 @@ namespace UnitTest // given a left mouse down ray in world space // consume the mouse move event state.m_actionDispatcher->CameraState(m_cameraState) - ->MouseLButtonDown() ->MousePosition(AzManipulatorTestFramework::GetCameraStateViewportCenter(m_cameraState)) + ->MouseLButtonDown() ->ExpectTrue(state.m_linearManipulator->PerformingAction()) ->ExpectManipulatorBeingInteracted() ->MouseLButtonUp() diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Application/ToolsApplication.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/Application/ToolsApplication.cpp index dcdaaf5f7d..0f0bbf2b41 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Application/ToolsApplication.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Application/ToolsApplication.cpp @@ -1198,14 +1198,25 @@ namespace AzToolsFramework AZ::EntityId ToolsApplication::GetCurrentLevelEntityId() { - AzFramework::EntityContextId editorEntityContextId = AzFramework::EntityContextId::CreateNull(); - AzToolsFramework::EditorEntityContextRequestBus::BroadcastResult(editorEntityContextId, &AzToolsFramework::EditorEntityContextRequestBus::Events::GetEditorEntityContextId); - AZ::SliceComponent* rootSliceComponent = nullptr; - AzFramework::SliceEntityOwnershipServiceRequestBus::EventResult(rootSliceComponent, editorEntityContextId, - &AzFramework::SliceEntityOwnershipServiceRequestBus::Events::GetRootSlice); - if (rootSliceComponent && rootSliceComponent->GetMetadataEntity()) + if (IsPrefabSystemEnabled()) { - return rootSliceComponent->GetMetadataEntity()->GetId(); + if (auto prefabPublicInterface = AZ::Interface::Get()) + { + return prefabPublicInterface->GetLevelInstanceContainerEntityId(); + } + } + else + { + AzFramework::EntityContextId editorEntityContextId = AzFramework::EntityContextId::CreateNull(); + AzToolsFramework::EditorEntityContextRequestBus::BroadcastResult( + editorEntityContextId, &AzToolsFramework::EditorEntityContextRequestBus::Events::GetEditorEntityContextId); + AZ::SliceComponent* rootSliceComponent = nullptr; + AzFramework::SliceEntityOwnershipServiceRequestBus::EventResult( + rootSliceComponent, editorEntityContextId, &AzFramework::SliceEntityOwnershipServiceRequestBus::Events::GetRootSlice); + if (rootSliceComponent && rootSliceComponent->GetMetadataEntity()) + { + return rootSliceComponent->GetMetadataEntity()->GetId(); + } } return AZ::EntityId(); diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/ComponentMode/ComponentModeCollection.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/ComponentMode/ComponentModeCollection.cpp index 07e025fc60..f07e87fad2 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/ComponentMode/ComponentModeCollection.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/ComponentMode/ComponentModeCollection.cpp @@ -448,7 +448,11 @@ namespace AzToolsFramework ViewportUi::ViewportUiRequestBus::Event( ViewportUi::DefaultViewportId, &ViewportUi::ViewportUiRequestBus::Events::CreateViewportBorder, - componentMode.m_componentMode->GetComponentModeName().c_str()); + componentMode.m_componentMode->GetComponentModeName().c_str(), + [] + { + ComponentModeSystemRequestBus::Broadcast(&ComponentModeSystemRequests::EndComponentMode); + }); } RefreshActions(); diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/ComponentMode/EditorBaseComponentMode.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/ComponentMode/EditorBaseComponentMode.cpp index f449478306..e780c38822 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/ComponentMode/EditorBaseComponentMode.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/ComponentMode/EditorBaseComponentMode.cpp @@ -55,8 +55,11 @@ namespace AzToolsFramework GetEntityComponentIdPair(), elementIdsToDisplay); // create the component mode border with the specific name for this component mode ViewportUi::ViewportUiRequestBus::Event( - ViewportUi::DefaultViewportId, &ViewportUi::ViewportUiRequestBus::Events::CreateViewportBorder, - GetComponentModeName()); + ViewportUi::DefaultViewportId, &ViewportUi::ViewportUiRequestBus::Events::CreateViewportBorder, GetComponentModeName(), + [] + { + ComponentModeSystemRequestBus::Broadcast(&ComponentModeSystemRequests::EndComponentMode); + }); // set the EntityComponentId for this ComponentMode to active in the ComponentModeViewportUi system ComponentModeViewportUiRequestBus::Event( GetComponentType(), &ComponentModeViewportUiRequestBus::Events::SetViewportUiActiveEntityComponentId, diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabFocusHandler.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabFocusHandler.cpp index 5b51944a75..744c53ef5a 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabFocusHandler.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabFocusHandler.cpp @@ -98,7 +98,7 @@ namespace AzToolsFramework::Prefab } // Retrieve parent of currently focused prefab. - InstanceOptionalReference parentInstance = m_instanceFocusHierarchy[hierarchySize - 2]; + InstanceOptionalReference parentInstance = GetReferenceFromContainerEntityId(m_instanceFocusHierarchy[hierarchySize - 2]); // Use container entity of parent Instance for focus operations. AZ::EntityId entityId = parentInstance->get().GetContainerEntityId(); @@ -132,7 +132,7 @@ namespace AzToolsFramework::Prefab return AZ::Failure(AZStd::string("Prefab Focus Handler: Invalid index on FocusOnPathIndex.")); } - InstanceOptionalReference focusedInstance = m_instanceFocusHierarchy[index]; + InstanceOptionalReference focusedInstance = GetReferenceFromContainerEntityId(m_instanceFocusHierarchy[index]); return FocusOnOwningPrefab(focusedInstance->get().GetContainerEntityId()); } @@ -172,7 +172,8 @@ namespace AzToolsFramework::Prefab // Close all container entities in the old path. CloseInstanceContainers(m_instanceFocusHierarchy); - m_focusedInstance = focusedInstance; + // Do not store the container for the root instance, use an invalid EntityId instead. + m_focusedInstanceContainerEntityId = focusedInstance->get().GetParentInstance().has_value() ? focusedInstance->get().GetContainerEntityId() : AZ::EntityId(); m_focusedTemplateId = focusedInstance->get().GetTemplateId(); // Focus on the descendants of the container entity in the Editor, if the interface is initialized. @@ -206,56 +207,55 @@ namespace AzToolsFramework::Prefab InstanceOptionalReference PrefabFocusHandler::GetFocusedPrefabInstance( [[maybe_unused]] AzFramework::EntityContextId entityContextId) const { - return m_focusedInstance; + return GetReferenceFromContainerEntityId(m_focusedInstanceContainerEntityId); } AZ::EntityId PrefabFocusHandler::GetFocusedPrefabContainerEntityId([[maybe_unused]] AzFramework::EntityContextId entityContextId) const { - if (!m_focusedInstance.has_value()) - { - // PrefabFocusHandler has not been initialized yet. - return AZ::EntityId(); - } - - return m_focusedInstance->get().GetContainerEntityId(); + return m_focusedInstanceContainerEntityId; } bool PrefabFocusHandler::IsOwningPrefabBeingFocused(AZ::EntityId entityId) const { - if (!m_focusedInstance.has_value()) - { - // PrefabFocusHandler has not been initialized yet. - return false; - } - if (!entityId.IsValid()) { return false; } InstanceOptionalReference instance = m_instanceEntityMapperInterface->FindOwningInstance(entityId); + if (!instance.has_value()) + { + return false; + } - return instance.has_value() && (&instance->get() == &m_focusedInstance->get()); + // If this is owned by the root instance, that corresponds to an invalid m_focusedInstanceContainerEntityId. + if (!instance->get().GetParentInstance().has_value()) + { + return !m_focusedInstanceContainerEntityId.IsValid(); + } + + return (instance->get().GetContainerEntityId() == m_focusedInstanceContainerEntityId); } bool PrefabFocusHandler::IsOwningPrefabInFocusHierarchy(AZ::EntityId entityId) const { - if (!m_focusedInstance.has_value()) - { - // PrefabFocusHandler has not been initialized yet. - return false; - } - if (!entityId.IsValid()) { return false; } + // If the focus is on the root, m_focusedInstanceContainerEntityId will be the invalid id. + // In those case all entities are in the focus hierarchy and should return true. + if (!m_focusedInstanceContainerEntityId.IsValid()) + { + return true; + } + InstanceOptionalReference instance = m_instanceEntityMapperInterface->FindOwningInstance(entityId); while (instance.has_value()) { - if (&instance->get() == &m_focusedInstance->get()) + if (instance->get().GetContainerEntityId() == m_focusedInstanceContainerEntityId) { return true; } @@ -290,8 +290,9 @@ namespace AzToolsFramework::Prefab // Determine if the entityId is the container for any of the instances in the vector. auto result = AZStd::find_if( m_instanceFocusHierarchy.begin(), m_instanceFocusHierarchy.end(), - [entityId](const InstanceOptionalReference& instance) + [&, entityId](const AZ::EntityId& containerEntityId) { + InstanceOptionalReference instance = GetReferenceFromContainerEntityId(containerEntityId); return (instance->get().GetContainerEntityId() == entityId); } ); @@ -316,8 +317,9 @@ namespace AzToolsFramework::Prefab // Determine if the templateId matches any of the instances in the vector. auto result = AZStd::find_if( m_instanceFocusHierarchy.begin(), m_instanceFocusHierarchy.end(), - [templateId](const InstanceOptionalReference& instance) + [&, templateId](const AZ::EntityId& containerEntityId) { + InstanceOptionalReference instance = GetReferenceFromContainerEntityId(containerEntityId); return (instance->get().GetTemplateId() == templateId); } ); @@ -336,10 +338,17 @@ namespace AzToolsFramework::Prefab AZStd::list instanceFocusList; - InstanceOptionalReference currentInstance = m_focusedInstance; + InstanceOptionalReference currentInstance = GetReferenceFromContainerEntityId(m_focusedInstanceContainerEntityId); while (currentInstance.has_value()) { - m_instanceFocusHierarchy.emplace_back(currentInstance); + if (currentInstance->get().GetParentInstance().has_value()) + { + m_instanceFocusHierarchy.emplace_back(currentInstance->get().GetContainerEntityId()); + } + else + { + m_instanceFocusHierarchy.emplace_back(AZ::EntityId()); + } currentInstance = currentInstance->get().GetParentInstance(); } @@ -357,42 +366,48 @@ namespace AzToolsFramework::Prefab size_t index = 0; size_t maxIndex = m_instanceFocusHierarchy.size() - 1; - for (const InstanceOptionalReference& instance : m_instanceFocusHierarchy) + for (const AZ::EntityId containerEntityId : m_instanceFocusHierarchy) { - AZStd::string prefabName; - - if (index < maxIndex) + InstanceOptionalReference instance = GetReferenceFromContainerEntityId(containerEntityId); + if (instance.has_value()) { - // Get the filename without the extension (stem). - prefabName = instance->get().GetTemplateSourcePath().Stem().Native(); - } - else - { - // Get the full filename. - prefabName = instance->get().GetTemplateSourcePath().Filename().Native(); - } + AZStd::string prefabName; - if (prefabSystemComponentInterface->IsTemplateDirty(instance->get().GetTemplateId())) - { - prefabName += "*"; - } + if (index < maxIndex) + { + // Get the filename without the extension (stem). + prefabName = instance->get().GetTemplateSourcePath().Stem().Native(); + } + else + { + // Get the full filename. + prefabName = instance->get().GetTemplateSourcePath().Filename().Native(); + } - m_instanceFocusPath.Append(prefabName); + if (prefabSystemComponentInterface->IsTemplateDirty(instance->get().GetTemplateId())) + { + prefabName += "*"; + } + + m_instanceFocusPath.Append(prefabName); + } ++index; } } - void PrefabFocusHandler::OpenInstanceContainers(const AZStd::vector& instances) const + void PrefabFocusHandler::OpenInstanceContainers(const AZStd::vector& instances) const { // If this is called outside the Editor, this interface won't be initialized. if (!m_containerEntityInterface) { return; } - - for (const InstanceOptionalReference& instance : instances) + + for (const AZ::EntityId containerEntityId : instances) { + InstanceOptionalReference instance = GetReferenceFromContainerEntityId(containerEntityId); + if (instance.has_value()) { m_containerEntityInterface->SetContainerOpen(instance->get().GetContainerEntityId(), true); @@ -400,7 +415,7 @@ namespace AzToolsFramework::Prefab } } - void PrefabFocusHandler::CloseInstanceContainers(const AZStd::vector& instances) const + void PrefabFocusHandler::CloseInstanceContainers(const AZStd::vector& instances) const { // If this is called outside the Editor, this interface won't be initialized. if (!m_containerEntityInterface) @@ -408,8 +423,10 @@ namespace AzToolsFramework::Prefab return; } - for (const InstanceOptionalReference& instance : instances) + for (const AZ::EntityId containerEntityId : instances) { + InstanceOptionalReference instance = GetReferenceFromContainerEntityId(containerEntityId); + if (instance.has_value()) { m_containerEntityInterface->SetContainerOpen(instance->get().GetContainerEntityId(), false); @@ -417,4 +434,22 @@ namespace AzToolsFramework::Prefab } } + InstanceOptionalReference PrefabFocusHandler::GetReferenceFromContainerEntityId(AZ::EntityId containerEntityId) const + { + if (!containerEntityId.IsValid()) + { + PrefabEditorEntityOwnershipInterface* prefabEditorEntityOwnershipInterface = + AZ::Interface::Get(); + + if (!prefabEditorEntityOwnershipInterface) + { + return AZStd::nullopt; + } + + return prefabEditorEntityOwnershipInterface->GetRootPrefabInstance(); + } + + return m_instanceEntityMapperInterface->FindOwningInstance(containerEntityId); + } + } // namespace AzToolsFramework::Prefab diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabFocusHandler.h b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabFocusHandler.h index 75b9666389..2e23059a01 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabFocusHandler.h +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabFocusHandler.h @@ -73,16 +73,19 @@ namespace AzToolsFramework::Prefab void RefreshInstanceFocusList(); void RefreshInstanceFocusPath(); - void OpenInstanceContainers(const AZStd::vector& instances) const; - void CloseInstanceContainers(const AZStd::vector& instances) const; + void OpenInstanceContainers(const AZStd::vector& instances) const; + void CloseInstanceContainers(const AZStd::vector& instances) const; - //! The instance the editor is currently focusing on. - InstanceOptionalReference m_focusedInstance; + InstanceOptionalReference GetReferenceFromContainerEntityId(AZ::EntityId containerEntityId) const; + + //! The EntityId of the prefab container entity for the instance the editor is currently focusing on. + AZ::EntityId m_focusedInstanceContainerEntityId = AZ::EntityId(); //! The templateId of the focused instance. TemplateId m_focusedTemplateId; - //! The list of instances going from the root (index 0) to the focused instance. - AZStd::vector m_instanceFocusHierarchy; - //! A path containing the names of the containers in the instance focus hierarchy, separated with a /. + //! The list of instances going from the root (index 0) to the focused instance, + //! referenced by their prefab container's EntityId. + AZStd::vector m_instanceFocusHierarchy; + //! A path containing the filenames of the instances in the focus hierarchy, separated with a /. AZ::IO::Path m_instanceFocusPath; ContainerEntityInterface* m_containerEntityInterface = nullptr; diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/UI/PropertyEditor/PropertyAssetCtrl.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/UI/PropertyEditor/PropertyAssetCtrl.cpp index e97be57470..70e5aafe8a 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/UI/PropertyEditor/PropertyAssetCtrl.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/UI/PropertyEditor/PropertyAssetCtrl.cpp @@ -527,8 +527,8 @@ namespace AzToolsFramework m_errorButton = nullptr; } } - - void PropertyAssetCtrl::UpdateErrorButton(const AZStd::string& errorLog) + + void PropertyAssetCtrl::UpdateErrorButton() { if (m_errorButton) { @@ -543,12 +543,17 @@ namespace AzToolsFramework m_errorButton->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed); m_errorButton->setFixedSize(QSize(16, 16)); m_errorButton->setMouseTracking(true); - m_errorButton->setIcon(QIcon("Icons/PropertyEditor/error_icon.png")); + m_errorButton->setIcon(QIcon(":/PropertyEditor/Resources/error_icon.png")); m_errorButton->setToolTip("Show Errors"); // Insert the error button after the asset label qobject_cast(layout())->insertWidget(1, m_errorButton); } + } + + void PropertyAssetCtrl::UpdateErrorButtonWithLog(const AZStd::string& errorLog) + { + UpdateErrorButton(); // Connect pressed to opening the error dialog // Must capture this for call to QObject::connect @@ -587,6 +592,21 @@ namespace AzToolsFramework logDialog->show(); }); } + + void PropertyAssetCtrl::UpdateErrorButtonWithMessage(const AZStd::string& message) + { + UpdateErrorButton(); + + connect(m_errorButton, &QPushButton::clicked, this, [this, message]() { + QMessageBox::critical(nullptr, "Error", message.c_str()); + + // Without this, the error button would maintain focus after clicking, which left the red error icon in a blue-highlighted state + if (parentWidget()) + { + parentWidget()->setFocus(); + } + }); + } void PropertyAssetCtrl::ClearAssetInternal() { @@ -960,7 +980,6 @@ namespace AzToolsFramework else { const AZ::Data::AssetId assetID = GetCurrentAssetID(); - m_currentAssetHint = ""; AZ::Outcome jobOutcome = AZ::Failure(); AssetSystemJobRequestBus::BroadcastResult(jobOutcome, &AssetSystemJobRequestBus::Events::GetAssetJobsInfoByAssetID, assetID, false, false); @@ -1018,7 +1037,7 @@ namespace AzToolsFramework // In case of failure, render failure icon case AssetSystem::JobStatus::Failed: { - UpdateErrorButton(errorLog); + UpdateErrorButtonWithLog(errorLog); } break; @@ -1043,6 +1062,10 @@ namespace AzToolsFramework m_currentAssetHint = assetPath; } } + else + { + UpdateErrorButtonWithMessage(AZStd::string::format("Asset is missing.\n\nID: %s\nHint:%s", assetID.ToString().c_str(), GetCurrentAssetHint().c_str())); + } } // Get the asset file name diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/UI/PropertyEditor/PropertyAssetCtrl.hxx b/Code/Framework/AzToolsFramework/AzToolsFramework/UI/PropertyEditor/PropertyAssetCtrl.hxx index 0b98278bc5..58ddbb967e 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/UI/PropertyEditor/PropertyAssetCtrl.hxx +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/UI/PropertyEditor/PropertyAssetCtrl.hxx @@ -168,7 +168,9 @@ namespace AzToolsFramework bool IsCorrectMimeData(const QMimeData* pData, AZ::Data::AssetId* pAssetId = nullptr, AZ::Data::AssetType* pAssetType = nullptr) const; void ClearErrorButton(); - void UpdateErrorButton(const AZStd::string& errorLog); + void UpdateErrorButton(); + void UpdateErrorButtonWithLog(const AZStd::string& errorLog); + void UpdateErrorButtonWithMessage(const AZStd::string& message); virtual const AZStd::string GetFolderSelection() const { return AZStd::string(); } virtual void SetFolderSelection(const AZStd::string& /* folderPath */) {} virtual void ClearAssetInternal(); diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/UnitTest/AzToolsFrameworkTestHelpers.h b/Code/Framework/AzToolsFramework/AzToolsFramework/UnitTest/AzToolsFrameworkTestHelpers.h index 4a7039423c..1e29f1dbce 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/UnitTest/AzToolsFrameworkTestHelpers.h +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/UnitTest/AzToolsFrameworkTestHelpers.h @@ -158,7 +158,10 @@ namespace UnitTest { // Create & Start a new ToolsApplication if there's no existing one m_app = CreateTestApplication(); - m_app->Start(AzFramework::Application::Descriptor()); + AZ::ComponentApplication::StartupParameters startupParameters; + startupParameters.m_loadAssetCatalog = false; + + m_app->Start(AzFramework::Application::Descriptor(), startupParameters); } // without this, the user settings component would attempt to save on finalize/shutdown. Since the file is diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Viewport/ViewportMessages.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/Viewport/ViewportMessages.cpp index e3b45aca2b..8f8bd3e3f9 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Viewport/ViewportMessages.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Viewport/ViewportMessages.cpp @@ -6,6 +6,7 @@ * */ +#include #include namespace AzToolsFramework @@ -62,4 +63,33 @@ namespace AzToolsFramework return circleBoundWidth; } + + AZ::Vector3 FindClosestPickIntersection( + AzFramework::ViewportId viewportId, const AzFramework::ScreenPoint& screenPoint, const float rayLength, const float defaultDistance) + { + using AzToolsFramework::ViewportInteraction::ViewportInteractionRequestBus; + AzToolsFramework::ViewportInteraction::ProjectedViewportRay viewportRay{}; + ViewportInteractionRequestBus::EventResult( + viewportRay, viewportId, &ViewportInteractionRequestBus::Events::ViewportScreenToWorldRay, screenPoint); + + AzFramework::RenderGeometry::RayRequest ray; + ray.m_startWorldPosition = viewportRay.origin; + ray.m_endWorldPosition = viewportRay.origin + viewportRay.direction * rayLength; + ray.m_onlyVisible = true; + + AzFramework::RenderGeometry::RayResult renderGeometryIntersectionResult; + AzFramework::RenderGeometry::IntersectorBus::EventResult( + renderGeometryIntersectionResult, AzToolsFramework::GetEntityContextId(), + &AzFramework::RenderGeometry::IntersectorBus::Events::RayIntersect, ray); + + // attempt a ray intersection with any visible mesh and return the intersection position if successful + if (renderGeometryIntersectionResult) + { + return renderGeometryIntersectionResult.m_worldPosition; + } + else + { + return viewportRay.origin + viewportRay.direction * defaultDistance; + } + } } // namespace AzToolsFramework diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Viewport/ViewportMessages.h b/Code/Framework/AzToolsFramework/AzToolsFramework/Viewport/ViewportMessages.h index 8ec772f0da..aa97eb361e 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Viewport/ViewportMessages.h +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Viewport/ViewportMessages.h @@ -162,12 +162,11 @@ namespace AzToolsFramework //! Multiply by DeviceScalingFactor to get the position in viewport pixel space. virtual AzFramework::ScreenPoint ViewportWorldToScreen(const AZ::Vector3& worldPosition) = 0; //! Transforms a point from Qt widget screen space to world space based on the given clip space depth. - //! Depth specifies a relative camera depth to project in the range of [0.f, 1.f]. //! Returns the world space position if successful. - virtual AZStd::optional ViewportScreenToWorld(const AzFramework::ScreenPoint& screenPosition, float depth) = 0; + virtual AZ::Vector3 ViewportScreenToWorld(const AzFramework::ScreenPoint& screenPosition) = 0; //! Casts a point in screen space to a ray in world space originating from the viewport camera frustum's near plane. //! Returns a ray containing the ray's origin and a direction normal, if successful. - virtual AZStd::optional ViewportScreenToWorldRay(const AzFramework::ScreenPoint& screenPosition) = 0; + virtual ProjectedViewportRay ViewportScreenToWorldRay(const AzFramework::ScreenPoint& screenPosition) = 0; //! Gets the DPI scaling factor that translates Qt widget space into viewport pixel space. virtual float DeviceScalingFactor() = 0; @@ -229,9 +228,6 @@ namespace AzToolsFramework class MainEditorViewportInteractionRequests { public: - //! Given a point in screen space, return the picked entity (if any). - //! Picked EntityId will be returned, InvalidEntityId will be returned on failure. - virtual AZ::EntityId PickEntity(const AzFramework::ScreenPoint& point) = 0; //! Given a point in screen space, return the terrain position in world space. virtual AZ::Vector3 PickTerrain(const AzFramework::ScreenPoint& point) = 0; //! Return the terrain height given a world position in 2d (xy plane). @@ -266,7 +262,6 @@ namespace AzToolsFramework { public: static const AZ::EBusAddressPolicy AddressPolicy = AZ::EBusAddressPolicy::Single; - static const AZ::EBusHandlerPolicy HandlerPolicy = AZ::EBusHandlerPolicy::Single; //! Returns the current state of the keyboard modifier keys. virtual KeyboardModifiers QueryKeyboardModifiers() = 0; @@ -290,7 +285,6 @@ namespace AzToolsFramework { public: static const AZ::EBusAddressPolicy AddressPolicy = AZ::EBusAddressPolicy::Single; - static const AZ::EBusHandlerPolicy HandlerPolicy = AZ::EBusHandlerPolicy::Single; //! Returns the current time in seconds. //! This interface can be overridden for the purposes of testing to simplify viewport input requests. @@ -340,6 +334,12 @@ namespace AzToolsFramework return entityContextId; } + //! Performs an intersection test against meshes in the scene, if there is a hit (the ray intersects + //! a mesh), that position is returned, otherwise a point projected defaultDistance from the + //! origin of the ray will be returned. + AZ::Vector3 FindClosestPickIntersection( + AzFramework::ViewportId viewportId, const AzFramework::ScreenPoint& screenPoint, float rayLength, float defaultDistance); + //! Maps a mouse interaction event to a ClickDetector event. //! @note Function only cares about up or down events, all other events are mapped to Nil (ignored). AzFramework::ClickDetector::ClickEvent ClickDetectorEventFromViewportInteraction( diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportSelection/EditorHelpers.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportSelection/EditorHelpers.cpp index 0f94b95e5f..ee30b9e29d 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportSelection/EditorHelpers.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportSelection/EditorHelpers.cpp @@ -148,7 +148,6 @@ namespace AzToolsFramework return false; } - EditorHelpers::EditorHelpers(const EditorVisibleEntityDataCache* entityDataCache) : m_entityDataCache(entityDataCache) { @@ -190,7 +189,10 @@ namespace AzToolsFramework if (helpersVisible) { // some components choose to hide their icons (e.g. meshes) - if (!m_entityDataCache->IsVisibleEntityIconHidden(entityCacheIndex)) + // we also do not want to test against icons that may not be showing as they're inside a 'closed' entity container + // (these icons only become visible when it is opened for editing) + if (!m_entityDataCache->IsVisibleEntityIconHidden(entityCacheIndex) && + m_entityDataCache->IsVisibleEntityIndividuallySelectableInViewport(entityCacheIndex)) { const AZ::Vector3& entityPosition = m_entityDataCache->GetVisibleEntityPosition(entityCacheIndex); @@ -235,7 +237,7 @@ namespace AzToolsFramework viewportId, &ViewportInteraction::ViewportMouseCursorRequestBus::Events::SetOverrideCursor, ViewportInteraction::CursorStyleOverride::Forbidden); } - + if (mouseInteraction.m_mouseInteraction.m_mouseButtons.Left() && mouseInteraction.m_mouseEvent == ViewportInteraction::MouseEvent::Down || mouseInteraction.m_mouseEvent == ViewportInteraction::MouseEvent::DoubleClick) diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportSelection/EditorSelectionUtil.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportSelection/EditorSelectionUtil.cpp index a5ef66e7a3..0a7bed6b18 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportSelection/EditorSelectionUtil.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportSelection/EditorSelectionUtil.cpp @@ -18,9 +18,6 @@ namespace AzToolsFramework { - // default ray length for picking in the viewport - static const float EditorPickRayLength = 1000.0f; - AZ::Vector3 CalculateCenterOffset(const AZ::EntityId entityId, const EditorTransformComponentSelectionRequests::Pivot pivot) { if (Centered(pivot)) diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportSelection/EditorSelectionUtil.h b/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportSelection/EditorSelectionUtil.h index d58549b329..5c9f47fdd3 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportSelection/EditorSelectionUtil.h +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportSelection/EditorSelectionUtil.h @@ -26,6 +26,9 @@ namespace AzFramework namespace AzToolsFramework { + //! Default ray length for picking in the viewport. + inline constexpr float EditorPickRayLength = 1000.0f; + //! Is the pivot at the center of the object (middle of extents) or at the //! exported authored object root position. inline bool Centered(const EditorTransformComponentSelectionRequests::Pivot pivot) diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportSelection/EditorTransformComponentSelection.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportSelection/EditorTransformComponentSelection.cpp index c16a458be7..9ac28cfd91 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportSelection/EditorTransformComponentSelection.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportSelection/EditorTransformComponentSelection.cpp @@ -27,6 +27,7 @@ #include #include #include +#include #include #include #include @@ -409,7 +410,7 @@ namespace AzToolsFramework const AzFramework::CameraState cameraState = GetCameraState(viewportId); for (size_t entityCacheIndex = 0; entityCacheIndex < entityDataCache.VisibleEntityDataCount(); ++entityCacheIndex) { - if (!entityDataCache.IsVisibleEntitySelectableInViewport(entityCacheIndex)) + if (!entityDataCache.IsVisibleEntityIndividuallySelectableInViewport(entityCacheIndex)) { continue; } @@ -983,7 +984,7 @@ namespace AzToolsFramework { if (auto entityIndex = entityDataCache.GetVisibleEntityIndexFromId(entityId)) { - if (entityDataCache.IsVisibleEntitySelectableInViewport(*entityIndex)) + if (entityDataCache.IsVisibleEntityIndividuallySelectableInViewport(*entityIndex)) { return *entityIndex; } @@ -1014,6 +1015,15 @@ namespace AzToolsFramework ToolsApplicationNotificationBus::Broadcast(&ToolsApplicationNotificationBus::Events::InvalidatePropertyDisplay, Refresh_Values); } + // leaves focus mode by focusing on the parent of the current perfab in the entity outliner + static void LeaveFocusMode() + { + if (auto prefabFocusPublicInterface = AZ::Interface::Get()) + { + prefabFocusPublicInterface->FocusOnParentOfFocusedPrefab(GetEntityContextId()); + } + } + EditorTransformComponentSelection::EditorTransformComponentSelection(const EditorVisibleEntityDataCache* entityDataCache) : m_entityDataCache(entityDataCache) { @@ -3674,7 +3684,8 @@ namespace AzToolsFramework case ViewportEditorMode::Focus: { ViewportUi::ViewportUiRequestBus::Event( - ViewportUi::DefaultViewportId, &ViewportUi::ViewportUiRequestBus::Events::CreateViewportBorder, "Focus Mode"); + ViewportUi::DefaultViewportId, &ViewportUi::ViewportUiRequestBus::Events::CreateViewportBorder, "Focus Mode", + LeaveFocusMode); } break; case ViewportEditorMode::Default: @@ -3703,12 +3714,14 @@ namespace AzToolsFramework if (editorModeState.IsModeActive(ViewportEditorMode::Focus)) { ViewportUi::ViewportUiRequestBus::Event( - ViewportUi::DefaultViewportId, &ViewportUi::ViewportUiRequestBus::Events::CreateViewportBorder, "Focus Mode"); + ViewportUi::DefaultViewportId, &ViewportUi::ViewportUiRequestBus::Events::CreateViewportBorder, "Focus Mode", + LeaveFocusMode); } } break; case ViewportEditorMode::Focus: { + ViewportUi::ViewportUiRequestBus::Event( ViewportUi::DefaultViewportId, &ViewportUi::ViewportUiRequestBus::Events::RemoveViewportBorder); } diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportSelection/EditorVisibleEntityDataCache.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportSelection/EditorVisibleEntityDataCache.cpp index 328cfc3ae5..58c25b944c 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportSelection/EditorVisibleEntityDataCache.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportSelection/EditorVisibleEntityDataCache.cpp @@ -293,12 +293,10 @@ namespace AzToolsFramework return m_impl->m_visibleEntityDatas[index].m_iconHidden; } - bool EditorVisibleEntityDataCache::IsVisibleEntitySelectableInViewport(size_t index) const + bool EditorVisibleEntityDataCache::IsVisibleEntityIndividuallySelectableInViewport(const size_t index) const { - return m_impl->m_visibleEntityDatas[index].m_visible - && !m_impl->m_visibleEntityDatas[index].m_locked - && m_impl->m_visibleEntityDatas[index].m_inFocus - && !m_impl->m_visibleEntityDatas[index].m_descendantOfClosedContainer; + return m_impl->m_visibleEntityDatas[index].m_visible && !m_impl->m_visibleEntityDatas[index].m_locked && + m_impl->m_visibleEntityDatas[index].m_inFocus && !m_impl->m_visibleEntityDatas[index].m_descendantOfClosedContainer; } AZStd::optional EditorVisibleEntityDataCache::GetVisibleEntityIndexFromId(const AZ::EntityId entityId) const diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportSelection/EditorVisibleEntityDataCache.h b/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportSelection/EditorVisibleEntityDataCache.h index 16fa1b6d14..4262d334df 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportSelection/EditorVisibleEntityDataCache.h +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportSelection/EditorVisibleEntityDataCache.h @@ -55,7 +55,10 @@ namespace AzToolsFramework bool IsVisibleEntityVisible(size_t index) const; bool IsVisibleEntitySelected(size_t index) const; bool IsVisibleEntityIconHidden(size_t index) const; - bool IsVisibleEntitySelectableInViewport(size_t index) const; + //! Returns true if the entity is individually selectable (none of its ancestors are a closed container entity). + //! @note It may still be desirable to be able to 'click' an entity that is a descendant of a closed container + //! to select the container itself, not the individual entity. + bool IsVisibleEntityIndividuallySelectableInViewport(size_t index) const; AZStd::optional GetVisibleEntityIndexFromId(AZ::EntityId entityId) const; diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportUi/ViewportUiCluster.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportUi/ViewportUiCluster.cpp index bc299f9985..365ba237db 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportUi/ViewportUiCluster.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportUi/ViewportUiCluster.cpp @@ -62,9 +62,6 @@ namespace AzToolsFramework::ViewportUi::Internal return; } - // set hover to true by default - action->setProperty("IconHasHoverEffect", true); - // add the action addAction(action); diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportUi/ViewportUiDisplay.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportUi/ViewportUiDisplay.cpp index b948a18578..c1bddbe3c3 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportUi/ViewportUiDisplay.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportUi/ViewportUiDisplay.cpp @@ -20,7 +20,9 @@ namespace AzToolsFramework::ViewportUi::Internal { const static int HighlightBorderSize = 5; - const static char* HighlightBorderColor = "#4A90E2"; + const static char* const HighlightBorderColor = "#4A90E2"; + const static int HighlightBorderBackButtonIconSize = 20; + const static char* const HighlightBorderBackButtonIconFile = "X_axis.svg"; static void UnparentWidgets(ViewportUiElementIdInfoLookup& viewportUiElementIdInfoLookup) { @@ -62,6 +64,7 @@ namespace AzToolsFramework::ViewportUi::Internal , m_fullScreenLayout(&m_uiOverlay) , m_uiOverlayLayout() , m_viewportBorderText(&m_uiOverlay) + , m_viewportBorderBackButton(&m_uiOverlay) { } @@ -254,7 +257,7 @@ namespace AzToolsFramework::ViewportUi::Internal auto viewportUiMapElement = m_viewportUiElements.find(elementId); if (viewportUiMapElement != m_viewportUiElements.end()) { - viewportUiMapElement->second.m_widget->setVisible(false); + viewportUiMapElement->second.m_widget->hide(); viewportUiMapElement->second.m_widget->setParent(nullptr); m_viewportUiElements.erase(viewportUiMapElement); } @@ -269,7 +272,7 @@ namespace AzToolsFramework::ViewportUi::Internal { if (ViewportUiElementInfo element = GetViewportUiElementInfo(elementId); element.m_widget) { - element.m_widget->setVisible(true); + element.m_widget->show(); } } @@ -277,7 +280,7 @@ namespace AzToolsFramework::ViewportUi::Internal { if (ViewportUiElementInfo element = GetViewportUiElementInfo(elementId); element.m_widget) { - element.m_widget->setVisible(false); + element.m_widget->hide(); } } @@ -291,27 +294,34 @@ namespace AzToolsFramework::ViewportUi::Internal return false; } - void ViewportUiDisplay::CreateViewportBorder(const AZStd::string& borderTitle) + void ViewportUiDisplay::CreateViewportBorder( + const AZStd::string& borderTitle, AZStd::optional backButtonCallback) { - const AZStd::string styleSheet = AZStd::string::format( - "border: %dpx solid %s; border-top: %dpx solid %s;", HighlightBorderSize, HighlightBorderColor, ViewportUiTopBorderSize, - HighlightBorderColor); - m_uiOverlay.setStyleSheet(styleSheet.c_str()); + m_uiOverlay.setStyleSheet(QString("border: %1px solid %2; border-top: %3px solid %4;") + .arg( + QString::number(HighlightBorderSize), HighlightBorderColor, + QString::number(ViewportUiTopBorderSize), HighlightBorderColor)); m_uiOverlayLayout.setContentsMargins( HighlightBorderSize + ViewportUiOverlayMargin, ViewportUiTopBorderSize + ViewportUiOverlayMargin, HighlightBorderSize + ViewportUiOverlayMargin, HighlightBorderSize + ViewportUiOverlayMargin); - m_viewportBorderText.setVisible(true); + m_viewportBorderText.show(); m_viewportBorderText.setText(borderTitle.c_str()); UpdateUiOverlayGeometry(); + + // only display the back button if a callback was provided + m_viewportBorderBackButtonCallback = backButtonCallback; + m_viewportBorderBackButton.setVisible(m_viewportBorderBackButtonCallback.has_value()); } void ViewportUiDisplay::RemoveViewportBorder() { - m_viewportBorderText.setVisible(false); + m_viewportBorderText.hide(); m_uiOverlay.setStyleSheet("border: none;"); m_uiOverlayLayout.setContentsMargins( ViewportUiOverlayMargin, ViewportUiOverlayMargin + ViewportUiOverlayTopMarginPadding, ViewportUiOverlayMargin, ViewportUiOverlayMargin); + m_viewportBorderBackButtonCallback.reset(); + m_viewportBorderBackButton.hide(); } void ViewportUiDisplay::PositionViewportUiElementFromWorldSpace(ViewportUiElementId elementId, const AZ::Vector3& pos) @@ -350,23 +360,46 @@ namespace AzToolsFramework::ViewportUi::Internal { m_uiMainWindow.setObjectName(QString("ViewportUiWindow")); ConfigureWindowForViewportUi(&m_uiMainWindow); - m_uiMainWindow.setVisible(false); + m_uiMainWindow.hide(); m_uiOverlay.setObjectName(QString("ViewportUiOverlay")); m_uiMainWindow.setCentralWidget(&m_uiOverlay); - m_uiOverlay.setVisible(false); + m_uiOverlay.hide(); // remove any spacing and margins from the UI Overlay Layout m_fullScreenLayout.setSpacing(0); m_fullScreenLayout.setContentsMargins(0, 0, 0, 0); m_fullScreenLayout.addLayout(&m_uiOverlayLayout, 0, 0, 1, 1); - // format the label which will appear on top of the highlight border - AZStd::string styleSheet = AZStd::string::format("background-color: %s; border: none;", HighlightBorderColor); - m_viewportBorderText.setStyleSheet(styleSheet.c_str()); + // style the label which will appear on top of the highlight border + m_viewportBorderText.setStyleSheet(QString("background-color: %1; border: none").arg(HighlightBorderColor)); m_viewportBorderText.setFixedHeight(ViewportUiTopBorderSize); - m_viewportBorderText.setVisible(false); + m_viewportBorderText.hide(); m_fullScreenLayout.addWidget(&m_viewportBorderText, 0, 0, Qt::AlignTop | Qt::AlignHCenter); + + m_viewportBorderBackButton.setAutoRaise(true); // hover highlight + m_viewportBorderBackButton.hide(); + + QIcon backButtonIcon(QString(":/stylesheet/img/UI20/toolbar/%1").arg(HighlightBorderBackButtonIconFile)); + m_viewportBorderBackButton.setIcon(backButtonIcon); + m_viewportBorderBackButton.setIconSize(QSize(HighlightBorderBackButtonIconSize, HighlightBorderBackButtonIconSize)); + + // setup the handler for the back button to call the user provided callback (if any) + QObject::connect( + &m_viewportBorderBackButton, &QToolButton::clicked, + [this] + { + if (m_viewportBorderBackButtonCallback.has_value()) + { + // we need to swap out the existing back button callback because it will be reset in RemoveViewportBorder() + // so preserve the lifetime with this temporary callback until after the call to RemoveViewportBorder() + AZStd::optional backButtonCallback; + m_viewportBorderBackButtonCallback.swap(backButtonCallback); + RemoveViewportBorder(); + (*backButtonCallback)(); + } + }); + m_fullScreenLayout.addWidget(&m_viewportBorderBackButton, 0, 0, Qt::AlignTop | Qt::AlignRight); } void ViewportUiDisplay::PrepareWidgetForViewportUi(QPointer widget) @@ -414,16 +447,9 @@ namespace AzToolsFramework::ViewportUi::Internal region += m_uiOverlay.childrenRegion(); // set viewport ui visibility depending on if elements are present - if (region.isEmpty() || !UiDisplayEnabled()) - { - m_uiMainWindow.setVisible(false); - m_uiOverlay.setVisible(false); - } - else - { - m_uiMainWindow.setVisible(true); - m_uiOverlay.setVisible(true); - } + const bool visible = !region.isEmpty() && UiDisplayEnabled(); + m_uiMainWindow.setVisible(visible); + m_uiOverlay.setVisible(visible); m_uiMainWindow.setMask(region); } diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportUi/ViewportUiDisplay.h b/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportUi/ViewportUiDisplay.h index 32b746a1ac..dba0f25830 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportUi/ViewportUiDisplay.h +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportUi/ViewportUiDisplay.h @@ -17,6 +17,7 @@ #include #include #include +#include AZ_PUSH_DISABLE_WARNING(4251, "-Wunknown-warning-option") #include @@ -89,7 +90,7 @@ namespace AzToolsFramework::ViewportUi::Internal AZStd::shared_ptr GetViewportUiElement(ViewportUiElementId elementId); bool IsViewportUiElementVisible(ViewportUiElementId elementId); - void CreateViewportBorder(const AZStd::string& borderTitle); + void CreateViewportBorder(const AZStd::string& borderTitle, AZStd::optional backButtonCallback); void RemoveViewportBorder(); private: @@ -113,7 +114,10 @@ namespace AzToolsFramework::ViewportUi::Internal QWidget m_uiOverlay; //!< The UI Overlay which displays Viewport UI Elements. QGridLayout m_fullScreenLayout; //!< The layout which extends across the full screen. ViewportUiDisplayLayout m_uiOverlayLayout; //!< The layout used for optionally anchoring Viewport UI Elements. - QLabel m_viewportBorderText; //!< The text used for the viewport border. + QLabel m_viewportBorderText; //!< The text used for the viewport highlight border. + QToolButton m_viewportBorderBackButton; //!< The button to return from the viewport highlight border (only displayed if callback provided). + //! The optional callback for when the viewport highlight border back button is pressed. + AZStd::optional m_viewportBorderBackButtonCallback; QWidget* m_renderOverlay; QPointer m_fullScreenWidget; //!< Reference to the widget attached to m_fullScreenLayout if any. diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportUi/ViewportUiManager.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportUi/ViewportUiManager.cpp index 1f14b12b7d..143da34074 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportUi/ViewportUiManager.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportUi/ViewportUiManager.cpp @@ -240,9 +240,10 @@ namespace AzToolsFramework::ViewportUi } } - void ViewportUiManager::CreateViewportBorder(const AZStd::string& borderTitle) + void ViewportUiManager::CreateViewportBorder( + const AZStd::string& borderTitle, AZStd::optional backButtonCallback) { - m_viewportUi->CreateViewportBorder(borderTitle); + m_viewportUi->CreateViewportBorder(borderTitle, backButtonCallback); } void ViewportUiManager::RemoveViewportBorder() diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportUi/ViewportUiManager.h b/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportUi/ViewportUiManager.h index ce7e5aafe9..54f1eb5a57 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportUi/ViewportUiManager.h +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportUi/ViewportUiManager.h @@ -50,7 +50,8 @@ namespace AzToolsFramework::ViewportUi void RegisterTextFieldCallback(TextFieldId textFieldId, AZ::Event::Handler& handler) override; void RemoveTextField(TextFieldId textFieldId) override; void SetTextFieldVisible(TextFieldId textFieldId, bool visible) override; - void CreateViewportBorder(const AZStd::string& borderTitle) override; + void CreateViewportBorder( + const AZStd::string& borderTitle, AZStd::optional backButtonCallback) override; void RemoveViewportBorder() override; void PressButton(ClusterId clusterId, ButtonId buttonId) override; void PressButton(SwitcherId switcherId, ButtonId buttonId) override; diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportUi/ViewportUiRequestBus.h b/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportUi/ViewportUiRequestBus.h index 3c6f7094cb..9ac6feb8c8 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportUi/ViewportUiRequestBus.h +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportUi/ViewportUiRequestBus.h @@ -22,6 +22,9 @@ namespace AzToolsFramework::ViewportUi using SwitcherId = IdType; using TextFieldId = IdType; + //! Callback function for viewport UI back button. + using ViewportUiBackButtonCallback = AZStd::function; + inline const ViewportUiElementId InvalidViewportUiElementId = ViewportUiElementId(0); inline const ButtonId InvalidButtonId = ButtonId(0); inline const ClusterId InvalidClusterId = ClusterId(0); @@ -95,9 +98,9 @@ namespace AzToolsFramework::ViewportUi virtual void RemoveTextField(TextFieldId textFieldId) = 0; //! Sets the visibility of the text field. virtual void SetTextFieldVisible(TextFieldId textFieldId, bool visible) = 0; - //! Create the highlight border for Component Mode. - virtual void CreateViewportBorder(const AZStd::string& borderTitle) = 0; - //! Remove the highlight border for Component Mode. + //! Create the highlight border with optional back button to exit the given editor mode. + virtual void CreateViewportBorder(const AZStd::string& borderTitle, AZStd::optional backButtonCallback) = 0; + //! Remove the highlight border. virtual void RemoveViewportBorder() = 0; //! Invoke a button press on a cluster. virtual void PressButton(ClusterId clusterId, ButtonId buttonId) = 0; diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportUi/ViewportUiSwitcher.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportUi/ViewportUiSwitcher.cpp index 6b8b1873f7..c4be11ac66 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportUi/ViewportUiSwitcher.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportUi/ViewportUiSwitcher.cpp @@ -22,8 +22,6 @@ namespace AzToolsFramework::ViewportUi::Internal // Add am empty active button (is set in the call to SetActiveMode) m_activeButton = new QToolButton(); - // No hover effect for the main button as it's not clickable - m_activeButton->setProperty("IconHasHoverEffect", false); m_activeButton->setCheckable(false); m_activeButton->setToolButtonStyle(Qt::ToolButtonTextBesideIcon); addWidget(m_activeButton); @@ -56,9 +54,6 @@ namespace AzToolsFramework::ViewportUi::Internal return; } - // set hover to true by default - action->setProperty("IconHasHoverEffect", true); - // add the action addAction(action); diff --git a/Code/Framework/AzToolsFramework/Tests/BoundsTestComponent.cpp b/Code/Framework/AzToolsFramework/Tests/BoundsTestComponent.cpp index 1aa7b39593..fa5a6b344a 100644 --- a/Code/Framework/AzToolsFramework/Tests/BoundsTestComponent.cpp +++ b/Code/Framework/AzToolsFramework/Tests/BoundsTestComponent.cpp @@ -40,6 +40,9 @@ namespace UnitTest { AzFramework::BoundsRequestBus::Handler::BusConnect(GetEntityId()); AzToolsFramework::EditorComponentSelectionRequestsBus::Handler::BusConnect(GetEntityId()); + + // default local bounds to unit cube + m_localBounds = AZ::Aabb::CreateFromMinMax(AZ::Vector3(-0.5f), AZ::Vector3(0.5f)); } void BoundsTestComponent::Deactivate() @@ -57,7 +60,6 @@ namespace UnitTest AZ::Aabb BoundsTestComponent::GetLocalBounds() { - return AZ::Aabb::CreateFromMinMax(AZ::Vector3(-0.5f), AZ::Vector3(0.5f)); + return m_localBounds; } - } // namespace UnitTest diff --git a/Code/Framework/AzToolsFramework/Tests/BoundsTestComponent.h b/Code/Framework/AzToolsFramework/Tests/BoundsTestComponent.h index 036f9c8798..358a9f810a 100644 --- a/Code/Framework/AzToolsFramework/Tests/BoundsTestComponent.h +++ b/Code/Framework/AzToolsFramework/Tests/BoundsTestComponent.h @@ -41,5 +41,7 @@ namespace UnitTest // BoundsRequestBus overrides ... AZ::Aabb GetWorldBounds() override; AZ::Aabb GetLocalBounds() override; + + AZ::Aabb m_localBounds; //!< Local bounds that can be modified for certain tests (defaults to unit cube). }; } // namespace UnitTest diff --git a/Code/Framework/AzToolsFramework/Tests/EditorTransformComponentSelectionTests.cpp b/Code/Framework/AzToolsFramework/Tests/EditorTransformComponentSelectionTests.cpp index 81909ac511..4f4c3eb456 100644 --- a/Code/Framework/AzToolsFramework/Tests/EditorTransformComponentSelectionTests.cpp +++ b/Code/Framework/AzToolsFramework/Tests/EditorTransformComponentSelectionTests.cpp @@ -38,7 +38,7 @@ #include #include -#include +#include namespace AZ { @@ -493,12 +493,8 @@ namespace UnitTest /////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Then - AzToolsFramework::EntityIdList selectedEntities; - AzToolsFramework::ToolsApplicationRequestBus::BroadcastResult( - selectedEntities, &AzToolsFramework::ToolsApplicationRequestBus::Events::GetSelectedEntities); - - AzToolsFramework::EntityIdList expectedSelectedEntities = { entity4, entity5, entity6 }; - + const AzToolsFramework::EntityIdList selectedEntities = SelectedEntities(); + const AzToolsFramework::EntityIdList expectedSelectedEntities = { entity4, entity5, entity6 }; EXPECT_THAT(selectedEntities, UnorderedElementsAreArray(expectedSelectedEntities)); /////////////////////////////////////////////////////////////////////////////////////////////////////////////// } @@ -527,12 +523,8 @@ namespace UnitTest /////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Then - AzToolsFramework::EntityIdList selectedEntities; - AzToolsFramework::ToolsApplicationRequestBus::BroadcastResult( - selectedEntities, &AzToolsFramework::ToolsApplicationRequestBus::Events::GetSelectedEntities); - - AzToolsFramework::EntityIdList expectedSelectedEntities = { m_entityId1, entity2, entity3, entity4 }; - + const AzToolsFramework::EntityIdList selectedEntities = SelectedEntities(); + const AzToolsFramework::EntityIdList expectedSelectedEntities = { m_entityId1, entity2, entity3, entity4 }; EXPECT_THAT(selectedEntities, UnorderedElementsAreArray(expectedSelectedEntities)); /////////////////////////////////////////////////////////////////////////////////////////////////////////////// } @@ -946,6 +938,42 @@ namespace UnitTest EXPECT_THAT(selectedEntitiesAfter, UnorderedElementsAre(m_entityId1)); } + TEST_F( + EditorTransformComponentSelectionViewportPickingManipulatorTestFixture, BoundsBetweenCameraAndNearClipPlaneDoesNotIntersectMouseRay) + { + // move camera to 10 units along the y-axis + AzFramework::SetCameraTransform(m_cameraState, AZ::Transform::CreateTranslation(AZ::Vector3::CreateAxisY(10.0f))); + + // send a very narrow bounds for entity1 + AZ::Entity* entity1 = AzToolsFramework::GetEntityById(m_entityId1); + auto* boundTestComponent = entity1->FindComponent(); + boundTestComponent->m_localBounds = + AZ::Aabb::CreateFromMinMax(AZ::Vector3(-0.5f, -0.0025f, -0.5f), AZ::Vector3(0.5f, 0.0025f, 0.5f)); + + // move entity1 in front of the camera between it and the near clip plane + AZ::TransformBus::Event( + m_entityId1, &AZ::TransformBus::Events::SetWorldTM, AZ::Transform::CreateTranslation(AZ::Vector3::CreateAxisY(10.05f))); + // move entity2 behind entity1 + AZ::TransformBus::Event( + m_entityId2, &AZ::TransformBus::Events::SetWorldTM, AZ::Transform::CreateTranslation(AZ::Vector3::CreateAxisY(15.0f))); + + const auto entity2ScreenPosition = AzFramework::WorldToScreen(AzToolsFramework::GetWorldTranslation(m_entityId2), m_cameraState); + + // click the entity in the viewport + m_actionDispatcher->SetStickySelect(true) + ->CameraState(m_cameraState) + ->MousePosition(entity2ScreenPosition) + ->CameraState(m_cameraState) + ->MouseLButtonDown() + ->MouseLButtonUp(); + + // ensure entity1 is not selected as it is before the near clip plane + using ::testing::UnorderedElementsAreArray; + const AzToolsFramework::EntityIdList selectedEntities = SelectedEntities(); + const AzToolsFramework::EntityIdList expectedSelectedEntities = { m_entityId2 }; + EXPECT_THAT(selectedEntities, UnorderedElementsAreArray(expectedSelectedEntities)); + } + class EditorTransformComponentSelectionViewportPickingManipulatorTestFixtureParam : public EditorTransformComponentSelectionViewportPickingManipulatorTestFixture , public ::testing::WithParamInterface diff --git a/Code/Framework/AzToolsFramework/Tests/EditorVertexSelectionTests.cpp b/Code/Framework/AzToolsFramework/Tests/EditorVertexSelectionTests.cpp index d08c9646a2..93010aa63d 100644 --- a/Code/Framework/AzToolsFramework/Tests/EditorVertexSelectionTests.cpp +++ b/Code/Framework/AzToolsFramework/Tests/EditorVertexSelectionTests.cpp @@ -23,6 +23,7 @@ #include #include #include +#include using namespace AzToolsFramework; diff --git a/Code/Framework/AzToolsFramework/Tests/Prefab/PrefabFocus/PrefabFocusTests.cpp b/Code/Framework/AzToolsFramework/Tests/Prefab/PrefabFocus/PrefabFocusTests.cpp index 86c73e72e5..6bf964f038 100644 --- a/Code/Framework/AzToolsFramework/Tests/Prefab/PrefabFocus/PrefabFocusTests.cpp +++ b/Code/Framework/AzToolsFramework/Tests/Prefab/PrefabFocus/PrefabFocusTests.cpp @@ -106,7 +106,9 @@ namespace UnitTest inline static const char* Passenger2EntityName = "Passenger2"; }; - TEST_F(PrefabFocusTests, PrefabFocus_FocusOnOwningPrefab_RootContainer) + // Test was disabled because the implementation of GetFocusedPrefabInstance now relies on the Prefab EOS, + // which is not used by our test environment. This can be restored once Instance handles are implemented. + TEST_F(PrefabFocusTests, DISABLED_PrefabFocus_FocusOnOwningPrefab_RootContainer) { // Verify FocusOnOwningPrefab works when passing the container entity of the root prefab. { @@ -121,7 +123,9 @@ namespace UnitTest } } - TEST_F(PrefabFocusTests, PrefabFocus_FocusOnOwningPrefab_RootEntity) + // Test was disabled because the implementation of GetFocusedPrefabInstance now relies on the Prefab EOS, + // which is not used by our test environment. This can be restored once Instance handles are implemented. + TEST_F(PrefabFocusTests, DISABLED_PrefabFocus_FocusOnOwningPrefab_RootEntity) { // Verify FocusOnOwningPrefab works when passing a nested entity of the root prefab. { diff --git a/Code/Framework/AzToolsFramework/Tests/Viewport/ViewportScreenTests.cpp b/Code/Framework/AzToolsFramework/Tests/Viewport/ViewportScreenTests.cpp index e8fce6653f..58c28f8568 100644 --- a/Code/Framework/AzToolsFramework/Tests/Viewport/ViewportScreenTests.cpp +++ b/Code/Framework/AzToolsFramework/Tests/Viewport/ViewportScreenTests.cpp @@ -17,6 +17,7 @@ #include #include #include +#include namespace UnitTest { @@ -35,6 +36,7 @@ namespace UnitTest const auto worldResult = AzFramework::ScreenToWorld(screenPoint, cameraState); return AzFramework::WorldToScreen(worldResult, cameraState); } + //////////////////////////////////////////////////////////////////////////////////////////////////////// // ScreenPoint tests TEST(ViewportScreen, WorldToScreenAndScreenToWorldReturnsTheSameValueIdentityCameraOffsetFromOrigin) @@ -102,8 +104,8 @@ namespace UnitTest } //////////////////////////////////////////////////////////////////////////////////////////////////////// - // NDC tests - TEST(ViewportScreen, WorldToScreenNDCAndScreenNDCToWorldReturnsTheSameValueIdentityCameraOffsetFromOrigin) + // Ndc tests + TEST(ViewportScreen, WorldToScreenNdcAndScreenNdcToWorldReturnsTheSameValueIdentityCameraOffsetFromOrigin) { using NdcPoint = AZ::Vector2; @@ -136,7 +138,7 @@ namespace UnitTest } } - TEST(ViewportScreen, WorldToScreenNDCAndScreenNDCToWorldReturnsTheSameValueOrientatedCamera) + TEST(ViewportScreen, WorldToScreenNdcAndScreenNdcToWorldReturnsTheSameValueOrientatedCamera) { using NdcPoint = AZ::Vector2; @@ -153,7 +155,7 @@ namespace UnitTest // note: nearClip is 0.1 - the world space value returned will be aligned to the near clip // plane of the camera so use that to confirm the mapping to/from is correct - TEST(ViewportScreen, ScreenNDCToWorldReturnsPositionOnNearClipPlaneInWorldSpace) + TEST(ViewportScreen, ScreenNdcToWorldReturnsPositionOnNearClipPlaneInWorldSpace) { using NdcPoint = AZ::Vector2; diff --git a/Code/Tools/AssetProcessor/AssetBuilderSDK/AssetBuilderSDK/AssetBuilderSDK.cpp b/Code/Tools/AssetProcessor/AssetBuilderSDK/AssetBuilderSDK/AssetBuilderSDK.cpp index f9b5d6aef7..b5323dd419 100644 --- a/Code/Tools/AssetProcessor/AssetBuilderSDK/AssetBuilderSDK/AssetBuilderSDK.cpp +++ b/Code/Tools/AssetProcessor/AssetBuilderSDK/AssetBuilderSDK/AssetBuilderSDK.cpp @@ -23,6 +23,8 @@ #include ////////////////////////////////////////////////////////////////////////// +#include + namespace AssetBuilderSDK { const char* const ErrorWindow = "Error"; //Use this window name to log error messages. @@ -1599,4 +1601,70 @@ namespace AssetBuilderSDK { return m_errorsOccurred; } + + AZ::u64 GetHashFromIOStream(AZ::IO::GenericStream& readStream, AZ::IO::SizeType* bytesReadOut, int hashMsDelay) + { + constexpr AZ::u64 HashBufferSize = 1024 * 64; + char buffer[HashBufferSize]; + + if(readStream.IsOpen() && readStream.CanRead()) + { + AZ::IO::SizeType bytesRead; + + auto* state = XXH64_createState(); + + if(state == nullptr) + { + AZ_Assert(false, "Failed to create hash state"); + return 0; + } + + if (XXH64_reset(state, 0) == XXH_ERROR) + { + AZ_Assert(false, "Failed to reset hash state"); + return 0; + } + + do + { + // In edge cases where another process is writing to this file while this hashing is occuring and that file wasn't locked, + // the following read check can fail because it performs an end of file check, and asserts and shuts down if the read size + // was smaller than the buffer and the read is not at the end of the file. The logic used to check end of file internal to read + // will be out of date in the edge cases where another process is actively writing to this file while this hash is running. + // The stream's length ends up more accurate in this case, preventing this assert and shut down. + // One area this occurs is the navigation mesh file (mnmnavmission0.bai) that's temporarily created when exporting a level, + // the navigation system can still be writing to this file when hashing begins, causing the EoF marker to change. + AZ::IO::SizeType remainingToRead = AZStd::min(readStream.GetLength() - readStream.GetCurPos(), aznumeric_cast(AZ_ARRAY_SIZE(buffer))); + bytesRead = readStream.Read(remainingToRead, buffer); + + if(bytesReadOut) + { + *bytesReadOut += bytesRead; + } + + XXH64_update(state, buffer, bytesRead); + + // Used by unit tests to force the race condition mentioned above, to verify the crash fix. + if(hashMsDelay > 0) + { + AZStd::this_thread::sleep_for(AZStd::chrono::milliseconds(hashMsDelay)); + } + + } while (bytesRead > 0); + + auto hash = XXH64_digest(state); + + XXH64_freeState(state); + + return hash; + } + return 0; + } + + AZ::u64 GetFileHash(const char* filePath, AZ::IO::SizeType* bytesReadOut, int hashMsDelay) + { + constexpr bool ErrorOnReadFailure = true; + AZ::IO::FileIOStream readStream(filePath, AZ::IO::OpenMode::ModeRead | AZ::IO::OpenMode::ModeBinary, ErrorOnReadFailure); + return GetHashFromIOStream(readStream, bytesReadOut, hashMsDelay); + } } diff --git a/Code/Tools/AssetProcessor/AssetBuilderSDK/AssetBuilderSDK/AssetBuilderSDK.h b/Code/Tools/AssetProcessor/AssetBuilderSDK/AssetBuilderSDK/AssetBuilderSDK.h index 5a57fa1e72..f977e15be9 100644 --- a/Code/Tools/AssetProcessor/AssetBuilderSDK/AssetBuilderSDK/AssetBuilderSDK.h +++ b/Code/Tools/AssetProcessor/AssetBuilderSDK/AssetBuilderSDK/AssetBuilderSDK.h @@ -911,6 +911,19 @@ namespace AssetBuilderSDK //! There can be multiple builders running at once, so we need to filter out ones coming from other builders AZStd::thread_id m_jobThreadId; }; + + //! Get hash for a whole file + //! @filePath the path for the file + //! @bytesReadOut output the read file size in bytes + //! @hashMsDelay [Do not use except for unit test] add a delay in ms for between each block reading. + AZ::u64 GetFileHash(const char* filePath, AZ::IO::SizeType* bytesReadOut = nullptr, int hashMsDelay = 0); + + //! Get hash for a generic IO stream + //! @readStream the input readable stream + //! @bytesReadOut output the read size in bytes + //! @hashMsDelay [Do not use except for unit test] add a delay in ms for between each block reading. + AZ::u64 GetHashFromIOStream(AZ::IO::GenericStream& readStream, AZ::IO::SizeType* bytesReadOut = nullptr, int hashMsDelay = 0); + } // namespace AssetBuilderSDK namespace AZ diff --git a/Code/Tools/AssetProcessor/AssetBuilderSDK/CMakeLists.txt b/Code/Tools/AssetProcessor/AssetBuilderSDK/CMakeLists.txt index 635cd55f6c..bfbcc35663 100644 --- a/Code/Tools/AssetProcessor/AssetBuilderSDK/CMakeLists.txt +++ b/Code/Tools/AssetProcessor/AssetBuilderSDK/CMakeLists.txt @@ -32,6 +32,7 @@ ly_add_target( PUBLIC AZ::AzFramework AZ::AzToolsFramework + 3rdParty::xxhash ) ly_add_source_properties( SOURCES AssetBuilderSDK/AssetBuilderSDK.cpp diff --git a/Code/Tools/AssetProcessor/Platform/Linux/native/FileWatcher/FileWatcher_linux.cpp b/Code/Tools/AssetProcessor/Platform/Linux/native/FileWatcher/FileWatcher_linux.cpp index 2d3e671999..b7f7affd6d 100644 --- a/Code/Tools/AssetProcessor/Platform/Linux/native/FileWatcher/FileWatcher_linux.cpp +++ b/Code/Tools/AssetProcessor/Platform/Linux/native/FileWatcher/FileWatcher_linux.cpp @@ -32,7 +32,8 @@ struct FolderRootWatch::PlatformImplementation { if (m_iNotifyHandle < 0) { - m_iNotifyHandle = inotify_init(); + // The CLOEXEC flag prevents the inotify watchers from copying on fork/exec + m_iNotifyHandle = inotify_init1(IN_CLOEXEC); } return (m_iNotifyHandle >= 0); } diff --git a/Code/Tools/AssetProcessor/native/utilities/assetUtils.cpp b/Code/Tools/AssetProcessor/native/utilities/assetUtils.cpp index cacd6c4cc9..340f5343bd 100644 --- a/Code/Tools/AssetProcessor/native/utilities/assetUtils.cpp +++ b/Code/Tools/AssetProcessor/native/utilities/assetUtils.cpp @@ -1161,7 +1161,7 @@ namespace AssetUtilities { #ifndef AZ_TESTS_ENABLED // Only used for unit tests, speed is critical for GetFileHash. - AZ_UNUSED(hashMsDelay); + hashMsDelay = 0; #endif bool useFileHashing = ShouldUseFileHashing(); @@ -1170,10 +1170,10 @@ namespace AssetUtilities return 0; } + AZ::u64 hash = 0; if(!force) { auto* fileStateInterface = AZ::Interface::Get(); - AZ::u64 hash = 0; if (fileStateInterface && fileStateInterface->GetHash(filePath, &hash)) { @@ -1181,64 +1181,8 @@ namespace AssetUtilities } } - char buffer[FileHashBufferSize]; - - constexpr bool ErrorOnReadFailure = true; - AZ::IO::FileIOStream readStream(filePath, AZ::IO::OpenMode::ModeRead | AZ::IO::OpenMode::ModeBinary, ErrorOnReadFailure); - - if(readStream.IsOpen() && readStream.CanRead()) - { - AZ::IO::SizeType bytesRead; - - auto* state = XXH64_createState(); - - if(state == nullptr) - { - AZ_Assert(false, "Failed to create hash state"); - return 0; - } - - if (XXH64_reset(state, 0) == XXH_ERROR) - { - AZ_Assert(false, "Failed to reset hash state"); - return 0; - } - - do - { - // In edge cases where another process is writing to this file while this hashing is occuring and that file wasn't locked, - // the following read check can fail because it performs an end of file check, and asserts and shuts down if the read size - // was smaller than the buffer and the read is not at the end of the file. The logic used to check end of file internal to read - // will be out of date in the edge cases where another process is actively writing to this file while this hash is running. - // The stream's length ends up more accurate in this case, preventing this assert and shut down. - // One area this occurs is the navigation mesh file (mnmnavmission0.bai) that's temporarily created when exporting a level, - // the navigation system can still be writing to this file when hashing begins, causing the EoF marker to change. - AZ::IO::SizeType remainingToRead = AZStd::min(readStream.GetLength() - readStream.GetCurPos(), aznumeric_cast(AZ_ARRAY_SIZE(buffer))); - bytesRead = readStream.Read(remainingToRead, buffer); - - if(bytesReadOut) - { - *bytesReadOut += bytesRead; - } - - XXH64_update(state, buffer, bytesRead); -#ifdef AZ_TESTS_ENABLED - // Used by unit tests to force the race condition mentioned above, to verify the crash fix. - if(hashMsDelay > 0) - { - AZStd::this_thread::sleep_for(AZStd::chrono::milliseconds(hashMsDelay)); - } -#endif - - } while (bytesRead > 0); - - auto hash = XXH64_digest(state); - - XXH64_freeState(state); - - return hash; - } - return 0; + hash = AssetBuilderSDK::GetFileHash(filePath, bytesReadOut, hashMsDelay); + return hash; } AZ::u64 AdjustTimestamp(QDateTime timestamp) diff --git a/Code/Tools/AssetProcessor/native/utilities/assetUtils.h b/Code/Tools/AssetProcessor/native/utilities/assetUtils.h index 2145c3e0e6..46ec5d6145 100644 --- a/Code/Tools/AssetProcessor/native/utilities/assetUtils.h +++ b/Code/Tools/AssetProcessor/native/utilities/assetUtils.h @@ -238,7 +238,6 @@ namespace AssetUtilities // hashMsDelay is only for automated tests to test that writing to a file while it's hashing does not cause a crash. // hashMsDelay is not used in non-unit test builds. AZ::u64 GetFileHash(const char* filePath, bool force = false, AZ::IO::SizeType* bytesReadOut = nullptr, int hashMsDelay = 0); - inline constexpr AZ::u64 FileHashBufferSize = 1024 * 64; //! Adjusts a timestamp to fix timezone settings and account for any precision adjustment needed AZ::u64 AdjustTimestamp(QDateTime timestamp); diff --git a/Code/Tools/ProjectManager/Resources/Backgrounds/DefaultBackground.jpg b/Code/Tools/ProjectManager/Resources/Backgrounds/DefaultBackground.jpg index 3af15393c4..0d2ec8a301 100644 --- a/Code/Tools/ProjectManager/Resources/Backgrounds/DefaultBackground.jpg +++ b/Code/Tools/ProjectManager/Resources/Backgrounds/DefaultBackground.jpg @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:342c3eaccf68a178dfd8c2b1792a93a8c9197c8184dca11bf90706d7481df087 -size 1611268 +oid sha256:e9ad0383f3b917fa7f4efa307a8e109a70bb5f66deb197189d013f60eb8dc32c +size 1010250 diff --git a/Code/Tools/ProjectManager/Resources/Backgrounds/FtueBackground.jpg b/Code/Tools/ProjectManager/Resources/Backgrounds/FtueBackground.jpg index 44291a8b1d..258dc62429 100644 --- a/Code/Tools/ProjectManager/Resources/Backgrounds/FtueBackground.jpg +++ b/Code/Tools/ProjectManager/Resources/Backgrounds/FtueBackground.jpg @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:797794816e4b1702f1ae1f32b408c95c79eb1f8a95aba43cfad9cccc181b0bda -size 1135182 +oid sha256:84aab95ec8a5e3ba6ecb3aff1a814afc3171a937aa658decd18c2740623bd172 +size 984146 diff --git a/Code/Tools/ProjectManager/Source/CreateProjectCtrl.cpp b/Code/Tools/ProjectManager/Source/CreateProjectCtrl.cpp index 6b19e839d7..205395c935 100644 --- a/Code/Tools/ProjectManager/Source/CreateProjectCtrl.cpp +++ b/Code/Tools/ProjectManager/Source/CreateProjectCtrl.cpp @@ -15,6 +15,7 @@ #include #include #include +#include #include #include diff --git a/Code/Tools/ProjectManager/Source/DownloadController.cpp b/Code/Tools/ProjectManager/Source/DownloadController.cpp index 06e51b5116..9b64c5e276 100644 --- a/Code/Tools/ProjectManager/Source/DownloadController.cpp +++ b/Code/Tools/ProjectManager/Source/DownloadController.cpp @@ -73,13 +73,25 @@ namespace O3DE::ProjectManager emit GemDownloadProgress(m_gemNames.front(), bytesDownloaded, totalBytes); } - void DownloadController::HandleResults(const QString& result) + void DownloadController::HandleResults(const QString& result, const QString& detailedError) { bool succeeded = true; if (!result.isEmpty()) { - QMessageBox::critical(nullptr, tr("Gem download"), result); + if (!detailedError.isEmpty()) + { + QMessageBox gemDownloadError; + gemDownloadError.setIcon(QMessageBox::Critical); + gemDownloadError.setWindowTitle(tr("Gem download")); + gemDownloadError.setText(result); + gemDownloadError.setDetailedText(detailedError); + gemDownloadError.exec(); + } + else + { + QMessageBox::critical(nullptr, tr("Gem download"), result); + } succeeded = false; } diff --git a/Code/Tools/ProjectManager/Source/DownloadController.h b/Code/Tools/ProjectManager/Source/DownloadController.h index 211d9b48bc..5e637971e9 100644 --- a/Code/Tools/ProjectManager/Source/DownloadController.h +++ b/Code/Tools/ProjectManager/Source/DownloadController.h @@ -54,7 +54,7 @@ namespace O3DE::ProjectManager } public slots: void UpdateUIProgress(int bytesDownloaded, int totalBytes); - void HandleResults(const QString& result); + void HandleResults(const QString& result, const QString& detailedError); signals: void StartGemDownload(const QString& gemName); diff --git a/Code/Tools/ProjectManager/Source/DownloadWorker.cpp b/Code/Tools/ProjectManager/Source/DownloadWorker.cpp index 560bfe05de..e58c41c89e 100644 --- a/Code/Tools/ProjectManager/Source/DownloadWorker.cpp +++ b/Code/Tools/ProjectManager/Source/DownloadWorker.cpp @@ -24,16 +24,16 @@ namespace O3DE::ProjectManager { emit UpdateProgress(bytesDownloaded, totalBytes); }; - AZ::Outcome gemInfoResult = + AZ::Outcome> gemInfoResult = PythonBindingsInterface::Get()->DownloadGem(m_gemName, gemDownloadProgress, /*force*/true); if (gemInfoResult.IsSuccess()) { - emit Done(""); + emit Done("", ""); } else { - emit Done(tr("Gem download failed")); + emit Done(gemInfoResult.GetError().first.c_str(), gemInfoResult.GetError().second.c_str()); } } diff --git a/Code/Tools/ProjectManager/Source/DownloadWorker.h b/Code/Tools/ProjectManager/Source/DownloadWorker.h index 4084080ff7..d33de7bacc 100644 --- a/Code/Tools/ProjectManager/Source/DownloadWorker.h +++ b/Code/Tools/ProjectManager/Source/DownloadWorker.h @@ -32,7 +32,7 @@ namespace O3DE::ProjectManager signals: void UpdateProgress(int bytesDownloaded, int totalBytes); - void Done(QString result = ""); + void Done(QString result = "", QString detailedResult = ""); private: diff --git a/Code/Tools/ProjectManager/Source/EngineScreenCtrl.cpp b/Code/Tools/ProjectManager/Source/EngineScreenCtrl.cpp index 9d9110922f..1f41acd3d1 100644 --- a/Code/Tools/ProjectManager/Source/EngineScreenCtrl.cpp +++ b/Code/Tools/ProjectManager/Source/EngineScreenCtrl.cpp @@ -72,12 +72,7 @@ namespace O3DE::ProjectManager bool EngineScreenCtrl::ContainsScreen(ProjectManagerScreen screen) { - if (screen == m_engineSettingsScreen->GetScreenEnum() || screen == m_gemRepoScreen->GetScreenEnum()) - { - return true; - } - - return false; + return screen == m_engineSettingsScreen->GetScreenEnum() || screen == m_gemRepoScreen->GetScreenEnum(); } void EngineScreenCtrl::NotifyCurrentScreen() diff --git a/Code/Tools/ProjectManager/Source/GemCatalog/GemCatalogHeaderWidget.cpp b/Code/Tools/ProjectManager/Source/GemCatalog/GemCatalogHeaderWidget.cpp index e676ba73d3..d6f4da0051 100644 --- a/Code/Tools/ProjectManager/Source/GemCatalog/GemCatalogHeaderWidget.cpp +++ b/Code/Tools/ProjectManager/Source/GemCatalog/GemCatalogHeaderWidget.cpp @@ -7,25 +7,32 @@ */ #include +#include + #include + #include #include #include #include #include -#include #include #include #include +#include +#include namespace O3DE::ProjectManager { - CartOverlayWidget::CartOverlayWidget(GemModel* gemModel, DownloadController* downloadController, QWidget* parent) - : QWidget(parent) + GemCartWidget::GemCartWidget(GemModel* gemModel, DownloadController* downloadController, QWidget* parent) + : QScrollArea(parent) , m_gemModel(gemModel) , m_downloadController(downloadController) { setObjectName("GemCatalogCart"); + setWidgetResizable(true); + setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); + setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded); m_layout = new QVBoxLayout(); m_layout->setSpacing(0); @@ -118,17 +125,15 @@ namespace O3DE::ProjectManager } return dependencies; }); - - setWindowFlags(Qt::FramelessWindowHint | Qt::Dialog); } - CartOverlayWidget::~CartOverlayWidget() + GemCartWidget::~GemCartWidget() { // disconnect from all download controller signals disconnect(m_downloadController, nullptr, this, nullptr); } - void CartOverlayWidget::CreateGemSection(const QString& singularTitle, const QString& pluralTitle, GetTagIndicesCallback getTagIndices) + void GemCartWidget::CreateGemSection(const QString& singularTitle, const QString& pluralTitle, GetTagIndicesCallback getTagIndices) { QWidget* widget = new QWidget(); widget->setFixedWidth(s_width); @@ -164,12 +169,12 @@ namespace O3DE::ProjectManager update(); } - void CartOverlayWidget::OnCancelDownloadActivated(const QString& gemName) + void GemCartWidget::OnCancelDownloadActivated(const QString& gemName) { m_downloadController->CancelGemDownload(gemName); } - void CartOverlayWidget::CreateDownloadSection() + void GemCartWidget::CreateDownloadSection() { m_downloadSectionWidget = new QWidget(); m_downloadSectionWidget->setFixedWidth(s_width); @@ -223,12 +228,12 @@ namespace O3DE::ProjectManager } // connect to download controller data changed - connect(m_downloadController, &DownloadController::GemDownloadAdded, this, &CartOverlayWidget::GemDownloadAdded); - connect(m_downloadController, &DownloadController::GemDownloadRemoved, this, &CartOverlayWidget::GemDownloadRemoved); - connect(m_downloadController, &DownloadController::GemDownloadProgress, this, &CartOverlayWidget::GemDownloadProgress); + connect(m_downloadController, &DownloadController::GemDownloadAdded, this, &GemCartWidget::GemDownloadAdded); + connect(m_downloadController, &DownloadController::GemDownloadRemoved, this, &GemCartWidget::GemDownloadRemoved); + connect(m_downloadController, &DownloadController::GemDownloadProgress, this, &GemCartWidget::GemDownloadProgress); } - void CartOverlayWidget::GemDownloadAdded(const QString& gemName) + void GemCartWidget::GemDownloadAdded(const QString& gemName) { // Containing widget for the current download item QWidget* newGemDownloadWidget = new QWidget(); @@ -246,7 +251,7 @@ namespace O3DE::ProjectManager nameProgressLayout->addStretch(); QLabel* cancelText = new QLabel(tr("Cancel").arg(gemName), newGemDownloadWidget); cancelText->setTextInteractionFlags(Qt::LinksAccessibleByMouse); - connect(cancelText, &QLabel::linkActivated, this, &CartOverlayWidget::OnCancelDownloadActivated); + connect(cancelText, &QLabel::linkActivated, this, &GemCartWidget::OnCancelDownloadActivated); nameProgressLayout->addWidget(cancelText); downloadingGemLayout->addLayout(nameProgressLayout); @@ -267,7 +272,7 @@ namespace O3DE::ProjectManager m_downloadingListWidget->show(); } - void CartOverlayWidget::GemDownloadRemoved(const QString& gemName) + void GemCartWidget::GemDownloadRemoved(const QString& gemName) { QWidget* gemToRemove = m_downloadingListWidget->findChild(gemName); if (gemToRemove) @@ -289,7 +294,7 @@ namespace O3DE::ProjectManager } } - void CartOverlayWidget::GemDownloadProgress(const QString& gemName, int bytesDownloaded, int totalBytes) + void GemCartWidget::GemDownloadProgress(const QString& gemName, int bytesDownloaded, int totalBytes) { QWidget* gemToUpdate = m_downloadingListWidget->findChild(gemName); if (gemToUpdate) @@ -324,7 +329,7 @@ namespace O3DE::ProjectManager } } - QVector CartOverlayWidget::GetTagsFromModelIndices(const QVector& gems) const + QVector GemCartWidget::GetTagsFromModelIndices(const QVector& gems) const { QVector tags; tags.reserve(gems.size()); @@ -349,7 +354,7 @@ namespace O3DE::ProjectManager iconButton->setFocusPolicy(Qt::NoFocus); iconButton->setIcon(QIcon(":/Summary.svg")); iconButton->setFixedSize(s_iconSize, s_iconSize); - connect(iconButton, &QPushButton::clicked, this, &CartButton::ShowOverlay); + connect(iconButton, &QPushButton::clicked, this, &CartButton::ShowGemCart); m_layout->addWidget(iconButton); m_countLabel = new QLabel(); @@ -362,7 +367,7 @@ namespace O3DE::ProjectManager m_dropDownButton->setFocusPolicy(Qt::NoFocus); m_dropDownButton->setIcon(QIcon(":/CarrotArrowDown.svg")); m_dropDownButton->setFixedSize(s_arrowDownIconSize, s_arrowDownIconSize); - connect(m_dropDownButton, &QPushButton::clicked, this, &CartButton::ShowOverlay); + connect(m_dropDownButton, &QPushButton::clicked, this, &CartButton::ShowGemCart); m_layout->addWidget(m_dropDownButton); // Adjust the label text whenever the model gets updated. @@ -377,28 +382,28 @@ namespace O3DE::ProjectManager m_dropDownButton->setVisible(!toBeAdded.isEmpty() || !toBeRemoved.isEmpty()); // Automatically close the overlay window in case there are no gems to be activated or deactivated anymore. - if (m_cartOverlay && toBeAdded.isEmpty() && toBeRemoved.isEmpty()) + if (m_gemCart && toBeAdded.isEmpty() && toBeRemoved.isEmpty()) { - m_cartOverlay->deleteLater(); - m_cartOverlay = nullptr; + m_gemCart->deleteLater(); + m_gemCart = nullptr; } }); } void CartButton::mousePressEvent([[maybe_unused]] QMouseEvent* event) { - ShowOverlay(); + ShowGemCart(); } void CartButton::hideEvent(QHideEvent*) { - if (m_cartOverlay) + if (m_gemCart) { - m_cartOverlay->hide(); + m_gemCart->hide(); } } - void CartButton::ShowOverlay() + void CartButton::ShowGemCart() { const QVector toBeAdded = m_gemModel->GatherGemsToBeAdded(/*includeDependencies=*/true); const QVector toBeRemoved = m_gemModel->GatherGemsToBeRemoved(/*includeDependencies=*/true); @@ -407,37 +412,33 @@ namespace O3DE::ProjectManager return; } - if (m_cartOverlay) + if (m_gemCart) { // Directly delete the former overlay before creating the new one. // Don't use deleteLater() here. This might overwrite the new overlay pointer // depending on the event queue. - delete m_cartOverlay; + delete m_gemCart; } - m_cartOverlay = new CartOverlayWidget(m_gemModel, m_downloadController, this); - connect(m_cartOverlay, &QWidget::destroyed, this, [=] + m_gemCart = new GemCartWidget(m_gemModel, m_downloadController, this); + connect(m_gemCart, &QWidget::destroyed, this, [=] { // Reset the overlay pointer on destruction to prevent dangling pointers. - m_cartOverlay = nullptr; + m_gemCart = nullptr; + // Tell header gem cart is no longer open + UpdateGemCart(nullptr); }); - m_cartOverlay->show(); + m_gemCart->show(); - const QPoint parentPos = m_dropDownButton->mapToParent(m_dropDownButton->pos()); - const QPoint globalPos = m_dropDownButton->mapToGlobal(m_dropDownButton->pos()); - const QPoint offset(-4, 10); - m_cartOverlay->setGeometry(globalPos.x() - parentPos.x() - m_cartOverlay->width() + width() + offset.x(), - globalPos.y() + offset.y(), - m_cartOverlay->width(), - m_cartOverlay->height()); + emit UpdateGemCart(m_gemCart); } CartButton::~CartButton() { // Make sure the overlay window is automatically closed in case the gem catalog is destroyed. - if (m_cartOverlay) + if (m_gemCart) { - m_cartOverlay->deleteLater(); + m_gemCart->deleteLater(); } } @@ -514,6 +515,17 @@ namespace O3DE::ProjectManager connect(m_downloadController, &DownloadController::GemDownloadAdded, this, &GemCatalogHeaderWidget::GemDownloadAdded); connect(m_downloadController, &DownloadController::GemDownloadRemoved, this, &GemCatalogHeaderWidget::GemDownloadRemoved); + + connect( + m_cartButton, &CartButton::UpdateGemCart, this, + [this](QWidget* gemCart) + { + GemCartShown(gemCart); + if (gemCart) + { + emit UpdateGemCart(gemCart); + } + }); } void GemCatalogHeaderWidget::GemDownloadAdded(const QString& /*gemName*/) @@ -521,7 +533,7 @@ namespace O3DE::ProjectManager m_downloadSpinner->show(); m_downloadLabel->show(); m_downloadSpinnerMovie->start(); - m_cartButton->ShowOverlay(); + m_cartButton->ShowGemCart(); } void GemCatalogHeaderWidget::GemDownloadRemoved(const QString& /*gemName*/) @@ -534,8 +546,44 @@ namespace O3DE::ProjectManager } } + void GemCatalogHeaderWidget::GemCartShown(bool state) + { + m_showGemCart = state; + repaint(); + } + void GemCatalogHeaderWidget::ReinitForProject() { m_filterLineEdit->setText({}); } + + void GemCatalogHeaderWidget::paintEvent([[maybe_unused]] QPaintEvent* event) + { + // Only show triangle when cart is shown + if (!m_showGemCart) + { + return; + } + + const QPoint buttonPos = m_cartButton->pos(); + const QSize buttonSize = m_cartButton->size(); + + // Draw isosceles triangle with top point touching bottom of cartButton + // Bottom aligned with header bottom and top of right panel + const QPoint topPoint(buttonPos.x() + buttonSize.width() / 2, buttonPos.y() + buttonSize.height()); + const QPoint bottomLeftPoint(topPoint.x() - 20, height()); + const QPoint bottomRightPoint(topPoint.x() + 20, height()); + + QPainterPath trianglePath; + trianglePath.moveTo(topPoint); + trianglePath.lineTo(bottomLeftPoint); + trianglePath.lineTo(bottomRightPoint); + trianglePath.lineTo(topPoint); + + QPainter painter(this); + painter.setRenderHint(QPainter::Antialiasing, true); + painter.setPen(Qt::NoPen); + painter.fillPath(trianglePath, QBrush(QColor("#555555"))); + } + } // namespace O3DE::ProjectManager diff --git a/Code/Tools/ProjectManager/Source/GemCatalog/GemCatalogHeaderWidget.h b/Code/Tools/ProjectManager/Source/GemCatalog/GemCatalogHeaderWidget.h index 5174fde57d..b749e9831d 100644 --- a/Code/Tools/ProjectManager/Source/GemCatalog/GemCatalogHeaderWidget.h +++ b/Code/Tools/ProjectManager/Source/GemCatalog/GemCatalogHeaderWidget.h @@ -14,8 +14,10 @@ #include #include #include -#include #include + +#include +#include #endif QT_FORWARD_DECLARE_CLASS(QPushButton) @@ -28,14 +30,14 @@ QT_FORWARD_DECLARE_CLASS(QMovie) namespace O3DE::ProjectManager { - class CartOverlayWidget - : public QWidget + class GemCartWidget + : public QScrollArea { Q_OBJECT // AUTOMOC public: - CartOverlayWidget(GemModel* gemModel, DownloadController* downloadController, QWidget* parent = nullptr); - ~CartOverlayWidget(); + GemCartWidget(GemModel* gemModel, DownloadController* downloadController, QWidget* parent = nullptr); + ~GemCartWidget(); public slots: void GemDownloadAdded(const QString& gemName); @@ -68,7 +70,10 @@ namespace O3DE::ProjectManager public: CartButton(GemModel* gemModel, DownloadController* downloadController, QWidget* parent = nullptr); ~CartButton(); - void ShowOverlay(); + void ShowGemCart(); + + signals: + void UpdateGemCart(QWidget* gemCart); private: void mousePressEvent(QMouseEvent* event) override; @@ -78,7 +83,7 @@ namespace O3DE::ProjectManager QHBoxLayout* m_layout = nullptr; QLabel* m_countLabel = nullptr; QPushButton* m_dropDownButton = nullptr; - CartOverlayWidget* m_cartOverlay = nullptr; + GemCartWidget* m_gemCart = nullptr; DownloadController* m_downloadController = nullptr; inline constexpr static int s_iconSize = 24; @@ -99,11 +104,16 @@ namespace O3DE::ProjectManager public slots: void GemDownloadAdded(const QString& gemName); void GemDownloadRemoved(const QString& gemName); + void GemCartShown(bool state = false); signals: void AddGem(); void OpenGemsRepo(); void RefreshGems(); + void UpdateGemCart(QWidget* gemCart); + + protected slots: + void paintEvent(QPaintEvent* event) override; private: AzQtComponents::SearchLineEdit* m_filterLineEdit = nullptr; @@ -113,5 +123,6 @@ namespace O3DE::ProjectManager QLabel* m_downloadLabel = nullptr; QMovie* m_downloadSpinnerMovie = nullptr; CartButton* m_cartButton = nullptr; + bool m_showGemCart = false; }; } // namespace O3DE::ProjectManager diff --git a/Code/Tools/ProjectManager/Source/GemCatalog/GemCatalogScreen.cpp b/Code/Tools/ProjectManager/Source/GemCatalog/GemCatalogScreen.cpp index 0dacbbb906..1d4f354fb5 100644 --- a/Code/Tools/ProjectManager/Source/GemCatalog/GemCatalogScreen.cpp +++ b/Code/Tools/ProjectManager/Source/GemCatalog/GemCatalogScreen.cpp @@ -8,6 +8,11 @@ #include #include +#include +#include +#include +#include +#include #include #include #include @@ -28,6 +33,7 @@ #include #include #include +#include namespace O3DE::ProjectManager { @@ -51,9 +57,12 @@ namespace O3DE::ProjectManager vLayout->addWidget(m_headerWidget); connect(m_gemModel, &GemModel::gemStatusChanged, this, &GemCatalogScreen::OnGemStatusChanged); + connect(m_gemModel, &GemModel::dependencyGemStatusChanged, this, &GemCatalogScreen::OnDependencyGemStatusChanged); + connect(m_gemModel->GetSelectionModel(), &QItemSelectionModel::selectionChanged, this, [this]{ ShowInspector(); }); connect(m_headerWidget, &GemCatalogHeaderWidget::RefreshGems, this, &GemCatalogScreen::Refresh); connect(m_headerWidget, &GemCatalogHeaderWidget::OpenGemsRepo, this, &GemCatalogScreen::HandleOpenGemRepo); connect(m_headerWidget, &GemCatalogHeaderWidget::AddGem, this, &GemCatalogScreen::OnAddGemClicked); + connect(m_headerWidget, &GemCatalogHeaderWidget::UpdateGemCart, this, &GemCatalogScreen::UpdateAndShowGemCart); connect(m_downloadController, &DownloadController::Done, this, &GemCatalogScreen::OnGemDownloadResult); QHBoxLayout* hLayout = new QHBoxLayout(); @@ -61,8 +70,11 @@ namespace O3DE::ProjectManager vLayout->addLayout(hLayout); m_gemListView = new GemListView(m_proxyModel, m_proxyModel->GetSelectionModel(), this); + + m_rightPanelStack = new QStackedWidget(this); + m_rightPanelStack->setFixedWidth(240); + m_gemInspector = new GemInspector(m_gemModel, this); - m_gemInspector->setFixedWidth(240); connect(m_gemInspector, &GemInspector::TagClicked, [=](const Tag& tag) { SelectGem(tag.id); }); connect(m_gemInspector, &GemInspector::UpdateGem, this, &GemCatalogScreen::UpdateGem); @@ -85,7 +97,9 @@ namespace O3DE::ProjectManager hLayout->addWidget(filterWidget); hLayout->addLayout(middleVLayout); - hLayout->addWidget(m_gemInspector); + + hLayout->addWidget(m_rightPanelStack); + m_rightPanelStack->addWidget(m_gemInspector); m_notificationsView = AZStd::make_unique(this, AZ_CRC("GemCatalogNotificationsView")); m_notificationsView->SetOffset(QPoint(10, 70)); @@ -188,7 +202,7 @@ namespace O3DE::ProjectManager } // add all the gem repos into the hash - const AZ::Outcome, AZStd::string>& allRepoGemInfosResult = PythonBindingsInterface::Get()->GetAllGemRepoGemsInfos(); + const AZ::Outcome, AZStd::string>& allRepoGemInfosResult = PythonBindingsInterface::Get()->GetGemInfosForAllRepos(); if (allRepoGemInfosResult.IsSuccess()) { const QVector& allRepoGemInfos = allRepoGemInfosResult.GetValue(); @@ -266,7 +280,8 @@ namespace O3DE::ProjectManager { notification += tr(" and "); } - if (added && GemModel::GetDownloadStatus(modelIndex) == GemInfo::DownloadStatus::NotDownloaded) + if (added && (GemModel::GetDownloadStatus(modelIndex) == GemInfo::DownloadStatus::NotDownloaded) || + (GemModel::GetDownloadStatus(modelIndex) == GemInfo::DownloadStatus::DownloadFailed)) { m_downloadController->AddGemDownload(GemModel::GetName(modelIndex)); GemModel::SetDownloadStatus(*m_gemModel, modelIndex, GemInfo::DownloadStatus::Downloading); @@ -291,6 +306,18 @@ namespace O3DE::ProjectManager } } + void GemCatalogScreen::OnDependencyGemStatusChanged(const QString& gemName) + { + QModelIndex modelIndex = m_gemModel->FindIndexByNameString(gemName); + bool added = GemModel::IsAddedDependency(modelIndex); + if (added && (GemModel::GetDownloadStatus(modelIndex) == GemInfo::DownloadStatus::NotDownloaded) || + (GemModel::GetDownloadStatus(modelIndex) == GemInfo::DownloadStatus::DownloadFailed)) + { + m_downloadController->AddGemDownload(GemModel::GetName(modelIndex)); + GemModel::SetDownloadStatus(*m_gemModel, modelIndex, GemInfo::DownloadStatus::Downloading); + } + } + void GemCatalogScreen::SelectGem(const QString& gemName) { QModelIndex modelIndex = m_gemModel->FindIndexByNameString(gemName); @@ -303,6 +330,8 @@ namespace O3DE::ProjectManager QModelIndex proxyIndex = m_proxyModel->mapFromSource(modelIndex); m_proxyModel->GetSelectionModel()->setCurrentIndex(proxyIndex, QItemSelectionModel::ClearAndSelect); m_gemListView->scrollTo(proxyIndex); + + ShowInspector(); } void GemCatalogScreen::UpdateGem(const QModelIndex& modelIndex) @@ -363,8 +392,12 @@ namespace O3DE::ProjectManager { const QString selectedGemPath = m_gemModel->GetPath(modelIndex); - // Remove gem from gems to be added + const bool wasAdded = GemModel::WasPreviouslyAdded(modelIndex); + const bool wasAddedDependency = GemModel::WasPreviouslyAddedDependency(modelIndex); + + // Remove gem from gems to be added to update any dependencies GemModel::SetIsAdded(*m_gemModel, modelIndex, false); + GemModel::DeactivateDependentGems(*m_gemModel, modelIndex); // Unregister the gem auto unregisterResult = PythonBindingsInterface::Get()->UnregisterGem(selectedGemPath); @@ -391,6 +424,8 @@ namespace O3DE::ProjectManager // Select remote gem QModelIndex remoteGemIndex = m_gemModel->FindIndexByNameString(selectedGemName); + GemModel::SetWasPreviouslyAdded(*m_gemModel, remoteGemIndex, wasAdded); + GemModel::SetWasPreviouslyAddedDependency(*m_gemModel, remoteGemIndex, wasAddedDependency); QModelIndex proxyIndex = m_proxyModel->mapFromSource(remoteGemIndex); m_proxyModel->GetSelectionModel()->setCurrentIndex(proxyIndex, QItemSelectionModel::ClearAndSelect); } @@ -435,7 +470,7 @@ namespace O3DE::ProjectManager m_gemModel->AddGem(gemInfo); } - const AZ::Outcome, AZStd::string>& allRepoGemInfosResult = PythonBindingsInterface::Get()->GetAllGemRepoGemsInfos(); + const AZ::Outcome, AZStd::string>& allRepoGemInfosResult = PythonBindingsInterface::Get()->GetGemInfosForAllRepos(); if (allRepoGemInfosResult.IsSuccess()) { const QVector& allRepoGemInfos = allRepoGemInfosResult.GetValue(); @@ -491,6 +526,12 @@ namespace O3DE::ProjectManager } } + void GemCatalogScreen::ShowInspector() + { + m_rightPanelStack->setCurrentIndex(RightPanelWidgetOrder::Inspector); + m_headerWidget->GemCartShown(); + } + GemCatalogScreen::EnableDisableGemsResult GemCatalogScreen::EnableDisableGemsForProject(const QString& projectPath) { IPythonBindings* pythonBindings = PythonBindingsInterface::Get(); @@ -523,7 +564,9 @@ namespace O3DE::ProjectManager const QString& gemPath = GemModel::GetPath(modelIndex); // make sure any remote gems we added were downloaded successfully - if (GemModel::GetGemOrigin(modelIndex) == GemInfo::Remote && GemModel::GetDownloadStatus(modelIndex) != GemInfo::Downloaded) + const GemInfo::DownloadStatus status = GemModel::GetDownloadStatus(modelIndex); + if (GemModel::GetGemOrigin(modelIndex) == GemInfo::Remote && + !(status == GemInfo::Downloaded || status == GemInfo::DownloadSuccessful)) { QMessageBox::critical( nullptr, "Cannot add gem that isn't downloaded", @@ -570,6 +613,18 @@ namespace O3DE::ProjectManager emit ChangeScreenRequest(ProjectManagerScreen::GemRepos); } + void GemCatalogScreen::UpdateAndShowGemCart(QWidget* cartWidget) + { + QWidget* previousCart = m_rightPanelStack->widget(RightPanelWidgetOrder::Cart); + if (previousCart) + { + m_rightPanelStack->removeWidget(previousCart); + } + + m_rightPanelStack->insertWidget(RightPanelWidgetOrder::Cart, cartWidget); + m_rightPanelStack->setCurrentIndex(RightPanelWidgetOrder::Cart); + } + void GemCatalogScreen::OnGemDownloadResult(const QString& gemName, bool succeeded) { if (succeeded) @@ -620,6 +675,8 @@ namespace O3DE::ProjectManager QModelIndex index = m_gemModel->FindIndexByNameString(gemName); if (index.isValid()) { + GemModel::SetIsAdded(*m_gemModel, index, false); + GemModel::DeactivateDependentGems(*m_gemModel, index); GemModel::SetDownloadStatus(*m_gemModel, index, GemInfo::DownloadFailed); } } diff --git a/Code/Tools/ProjectManager/Source/GemCatalog/GemCatalogScreen.h b/Code/Tools/ProjectManager/Source/GemCatalog/GemCatalogScreen.h index c5fbb057ef..20b0c27ff8 100644 --- a/Code/Tools/ProjectManager/Source/GemCatalog/GemCatalogScreen.h +++ b/Code/Tools/ProjectManager/Source/GemCatalog/GemCatalogScreen.h @@ -12,18 +12,24 @@ #include #include #include -#include -#include -#include -#include -#include -#include + #include #include #endif +QT_FORWARD_DECLARE_CLASS(QVBoxLayout) +QT_FORWARD_DECLARE_CLASS(QStackedWidget) + namespace O3DE::ProjectManager { + QT_FORWARD_DECLARE_CLASS(GemCatalogHeaderWidget) + QT_FORWARD_DECLARE_CLASS(GemFilterWidget) + QT_FORWARD_DECLARE_CLASS(GemListView) + QT_FORWARD_DECLARE_CLASS(GemInspector) + QT_FORWARD_DECLARE_CLASS(GemModel) + QT_FORWARD_DECLARE_CLASS(GemSortFilterProxyModel) + QT_FORWARD_DECLARE_CLASS(DownloadController) + class GemCatalogScreen : public ScreenWidget { @@ -47,6 +53,7 @@ namespace O3DE::ProjectManager public slots: void OnGemStatusChanged(const QString& gemName, uint32_t numChangedDependencies); + void OnDependencyGemStatusChanged(const QString& gemName); void OnAddGemClicked(); void SelectGem(const QString& gemName); void OnGemDownloadResult(const QString& gemName, bool succeeded = true); @@ -62,14 +69,22 @@ namespace O3DE::ProjectManager private slots: void HandleOpenGemRepo(); - + void UpdateAndShowGemCart(QWidget* cartWidget); + void ShowInspector(); private: + enum RightPanelWidgetOrder + { + Inspector = 0, + Cart + }; + void FillModel(const QString& projectPath); AZStd::unique_ptr m_notificationsView; GemListView* m_gemListView = nullptr; + QStackedWidget* m_rightPanelStack = nullptr; GemInspector* m_gemInspector = nullptr; GemModel* m_gemModel = nullptr; GemCatalogHeaderWidget* m_headerWidget = nullptr; diff --git a/Code/Tools/ProjectManager/Source/GemCatalog/GemInspector.cpp b/Code/Tools/ProjectManager/Source/GemCatalog/GemInspector.cpp index 26844b43e6..8bdd1f0f0f 100644 --- a/Code/Tools/ProjectManager/Source/GemCatalog/GemInspector.cpp +++ b/Code/Tools/ProjectManager/Source/GemCatalog/GemInspector.cpp @@ -53,10 +53,13 @@ namespace O3DE::ProjectManager Update(selectedIndices[0]); } - void SetLabelElidedText(QLabel* label, QString text) + void SetLabelElidedText(QLabel* label, QString text, int labelWidth = 0) { QFontMetrics nameFontMetrics(label->font()); - int labelWidth = label->width(); + if (!labelWidth) + { + labelWidth = label->width(); + } // Don't elide if the widgets are sized too small (sometimes occurs when loading gem catalog) if (labelWidth > 100) @@ -84,7 +87,8 @@ namespace O3DE::ProjectManager m_summaryLabel->setText(m_model->GetSummary(modelIndex)); m_summaryLabel->adjustSize(); - m_licenseLinkLabel->setText(m_model->GetLicenseText(modelIndex)); + // Manually define remaining space to elide text because spacer would like to take all of the space + SetLabelElidedText(m_licenseLinkLabel, m_model->GetLicenseText(modelIndex), width() - m_licenseLabel->width() - 35); m_licenseLinkLabel->SetUrl(m_model->GetLicenseLink(modelIndex)); m_directoryLinkLabel->SetUrl(m_model->GetDirectoryLink(modelIndex)); @@ -175,8 +179,8 @@ namespace O3DE::ProjectManager licenseHLayout->setAlignment(Qt::AlignLeft); m_mainLayout->addLayout(licenseHLayout); - QLabel* licenseLabel = CreateStyledLabel(licenseHLayout, s_baseFontSize, s_headerColor); - licenseLabel->setText(tr("License: ")); + m_licenseLabel = CreateStyledLabel(licenseHLayout, s_baseFontSize, s_headerColor); + m_licenseLabel->setText(tr("License: ")); m_licenseLinkLabel = new LinkLabel("", QUrl(), s_baseFontSize); licenseHLayout->addWidget(m_licenseLinkLabel); diff --git a/Code/Tools/ProjectManager/Source/GemCatalog/GemInspector.h b/Code/Tools/ProjectManager/Source/GemCatalog/GemInspector.h index 6a5de17fcd..1713191623 100644 --- a/Code/Tools/ProjectManager/Source/GemCatalog/GemInspector.h +++ b/Code/Tools/ProjectManager/Source/GemCatalog/GemInspector.h @@ -64,6 +64,7 @@ namespace O3DE::ProjectManager QLabel* m_nameLabel = nullptr; QLabel* m_creatorLabel = nullptr; QLabel* m_summaryLabel = nullptr; + QLabel* m_licenseLabel = nullptr; LinkLabel* m_licenseLinkLabel = nullptr; LinkLabel* m_directoryLinkLabel = nullptr; LinkLabel* m_documentationLinkLabel = nullptr; diff --git a/Code/Tools/ProjectManager/Source/GemCatalog/GemModel.cpp b/Code/Tools/ProjectManager/Source/GemCatalog/GemModel.cpp index 95fdc8e1e2..d163ab9076 100644 --- a/Code/Tools/ProjectManager/Source/GemCatalog/GemModel.cpp +++ b/Code/Tools/ProjectManager/Source/GemCatalog/GemModel.cpp @@ -357,6 +357,8 @@ namespace O3DE::ProjectManager if (!IsAdded(dependency)) { numChangedDependencies++; + const QString dependencyName = gemModel->GetName(dependency); + gemModel->emit dependencyGemStatusChanged(dependencyName); } } } @@ -381,6 +383,8 @@ namespace O3DE::ProjectManager if (!IsAdded(dependency)) { numChangedDependencies++; + const QString dependencyName = gemModel->GetName(dependency); + gemModel->emit dependencyGemStatusChanged(dependencyName); } } } @@ -479,6 +483,23 @@ namespace O3DE::ProjectManager return previouslyAdded && !added; } + void GemModel::DeactivateDependentGems(QAbstractItemModel& model, const QModelIndex& modelIndex) + { + GemModel* gemModel = GetSourceModel(&model); + AZ_Assert(gemModel, "Failed to obtain GemModel"); + + QVector dependentGems = gemModel->GatherDependentGems(modelIndex); + if (!dependentGems.isEmpty()) + { + // we need to deactivate all gems that depend on this one + for (auto dependentModelIndex : dependentGems) + { + SetIsAdded(model, dependentModelIndex, false); + } + + } + } + void GemModel::SetDownloadStatus(QAbstractItemModel& model, const QModelIndex& modelIndex, GemInfo::DownloadStatus status) { model.setData(modelIndex, status, RoleDownloadStatus); diff --git a/Code/Tools/ProjectManager/Source/GemCatalog/GemModel.h b/Code/Tools/ProjectManager/Source/GemCatalog/GemModel.h index bb89d46861..cb99581468 100644 --- a/Code/Tools/ProjectManager/Source/GemCatalog/GemModel.h +++ b/Code/Tools/ProjectManager/Source/GemCatalog/GemModel.h @@ -99,6 +99,7 @@ namespace O3DE::ProjectManager static bool NeedsToBeRemoved(const QModelIndex& modelIndex, bool includeDependencies = false); static bool HasRequirement(const QModelIndex& modelIndex); static void UpdateDependencies(QAbstractItemModel& model, const QString& gemName, bool isAdded); + static void DeactivateDependentGems(QAbstractItemModel& model, const QModelIndex& modelIndex); static void SetDownloadStatus(QAbstractItemModel& model, const QModelIndex& modelIndex, GemInfo::DownloadStatus status); bool DoGemsToBeAddedHaveRequirements() const; @@ -113,6 +114,7 @@ namespace O3DE::ProjectManager signals: void gemStatusChanged(const QString& gemName, uint32_t numChangedDependencies); + void dependencyGemStatusChanged(const QString& gemName); protected slots: void OnRowsAboutToBeRemoved(const QModelIndex& parent, int first, int last); diff --git a/Code/Tools/ProjectManager/Source/GemRepo/GemRepoInfo.h b/Code/Tools/ProjectManager/Source/GemRepo/GemRepoInfo.h index f1d1c2a8a2..c22511faad 100644 --- a/Code/Tools/ProjectManager/Source/GemRepo/GemRepoInfo.h +++ b/Code/Tools/ProjectManager/Source/GemRepo/GemRepoInfo.h @@ -37,7 +37,7 @@ namespace O3DE::ProjectManager QString m_additionalInfo = ""; QString m_directoryLink = ""; QString m_repoUri = ""; - QStringList m_includedGemPaths = {}; + QStringList m_includedGemUris = {}; QDateTime m_lastUpdated; }; } // namespace O3DE::ProjectManager diff --git a/Code/Tools/ProjectManager/Source/GemRepo/GemRepoInspector.cpp b/Code/Tools/ProjectManager/Source/GemRepo/GemRepoInspector.cpp index f816e86733..24a3e58ea2 100644 --- a/Code/Tools/ProjectManager/Source/GemRepo/GemRepoInspector.cpp +++ b/Code/Tools/ProjectManager/Source/GemRepo/GemRepoInspector.cpp @@ -8,6 +8,7 @@ #include #include +#include #include #include @@ -60,8 +61,10 @@ namespace O3DE::ProjectManager // Repo name and url link m_nameLabel->setText(m_model->GetName(modelIndex)); - m_repoLinkLabel->setText(m_model->GetRepoUri(modelIndex)); - m_repoLinkLabel->SetUrl(m_model->GetRepoUri(modelIndex)); + + const QString repoUri = m_model->GetRepoUri(modelIndex); + m_repoLinkLabel->setText(repoUri); + m_repoLinkLabel->SetUrl(repoUri); // Repo summary m_summaryLabel->setText(m_model->GetSummary(modelIndex)); diff --git a/Code/Tools/ProjectManager/Source/GemRepo/GemRepoModel.cpp b/Code/Tools/ProjectManager/Source/GemRepo/GemRepoModel.cpp index 6189b6d8bf..436f84019a 100644 --- a/Code/Tools/ProjectManager/Source/GemRepo/GemRepoModel.cpp +++ b/Code/Tools/ProjectManager/Source/GemRepo/GemRepoModel.cpp @@ -41,7 +41,7 @@ namespace O3DE::ProjectManager item->setData(gemRepoInfo.m_lastUpdated, RoleLastUpdated); item->setData(gemRepoInfo.m_path, RolePath); item->setData(gemRepoInfo.m_additionalInfo, RoleAdditionalInfo); - item->setData(gemRepoInfo.m_includedGemPaths, RoleIncludedGems); + item->setData(gemRepoInfo.m_includedGemUris, RoleIncludedGems); appendRow(item); @@ -98,7 +98,7 @@ namespace O3DE::ProjectManager return modelIndex.data(RolePath).toString(); } - QStringList GemRepoModel::GetIncludedGemPaths(const QModelIndex& modelIndex) + QStringList GemRepoModel::GetIncludedGemUris(const QModelIndex& modelIndex) { return modelIndex.data(RoleIncludedGems).toStringList(); } @@ -118,23 +118,19 @@ namespace O3DE::ProjectManager QVector GemRepoModel::GetIncludedGemInfos(const QModelIndex& modelIndex) { - QVector allGemInfos; - QStringList repoGemPaths = GetIncludedGemPaths(modelIndex); + QString repoUri = GetRepoUri(modelIndex); - for (const QString& gemPath : repoGemPaths) + const AZ::Outcome, AZStd::string>& gemInfosResult = PythonBindingsInterface::Get()->GetGemInfosForRepo(repoUri); + if (gemInfosResult.IsSuccess()) { - AZ::Outcome gemInfoResult = PythonBindingsInterface::Get()->GetGemInfo(gemPath); - if (gemInfoResult.IsSuccess()) - { - allGemInfos.append(gemInfoResult.GetValue()); - } - else - { - QMessageBox::critical(nullptr, tr("Gem Not Found"), tr("Cannot find info for gem %1.").arg(gemPath)); - } + return gemInfosResult.GetValue(); + } + else + { + QMessageBox::critical(nullptr, tr("Gems not found"), tr("Cannot find info for gems from repo %1").arg(GetName(modelIndex))); } - return allGemInfos; + return QVector(); } bool GemRepoModel::IsEnabled(const QModelIndex& modelIndex) diff --git a/Code/Tools/ProjectManager/Source/GemRepo/GemRepoModel.h b/Code/Tools/ProjectManager/Source/GemRepo/GemRepoModel.h index 66fe972a95..68991a0509 100644 --- a/Code/Tools/ProjectManager/Source/GemRepo/GemRepoModel.h +++ b/Code/Tools/ProjectManager/Source/GemRepo/GemRepoModel.h @@ -39,7 +39,7 @@ namespace O3DE::ProjectManager static QDateTime GetLastUpdated(const QModelIndex& modelIndex); static QString GetPath(const QModelIndex& modelIndex); - static QStringList GetIncludedGemPaths(const QModelIndex& modelIndex); + static QStringList GetIncludedGemUris(const QModelIndex& modelIndex); static QVector GetIncludedGemTags(const QModelIndex& modelIndex); static QVector GetIncludedGemInfos(const QModelIndex& modelIndex); diff --git a/Code/Tools/ProjectManager/Source/GemRepo/GemRepoScreen.cpp b/Code/Tools/ProjectManager/Source/GemRepo/GemRepoScreen.cpp index 91432c2346..f62c30c280 100644 --- a/Code/Tools/ProjectManager/Source/GemRepo/GemRepoScreen.cpp +++ b/Code/Tools/ProjectManager/Source/GemRepo/GemRepoScreen.cpp @@ -92,8 +92,9 @@ namespace O3DE::ProjectManager return; } - bool addGemRepoResult = PythonBindingsInterface::Get()->AddGemRepo(repoUri); - if (addGemRepoResult) + AZ::Outcome < void, + AZStd::pair> addGemRepoResult = PythonBindingsInterface::Get()->AddGemRepo(repoUri); + if (addGemRepoResult.IsSuccess()) { Reinit(); emit OnRefresh(); @@ -101,8 +102,21 @@ namespace O3DE::ProjectManager else { QString failureMessage = tr("Failed to add gem repo: %1.").arg(repoUri); - QMessageBox::critical(this, tr("Operation failed"), failureMessage); - AZ_Error("Project Manger", false, failureMessage.toUtf8()); + if (!addGemRepoResult.GetError().second.empty()) + { + QMessageBox addRepoError; + addRepoError.setIcon(QMessageBox::Critical); + addRepoError.setWindowTitle(failureMessage); + addRepoError.setText(addGemRepoResult.GetError().first.c_str()); + addRepoError.setDetailedText(addGemRepoResult.GetError().second.c_str()); + addRepoError.exec(); + } + else + { + QMessageBox::critical(this, failureMessage, addGemRepoResult.GetError().first.c_str()); + } + + AZ_Error("Project Manager", false, failureMessage.toUtf8()); } } } diff --git a/Code/Tools/ProjectManager/Source/ProjectBuilderController.cpp b/Code/Tools/ProjectManager/Source/ProjectBuilderController.cpp index 7981e9d758..ecb125ae4e 100644 --- a/Code/Tools/ProjectManager/Source/ProjectBuilderController.cpp +++ b/Code/Tools/ProjectManager/Source/ProjectBuilderController.cpp @@ -9,12 +9,14 @@ #include #include #include +#include + +#include #include #include #include - namespace O3DE::ProjectManager { ProjectBuilderController::ProjectBuilderController(const ProjectInfo& projectInfo, ProjectButton* projectButton, QWidget* parent) @@ -27,6 +29,15 @@ namespace O3DE::ProjectManager m_worker = new ProjectBuilderWorker(m_projectInfo); m_worker->moveToThread(&m_workerThread); + auto settingsRegistry = AZ::SettingsRegistry::Get(); + if (settingsRegistry) + { + // Remove key here in case Project Manager crashing while building that causes HandleResults to not be called + QString settingsKey = GetProjectBuiltSuccessfullyKey(m_projectInfo.m_projectName); + settingsRegistry->Remove(settingsKey.toStdString().c_str()); + SaveProjectManagerSettings(); + } + connect(&m_workerThread, &QThread::finished, m_worker, &ProjectBuilderWorker::deleteLater); connect(&m_workerThread, &QThread::started, m_worker, &ProjectBuilderWorker::BuildProject); connect(m_worker, &ProjectBuilderWorker::Done, this, &ProjectBuilderController::HandleResults); @@ -80,6 +91,8 @@ namespace O3DE::ProjectManager void ProjectBuilderController::HandleResults(const QString& result) { + QString settingsKey = GetProjectBuiltSuccessfullyKey(m_projectInfo.m_projectName); + if (!result.isEmpty()) { if (result.contains(tr("log"))) @@ -109,12 +122,26 @@ namespace O3DE::ProjectManager emit NotifyBuildProject(m_projectInfo); } + auto settingsRegistry = AZ::SettingsRegistry::Get(); + if (settingsRegistry) + { + settingsRegistry->Remove(settingsKey.toStdString().c_str()); + SaveProjectManagerSettings(); + } + emit Done(false); return; } else { m_projectInfo.m_buildFailed = false; + + auto settingsRegistry = AZ::SettingsRegistry::Get(); + if (settingsRegistry) + { + settingsRegistry->Set(settingsKey.toStdString().c_str(), true); + SaveProjectManagerSettings(); + } } emit Done(true); diff --git a/Code/Tools/ProjectManager/Source/ProjectButtonWidget.cpp b/Code/Tools/ProjectManager/Source/ProjectButtonWidget.cpp index 98916cccf6..2f4fe901bb 100644 --- a/Code/Tools/ProjectManager/Source/ProjectButtonWidget.cpp +++ b/Code/Tools/ProjectManager/Source/ProjectButtonWidget.cpp @@ -203,6 +203,7 @@ namespace O3DE::ProjectManager QMenu* menu = new QMenu(this); menu->addAction(tr("Edit Project Settings..."), this, [this]() { emit EditProject(m_projectInfo.m_path); }); + menu->addAction(tr("Configure Gems..."), this, [this]() { emit EditProjectGems(m_projectInfo.m_path); }); menu->addAction(tr("Build"), this, [this]() { emit BuildProject(m_projectInfo); }); menu->addAction(tr("Open CMake GUI..."), this, [this]() { emit OpenCMakeGUI(m_projectInfo); }); menu->addSeparator(); diff --git a/Code/Tools/ProjectManager/Source/ProjectButtonWidget.h b/Code/Tools/ProjectManager/Source/ProjectButtonWidget.h index 5e81dfc2d9..ccb644c458 100644 --- a/Code/Tools/ProjectManager/Source/ProjectButtonWidget.h +++ b/Code/Tools/ProjectManager/Source/ProjectButtonWidget.h @@ -95,6 +95,7 @@ namespace O3DE::ProjectManager signals: void OpenProject(const QString& projectName); void EditProject(const QString& projectName); + void EditProjectGems(const QString& projectName); void CopyProject(const ProjectInfo& projectInfo); void RemoveProject(const QString& projectName); void DeleteProject(const QString& projectName); diff --git a/Code/Tools/ProjectManager/Source/ProjectManagerSettings.cpp b/Code/Tools/ProjectManager/Source/ProjectManagerSettings.cpp new file mode 100644 index 0000000000..3049a6d70c --- /dev/null +++ b/Code/Tools/ProjectManager/Source/ProjectManagerSettings.cpp @@ -0,0 +1,54 @@ +/* + * 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 "ProjectManagerSettings.h" + +#include +#include +#include + +namespace O3DE::ProjectManager +{ + void SaveProjectManagerSettings() + { + auto settingsRegistry = AZ::SettingsRegistry::Get(); + AZ::SettingsRegistryMergeUtils::DumperSettings dumperSettings; + dumperSettings.m_prettifyOutput = true; + dumperSettings.m_jsonPointerPrefix = ProjectManagerKeyPrefix; + + AZStd::string stringBuffer; + AZ::IO::ByteContainerStream stringStream(&stringBuffer); + if (!AZ::SettingsRegistryMergeUtils::DumpSettingsRegistryToStream( + *settingsRegistry, ProjectManagerKeyPrefix, stringStream, dumperSettings)) + { + AZ_Warning("ProjectManager", false, "Could not save Project Manager settings to stream"); + return; + } + + AZ::IO::FixedMaxPath o3deUserPath = AZ::Utils::GetO3deManifestDirectory(); + o3deUserPath /= AZ::SettingsRegistryInterface::RegistryFolder; + o3deUserPath /= "ProjectManager.setreg"; + + bool saved = false; + constexpr auto configurationMode = + AZ::IO::SystemFile::SF_OPEN_CREATE | AZ::IO::SystemFile::SF_OPEN_CREATE_PATH | AZ::IO::SystemFile::SF_OPEN_WRITE_ONLY; + + AZ::IO::SystemFile outputFile; + if (outputFile.Open(o3deUserPath.c_str(), configurationMode)) + { + saved = outputFile.Write(stringBuffer.data(), stringBuffer.size()) == stringBuffer.size(); + } + + AZ_Warning("ProjectManager", saved, "Unable to save Project Manager registry file to path: %s", o3deUserPath.c_str()); + } + + QString GetProjectBuiltSuccessfullyKey(const QString& projectName) + { + return QString("%1/Projects/%2/BuiltSuccessfully").arg(ProjectManagerKeyPrefix).arg(projectName); + } +} diff --git a/Code/Tools/ProjectManager/Source/ProjectManagerSettings.h b/Code/Tools/ProjectManager/Source/ProjectManagerSettings.h new file mode 100644 index 0000000000..3454909062 --- /dev/null +++ b/Code/Tools/ProjectManager/Source/ProjectManagerSettings.h @@ -0,0 +1,21 @@ +/* + * 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 +{ + static constexpr char ProjectManagerKeyPrefix[] = "/O3DE/ProjectManager"; + + void SaveProjectManagerSettings(); + QString GetProjectBuiltSuccessfullyKey(const QString& projectName); +} diff --git a/Code/Tools/ProjectManager/Source/ProjectSettingsScreen.cpp b/Code/Tools/ProjectManager/Source/ProjectSettingsScreen.cpp index 88ae3d6319..d4ac43d655 100644 --- a/Code/Tools/ProjectManager/Source/ProjectSettingsScreen.cpp +++ b/Code/Tools/ProjectManager/Source/ProjectSettingsScreen.cpp @@ -19,6 +19,7 @@ #include #include #include +#include namespace O3DE::ProjectManager { @@ -33,11 +34,23 @@ namespace O3DE::ProjectManager // if we don't set this in a frame (just use a sub-layout) all the content will align incorrectly horizontally QFrame* projectSettingsFrame = new QFrame(this); projectSettingsFrame->setObjectName("projectSettings"); - m_verticalLayout = new QVBoxLayout(); - // you cannot remove content margins in qss - m_verticalLayout->setContentsMargins(0, 0, 0, 0); + QVBoxLayout* vLayout = new QVBoxLayout(); + vLayout->setMargin(0); + vLayout->setAlignment(Qt::AlignTop); + projectSettingsFrame->setLayout(vLayout); + + QScrollArea* scrollArea = new QScrollArea(this); + scrollArea->setWidgetResizable(true); + vLayout->addWidget(scrollArea); + + QWidget* scrollWidget = new QWidget(this); + scrollArea->setWidget(scrollWidget); + + m_verticalLayout = new QVBoxLayout(); + m_verticalLayout->setMargin(0); m_verticalLayout->setAlignment(Qt::AlignTop); + scrollWidget->setLayout(m_verticalLayout); m_projectName = new FormLineEditWidget(tr("Project name"), "", this); connect(m_projectName->lineEdit(), &QLineEdit::textChanged, this, &ProjectSettingsScreen::OnProjectNameUpdated); diff --git a/Code/Tools/ProjectManager/Source/ProjectsScreen.cpp b/Code/Tools/ProjectManager/Source/ProjectsScreen.cpp index f86a689e59..4a82783949 100644 --- a/Code/Tools/ProjectManager/Source/ProjectsScreen.cpp +++ b/Code/Tools/ProjectManager/Source/ProjectsScreen.cpp @@ -14,6 +14,7 @@ #include #include #include +#include #include #include @@ -22,6 +23,7 @@ #include #include #include +#include #include #include @@ -181,6 +183,7 @@ namespace O3DE::ProjectManager connect(projectButton, &ProjectButton::OpenProject, this, &ProjectsScreen::HandleOpenProject); connect(projectButton, &ProjectButton::EditProject, this, &ProjectsScreen::HandleEditProject); + connect(projectButton, &ProjectButton::EditProjectGems, this, &ProjectsScreen::HandleEditProjectGems); connect(projectButton, &ProjectButton::CopyProject, this, &ProjectsScreen::HandleCopyProject); connect(projectButton, &ProjectButton::RemoveProject, this, &ProjectsScreen::HandleRemoveProject); connect(projectButton, &ProjectButton::DeleteProject, this, &ProjectsScreen::HandleDeleteProject); @@ -269,17 +272,36 @@ namespace O3DE::ProjectManager // Add any missing project buttons and restore buttons to default state for (const ProjectInfo& project : projectsVector) { + ProjectButton* currentButton = nullptr; if (!m_projectButtons.contains(QDir::toNativeSeparators(project.m_path))) { - m_projectButtons.insert(QDir::toNativeSeparators(project.m_path), CreateProjectButton(project)); + currentButton = CreateProjectButton(project); + m_projectButtons.insert(QDir::toNativeSeparators(project.m_path), currentButton); } else { auto projectButtonIter = m_projectButtons.find(QDir::toNativeSeparators(project.m_path)); if (projectButtonIter != m_projectButtons.end()) { - projectButtonIter.value()->RestoreDefaultState(); - m_projectsFlowLayout->addWidget(projectButtonIter.value()); + currentButton = projectButtonIter.value(); + currentButton->RestoreDefaultState(); + m_projectsFlowLayout->addWidget(currentButton); + } + } + + // Check whether project manager has successfully built the project + if (currentButton) + { + auto settingsRegistry = AZ::SettingsRegistry::Get(); + bool projectBuiltSuccessfully = false; + if (settingsRegistry) + { + QString settingsKey = GetProjectBuiltSuccessfullyKey(project.m_projectName); + settingsRegistry->Get(projectBuiltSuccessfully, settingsKey.toStdString().c_str()); + } + if (!projectBuiltSuccessfully) + { + currentButton->ShowBuildRequired(); } } } @@ -448,6 +470,14 @@ namespace O3DE::ProjectManager emit ChangeScreenRequest(ProjectManagerScreen::UpdateProject); } } + void ProjectsScreen::HandleEditProjectGems(const QString& projectPath) + { + if (!WarnIfInBuildQueue(projectPath)) + { + emit NotifyCurrentProject(projectPath); + emit ChangeScreenRequest(ProjectManagerScreen::GemCatalog); + } + } void ProjectsScreen::HandleCopyProject(const ProjectInfo& projectInfo) { if (!WarnIfInBuildQueue(projectInfo.m_path)) diff --git a/Code/Tools/ProjectManager/Source/ProjectsScreen.h b/Code/Tools/ProjectManager/Source/ProjectsScreen.h index 859f8d0eae..c690621fb6 100644 --- a/Code/Tools/ProjectManager/Source/ProjectsScreen.h +++ b/Code/Tools/ProjectManager/Source/ProjectsScreen.h @@ -46,6 +46,7 @@ namespace O3DE::ProjectManager void HandleAddProjectButton(); void HandleOpenProject(const QString& projectPath); void HandleEditProject(const QString& projectPath); + void HandleEditProjectGems(const QString& projectPath); void HandleCopyProject(const ProjectInfo& projectInfo); void HandleRemoveProject(const QString& projectPath); void HandleDeleteProject(const QString& projectPath); diff --git a/Code/Tools/ProjectManager/Source/PythonBindings.cpp b/Code/Tools/ProjectManager/Source/PythonBindings.cpp index d1dedaaec4..12f97e6d2e 100644 --- a/Code/Tools/ProjectManager/Source/PythonBindings.cpp +++ b/Code/Tools/ProjectManager/Source/PythonBindings.cpp @@ -23,6 +23,7 @@ #include #include #include +#include #include #include @@ -210,6 +211,16 @@ namespace RedirectOutput }); SetRedirection("stderr", g_redirect_stderr_saved, g_redirect_stderr, []([[maybe_unused]] const char* msg) { + AZStd::string lastPythonError = msg; + constexpr const char* pythonErrorPrefix = "ERROR:root:"; + constexpr size_t lengthOfErrorPrefix = AZStd::char_traits::length(pythonErrorPrefix); + auto errorPrefix = lastPythonError.find(pythonErrorPrefix); + if (errorPrefix != AZStd::string::npos) + { + lastPythonError.erase(errorPrefix, lengthOfErrorPrefix); + } + O3DE::ProjectManager::PythonBindingsInterface::Get()->AddErrorString(lastPythonError); + AZ_TracePrintf("Python", msg); }); @@ -376,6 +387,8 @@ namespace O3DE::ProjectManager pybind11::gil_scoped_release release; pybind11::gil_scoped_acquire acquire; + ClearErrorStrings(); + try { executionCallback(); @@ -1051,7 +1064,7 @@ namespace O3DE::ProjectManager return result && refreshResult; } - bool PythonBindings::AddGemRepo(const QString& repoUri) + AZ::Outcome> PythonBindings::AddGemRepo(const QString& repoUri) { bool registrationResult = false; bool result = ExecuteWithLock( @@ -1065,7 +1078,12 @@ namespace O3DE::ProjectManager registrationResult = !pythonRegistrationResult.cast(); }); - return result && registrationResult; + if (!result || !registrationResult) + { + return AZ::Failure>(GetSimpleDetailedErrorPair()); + } + + return AZ::Success(); } bool PythonBindings::RemoveGemRepo(const QString& repoUri) @@ -1135,11 +1153,11 @@ namespace O3DE::ProjectManager gemRepoInfo.m_isEnabled = false; } - if (data.contains("gem_paths")) + if (data.contains("gems")) { - for (auto gemPath : data["gem_paths"]) + for (auto gemPath : data["gems"]) { - gemRepoInfo.m_includedGemPaths.push_back(Py_To_String(gemPath)); + gemRepoInfo.m_includedGemUris.push_back(Py_To_String(gemPath)); } } } @@ -1188,7 +1206,35 @@ namespace O3DE::ProjectManager return AZ::Success(AZStd::move(gemRepos)); } - AZ::Outcome, AZStd::string> PythonBindings::GetAllGemRepoGemsInfos() + AZ::Outcome, AZStd::string> PythonBindings::GetGemInfosForRepo(const QString& repoUri) + { + QVector gemInfos; + AZ::Outcome result = ExecuteWithLockErrorHandling( + [&] + { + auto pyUri = QString_To_Py_String(repoUri); + auto gemPaths = m_repo.attr("get_gem_json_paths_from_cached_repo")(pyUri); + + if (pybind11::isinstance(gemPaths)) + { + for (auto path : gemPaths) + { + GemInfo gemInfo = GemInfoFromPath(path, pybind11::none()); + gemInfo.m_downloadStatus = GemInfo::DownloadStatus::NotDownloaded; + gemInfos.push_back(gemInfo); + } + } + }); + + if (!result.IsSuccess()) + { + return AZ::Failure(result.GetError()); + } + + return AZ::Success(AZStd::move(gemInfos)); + } + + AZ::Outcome, AZStd::string> PythonBindings::GetGemInfosForAllRepos() { QVector gemInfos; AZ::Outcome result = ExecuteWithLockErrorHandling( @@ -1215,7 +1261,7 @@ namespace O3DE::ProjectManager return AZ::Success(AZStd::move(gemInfos)); } - AZ::Outcome PythonBindings::DownloadGem( + AZ::Outcome> PythonBindings::DownloadGem( const QString& gemName, std::function gemProgressCallback, bool force) { // This process is currently limited to download a single gem at a time. @@ -1244,11 +1290,12 @@ namespace O3DE::ProjectManager if (!result.IsSuccess()) { - return result; + AZStd::pair pythonRunError(result.GetError(), result.GetError()); + return AZ::Failure>(AZStd::move(pythonRunError)); } else if (!downloadSucceeded) { - return AZ::Failure("Failed to download gem."); + return AZ::Failure>(GetSimpleDetailedErrorPair()); } return AZ::Success(); @@ -1274,4 +1321,23 @@ namespace O3DE::ProjectManager return result && updateAvaliableResult; } + + AZStd::pair PythonBindings::GetSimpleDetailedErrorPair() + { + AZStd::string detailedString = m_pythonErrorStrings.size() == 1 + ? "" + : AZStd::accumulate(m_pythonErrorStrings.begin(), m_pythonErrorStrings.end(), AZStd::string("")); + + return AZStd::pair(m_pythonErrorStrings.front(), detailedString); + } + + void PythonBindings::AddErrorString(AZStd::string errorString) + { + m_pythonErrorStrings.push_back(errorString); + } + + void PythonBindings::ClearErrorStrings() + { + m_pythonErrorStrings.clear(); + } } diff --git a/Code/Tools/ProjectManager/Source/PythonBindings.h b/Code/Tools/ProjectManager/Source/PythonBindings.h index ecc6f65dc3..48841b6565 100644 --- a/Code/Tools/ProjectManager/Source/PythonBindings.h +++ b/Code/Tools/ProjectManager/Source/PythonBindings.h @@ -62,14 +62,19 @@ namespace O3DE::ProjectManager // Gem Repos AZ::Outcome RefreshGemRepo(const QString& repoUri) override; bool RefreshAllGemRepos() override; - bool AddGemRepo(const QString& repoUri) override; + AZ::Outcome> AddGemRepo(const QString& repoUri) override; bool RemoveGemRepo(const QString& repoUri) override; AZ::Outcome, AZStd::string> GetAllGemRepoInfos() override; - AZ::Outcome, AZStd::string> GetAllGemRepoGemsInfos() override; - AZ::Outcome DownloadGem(const QString& gemName, std::function gemProgressCallback, bool force = false) override; + AZ::Outcome, AZStd::string> GetGemInfosForRepo(const QString& repoUri) override; + AZ::Outcome, AZStd::string> GetGemInfosForAllRepos() override; + AZ::Outcome> DownloadGem( + const QString& gemName, std::function gemProgressCallback, bool force = false) override; void CancelDownload() override; bool IsGemUpdateAvaliable(const QString& gemName, const QString& lastUpdated) override; + void AddErrorString(AZStd::string errorString) override; + void ClearErrorStrings() override; + private: AZ_DISABLE_COPY_MOVE(PythonBindings); @@ -82,6 +87,7 @@ namespace O3DE::ProjectManager AZ::Outcome GemRegistration(const QString& gemPath, const QString& projectPath, bool remove = false); bool RegisterThisEngine(); bool StopPython(); + AZStd::pair GetSimpleDetailedErrorPair(); bool m_pythonStarted = false; @@ -101,5 +107,6 @@ namespace O3DE::ProjectManager pybind11::handle m_pathlib; bool m_requestCancelDownload = false; + AZStd::vector m_pythonErrorStrings; }; } diff --git a/Code/Tools/ProjectManager/Source/PythonBindingsInterface.h b/Code/Tools/ProjectManager/Source/PythonBindingsInterface.h index 65337869fd..c7c8af2ce1 100644 --- a/Code/Tools/ProjectManager/Source/PythonBindingsInterface.h +++ b/Code/Tools/ProjectManager/Source/PythonBindingsInterface.h @@ -200,9 +200,9 @@ namespace O3DE::ProjectManager /** * Registers this gem repo with the current engine. * @param repoUri the absolute filesystem path or url to the gem repo. - * @return true on success, false on failure. + * @return an outcome with a pair of string error and detailed messages on failure. */ - virtual bool AddGemRepo(const QString& repoUri) = 0; + virtual AZ::Outcome> AddGemRepo(const QString& repoUri) = 0; /** * Unregisters this gem repo with the current engine. @@ -217,20 +217,27 @@ namespace O3DE::ProjectManager */ virtual AZ::Outcome, AZStd::string> GetAllGemRepoInfos() = 0; + /** + * Gathers all gem infos from the provided repo + * @param repoUri the absolute filesystem path or url to the gem repo. + * @return A list of gem infos. + */ + virtual AZ::Outcome, AZStd::string> GetGemInfosForRepo(const QString& repoUri) = 0; + /** * Gathers all gem infos for all gems registered from repos. * @return A list of gem infos. */ - virtual AZ::Outcome, AZStd::string> GetAllGemRepoGemsInfos() = 0; + virtual AZ::Outcome, AZStd::string> GetGemInfosForAllRepos() = 0; /** * Downloads and registers a Gem. * @param gemName the name of the Gem to download. * @param gemProgressCallback a callback function that is called with an int percentage download value. * @param force should we forcibly overwrite the old version of the gem. - * @return an outcome with a string error message on failure. + * @return an outcome with a pair of string error and detailed messages on failure. */ - virtual AZ::Outcome DownloadGem( + virtual AZ::Outcome> DownloadGem( const QString& gemName, std::function gemProgressCallback, bool force = false) = 0; /** @@ -245,6 +252,17 @@ namespace O3DE::ProjectManager * @return true if update is avaliable, false if not. */ virtual bool IsGemUpdateAvaliable(const QString& gemName, const QString& lastUpdated) = 0; + + /** + * Add an error string to be returned when the current python call is complete. + * @param The error string to be displayed. + */ + virtual void AddErrorString(AZStd::string errorString) = 0; + + /** + * Clears the current list of error strings. + */ + virtual void ClearErrorStrings() = 0; }; using PythonBindingsInterface = AZ::Interface; diff --git a/Code/Tools/ProjectManager/Source/ScreenWidget.h b/Code/Tools/ProjectManager/Source/ScreenWidget.h index 148dcdb8c8..a84fb0be80 100644 --- a/Code/Tools/ProjectManager/Source/ScreenWidget.h +++ b/Code/Tools/ProjectManager/Source/ScreenWidget.h @@ -47,9 +47,9 @@ namespace O3DE::ProjectManager return tr("Missing"); } - virtual bool ContainsScreen([[maybe_unused]] ProjectManagerScreen screen) + virtual bool ContainsScreen(ProjectManagerScreen screen) { - return false; + return GetScreenEnum() == screen; } virtual void GoToScreen([[maybe_unused]] ProjectManagerScreen screen) { @@ -58,7 +58,6 @@ namespace O3DE::ProjectManager //! Notify this screen it is the current screen virtual void NotifyCurrentScreen() { - } signals: diff --git a/Code/Tools/ProjectManager/Source/UpdateProjectCtrl.cpp b/Code/Tools/ProjectManager/Source/UpdateProjectCtrl.cpp index fb16484961..36d78ed2ac 100644 --- a/Code/Tools/ProjectManager/Source/UpdateProjectCtrl.cpp +++ b/Code/Tools/ProjectManager/Source/UpdateProjectCtrl.cpp @@ -15,6 +15,9 @@ #include #include #include +#include +#include +#include #include #include @@ -94,6 +97,17 @@ namespace O3DE::ProjectManager return ProjectManagerScreen::UpdateProject; } + bool UpdateProjectCtrl::ContainsScreen(ProjectManagerScreen screen) + { + // Do not include GemRepos because we don't want to advertise jumping to it from all other screens here + return screen == GetScreenEnum() || screen == ProjectManagerScreen::GemCatalog; + } + + void UpdateProjectCtrl::GoToScreen(ProjectManagerScreen screen) + { + OnChangeScreenRequest(screen); + } + // Called when pressing "Edit Project Settings..." void UpdateProjectCtrl::NotifyCurrentScreen() { @@ -114,6 +128,16 @@ namespace O3DE::ProjectManager m_stack->setCurrentWidget(m_gemRepoScreen); Update(); } + else if (screen == ProjectManagerScreen::GemCatalog) + { + m_stack->setCurrentWidget(m_gemCatalogScreen); + Update(); + } + else if (screen == ProjectManagerScreen::UpdateProjectSettings) + { + m_stack->setCurrentWidget(m_updateSettingsScreen); + Update(); + } else { emit ChangeScreenRequest(screen); @@ -280,6 +304,21 @@ namespace O3DE::ProjectManager } } + if (newProjectSettings.m_projectName != m_projectInfo.m_projectName) + { + // update reg key + QString oldSettingsKey = GetProjectBuiltSuccessfullyKey(m_projectInfo.m_projectName); + QString newSettingsKey = GetProjectBuiltSuccessfullyKey(newProjectSettings.m_projectName); + + auto settingsRegistry = AZ::SettingsRegistry::Get(); + bool projectBuiltSuccessfully = false; + if (settingsRegistry && settingsRegistry->Get(projectBuiltSuccessfully, oldSettingsKey.toStdString().c_str())) + { + settingsRegistry->Set(newSettingsKey.toStdString().c_str(), projectBuiltSuccessfully); + SaveProjectManagerSettings(); + } + } + if (!newProjectSettings.m_newPreviewImagePath.isEmpty()) { if (!ProjectUtils::ReplaceProjectFile( diff --git a/Code/Tools/ProjectManager/Source/UpdateProjectCtrl.h b/Code/Tools/ProjectManager/Source/UpdateProjectCtrl.h index ee6fc792f2..070e2c58bf 100644 --- a/Code/Tools/ProjectManager/Source/UpdateProjectCtrl.h +++ b/Code/Tools/ProjectManager/Source/UpdateProjectCtrl.h @@ -24,7 +24,8 @@ namespace O3DE::ProjectManager QT_FORWARD_DECLARE_CLASS(GemCatalogScreen) QT_FORWARD_DECLARE_CLASS(GemRepoScreen) - class UpdateProjectCtrl : public ScreenWidget + class UpdateProjectCtrl + : public ScreenWidget { Q_OBJECT public: @@ -32,7 +33,8 @@ namespace O3DE::ProjectManager ~UpdateProjectCtrl() = default; ProjectManagerScreen GetScreenEnum() override; - protected: + bool ContainsScreen(ProjectManagerScreen screen) override; + void GoToScreen(ProjectManagerScreen screen) override; void NotifyCurrentScreen() override; protected slots: diff --git a/Code/Tools/ProjectManager/Source/UpdateProjectSettingsScreen.cpp b/Code/Tools/ProjectManager/Source/UpdateProjectSettingsScreen.cpp index 3bfc07c5b0..a430102c27 100644 --- a/Code/Tools/ProjectManager/Source/UpdateProjectSettingsScreen.cpp +++ b/Code/Tools/ProjectManager/Source/UpdateProjectSettingsScreen.cpp @@ -35,7 +35,7 @@ namespace O3DE::ProjectManager previewExtrasLayout->setContentsMargins(50, 0, 0, 0); QLabel* projectPreviewLabel = new QLabel(tr("Select an image (PNG). Minimum %1 x %2 pixels.") - .arg(QString::number(ProjectPreviewImageWidth), QString::number(ProjectPreviewImageHeight))); + .arg(QString::number(ProjectPreviewImageWidth), QString::number(ProjectPreviewImageHeight))); projectPreviewLabel->setObjectName("projectPreviewLabel"); previewExtrasLayout->addWidget(projectPreviewLabel); diff --git a/Code/Tools/ProjectManager/project_manager_files.cmake b/Code/Tools/ProjectManager/project_manager_files.cmake index fcfae2f336..43c11edacc 100644 --- a/Code/Tools/ProjectManager/project_manager_files.cmake +++ b/Code/Tools/ProjectManager/project_manager_files.cmake @@ -58,6 +58,8 @@ set(FILES Source/CreateProjectCtrl.cpp Source/UpdateProjectCtrl.h Source/UpdateProjectCtrl.cpp + Source/ProjectManagerSettings.h + Source/ProjectManagerSettings.cpp Source/ProjectsScreen.h Source/ProjectsScreen.cpp Source/ProjectSettingsScreen.h diff --git a/Gems/AWSClientAuth/Code/Include/Private/Authorization/AWSClientAuthCognitoCachingAuthenticatedCredentialsProvider.h b/Gems/AWSClientAuth/Code/Include/Private/Authorization/AWSClientAuthCognitoCachingAuthenticatedCredentialsProvider.h new file mode 100644 index 0000000000..ad7faf4671 --- /dev/null +++ b/Gems/AWSClientAuth/Code/Include/Private/Authorization/AWSClientAuthCognitoCachingAuthenticatedCredentialsProvider.h @@ -0,0 +1,44 @@ +/* + * 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 AWSClientAuth +{ + //! Cognito Caching Credentials Provider implementation that is derived from AWS Native SDK. + //! For use with authenticated credentials. + class AWSClientAuthCognitoCachingAuthenticatedCredentialsProvider + : public Aws::Auth::CognitoCachingCredentialsProvider + { + public: + AWSClientAuthCognitoCachingAuthenticatedCredentialsProvider( + const std::shared_ptr& identityRepository, + const std::shared_ptr& cognitoIdentityClient = nullptr); + + protected: + Aws::CognitoIdentity::Model::GetCredentialsForIdentityOutcome GetCredentialsFromCognito() const override; + }; + + //! Cognito Caching Credentials Provider implementation that is eventually derived from AWS Native SDK. + //! For use with anonymous credentials. + class AWSClientAuthCachingAnonymousCredsProvider : public AWSClientAuthCognitoCachingAuthenticatedCredentialsProvider + { + public: + AWSClientAuthCachingAnonymousCredsProvider( + const std::shared_ptr& identityRepository, + const std::shared_ptr& cognitoIdentityClient = nullptr); + + protected: + Aws::CognitoIdentity::Model::GetCredentialsForIdentityOutcome GetCredentialsFromCognito() const override; + }; + +} // namespace AWSClientAuth diff --git a/Gems/AWSClientAuth/Code/Include/Private/Authorization/AWSCognitoAuthorizationController.h b/Gems/AWSClientAuth/Code/Include/Private/Authorization/AWSCognitoAuthorizationController.h index 042be8fe89..1378feff19 100644 --- a/Gems/AWSClientAuth/Code/Include/Private/Authorization/AWSCognitoAuthorizationController.h +++ b/Gems/AWSClientAuth/Code/Include/Private/Authorization/AWSCognitoAuthorizationController.h @@ -9,6 +9,7 @@ #pragma once #include +#include #include #include #include @@ -51,8 +52,8 @@ namespace AWSClientAuth std::shared_ptr m_persistentCognitoIdentityProvider; std::shared_ptr m_persistentAnonymousCognitoIdentityProvider; - std::shared_ptr m_cognitoCachingCredentialsProvider; - std::shared_ptr m_cognitoCachingAnonymousCredentialsProvider; + std::shared_ptr m_cognitoCachingCredentialsProvider; + std::shared_ptr m_cognitoCachingAnonymousCredentialsProvider; AZStd::string m_cognitoIdentityPoolId; AZStd::string m_formattedCognitoUserPoolId; diff --git a/Gems/AWSClientAuth/Code/Source/Authorization/AWSClientAuthCognitoCachingAuthenticatedCredentialsProvider.cpp b/Gems/AWSClientAuth/Code/Source/Authorization/AWSClientAuthCognitoCachingAuthenticatedCredentialsProvider.cpp new file mode 100644 index 0000000000..2492afa441 --- /dev/null +++ b/Gems/AWSClientAuth/Code/Source/Authorization/AWSClientAuthCognitoCachingAuthenticatedCredentialsProvider.cpp @@ -0,0 +1,122 @@ +/* + * 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 AWSClientAuth +{ + static const char* AUTH_LOG_TAG = "AWSClientAuthCognitoCachingAuthenticatedCredentialsProvider"; + static const char* ANON_LOG_TAG = "AWSClientAuthCachingAnonymousCredsProvider"; + + // Modification of https://github.com/aws/aws-sdk-cpp/blob/main/aws-cpp-sdk-identity-management/source/auth/CognitoCachingCredentialsProvider.cpp#L92 + // to work around account ID requirement. Account id is not required for call to succeed and is not set unless provided. + // see: https://github.com/aws/aws-sdk-cpp/issues/1448 + Aws::CognitoIdentity::Model::GetCredentialsForIdentityOutcome FetchCredsFromCognito( + const Aws::CognitoIdentity::CognitoIdentityClient& cognitoIdentityClient, + Aws::Auth::PersistentCognitoIdentityProvider& identityRepository, + const char* logTag, + bool includeLogins) + { + auto logins = identityRepository.GetLogins(); + Aws::Map cognitoLogins; + for (auto& login : logins) + { + cognitoLogins[login.first] = login.second.accessToken; + } + + if (!identityRepository.HasIdentityId()) + { + auto accountId = identityRepository.GetAccountId(); + auto identityPoolId = identityRepository.GetIdentityPoolId(); + + Aws::CognitoIdentity::Model::GetIdRequest getIdRequest; + getIdRequest.SetIdentityPoolId(identityPoolId); + + if (!accountId.empty()) // new check + { + getIdRequest.SetAccountId(accountId); + AWS_LOGSTREAM_INFO(logTag, "Identity not found, requesting an id for accountId " + << accountId << " identity pool id " + << identityPoolId << " with logins."); + } + else + { + AWS_LOGSTREAM_INFO( + logTag, "Identity not found, requesting an id for identity pool id %s" << identityPoolId << " with logins."); + } + if (includeLogins) + { + getIdRequest.SetLogins(cognitoLogins); + } + + auto getIdOutcome = cognitoIdentityClient.GetId(getIdRequest); + if (getIdOutcome.IsSuccess()) + { + auto identityId = getIdOutcome.GetResult().GetIdentityId(); + AWS_LOGSTREAM_INFO(logTag, "Successfully retrieved identity: " << identityId); + identityRepository.PersistIdentityId(identityId); + } + else + { + AWS_LOGSTREAM_ERROR( + logTag, + "Failed to retrieve identity. Error: " << getIdOutcome.GetError().GetExceptionName() << " " + << getIdOutcome.GetError().GetMessage()); + return Aws::CognitoIdentity::Model::GetCredentialsForIdentityOutcome(getIdOutcome.GetError()); + } + } + + Aws::CognitoIdentity::Model::GetCredentialsForIdentityRequest getCredentialsForIdentityRequest; + getCredentialsForIdentityRequest.SetIdentityId(identityRepository.GetIdentityId()); + if (includeLogins) + { + getCredentialsForIdentityRequest.SetLogins(cognitoLogins); + } + + return cognitoIdentityClient.GetCredentialsForIdentity(getCredentialsForIdentityRequest); + } + + AWSClientAuthCognitoCachingAuthenticatedCredentialsProvider::AWSClientAuthCognitoCachingAuthenticatedCredentialsProvider( + const std::shared_ptr& identityRepository, + const std::shared_ptr& cognitoIdentityClient) + : CognitoCachingCredentialsProvider(identityRepository, cognitoIdentityClient) + { + } + + Aws::CognitoIdentity::Model::GetCredentialsForIdentityOutcome + AWSClientAuthCognitoCachingAuthenticatedCredentialsProvider::GetCredentialsFromCognito() const + { + return FetchCredsFromCognito(*m_cognitoIdentityClient, *m_identityRepository, AUTH_LOG_TAG, true); + } + + AWSClientAuthCachingAnonymousCredsProvider::AWSClientAuthCachingAnonymousCredsProvider( + const std::shared_ptr& identityRepository, + const std::shared_ptr& cognitoIdentityClient) + : AWSClientAuthCognitoCachingAuthenticatedCredentialsProvider(identityRepository, cognitoIdentityClient) + { + } + + Aws::CognitoIdentity::Model::GetCredentialsForIdentityOutcome AWSClientAuthCachingAnonymousCredsProvider:: + GetCredentialsFromCognito() const + { + return FetchCredsFromCognito(*m_cognitoIdentityClient, *m_identityRepository, ANON_LOG_TAG, false); + } + + +} // namespace AWSClientAuth diff --git a/Gems/AWSClientAuth/Code/Source/Authorization/AWSCognitoAuthorizationController.cpp b/Gems/AWSClientAuth/Code/Source/Authorization/AWSCognitoAuthorizationController.cpp index 3af28582d6..f53149c90f 100644 --- a/Gems/AWSClientAuth/Code/Source/Authorization/AWSCognitoAuthorizationController.cpp +++ b/Gems/AWSClientAuth/Code/Source/Authorization/AWSCognitoAuthorizationController.cpp @@ -8,6 +8,7 @@ #include #include +#include #include #include #include @@ -38,10 +39,12 @@ namespace AWSClientAuth auto identityClient = AZ::Interface::Get()->GetCognitoIdentityClient(); m_cognitoCachingCredentialsProvider = - std::make_shared(m_persistentCognitoIdentityProvider, identityClient); + std::make_shared( + m_persistentCognitoIdentityProvider, identityClient); m_cognitoCachingAnonymousCredentialsProvider = - std::make_shared(m_persistentAnonymousCognitoIdentityProvider, identityClient); + std::make_shared( + m_persistentAnonymousCognitoIdentityProvider, identityClient); } AWSCognitoAuthorizationController::~AWSCognitoAuthorizationController() @@ -65,9 +68,13 @@ namespace AWSClientAuth AWSCore::AWSResourceMappingRequestBus::BroadcastResult( m_cognitoIdentityPoolId, &AWSCore::AWSResourceMappingRequests::GetResourceNameId, CognitoIdentityPoolIdResourceMappingKey); - if (m_awsAccountId.empty() || m_cognitoIdentityPoolId.empty()) + if (m_awsAccountId.empty()) + { + AZ_TracePrintf("AWSCognitoAuthorizationController", "AWS account id not not configured. Proceeding without it."); + } + + if (m_cognitoIdentityPoolId.empty()) { - AZ_Warning("AWSCognitoAuthorizationController", !m_awsAccountId.empty(), "Missing AWS account id not configured."); AZ_Warning("AWSCognitoAuthorizationController", !m_cognitoIdentityPoolId.empty(), "Missing Cognito Identity pool id in resource mappings."); return false; } diff --git a/Gems/AWSClientAuth/Code/Tests/Authorization/AWSCognitoAuthorizationControllerTest.cpp b/Gems/AWSClientAuth/Code/Tests/Authorization/AWSCognitoAuthorizationControllerTest.cpp index 2269a2340a..19064eb1ed 100644 --- a/Gems/AWSClientAuth/Code/Tests/Authorization/AWSCognitoAuthorizationControllerTest.cpp +++ b/Gems/AWSClientAuth/Code/Tests/Authorization/AWSCognitoAuthorizationControllerTest.cpp @@ -62,6 +62,14 @@ TEST_F(AWSCognitoAuthorizationControllerTest, Initialize_Success) ASSERT_TRUE(m_mockController->m_cognitoIdentityPoolId == AWSClientAuthUnitTest::TEST_RESOURCE_NAME_ID); } +TEST_F(AWSCognitoAuthorizationControllerTest, Initialize_Success_GetAWSAccountEmpty) +{ + EXPECT_CALL(m_awsResourceMappingRequestBusMock, GetResourceNameId(testing::_)).Times(2); + EXPECT_CALL(m_awsResourceMappingRequestBusMock, GetDefaultAccountId()).Times(1).WillOnce(testing::Return("")); + EXPECT_CALL(m_awsResourceMappingRequestBusMock, GetDefaultRegion()).Times(1); + ASSERT_TRUE(m_mockController->Initialize()); +} + TEST_F(AWSCognitoAuthorizationControllerTest, RequestAWSCredentials_WithLogins_Success) { AWSClientAuth::AuthenticationTokens tokens( @@ -121,7 +129,7 @@ TEST_F(AWSCognitoAuthorizationControllerTest, MultipleCalls_UsesCacheCredentials m_mockController->RequestAWSCredentialsAsync(); } -TEST_F(AWSCognitoAuthorizationControllerTest, RequestAWSCredentials_Fail_GetIdError) +TEST_F(AWSCognitoAuthorizationControllerTest, RequestAWSCredentials_Fail_GetIdError) // fail { AWSClientAuth::AuthenticationTokens cognitoTokens( AWSClientAuthUnitTest::TEST_TOKEN, AWSClientAuthUnitTest::TEST_TOKEN, AWSClientAuthUnitTest::TEST_TOKEN, @@ -325,7 +333,7 @@ TEST_F(AWSCognitoAuthorizationControllerTest, GetCredentialsProvider_NoPersisted EXPECT_TRUE(actualCredentialsProvider == m_mockController->m_cognitoCachingAnonymousCredentialsProvider); } -TEST_F(AWSCognitoAuthorizationControllerTest, GetCredentialsProvider_NoPersistedLogins_NoAnonymousCredentials_ResultNullPtr) +TEST_F(AWSCognitoAuthorizationControllerTest, GetCredentialsProvider_NoPersistedLogins_NoAnonymousCredentials_ResultNullPtr) // fails { Aws::Client::AWSError error; error.SetExceptionName(AWSClientAuthUnitTest::TEST_EXCEPTION); @@ -437,11 +445,3 @@ TEST_F(AWSCognitoAuthorizationControllerTest, Initialize_Fail_GetResourceNameEmp EXPECT_CALL(m_awsResourceMappingRequestBusMock, GetDefaultAccountId()).Times(1); ASSERT_FALSE(m_mockController->Initialize()); } - -TEST_F(AWSCognitoAuthorizationControllerTest, Initialize_Fail_GetAWSAccountEmpty) -{ - EXPECT_CALL(m_awsResourceMappingRequestBusMock, GetResourceNameId(testing::_)).Times(1); - EXPECT_CALL(m_awsResourceMappingRequestBusMock, GetDefaultAccountId()).Times(1).WillOnce(testing::Return("")); - EXPECT_CALL(m_awsResourceMappingRequestBusMock, GetDefaultRegion()).Times(0); - ASSERT_FALSE(m_mockController->Initialize()); -} diff --git a/Gems/AWSClientAuth/Code/awsclientauth_files.cmake b/Gems/AWSClientAuth/Code/awsclientauth_files.cmake index bd4c971377..3b07b710e7 100644 --- a/Gems/AWSClientAuth/Code/awsclientauth_files.cmake +++ b/Gems/AWSClientAuth/Code/awsclientauth_files.cmake @@ -24,6 +24,7 @@ set(FILES Include/Private/Authorization/AWSCognitoAuthorizationController.h Include/Private/Authorization/AWSClientAuthPersistentCognitoIdentityProvider.h Include/Private/Authorization/AWSCognitoAuthorizationNotificationBusBehaviorHandler.h + Include/Private/Authorization/AWSClientAuthCognitoCachingAuthenticatedCredentialsProvider.h Include/Private/UserManagement/AWSCognitoUserManagementController.h Include/Private/UserManagement/UserManagementNotificationBusBehaviorHandler.h @@ -45,6 +46,7 @@ set(FILES Source/Authorization/ClientAuthAWSCredentials.cpp Source/Authorization/AWSCognitoAuthorizationController.cpp Source/Authorization/AWSClientAuthPersistentCognitoIdentityProvider.cpp + Source/Authorization/AWSClientAuthCognitoCachingAuthenticatedCredentialsProvider.cpp Source/UserManagement/AWSCognitoUserManagementController.cpp ) diff --git a/Gems/AWSCore/Code/Tests/ResourceMapping/AWSResourceMappingManagerTest.cpp b/Gems/AWSCore/Code/Tests/ResourceMapping/AWSResourceMappingManagerTest.cpp index a90518006f..81ea166848 100644 --- a/Gems/AWSCore/Code/Tests/ResourceMapping/AWSResourceMappingManagerTest.cpp +++ b/Gems/AWSCore/Code/Tests/ResourceMapping/AWSResourceMappingManagerTest.cpp @@ -84,7 +84,7 @@ static constexpr const char TEST_VALID_EMPTY_ACCOUNTID_RESOURCE_MAPPING_CONFIG_F }, "AccountId": "", "Region": "us-west-2", - "Version": "1.0.0" + "Version": "1.1.0" })"; static constexpr const char TEST_INVALID_RESOURCE_MAPPING_CONFIG_FILE[] = diff --git a/Gems/AWSCore/Code/Tools/ResourceMappingTool/utils/json_utils.py b/Gems/AWSCore/Code/Tools/ResourceMappingTool/utils/json_utils.py index 7926cca970..8c094a895c 100755 --- a/Gems/AWSCore/Code/Tools/ResourceMappingTool/utils/json_utils.py +++ b/Gems/AWSCore/Code/Tools/ResourceMappingTool/utils/json_utils.py @@ -24,7 +24,7 @@ _RESOURCE_MAPPING_TYPE_JSON_KEY_NAME: str = "Type" _RESOURCE_MAPPING_NAMEID_JSON_KEY_NAME: str = "Name/ID" _RESOURCE_MAPPING_REGION_JSON_KEY_NAME: str = "Region" _RESOURCE_MAPPING_VERSION_JSON_KEY_NAME: str = "Version" -_RESOURCE_MAPPING_JSON_FORMAT_VERSION: str = "1.0.0" +_RESOURCE_MAPPING_JSON_FORMAT_VERSION: str = "1.1.0" RESOURCE_MAPPING_ACCOUNTID_JSON_KEY_NAME: str = "AccountId" RESOURCE_MAPPING_ACCOUNTID_TEMPLATE_VALUE: str = "EMPTY" diff --git a/Gems/Atom/Asset/ImageProcessingAtom/Config/Albedo.preset b/Gems/Atom/Asset/ImageProcessingAtom/Assets/Config/Albedo.preset similarity index 60% rename from Gems/Atom/Asset/ImageProcessingAtom/Config/Albedo.preset rename to Gems/Atom/Asset/ImageProcessingAtom/Assets/Config/Albedo.preset index fe2e7e0cb4..dc1f38d2da 100644 --- a/Gems/Atom/Asset/ImageProcessingAtom/Config/Albedo.preset +++ b/Gems/Atom/Asset/ImageProcessingAtom/Assets/Config/Albedo.preset @@ -7,16 +7,6 @@ "UUID": "{08A95286-ADB2-41E4-96EB-DB48F4726D6A}", "Name": "Albedo", "RGB_Weight": "CIEXYZ", - "FileMasks": [ - "_basecolor", - "_diff", - "_color", - "_col", - "_albedo", - "_alb", - "_bc", - "_diffuse" - ], "PixelFormat": "BC1", "DiscardAlpha": true, "IsPowerOf2": true, @@ -29,16 +19,6 @@ "UUID": "{08A95286-ADB2-41E4-96EB-DB48F4726D6A}", "Name": "Albedo", "RGB_Weight": "CIEXYZ", - "FileMasks": [ - "_diff", - "_color", - "_col", - "_albedo", - "_alb", - "_basecolor", - "_bc", - "_diffuse" - ], "PixelFormat": "ASTC_6x6", "MaxTextureSize": 2048, "DiscardAlpha": true, @@ -51,16 +31,6 @@ "UUID": "{08A95286-ADB2-41E4-96EB-DB48F4726D6A}", "Name": "Albedo", "RGB_Weight": "CIEXYZ", - "FileMasks": [ - "_diff", - "_color", - "_col", - "_albedo", - "_alb", - "_basecolor", - "_bc", - "_diffuse" - ], "PixelFormat": "ASTC_6x6", "MaxTextureSize": 2048, "DiscardAlpha": true, @@ -73,16 +43,6 @@ "UUID": "{08A95286-ADB2-41E4-96EB-DB48F4726D6A}", "Name": "Albedo", "RGB_Weight": "CIEXYZ", - "FileMasks": [ - "_diff", - "_color", - "_col", - "_albedo", - "_alb", - "_basecolor", - "_bc", - "_diffuse" - ], "PixelFormat": "BC1", "DiscardAlpha": true, "IsPowerOf2": true, @@ -94,16 +54,6 @@ "UUID": "{08A95286-ADB2-41E4-96EB-DB48F4726D6A}", "Name": "Albedo", "RGB_Weight": "CIEXYZ", - "FileMasks": [ - "_diff", - "_color", - "_col", - "_albedo", - "_alb", - "_basecolor", - "_bc", - "_diffuse" - ], "PixelFormat": "BC1", "DiscardAlpha": true, "IsPowerOf2": true, diff --git a/Gems/Atom/Asset/ImageProcessingAtom/Config/AlbedoWithCoverage.preset b/Gems/Atom/Asset/ImageProcessingAtom/Assets/Config/AlbedoWithCoverage.preset similarity index 60% rename from Gems/Atom/Asset/ImageProcessingAtom/Config/AlbedoWithCoverage.preset rename to Gems/Atom/Asset/ImageProcessingAtom/Assets/Config/AlbedoWithCoverage.preset index fda5a9cc52..439a057410 100644 --- a/Gems/Atom/Asset/ImageProcessingAtom/Config/AlbedoWithCoverage.preset +++ b/Gems/Atom/Asset/ImageProcessingAtom/Assets/Config/AlbedoWithCoverage.preset @@ -7,15 +7,6 @@ "UUID": "{57ED16B1-407B-4E29-BCFC-D3BAE60F2C85}", "Name": "AlbedoWithCoverage", "RGB_Weight": "CIEXYZ", - "FileMasks": [ - "_diff", - "_color", - "_albedo", - "_alb", - "_basecolor", - "_bc", - "_diffuse" - ], "PixelFormat": "BC1a", "IsPowerOf2": true, "MipMapSetting": { @@ -27,15 +18,6 @@ "UUID": "{57ED16B1-407B-4E29-BCFC-D3BAE60F2C85}", "Name": "AlbedoWithCoverage", "RGB_Weight": "CIEXYZ", - "FileMasks": [ - "_diff", - "_color", - "_albedo", - "_alb", - "_basecolor", - "_bc", - "_diffuse" - ], "PixelFormat": "ASTC_6x6", "IsPowerOf2": true, "MipMapSetting": { @@ -46,15 +28,6 @@ "UUID": "{57ED16B1-407B-4E29-BCFC-D3BAE60F2C85}", "Name": "AlbedoWithCoverage", "RGB_Weight": "CIEXYZ", - "FileMasks": [ - "_diff", - "_color", - "_albedo", - "_alb", - "_basecolor", - "_bc", - "_diffuse" - ], "PixelFormat": "ASTC_6x6", "IsPowerOf2": true, "MipMapSetting": { @@ -65,15 +38,6 @@ "UUID": "{57ED16B1-407B-4E29-BCFC-D3BAE60F2C85}", "Name": "AlbedoWithCoverage", "RGB_Weight": "CIEXYZ", - "FileMasks": [ - "_diff", - "_color", - "_albedo", - "_alb", - "_basecolor", - "_bc", - "_diffuse" - ], "PixelFormat": "BC1a", "IsPowerOf2": true, "MipMapSetting": { @@ -84,15 +48,6 @@ "UUID": "{57ED16B1-407B-4E29-BCFC-D3BAE60F2C85}", "Name": "AlbedoWithCoverage", "RGB_Weight": "CIEXYZ", - "FileMasks": [ - "_diff", - "_color", - "_albedo", - "_alb", - "_basecolor", - "_bc", - "_diffuse" - ], "PixelFormat": "BC1a", "IsPowerOf2": true, "MipMapSetting": { diff --git a/Gems/Atom/Asset/ImageProcessingAtom/Config/AlbedoWithGenericAlpha.preset b/Gems/Atom/Asset/ImageProcessingAtom/Assets/Config/AlbedoWithGenericAlpha.preset similarity index 55% rename from Gems/Atom/Asset/ImageProcessingAtom/Config/AlbedoWithGenericAlpha.preset rename to Gems/Atom/Asset/ImageProcessingAtom/Assets/Config/AlbedoWithGenericAlpha.preset index 19d2b2bbe6..c315ede21c 100644 --- a/Gems/Atom/Asset/ImageProcessingAtom/Config/AlbedoWithGenericAlpha.preset +++ b/Gems/Atom/Asset/ImageProcessingAtom/Assets/Config/AlbedoWithGenericAlpha.preset @@ -7,17 +7,7 @@ "UUID": "{5D9ECB52-4CD9-4CB8-80E3-10CAE5EFB8A2}", "Name": "AlbedoWithGenericAlpha", "RGB_Weight": "CIEXYZ", - "FileMasks": [ - "_diff", - "_color", - "_albedo", - "_alb", - "_basecolor", - "_bc", - "_diffuse" - ], - "PixelFormat": "BC3", - "IsPowerOf2": true, + "PixelFormat": "ASTC_4x4", "MipMapSetting": { "MipGenType": "Box" } @@ -27,18 +17,8 @@ "UUID": "{5D9ECB52-4CD9-4CB8-80E3-10CAE5EFB8A2}", "Name": "AlbedoWithGenericAlpha", "RGB_Weight": "CIEXYZ", - "FileMasks": [ - "_diff", - "_color", - "_albedo", - "_alb", - "_basecolor", - "_bc", - "_diffuse" - ], "PixelFormat": "ASTC_6x6", "MaxTextureSize": 2048, - "IsPowerOf2": true, "MipMapSetting": { "MipGenType": "Box" } @@ -47,18 +27,8 @@ "UUID": "{5D9ECB52-4CD9-4CB8-80E3-10CAE5EFB8A2}", "Name": "AlbedoWithGenericAlpha", "RGB_Weight": "CIEXYZ", - "FileMasks": [ - "_diff", - "_color", - "_albedo", - "_alb", - "_basecolor", - "_bc", - "_diffuse" - ], "PixelFormat": "ASTC_6x6", "MaxTextureSize": 2048, - "IsPowerOf2": true, "MipMapSetting": { "MipGenType": "Box" } @@ -67,17 +37,7 @@ "UUID": "{5D9ECB52-4CD9-4CB8-80E3-10CAE5EFB8A2}", "Name": "AlbedoWithGenericAlpha", "RGB_Weight": "CIEXYZ", - "FileMasks": [ - "_diff", - "_color", - "_albedo", - "_alb", - "_basecolor", - "_bc", - "_diffuse" - ], "PixelFormat": "BC3", - "IsPowerOf2": true, "MipMapSetting": { "MipGenType": "Box" } @@ -86,17 +46,7 @@ "UUID": "{5D9ECB52-4CD9-4CB8-80E3-10CAE5EFB8A2}", "Name": "AlbedoWithGenericAlpha", "RGB_Weight": "CIEXYZ", - "FileMasks": [ - "_diff", - "_color", - "_albedo", - "_alb", - "_basecolor", - "_bc", - "_diffuse" - ], "PixelFormat": "BC3", - "IsPowerOf2": true, "MipMapSetting": { "MipGenType": "Box" } diff --git a/Gems/Atom/Asset/ImageProcessingAtom/Config/AmbientOcclusion.preset b/Gems/Atom/Asset/ImageProcessingAtom/Assets/Config/AmbientOcclusion.preset similarity index 64% rename from Gems/Atom/Asset/ImageProcessingAtom/Config/AmbientOcclusion.preset rename to Gems/Atom/Asset/ImageProcessingAtom/Assets/Config/AmbientOcclusion.preset index d5acef34d6..573de18b88 100644 --- a/Gems/Atom/Asset/ImageProcessingAtom/Config/AmbientOcclusion.preset +++ b/Gems/Atom/Asset/ImageProcessingAtom/Assets/Config/AmbientOcclusion.preset @@ -8,12 +8,6 @@ "Name": "AmbientOcclusion", "SourceColor": "Linear", "DestColor": "Linear", - "FileMasks": [ - "_ao", - "_ambocc", - "_amb", - "_ambientocclusion" - ], "PixelFormat": "BC4" }, "PlatformsPresets": { @@ -22,12 +16,6 @@ "Name": "AmbientOcclusion", "SourceColor": "Linear", "DestColor": "Linear", - "FileMasks": [ - "_ao", - "_ambocc", - "_amb", - "_ambientocclusion" - ], "MaxTextureSize": 2048, "PixelFormat": "ASTC_4x4" }, @@ -36,12 +24,6 @@ "Name": "AmbientOcclusion", "SourceColor": "Linear", "DestColor": "Linear", - "FileMasks": [ - "_ao", - "_ambocc", - "_amb", - "_ambientocclusion" - ], "MaxTextureSize": 2048, "PixelFormat": "ASTC_4x4" }, @@ -50,12 +32,6 @@ "Name": "AmbientOcclusion", "SourceColor": "Linear", "DestColor": "Linear", - "FileMasks": [ - "_ao", - "_ambocc", - "_amb", - "_ambientocclusion" - ], "PixelFormat": "BC4" }, "provo": { @@ -63,12 +39,6 @@ "Name": "AmbientOcclusion", "SourceColor": "Linear", "DestColor": "Linear", - "FileMasks": [ - "_ao", - "_ambocc", - "_amb", - "_ambientocclusion" - ], "PixelFormat": "BC4" } } diff --git a/Gems/Atom/Asset/ImageProcessingAtom/Config/ConvolvedCubemap.preset b/Gems/Atom/Asset/ImageProcessingAtom/Assets/Config/ConvolvedCubemap.preset similarity index 88% rename from Gems/Atom/Asset/ImageProcessingAtom/Config/ConvolvedCubemap.preset rename to Gems/Atom/Asset/ImageProcessingAtom/Assets/Config/ConvolvedCubemap.preset index abdf6501be..1ef15ada45 100644 --- a/Gems/Atom/Asset/ImageProcessingAtom/Config/ConvolvedCubemap.preset +++ b/Gems/Atom/Asset/ImageProcessingAtom/Assets/Config/ConvolvedCubemap.preset @@ -8,10 +8,6 @@ "Name": "ConvolvedCubemap", "SourceColor": "Linear", "DestColor": "Linear", - "FileMasks": [ - "_ccm", - "_convolvedcubemap" - ], "SuppressEngineReduce": true, "PixelFormat": "R9G9B9E5", "DiscardAlpha": true, @@ -35,10 +31,6 @@ "Name": "ConvolvedCubemap", "SourceColor": "Linear", "DestColor": "Linear", - "FileMasks": [ - "_ccm", - "_convolvedcubemap" - ], "SuppressEngineReduce": true, "PixelFormat": "R9G9B9E5", "DiscardAlpha": true, @@ -61,10 +53,6 @@ "Name": "ConvolvedCubemap", "SourceColor": "Linear", "DestColor": "Linear", - "FileMasks": [ - "_ccm", - "_convolvedcubemap" - ], "SuppressEngineReduce": true, "PixelFormat": "R9G9B9E5", "DiscardAlpha": true, @@ -87,10 +75,6 @@ "Name": "ConvolvedCubemap", "SourceColor": "Linear", "DestColor": "Linear", - "FileMasks": [ - "_ccm", - "_convolvedcubemap" - ], "SuppressEngineReduce": true, "PixelFormat": "R9G9B9E5", "DiscardAlpha": true, @@ -113,10 +97,6 @@ "Name": "ConvolvedCubemap", "SourceColor": "Linear", "DestColor": "Linear", - "FileMasks": [ - "_ccm", - "_convolvedcubemap" - ], "SuppressEngineReduce": true, "PixelFormat": "R9G9B9E5", "DiscardAlpha": true, diff --git a/Gems/Atom/Asset/ImageProcessingAtom/Config/Decal_AlbedoWithOpacity.preset b/Gems/Atom/Asset/ImageProcessingAtom/Assets/Config/Decal_AlbedoWithOpacity.preset similarity index 86% rename from Gems/Atom/Asset/ImageProcessingAtom/Config/Decal_AlbedoWithOpacity.preset rename to Gems/Atom/Asset/ImageProcessingAtom/Assets/Config/Decal_AlbedoWithOpacity.preset index e2e009afc5..873d434380 100644 --- a/Gems/Atom/Asset/ImageProcessingAtom/Config/Decal_AlbedoWithOpacity.preset +++ b/Gems/Atom/Asset/ImageProcessingAtom/Assets/Config/Decal_AlbedoWithOpacity.preset @@ -6,9 +6,6 @@ "DefaultPreset": { "UUID": "{E06B5087-2640-49B6-B9BA-D40048162B90}", "Name": "Decal_AlbedoWithOpacity", - "FileMasks": [ - "_decal" - ], "PixelFormat": "BC7t", "IsPowerOf2": true, "MipMapSetting": { @@ -21,9 +18,6 @@ "android": { "UUID": "{E06B5087-2640-49B6-B9BA-D40048162B90}", "Name": "Decal_AlbedoWithOpacity", - "FileMasks": [ - "_decal" - ], "PixelFormat": "ASTC_4x4", "MaxTextureSize": 2048, "IsPowerOf2": true, @@ -36,9 +30,6 @@ "ios": { "UUID": "{E06B5087-2640-49B6-B9BA-D40048162B90}", "Name": "Decal_AlbedoWithOpacity", - "FileMasks": [ - "_decal" - ], "PixelFormat": "ASTC_4x4", "MaxTextureSize": 2048, "IsPowerOf2": true, @@ -51,9 +42,6 @@ "mac": { "UUID": "{E06B5087-2640-49B6-B9BA-D40048162B90}", "Name": "Decal_AlbedoWithOpacity", - "FileMasks": [ - "_decal" - ], "PixelFormat": "BC3", "IsPowerOf2": true, "MipMapSetting": { @@ -65,9 +53,6 @@ "provo": { "UUID": "{E06B5087-2640-49B6-B9BA-D40048162B90}", "Name": "Decal_AlbedoWithOpacity", - "FileMasks": [ - "_decal" - ], "PixelFormat": "BC7t", "IsPowerOf2": true, "MipMapSetting": { diff --git a/Gems/Atom/Asset/ImageProcessingAtom/Config/Displacement.preset b/Gems/Atom/Asset/ImageProcessingAtom/Assets/Config/Displacement.preset similarity index 59% rename from Gems/Atom/Asset/ImageProcessingAtom/Config/Displacement.preset rename to Gems/Atom/Asset/ImageProcessingAtom/Assets/Config/Displacement.preset index 28ac84d646..04f35dbd6f 100644 --- a/Gems/Atom/Asset/ImageProcessingAtom/Config/Displacement.preset +++ b/Gems/Atom/Asset/ImageProcessingAtom/Assets/Config/Displacement.preset @@ -8,18 +8,6 @@ "Name": "Displacement", "SourceColor": "Linear", "DestColor": "Linear", - "FileMasks": [ - "_displ", - "_disp", - "_dsp", - "_d", - "_dm", - "_displacement", - "_height", - "_hm", - "_ht", - "_h" - ], "PixelFormat": "BC4", "DiscardAlpha": true, "IsPowerOf2": true, @@ -33,18 +21,6 @@ "Name": "Displacement", "SourceColor": "Linear", "DestColor": "Linear", - "FileMasks": [ - "_displ", - "_disp", - "_dsp", - "_d", - "_dm", - "_displacement", - "_height", - "_hm", - "_ht", - "_h" - ], "PixelFormat": "ASTC_4x4", "MaxTextureSize": 2048, "DiscardAlpha": true, @@ -59,18 +35,6 @@ "Name": "Displacement", "SourceColor": "Linear", "DestColor": "Linear", - "FileMasks": [ - "_displ", - "_disp", - "_dsp", - "_d", - "_dm", - "_displacement", - "_height", - "_hm", - "_ht", - "_h" - ], "PixelFormat": "ASTC_4x4", "MaxTextureSize": 2048, "DiscardAlpha": true, @@ -84,18 +48,6 @@ "Name": "Displacement", "SourceColor": "Linear", "DestColor": "Linear", - "FileMasks": [ - "_displ", - "_disp", - "_dsp", - "_d", - "_dm", - "_displacement", - "_height", - "_hm", - "_ht", - "_h" - ], "PixelFormat": "BC4", "DiscardAlpha": true, "IsPowerOf2": true, @@ -108,18 +60,6 @@ "Name": "Displacement", "SourceColor": "Linear", "DestColor": "Linear", - "FileMasks": [ - "_displ", - "_disp", - "_dsp", - "_d", - "_dm", - "_displacement", - "_height", - "_hm", - "_ht", - "_h" - ], "PixelFormat": "BC4", "DiscardAlpha": true, "IsPowerOf2": true, diff --git a/Gems/Atom/Asset/ImageProcessingAtom/Config/Emissive.preset b/Gems/Atom/Asset/ImageProcessingAtom/Assets/Config/Emissive.preset similarity index 61% rename from Gems/Atom/Asset/ImageProcessingAtom/Config/Emissive.preset rename to Gems/Atom/Asset/ImageProcessingAtom/Assets/Config/Emissive.preset index f5e3a79357..798b8d1657 100644 --- a/Gems/Atom/Asset/ImageProcessingAtom/Config/Emissive.preset +++ b/Gems/Atom/Asset/ImageProcessingAtom/Assets/Config/Emissive.preset @@ -7,13 +7,6 @@ "UUID": "{07041D83-E0C3-4726-8735-CA0FE550C9A0}", "Name": "Emissive", "RGB_Weight": "CIEXYZ", - "FileMasks": [ - "_emissive", - "_e", - "_glow", - "_em", - "_emit" - ], "PixelFormat": "BC7", "DiscardAlpha": true }, @@ -22,13 +15,6 @@ "UUID": "{07041D83-E0C3-4726-8735-CA0FE550C9A0}", "Name": "Emissive", "RGB_Weight": "CIEXYZ", - "FileMasks": [ - "_emissive", - "_e", - "_glow", - "_em", - "_emit" - ], "PixelFormat": "ASTC_6x6", "MaxTextureSize": 2048, "DiscardAlpha": true @@ -37,13 +23,6 @@ "UUID": "{07041D83-E0C3-4726-8735-CA0FE550C9A0}", "Name": "Emissive", "RGB_Weight": "CIEXYZ", - "FileMasks": [ - "_emissive", - "_e", - "_glow", - "_em", - "_emit" - ], "PixelFormat": "ASTC_6x6", "MaxTextureSize": 2048, "DiscardAlpha": true @@ -52,13 +31,6 @@ "UUID": "{07041D83-E0C3-4726-8735-CA0FE550C9A0}", "Name": "Emissive", "RGB_Weight": "CIEXYZ", - "FileMasks": [ - "_emissive", - "_e", - "_glow", - "_em", - "_emit" - ], "PixelFormat": "BC7", "DiscardAlpha": true }, @@ -66,13 +38,6 @@ "UUID": "{07041D83-E0C3-4726-8735-CA0FE550C9A0}", "Name": "Emissive", "RGB_Weight": "CIEXYZ", - "FileMasks": [ - "_emissive", - "_e", - "_glow", - "_em", - "_emit" - ], "PixelFormat": "BC7", "DiscardAlpha": true } diff --git a/Gems/Atom/Asset/ImageProcessingAtom/Config/Gradient.preset b/Gems/Atom/Asset/ImageProcessingAtom/Assets/Config/Gradient.preset similarity index 100% rename from Gems/Atom/Asset/ImageProcessingAtom/Config/Gradient.preset rename to Gems/Atom/Asset/ImageProcessingAtom/Assets/Config/Gradient.preset diff --git a/Gems/Atom/Asset/ImageProcessingAtom/Config/Greyscale.preset b/Gems/Atom/Asset/ImageProcessingAtom/Assets/Config/Greyscale.preset similarity index 77% rename from Gems/Atom/Asset/ImageProcessingAtom/Config/Greyscale.preset rename to Gems/Atom/Asset/ImageProcessingAtom/Assets/Config/Greyscale.preset index c71ada1269..19439bad2d 100644 --- a/Gems/Atom/Asset/ImageProcessingAtom/Config/Greyscale.preset +++ b/Gems/Atom/Asset/ImageProcessingAtom/Assets/Config/Greyscale.preset @@ -8,11 +8,8 @@ "Name": "Greyscale", "SourceColor": "Linear", "DestColor": "Linear", - "FileMasks": [ - "_mask" - ], "PixelFormat": "BC4", - "IsPowerOf2": true, + "Swizzle": "rrr1", "MipMapSetting": { "MipGenType": "Box" } @@ -23,11 +20,8 @@ "Name": "Greyscale", "SourceColor": "Linear", "DestColor": "Linear", - "FileMasks": [ - "_mask" - ], "PixelFormat": "ASTC_4x4", - "IsPowerOf2": true, + "Swizzle": "rrr1", "MipMapSetting": { "MipGenType": "Box" } @@ -37,11 +31,8 @@ "Name": "Greyscale", "SourceColor": "Linear", "DestColor": "Linear", - "FileMasks": [ - "_mask" - ], "PixelFormat": "ASTC_4x4", - "IsPowerOf2": true, + "Swizzle": "rrr1", "MipMapSetting": { "MipGenType": "Box" } @@ -51,11 +42,8 @@ "Name": "Greyscale", "SourceColor": "Linear", "DestColor": "Linear", - "FileMasks": [ - "_mask" - ], "PixelFormat": "BC4", - "IsPowerOf2": true, + "Swizzle": "rrr1", "MipMapSetting": { "MipGenType": "Box" } @@ -65,11 +53,8 @@ "Name": "Greyscale", "SourceColor": "Linear", "DestColor": "Linear", - "FileMasks": [ - "_mask" - ], "PixelFormat": "BC4", - "IsPowerOf2": true, + "Swizzle": "rrr1", "MipMapSetting": { "MipGenType": "Box" } diff --git a/Gems/Atom/Asset/ImageProcessingAtom/Config/IBLDiffuse.preset b/Gems/Atom/Asset/ImageProcessingAtom/Assets/Config/IBLDiffuse.preset similarity index 90% rename from Gems/Atom/Asset/ImageProcessingAtom/Config/IBLDiffuse.preset rename to Gems/Atom/Asset/ImageProcessingAtom/Assets/Config/IBLDiffuse.preset index 8bd6b348d1..845f8e13e4 100644 --- a/Gems/Atom/Asset/ImageProcessingAtom/Config/IBLDiffuse.preset +++ b/Gems/Atom/Asset/ImageProcessingAtom/Assets/Config/IBLDiffuse.preset @@ -7,9 +7,6 @@ "UUID": "{E3706342-BF21-4D9C-AE28-9670EB3EF3C5}", "Name": "IBLDiffuse", "Description": "The input cubemap generates an IBL diffuse output cubemap.", - "FileMasks": [ - "_ibldiffusecm" - ], "SourceColor": "Linear", "DestColor": "Linear", "SuppressEngineReduce": true, @@ -31,9 +28,6 @@ "android": { "UUID": "{E3706342-BF21-4D9C-AE28-9670EB3EF3C5}", "Name": "IBLDiffuse", - "FileMasks": [ - "_ibldiffusecm" - ], "SourceColor": "Linear", "DestColor": "Linear", "SuppressEngineReduce": true, @@ -54,9 +48,6 @@ "ios": { "UUID": "{E3706342-BF21-4D9C-AE28-9670EB3EF3C5}", "Name": "IBLDiffuse", - "FileMasks": [ - "_ibldiffusecm" - ], "SourceColor": "Linear", "DestColor": "Linear", "SuppressEngineReduce": true, @@ -77,9 +68,6 @@ "mac": { "UUID": "{E3706342-BF21-4D9C-AE28-9670EB3EF3C5}", "Name": "IBLDiffuse", - "FileMasks": [ - "_ibldiffusecm" - ], "SourceColor": "Linear", "DestColor": "Linear", "SuppressEngineReduce": true, @@ -100,9 +88,6 @@ "provo": { "UUID": "{E3706342-BF21-4D9C-AE28-9670EB3EF3C5}", "Name": "IBLDiffuse", - "FileMasks": [ - "_ibldiffusecm" - ], "SourceColor": "Linear", "DestColor": "Linear", "SuppressEngineReduce": true, diff --git a/Gems/Atom/Asset/ImageProcessingAtom/Config/IBLGlobal.preset b/Gems/Atom/Asset/ImageProcessingAtom/Assets/Config/IBLGlobal.preset similarity index 83% rename from Gems/Atom/Asset/ImageProcessingAtom/Config/IBLGlobal.preset rename to Gems/Atom/Asset/ImageProcessingAtom/Assets/Config/IBLGlobal.preset index 717157f2aa..51daf44d6e 100644 --- a/Gems/Atom/Asset/ImageProcessingAtom/Config/IBLGlobal.preset +++ b/Gems/Atom/Asset/ImageProcessingAtom/Assets/Config/IBLGlobal.preset @@ -8,11 +8,6 @@ "Name": "IBLGlobal", "Description": "The input cubemap generates IBL specular and diffuse cubemaps.", "GenerateIBLOnly": true, - "FileMasks": [ - "_iblglobalcm", - "_cubemap", - "_cm" - ], "CubemapSettings": { "GenerateIBLSpecular": true, "IBLSpecularPreset": "IBLSpecular", diff --git a/Gems/Atom/Asset/ImageProcessingAtom/Config/IBLSkybox.preset b/Gems/Atom/Asset/ImageProcessingAtom/Assets/Config/IBLSkybox.preset similarity index 90% rename from Gems/Atom/Asset/ImageProcessingAtom/Config/IBLSkybox.preset rename to Gems/Atom/Asset/ImageProcessingAtom/Assets/Config/IBLSkybox.preset index eee9af4cea..1a596468bd 100644 --- a/Gems/Atom/Asset/ImageProcessingAtom/Config/IBLSkybox.preset +++ b/Gems/Atom/Asset/ImageProcessingAtom/Assets/Config/IBLSkybox.preset @@ -7,9 +7,6 @@ "UUID": "{E6441EAC-9843-484B-8EFC-C03B2935B48D}", "Name": "IBLSkybox", "Description": "The input cubemap generates a skybox, IBL specular, and IBL diffuse output cubemaps.", - "FileMasks": [ - "_iblskyboxcm" - ], "SourceColor": "Linear", "DestColor": "Linear", "SuppressEngineReduce": true, @@ -29,9 +26,6 @@ "android": { "UUID": "{E6441EAC-9843-484B-8EFC-C03B2935B48D}", "Name": "IBLSkybox", - "FileMasks": [ - "_iblskyboxcm" - ], "SourceColor": "Linear", "DestColor": "Linear", "SuppressEngineReduce": true, @@ -50,9 +44,6 @@ "ios": { "UUID": "{E6441EAC-9843-484B-8EFC-C03B2935B48D}", "Name": "IBLSkybox", - "FileMasks": [ - "_iblskyboxcm" - ], "SourceColor": "Linear", "DestColor": "Linear", "SuppressEngineReduce": true, @@ -71,9 +62,6 @@ "mac": { "UUID": "{E6441EAC-9843-484B-8EFC-C03B2935B48D}", "Name": "IBLSkybox", - "FileMasks": [ - "_iblskyboxcm" - ], "SourceColor": "Linear", "DestColor": "Linear", "SuppressEngineReduce": true, @@ -92,9 +80,6 @@ "provo": { "UUID": "{E6441EAC-9843-484B-8EFC-C03B2935B48D}", "Name": "IBLSkybox", - "FileMasks": [ - "_iblskyboxcm" - ], "SourceColor": "Linear", "DestColor": "Linear", "SuppressEngineReduce": true, diff --git a/Gems/Atom/Asset/ImageProcessingAtom/Config/IBLSpecular.preset b/Gems/Atom/Asset/ImageProcessingAtom/Assets/Config/IBLSpecular.preset similarity index 87% rename from Gems/Atom/Asset/ImageProcessingAtom/Config/IBLSpecular.preset rename to Gems/Atom/Asset/ImageProcessingAtom/Assets/Config/IBLSpecular.preset index 4f935c73ff..691f554540 100644 --- a/Gems/Atom/Asset/ImageProcessingAtom/Config/IBLSpecular.preset +++ b/Gems/Atom/Asset/ImageProcessingAtom/Assets/Config/IBLSpecular.preset @@ -7,10 +7,6 @@ "UUID": "{908DA68C-97FB-4C4A-97BC-5A55F30F14FA}", "Name": "IBLSpecular", "Description": "The input cubemap generates an IBL specular output cubemap.", - "FileMasks": [ - "_iblspecularcm", - "_iblspecularcm256" - ], "SourceColor": "Linear", "DestColor": "Linear", "SuppressEngineReduce": true, @@ -34,10 +30,6 @@ "android": { "UUID": "{908DA68C-97FB-4C4A-97BC-5A55F30F14FA}", "Name": "IBLSpecular", - "FileMasks": [ - "_iblspecularcm", - "_iblspecularcm256" - ], "SourceColor": "Linear", "DestColor": "Linear", "SuppressEngineReduce": true, @@ -60,10 +52,6 @@ "ios": { "UUID": "{908DA68C-97FB-4C4A-97BC-5A55F30F14FA}", "Name": "IBLSpecular", - "FileMasks": [ - "_iblspecularcm", - "_iblspecularcm256" - ], "SourceColor": "Linear", "DestColor": "Linear", "SuppressEngineReduce": true, @@ -86,10 +74,6 @@ "mac": { "UUID": "{908DA68C-97FB-4C4A-97BC-5A55F30F14FA}", "Name": "IBLSpecular", - "FileMasks": [ - "_iblspecularcm", - "_iblspecularcm256" - ], "SourceColor": "Linear", "DestColor": "Linear", "SuppressEngineReduce": true, @@ -112,10 +96,6 @@ "provo": { "UUID": "{908DA68C-97FB-4C4A-97BC-5A55F30F14FA}", "Name": "IBLSpecular", - "FileMasks": [ - "_iblspecularcm", - "_iblspecularcm256" - ], "SourceColor": "Linear", "DestColor": "Linear", "SuppressEngineReduce": true, diff --git a/Gems/Atom/Asset/ImageProcessingAtom/Config/IBLSpecularHigh.preset b/Gems/Atom/Asset/ImageProcessingAtom/Assets/Config/IBLSpecularHigh.preset similarity index 90% rename from Gems/Atom/Asset/ImageProcessingAtom/Config/IBLSpecularHigh.preset rename to Gems/Atom/Asset/ImageProcessingAtom/Assets/Config/IBLSpecularHigh.preset index ff4e143326..b436386864 100644 --- a/Gems/Atom/Asset/ImageProcessingAtom/Config/IBLSpecularHigh.preset +++ b/Gems/Atom/Asset/ImageProcessingAtom/Assets/Config/IBLSpecularHigh.preset @@ -7,9 +7,6 @@ "UUID": "{B66395E1-8D0E-4159-989B-FC2B9F091B75}", "Name": "IBLSpecularHigh", "Description": "The input cubemap generates an IBL specular output cubemap.", - "FileMasks": [ - "_iblspecularcm512" - ], "SourceColor": "Linear", "DestColor": "Linear", "SuppressEngineReduce": true, @@ -33,9 +30,6 @@ "android": { "UUID": "{B66395E1-8D0E-4159-989B-FC2B9F091B75}", "Name": "IBLSpecularHigh", - "FileMasks": [ - "_iblspecularcm512" - ], "SourceColor": "Linear", "DestColor": "Linear", "SuppressEngineReduce": true, @@ -58,9 +52,6 @@ "ios": { "UUID": "{B66395E1-8D0E-4159-989B-FC2B9F091B75}", "Name": "IBLSpecularHigh", - "FileMasks": [ - "_iblspecularcm512" - ], "SourceColor": "Linear", "DestColor": "Linear", "SuppressEngineReduce": true, @@ -83,9 +74,6 @@ "mac": { "UUID": "{B66395E1-8D0E-4159-989B-FC2B9F091B75}", "Name": "IBLSpecularHigh", - "FileMasks": [ - "_iblspecularcm512" - ], "SourceColor": "Linear", "DestColor": "Linear", "SuppressEngineReduce": true, @@ -108,9 +96,6 @@ "provo": { "UUID": "{B66395E1-8D0E-4159-989B-FC2B9F091B75}", "Name": "IBLSpecularHigh", - "FileMasks": [ - "_iblspecularcm512" - ], "SourceColor": "Linear", "DestColor": "Linear", "SuppressEngineReduce": true, diff --git a/Gems/Atom/Asset/ImageProcessingAtom/Config/IBLSpecularLow.preset b/Gems/Atom/Asset/ImageProcessingAtom/Assets/Config/IBLSpecularLow.preset similarity index 90% rename from Gems/Atom/Asset/ImageProcessingAtom/Config/IBLSpecularLow.preset rename to Gems/Atom/Asset/ImageProcessingAtom/Assets/Config/IBLSpecularLow.preset index ee9ddd6ac7..7810028efa 100644 --- a/Gems/Atom/Asset/ImageProcessingAtom/Config/IBLSpecularLow.preset +++ b/Gems/Atom/Asset/ImageProcessingAtom/Assets/Config/IBLSpecularLow.preset @@ -7,9 +7,6 @@ "UUID": "{7273ACAE-6E34-487C-AF71-99423A6E1CB0}", "Name": "IBLSpecularLow", "Description": "The input cubemap generates an IBL specular output cubemap.", - "FileMasks": [ - "_iblspecularcm128" - ], "SourceColor": "Linear", "DestColor": "Linear", "SuppressEngineReduce": true, @@ -33,9 +30,6 @@ "android": { "UUID": "{7273ACAE-6E34-487C-AF71-99423A6E1CB0}", "Name": "IBLSpecularLow", - "FileMasks": [ - "_iblspecularcm128" - ], "SourceColor": "Linear", "DestColor": "Linear", "SuppressEngineReduce": true, @@ -58,9 +52,6 @@ "ios": { "UUID": "{7273ACAE-6E34-487C-AF71-99423A6E1CB0}", "Name": "IBLSpecularLow", - "FileMasks": [ - "_iblspecularcm128" - ], "SourceColor": "Linear", "DestColor": "Linear", "SuppressEngineReduce": true, @@ -83,9 +74,6 @@ "mac": { "UUID": "{7273ACAE-6E34-487C-AF71-99423A6E1CB0}", "Name": "IBLSpecularLow", - "FileMasks": [ - "_iblspecularcm128" - ], "SourceColor": "Linear", "DestColor": "Linear", "SuppressEngineReduce": true, @@ -108,9 +96,6 @@ "provo": { "UUID": "{7273ACAE-6E34-487C-AF71-99423A6E1CB0}", "Name": "IBLSpecularLow", - "FileMasks": [ - "_iblspecularcm128" - ], "SourceColor": "Linear", "DestColor": "Linear", "SuppressEngineReduce": true, diff --git a/Gems/Atom/Asset/ImageProcessingAtom/Config/IBLSpecularVeryHigh.preset b/Gems/Atom/Asset/ImageProcessingAtom/Assets/Config/IBLSpecularVeryHigh.preset similarity index 90% rename from Gems/Atom/Asset/ImageProcessingAtom/Config/IBLSpecularVeryHigh.preset rename to Gems/Atom/Asset/ImageProcessingAtom/Assets/Config/IBLSpecularVeryHigh.preset index 08d9416935..a18885dad9 100644 --- a/Gems/Atom/Asset/ImageProcessingAtom/Config/IBLSpecularVeryHigh.preset +++ b/Gems/Atom/Asset/ImageProcessingAtom/Assets/Config/IBLSpecularVeryHigh.preset @@ -7,9 +7,6 @@ "UUID": "{5CD1AFA6-915B-4716-893C-A5B1F4074C22}", "Name": "IBLSpecularVeryHigh", "Description": "The input cubemap generates an IBL specular output cubemap.", - "FileMasks": [ - "_iblspecularcm1024" - ], "SourceColor": "Linear", "DestColor": "Linear", "SuppressEngineReduce": true, @@ -33,9 +30,6 @@ "android": { "UUID": "{5CD1AFA6-915B-4716-893C-A5B1F4074C22}", "Name": "IBLSpecularVeryHigh", - "FileMasks": [ - "_iblspecularcm1024" - ], "SourceColor": "Linear", "DestColor": "Linear", "SuppressEngineReduce": true, @@ -58,9 +52,6 @@ "ios": { "UUID": "{5CD1AFA6-915B-4716-893C-A5B1F4074C22}", "Name": "IBLSpecularVeryHigh", - "FileMasks": [ - "_iblspecularcm1024" - ], "SourceColor": "Linear", "DestColor": "Linear", "SuppressEngineReduce": true, @@ -83,9 +74,6 @@ "mac": { "UUID": "{5CD1AFA6-915B-4716-893C-A5B1F4074C22}", "Name": "IBLSpecularVeryHigh", - "FileMasks": [ - "_iblspecularcm1024" - ], "SourceColor": "Linear", "DestColor": "Linear", "SuppressEngineReduce": true, @@ -108,9 +96,6 @@ "provo": { "UUID": "{5CD1AFA6-915B-4716-893C-A5B1F4074C22}", "Name": "IBLSpecularVeryHigh", - "FileMasks": [ - "_iblspecularcm1024" - ], "SourceColor": "Linear", "DestColor": "Linear", "SuppressEngineReduce": true, diff --git a/Gems/Atom/Asset/ImageProcessingAtom/Config/IBLSpecularVeryLow.preset b/Gems/Atom/Asset/ImageProcessingAtom/Assets/Config/IBLSpecularVeryLow.preset similarity index 90% rename from Gems/Atom/Asset/ImageProcessingAtom/Config/IBLSpecularVeryLow.preset rename to Gems/Atom/Asset/ImageProcessingAtom/Assets/Config/IBLSpecularVeryLow.preset index c5c0788848..fb910b563a 100644 --- a/Gems/Atom/Asset/ImageProcessingAtom/Config/IBLSpecularVeryLow.preset +++ b/Gems/Atom/Asset/ImageProcessingAtom/Assets/Config/IBLSpecularVeryLow.preset @@ -7,9 +7,6 @@ "UUID": "{8293C236-D3E8-4352-8B18-C2E82EEE6547}", "Name": "IBLSpecularVeryLow", "Description": "The input cubemap generates an IBL specular output cubemap.", - "FileMasks": [ - "_iblspecularcm64" - ], "SourceColor": "Linear", "DestColor": "Linear", "SuppressEngineReduce": true, @@ -33,9 +30,6 @@ "android": { "UUID": "{8293C236-D3E8-4352-8B18-C2E82EEE6547}", "Name": "IBLSpecularVeryLow", - "FileMasks": [ - "_iblspecularcm64" - ], "SourceColor": "Linear", "DestColor": "Linear", "SuppressEngineReduce": true, @@ -58,9 +52,6 @@ "ios": { "UUID": "{8293C236-D3E8-4352-8B18-C2E82EEE6547}", "Name": "IBLSpecularVeryLow", - "FileMasks": [ - "_iblspecularcm64" - ], "SourceColor": "Linear", "DestColor": "Linear", "SuppressEngineReduce": true, @@ -83,9 +74,6 @@ "mac": { "UUID": "{8293C236-D3E8-4352-8B18-C2E82EEE6547}", "Name": "IBLSpecularVeryLow", - "FileMasks": [ - "_iblspecularcm64" - ], "SourceColor": "Linear", "DestColor": "Linear", "SuppressEngineReduce": true, @@ -108,9 +96,6 @@ "provo": { "UUID": "{8293C236-D3E8-4352-8B18-C2E82EEE6547}", "Name": "IBLSpecularVeryLow", - "FileMasks": [ - "_iblspecularcm64" - ], "SourceColor": "Linear", "DestColor": "Linear", "SuppressEngineReduce": true, diff --git a/Gems/Atom/Asset/ImageProcessingAtom/Assets/Config/ImageBuilder.settings b/Gems/Atom/Asset/ImageProcessingAtom/Assets/Config/ImageBuilder.settings new file mode 100644 index 0000000000..bba2855650 --- /dev/null +++ b/Gems/Atom/Asset/ImageProcessingAtom/Assets/Config/ImageBuilder.settings @@ -0,0 +1,154 @@ +{ + "Type": "JsonSerialization", + "Version": 1, + "ClassName": "BuilderSettingManager", + "ClassData": { + "BuildSettings": { + "android": { + "GlossScale": 16.0, + "GlossBias": 0.0, + "Streaming": false, + "Enable": true + }, + "ios": { + "GlossScale": 16.0, + "GlossBias": 0.0, + "Streaming": false, + "Enable": true + }, + "mac": { + "GlossScale": 16.0, + "GlossBias": 0.0, + "Streaming": false, + "Enable": true + }, + "pc": { + "GlossScale": 16.0, + "GlossBias": 0.0, + "Streaming": false, + "Enable": true + }, + "linux": { + "GlossScale": 16.0, + "GlossBias": 0.0, + "Streaming": false, + "Enable": true + }, + "provo": { + "GlossScale": 16.0, + "GlossBias": 0.0, + "Streaming": false, + "Enable": false + } + }, + "PresetsByFileMask": { + // albedo + "_basecolor": [ "Albedo", "AlbedoWithGenericAlpha", "AlbedoWithCoverage" ], + "_diff": [ "Albedo", "AlbedoWithGenericAlpha", "AlbedoWithCoverage" ], + "_diffuse": [ "Albedo", "AlbedoWithGenericAlpha", "AlbedoWithCoverage" ], + "_color": [ "Albedo", "AlbedoWithGenericAlpha", "AlbedoWithCoverage" ], + "_col": [ "Albedo", "AlbedoWithGenericAlpha", "AlbedoWithCoverage" ], + "_albedo": [ "Albedo", "AlbedoWithGenericAlpha", "AlbedoWithCoverage" ], + "_alb": [ "Albedo", "AlbedoWithGenericAlpha", "AlbedoWithCoverage" ], + "_bc": [ "Albedo", "AlbedoWithGenericAlpha", "AlbedoWithCoverage" ], + // normals + "_ddn": [ "Normals" ], + "_normal": [ "Normals" ], + "_normalmap": [ "Normals" ], + "_normals": [ "Normals" ], + "_norm": [ "Normals" ], + "_nor": [ "Normals" ], + "_nrm": [ "Normals" ], + "_nm": [ "Normals" ], + "_n": [ "Normals" ], + "_ddna": [ "NormalsWithSmoothness" ], + "_normala": [ "NormalsWithSmoothness" ], + "_nrma": [ "NormalsWithSmoothness" ], + "_nma": [ "NormalsWithSmoothness" ], + "_na": [ "NormalsWithSmoothness" ], + // refelctance + "_spec": [ "Reflectance" ], + "_specular": [ "Reflectance" ], + "_metallic": [ "Reflectance" ], + "_refl": [ "Reflectance" ], + "_ref": [ "Reflectance" ], + "_rf": [ "Reflectance" ], + "_gloss": [ "Reflectance" ], + "_g": [ "Reflectance" ], + "_f0": [ "Reflectance" ], + "_specf0": [ "Reflectance" ], + "_metal": [ "Reflectance" ], + "_mtl": [ "Reflectance" ], + "_m": [ "Reflectance" ], + "_mt": [ "Reflectance" ], + "_metalness": [ "Reflectance" ], + "_rough": [ "Reflectance" ], + "_roughness": [ "Reflectance" ], + // opacity + "_sss": [ "Opacity" ], + "_trans": [ "Opacity" ], + "_opac": [ "Opacity" ], + "_opacity": [ "Opacity" ], + "_o": [ "Opacity" ], + "_op": [ "Opacity" ], + "_mask": [ "Opacity", "Greyscale" ], + "_msk": [ "Opacity" ], + "_blend": [ "Opacity" ], + // AO + "_ao": [ "AmbientOcclusion" ], + "_ambocc": [ "AmbientOcclusion" ], + "_amb": [ "AmbientOcclusion" ], + "_ambientocclusion": [ "AmbientOcclusion" ], + // emissive + "_emissive": [ "Emissive" ], + "_e": [ "Emissive" ], + "_glow": [ "Emissive" ], + "_em": [ "Emissive" ], + "_emit": [ "Emissive" ], + // displacement + "_displ": [ "Displacement" ], + "_disp": [ "Displacement" ], + "_dsp": [ "Displacement" ], + "_d": [ "Displacement" ], + "_dm": [ "Displacement" ], + "_displacement": [ "Displacement" ], + "_height": [ "Displacement" ], + "_hm": [ "Displacement" ], + "_ht": [ "Displacement" ], + "_h": [ "Displacement" ], + // cubemap + "_ibldiffusecm": [ "IBLDiffuse" ], + "_iblskyboxcm": [ "IBLSkybox" ], + "_iblspecularcm": [ "IBLSpecular" ], + "_iblspecularcm64": [ "IBLSpecularVeryLow" ], + "_iblspecularcm128": [ "IBLSpecularLow" ], + "_iblspecularcm256": [ "IBLSpecular" ], + "_iblspecularcm512": [ "IBLSpecularHigh" ], + "_iblspecularcm1024": [ "IBLSpecularVeryHigh" ], + "_skyboxcm": [ "Skybox" ], + "_ccm": [ "ConvolvedCubemap" ], + "_convolvedcubemap": [ "ConvolvedCubemap" ], + "_iblglobalcm": [ "IBLGlobal" ], + "_cubemap": [ "IBLGlobal" ], + "_cm": [ "IBLGlobal" ], + // lut + "_lut": [ "LUT_RG8" ], + "_lutr32f": [ "LUT_R32F" ], + "_lutrgba8": [ "LUT_RGBA8" ], + "_lutrgba16": [ "LUT_RGBA16" ], + "_lutrgba16f": [ "LUT_RGBA16F" ], + "_lutrg16": [ "LUT_RG16" ], + "_lutrg32f": [ "LUT_RG32F" ], + "_lutrgba32f": [ "LUT_RGBA32F" ], + // layer mask + "_layers": [ "LayerMask" ], + "_rgbmask": [ "LayerMask" ], + // decal + "_decal": [ "Decal_AlbedoWithOpacity" ], + // ui + "_ui": [ "UserInterface_Compressed","UserInterface_Lossless" ] + }, + "DefaultPreset": "Albedo", + "DefaultPresetAlpha": "AlbedoWithGenericAlpha" + } +} diff --git a/Gems/Atom/Asset/ImageProcessingAtom/Config/LUT_R32F.preset b/Gems/Atom/Asset/ImageProcessingAtom/Assets/Config/LUT_R32F.preset similarity index 97% rename from Gems/Atom/Asset/ImageProcessingAtom/Config/LUT_R32F.preset rename to Gems/Atom/Asset/ImageProcessingAtom/Assets/Config/LUT_R32F.preset index 1bb23c6e96..693f268304 100644 --- a/Gems/Atom/Asset/ImageProcessingAtom/Config/LUT_R32F.preset +++ b/Gems/Atom/Asset/ImageProcessingAtom/Assets/Config/LUT_R32F.preset @@ -6,7 +6,6 @@ "DefaultPreset": { "UUID": "{10D4D7D8-23E2-4FC5-BE6A-DA9949D2C603}", "Name": "LUT_R32F", - "FileMasks": ["_lutr32f"], "SourceColor": "Linear", "DestColor": "Linear", "PixelFormat": "R32F" diff --git a/Gems/Atom/Asset/ImageProcessingAtom/Config/LUT_RG16.preset b/Gems/Atom/Asset/ImageProcessingAtom/Assets/Config/LUT_RG16.preset similarity index 100% rename from Gems/Atom/Asset/ImageProcessingAtom/Config/LUT_RG16.preset rename to Gems/Atom/Asset/ImageProcessingAtom/Assets/Config/LUT_RG16.preset diff --git a/Gems/Atom/Asset/ImageProcessingAtom/Config/LUT_RG32F.preset b/Gems/Atom/Asset/ImageProcessingAtom/Assets/Config/LUT_RG32F.preset similarity index 97% rename from Gems/Atom/Asset/ImageProcessingAtom/Config/LUT_RG32F.preset rename to Gems/Atom/Asset/ImageProcessingAtom/Assets/Config/LUT_RG32F.preset index 2cf0c6ca0a..7277a4b111 100644 --- a/Gems/Atom/Asset/ImageProcessingAtom/Config/LUT_RG32F.preset +++ b/Gems/Atom/Asset/ImageProcessingAtom/Assets/Config/LUT_RG32F.preset @@ -6,7 +6,6 @@ "DefaultPreset": { "UUID": "{52470B8B-0798-4E03-B0D3-039D5141CFEC}", "Name": "LUT_RG32F", - "FileMasks": ["_lutrg32f"], "SourceColor": "Linear", "DestColor": "Linear", "PixelFormat": "R32G32F" diff --git a/Gems/Atom/Asset/ImageProcessingAtom/Config/LUT_RG8.preset b/Gems/Atom/Asset/ImageProcessingAtom/Assets/Config/LUT_RG8.preset similarity index 79% rename from Gems/Atom/Asset/ImageProcessingAtom/Config/LUT_RG8.preset rename to Gems/Atom/Asset/ImageProcessingAtom/Assets/Config/LUT_RG8.preset index 9838d532b2..051cc2bedc 100644 --- a/Gems/Atom/Asset/ImageProcessingAtom/Config/LUT_RG8.preset +++ b/Gems/Atom/Asset/ImageProcessingAtom/Assets/Config/LUT_RG8.preset @@ -8,9 +8,6 @@ "Name": "LUT_RG8", "SourceColor": "Linear", "DestColor": "Linear", - "FileMasks": [ - "_lut" - ], "PixelFormat": "R8G8" }, "PlatformsPresets": { @@ -19,9 +16,6 @@ "Name": "LUT_RG8", "SourceColor": "Linear", "DestColor": "Linear", - "FileMasks": [ - "_lut" - ], "PixelFormat": "R8G8" }, "ios": { @@ -29,9 +23,6 @@ "Name": "LUT_RG8", "SourceColor": "Linear", "DestColor": "Linear", - "FileMasks": [ - "_lut" - ], "PixelFormat": "R8G8" }, "mac": { @@ -39,9 +30,6 @@ "Name": "LUT_RG8", "SourceColor": "Linear", "DestColor": "Linear", - "FileMasks": [ - "_lut" - ], "PixelFormat": "R8G8" }, "provo": { @@ -49,9 +37,6 @@ "Name": "LUT_RG8", "SourceColor": "Linear", "DestColor": "Linear", - "FileMasks": [ - "_lut" - ], "PixelFormat": "R8G8" } } diff --git a/Gems/Atom/Asset/ImageProcessingAtom/Config/LUT_RGBA16.preset b/Gems/Atom/Asset/ImageProcessingAtom/Assets/Config/LUT_RGBA16.preset similarity index 78% rename from Gems/Atom/Asset/ImageProcessingAtom/Config/LUT_RGBA16.preset rename to Gems/Atom/Asset/ImageProcessingAtom/Assets/Config/LUT_RGBA16.preset index f36d566d7e..ed940e5f25 100644 --- a/Gems/Atom/Asset/ImageProcessingAtom/Config/LUT_RGBA16.preset +++ b/Gems/Atom/Asset/ImageProcessingAtom/Assets/Config/LUT_RGBA16.preset @@ -8,9 +8,6 @@ "Name": "LUT_RGBA16", "SourceColor": "Linear", "DestColor": "Linear", - "FileMasks": [ - "_lutrgba16" - ], "PixelFormat": "R16G16B16A16" }, "PlatformsPresets": { @@ -19,9 +16,6 @@ "Name": "LUT_RGBA16", "SourceColor": "Linear", "DestColor": "Linear", - "FileMasks": [ - "_lutrgba16" - ], "PixelFormat": "R16G16B16A16" }, "ios": { @@ -29,9 +23,6 @@ "Name": "LUT_RGBA16", "SourceColor": "Linear", "DestColor": "Linear", - "FileMasks": [ - "_lutrgba16" - ], "PixelFormat": "R16G16B16A16" }, "osx_gl": { @@ -39,9 +30,6 @@ "Name": "LUT_RGBA16", "SourceColor": "Linear", "DestColor": "Linear", - "FileMasks": [ - "_lutrgba16" - ], "PixelFormat": "R16G16B16A16" }, "provo": { @@ -49,9 +37,6 @@ "Name": "LUT_RGBA16", "SourceColor": "Linear", "DestColor": "Linear", - "FileMasks": [ - "_lutrgba16" - ], "PixelFormat": "R16G16B16A16" } } diff --git a/Gems/Atom/Asset/ImageProcessingAtom/Config/LUT_RGBA16F.preset b/Gems/Atom/Asset/ImageProcessingAtom/Assets/Config/LUT_RGBA16F.preset similarity index 78% rename from Gems/Atom/Asset/ImageProcessingAtom/Config/LUT_RGBA16F.preset rename to Gems/Atom/Asset/ImageProcessingAtom/Assets/Config/LUT_RGBA16F.preset index 367c5101b3..f5d109b4a1 100644 --- a/Gems/Atom/Asset/ImageProcessingAtom/Config/LUT_RGBA16F.preset +++ b/Gems/Atom/Asset/ImageProcessingAtom/Assets/Config/LUT_RGBA16F.preset @@ -8,9 +8,6 @@ "Name": "LUT_RGBA16F", "SourceColor": "Linear", "DestColor": "Linear", - "FileMasks": [ - "_lutrgba16f" - ], "PixelFormat": "R16G16B16A16F" }, "PlatformsPresets": { @@ -19,9 +16,6 @@ "Name": "LUT_RGBA16F", "SourceColor": "Linear", "DestColor": "Linear", - "FileMasks": [ - "_lutrgba16f" - ], "PixelFormat": "R16G16B16A16F" }, "ios": { @@ -29,9 +23,6 @@ "Name": "LUT_RGBA16F", "SourceColor": "Linear", "DestColor": "Linear", - "FileMasks": [ - "_lutrgba16f" - ], "PixelFormat": "R16G16B16A16F" }, "osx_gl": { @@ -39,9 +30,6 @@ "Name": "LUT_RGBA16F", "SourceColor": "Linear", "DestColor": "Linear", - "FileMasks": [ - "_lutrgba16f" - ], "PixelFormat": "R16G16B16A16F" }, "provo": { @@ -49,9 +37,6 @@ "Name": "LUT_RGBA16F", "SourceColor": "Linear", "DestColor": "Linear", - "FileMasks": [ - "_lutrgba16f" - ], "PixelFormat": "R16G16B16A16F" } } diff --git a/Gems/Atom/Asset/ImageProcessingAtom/Config/LUT_RGBA32F.preset b/Gems/Atom/Asset/ImageProcessingAtom/Assets/Config/LUT_RGBA32F.preset similarity index 97% rename from Gems/Atom/Asset/ImageProcessingAtom/Config/LUT_RGBA32F.preset rename to Gems/Atom/Asset/ImageProcessingAtom/Assets/Config/LUT_RGBA32F.preset index 3a456825bf..b85cb66c9d 100644 --- a/Gems/Atom/Asset/ImageProcessingAtom/Config/LUT_RGBA32F.preset +++ b/Gems/Atom/Asset/ImageProcessingAtom/Assets/Config/LUT_RGBA32F.preset @@ -6,7 +6,6 @@ "DefaultPreset": { "UUID": "{AC4C49D4-2C70-425A-8DBF-E7FB2C61CF8D}", "Name": "LUT_RGBA32F", - "FileMasks": ["_lutrgba32f"], "SourceColor": "Linear", "DestColor": "Linear", "PixelFormat": "R32G32B32A32F" diff --git a/Gems/Atom/Asset/ImageProcessingAtom/Config/LUT_RGBA8.preset b/Gems/Atom/Asset/ImageProcessingAtom/Assets/Config/LUT_RGBA8.preset similarity index 100% rename from Gems/Atom/Asset/ImageProcessingAtom/Config/LUT_RGBA8.preset rename to Gems/Atom/Asset/ImageProcessingAtom/Assets/Config/LUT_RGBA8.preset diff --git a/Gems/Atom/Asset/ImageProcessingAtom/Config/LayerMask.preset b/Gems/Atom/Asset/ImageProcessingAtom/Assets/Config/LayerMask.preset similarity index 72% rename from Gems/Atom/Asset/ImageProcessingAtom/Config/LayerMask.preset rename to Gems/Atom/Asset/ImageProcessingAtom/Assets/Config/LayerMask.preset index 5ce06aaea2..d33db40547 100644 --- a/Gems/Atom/Asset/ImageProcessingAtom/Config/LayerMask.preset +++ b/Gems/Atom/Asset/ImageProcessingAtom/Assets/Config/LayerMask.preset @@ -8,10 +8,6 @@ "Name": "LayerMask", "SourceColor": "Linear", "DestColor": "Linear", - "FileMasks": [ - "_layers", - "_rgbmask" - ], "PixelFormat": "R8G8B8X8" }, "PlatformsPresets": { @@ -20,10 +16,6 @@ "Name": "LayerMask", "SourceColor": "Linear", "DestColor": "Linear", - "FileMasks": [ - "_layers", - "_rgbmask" - ], "PixelFormat": "R8G8B8X8" }, "ios": { @@ -31,10 +23,6 @@ "Name": "LayerMask", "SourceColor": "Linear", "DestColor": "Linear", - "FileMasks": [ - "_layers", - "_rgbmask" - ], "PixelFormat": "R8G8B8X8" }, "mac": { @@ -42,10 +30,6 @@ "Name": "LayerMask", "SourceColor": "Linear", "DestColor": "Linear", - "FileMasks": [ - "_layers", - "_rgbmask" - ], "PixelFormat": "R8G8B8X8" }, "provo": { @@ -53,10 +37,6 @@ "Name": "LayerMask", "SourceColor": "Linear", "DestColor": "Linear", - "FileMasks": [ - "_layers", - "_rgbmask" - ], "PixelFormat": "R8G8B8X8" } } diff --git a/Gems/Atom/Asset/ImageProcessingAtom/Config/Normals.preset b/Gems/Atom/Asset/ImageProcessingAtom/Assets/Config/Normals.preset similarity index 62% rename from Gems/Atom/Asset/ImageProcessingAtom/Config/Normals.preset rename to Gems/Atom/Asset/ImageProcessingAtom/Assets/Config/Normals.preset index eee0b88686..3f7a9ff111 100644 --- a/Gems/Atom/Asset/ImageProcessingAtom/Config/Normals.preset +++ b/Gems/Atom/Asset/ImageProcessingAtom/Assets/Config/Normals.preset @@ -8,17 +8,6 @@ "Name": "Normals", "SourceColor": "Linear", "DestColor": "Linear", - "FileMasks": [ - "_ddn", - "_normal", - "_normalmap", - "_normals", - "_norm", - "_nor", - "_nrm", - "_nm", - "_n" - ], "PixelFormat": "BC5s", "DiscardAlpha": true, "IsPowerOf2": true, @@ -33,17 +22,6 @@ "Name": "Normals", "SourceColor": "Linear", "DestColor": "Linear", - "FileMasks": [ - "_ddn", - "_normal", - "_normalmap", - "_normals", - "_norm", - "_nor", - "_nrm", - "_nm", - "_n" - ], "PixelFormat": "ASTC_4x4", "DiscardAlpha": true, "MaxTextureSize": 1024, @@ -58,17 +36,6 @@ "Name": "Normals", "SourceColor": "Linear", "DestColor": "Linear", - "FileMasks": [ - "_ddn", - "_normal", - "_normalmap", - "_normals", - "_norm", - "_nor", - "_nrm", - "_nm", - "_n" - ], "PixelFormat": "ASTC_4x4", "DiscardAlpha": true, "MaxTextureSize": 1024, @@ -83,17 +50,6 @@ "Name": "Normals", "SourceColor": "Linear", "DestColor": "Linear", - "FileMasks": [ - "_ddn", - "_normal", - "_normalmap", - "_normals", - "_norm", - "_nor", - "_nrm", - "_nm", - "_n" - ], "PixelFormat": "BC5s", "DiscardAlpha": true, "IsPowerOf2": true, @@ -107,17 +63,6 @@ "Name": "Normals", "SourceColor": "Linear", "DestColor": "Linear", - "FileMasks": [ - "_ddn", - "_normal", - "_normalmap", - "_normals", - "_norm", - "_nor", - "_nrm", - "_nm", - "_n" - ], "PixelFormat": "BC5s", "DiscardAlpha": true, "IsPowerOf2": true, diff --git a/Gems/Atom/Asset/ImageProcessingAtom/Config/NormalsWithSmoothness.preset b/Gems/Atom/Asset/ImageProcessingAtom/Assets/Config/NormalsWithSmoothness.preset similarity index 74% rename from Gems/Atom/Asset/ImageProcessingAtom/Config/NormalsWithSmoothness.preset rename to Gems/Atom/Asset/ImageProcessingAtom/Assets/Config/NormalsWithSmoothness.preset index 2c66cf9190..fd0abf3467 100644 --- a/Gems/Atom/Asset/ImageProcessingAtom/Config/NormalsWithSmoothness.preset +++ b/Gems/Atom/Asset/ImageProcessingAtom/Assets/Config/NormalsWithSmoothness.preset @@ -8,13 +8,6 @@ "Name": "NormalsWithSmoothness", "SourceColor": "Linear", "DestColor": "Linear", - "FileMasks": [ - "_ddna", - "_normala", - "_nrma", - "_nma", - "_na" - ], "PixelFormat": "BC5s", "PixelFormatAlpha": "BC4", "IsPowerOf2": true, @@ -30,13 +23,6 @@ "Name": "NormalsWithSmoothness", "SourceColor": "Linear", "DestColor": "Linear", - "FileMasks": [ - "_ddna", - "_normala", - "_nrma", - "_nma", - "_na" - ], "PixelFormat": "ASTC_4x4", "PixelFormatAlpha": "ASTC_4x4", "MaxTextureSize": 2048, @@ -52,13 +38,6 @@ "Name": "NormalsWithSmoothness", "SourceColor": "Linear", "DestColor": "Linear", - "FileMasks": [ - "_ddna", - "_normala", - "_nrma", - "_nma", - "_na" - ], "PixelFormat": "ASTC_4x4", "PixelFormatAlpha": "ASTC_4x4", "MaxTextureSize": 2048, @@ -74,13 +53,6 @@ "Name": "NormalsWithSmoothness", "SourceColor": "Linear", "DestColor": "Linear", - "FileMasks": [ - "_ddna", - "_normala", - "_nrma", - "_nma", - "_na" - ], "PixelFormat": "BC5s", "PixelFormatAlpha": "BC4", "IsPowerOf2": true, @@ -95,13 +67,6 @@ "Name": "NormalsWithSmoothness", "SourceColor": "Linear", "DestColor": "Linear", - "FileMasks": [ - "_ddna", - "_normala", - "_nrma", - "_nma", - "_na" - ], "PixelFormat": "BC5s", "PixelFormatAlpha": "BC4", "IsPowerOf2": true, diff --git a/Gems/Atom/Asset/ImageProcessingAtom/Config/Opacity.preset b/Gems/Atom/Asset/ImageProcessingAtom/Assets/Config/Opacity.preset similarity index 56% rename from Gems/Atom/Asset/ImageProcessingAtom/Config/Opacity.preset rename to Gems/Atom/Asset/ImageProcessingAtom/Assets/Config/Opacity.preset index 53998583cc..e896b74522 100644 --- a/Gems/Atom/Asset/ImageProcessingAtom/Config/Opacity.preset +++ b/Gems/Atom/Asset/ImageProcessingAtom/Assets/Config/Opacity.preset @@ -8,19 +8,8 @@ "Name": "Opacity", "SourceColor": "Linear", "DestColor": "Linear", - "FileMasks": [ - "_sss", - "_trans", - "_opac", - "_opacity", - "_o", - "_opac", - "_op", - "_mask", - "_msk", - "_blend" - ], "PixelFormat": "BC4", + "Swizzle": "rrr1", "IsPowerOf2": true, "MipMapSetting": { "MipGenType": "Box" @@ -32,19 +21,8 @@ "Name": "Opacity", "SourceColor": "Linear", "DestColor": "Linear", - "FileMasks": [ - "_sss", - "_trans", - "_opac", - "_opacity", - "_o", - "_opac", - "_op", - "_mask", - "_msk", - "_blend" - ], "PixelFormat": "ASTC_4x4", + "Swizzle": "rrr1", "MaxTextureSize": 2048, "IsPowerOf2": true, "MipMapSetting": { @@ -56,19 +34,8 @@ "Name": "Opacity", "SourceColor": "Linear", "DestColor": "Linear", - "FileMasks": [ - "_sss", - "_trans", - "_opac", - "_opacity", - "_o", - "_opac", - "_op", - "_mask", - "_msk", - "_blend" - ], "PixelFormat": "ASTC_4x4", + "Swizzle": "rrr1", "MaxTextureSize": 2048, "IsPowerOf2": true, "MipMapSetting": { @@ -80,19 +47,8 @@ "Name": "Opacity", "SourceColor": "Linear", "DestColor": "Linear", - "FileMasks": [ - "_sss", - "_trans", - "_opac", - "_opacity", - "_o", - "_opac", - "_op", - "_mask", - "_msk", - "_blend" - ], "PixelFormat": "BC4", + "Swizzle": "rrr1", "IsPowerOf2": true, "MipMapSetting": { "MipGenType": "Box" @@ -103,19 +59,8 @@ "Name": "Opacity", "SourceColor": "Linear", "DestColor": "Linear", - "FileMasks": [ - "_sss", - "_trans", - "_opac", - "_opacity", - "_o", - "_opac", - "_op", - "_mask", - "_msk", - "_blend" - ], "PixelFormat": "BC4", + "Swizzle": "rrr1", "IsPowerOf2": true, "MipMapSetting": { "MipGenType": "Box" diff --git a/Gems/Atom/Asset/ImageProcessingAtom/Config/ReferenceImage.preset b/Gems/Atom/Asset/ImageProcessingAtom/Assets/Config/ReferenceImage.preset similarity index 100% rename from Gems/Atom/Asset/ImageProcessingAtom/Config/ReferenceImage.preset rename to Gems/Atom/Asset/ImageProcessingAtom/Assets/Config/ReferenceImage.preset diff --git a/Gems/Atom/Asset/ImageProcessingAtom/Config/ReferenceImage_HDRLinear.preset b/Gems/Atom/Asset/ImageProcessingAtom/Assets/Config/ReferenceImage_HDRLinear.preset similarity index 100% rename from Gems/Atom/Asset/ImageProcessingAtom/Config/ReferenceImage_HDRLinear.preset rename to Gems/Atom/Asset/ImageProcessingAtom/Assets/Config/ReferenceImage_HDRLinear.preset diff --git a/Gems/Atom/Asset/ImageProcessingAtom/Config/ReferenceImage_HDRLinearUncompressed.preset b/Gems/Atom/Asset/ImageProcessingAtom/Assets/Config/ReferenceImage_HDRLinearUncompressed.preset similarity index 100% rename from Gems/Atom/Asset/ImageProcessingAtom/Config/ReferenceImage_HDRLinearUncompressed.preset rename to Gems/Atom/Asset/ImageProcessingAtom/Assets/Config/ReferenceImage_HDRLinearUncompressed.preset diff --git a/Gems/Atom/Asset/ImageProcessingAtom/Config/ReferenceImage_Linear.preset b/Gems/Atom/Asset/ImageProcessingAtom/Assets/Config/ReferenceImage_Linear.preset similarity index 100% rename from Gems/Atom/Asset/ImageProcessingAtom/Config/ReferenceImage_Linear.preset rename to Gems/Atom/Asset/ImageProcessingAtom/Assets/Config/ReferenceImage_Linear.preset diff --git a/Gems/Atom/Asset/ImageProcessingAtom/Assets/Config/Reflectance.preset b/Gems/Atom/Asset/ImageProcessingAtom/Assets/Config/Reflectance.preset new file mode 100644 index 0000000000..9e3c718978 --- /dev/null +++ b/Gems/Atom/Asset/ImageProcessingAtom/Assets/Config/Reflectance.preset @@ -0,0 +1,68 @@ +{ + "Type": "JsonSerialization", + "Version": 1, + "ClassName": "MultiplatformPresetSettings", + "ClassData": { + "DefaultPreset": { + "UUID": "{7A3CC95E-0A0C-4CA1-8357-5712B028B77D}", + "Name": "Reflectance", + "SourceColor": "Linear", + "DestColor": "Linear", + "PixelFormat": "BC4", + "IsPowerOf2": true, + "MipMapSetting": { + "MipGenType": "Box" + } + }, + "PlatformsPresets": { + "android": { + "UUID": "{7A3CC95E-0A0C-4CA1-8357-5712B028B77D}", + "Name": "Reflectance", + "SourceColor": "Linear", + "DestColor": "Linear", + "PixelFormat": "ASTC_6x6", + "Swizzle": "rrr1", + "MaxTextureSize": 2048, + "IsPowerOf2": true, + "MipMapSetting": { + "MipGenType": "Box" + } + }, + "ios": { + "UUID": "{7A3CC95E-0A0C-4CA1-8357-5712B028B77D}", + "Name": "Reflectance", + "SourceColor": "Linear", + "DestColor": "Linear", + "PixelFormat": "ASTC_6x6", + "Swizzle": "rrr1", + "MaxTextureSize": 2048, + "IsPowerOf2": true, + "MipMapSetting": { + "MipGenType": "Box" + } + }, + "mac": { + "UUID": "{7A3CC95E-0A0C-4CA1-8357-5712B028B77D}", + "Name": "Reflectance", + "SourceColor": "Linear", + "DestColor": "Linear", + "PixelFormat": "BC4", + "IsPowerOf2": true, + "MipMapSetting": { + "MipGenType": "Box" + } + }, + "provo": { + "UUID": "{7A3CC95E-0A0C-4CA1-8357-5712B028B77D}", + "Name": "Reflectance", + "SourceColor": "Linear", + "DestColor": "Linear", + "PixelFormat": "BC4", + "IsPowerOf2": true, + "MipMapSetting": { + "MipGenType": "Box" + } + } + } + } +} diff --git a/Gems/Atom/Asset/ImageProcessingAtom/Config/Skybox.preset b/Gems/Atom/Asset/ImageProcessingAtom/Assets/Config/Skybox.preset similarity index 86% rename from Gems/Atom/Asset/ImageProcessingAtom/Config/Skybox.preset rename to Gems/Atom/Asset/ImageProcessingAtom/Assets/Config/Skybox.preset index 4f71855ecf..b502872f92 100644 --- a/Gems/Atom/Asset/ImageProcessingAtom/Config/Skybox.preset +++ b/Gems/Atom/Asset/ImageProcessingAtom/Assets/Config/Skybox.preset @@ -6,9 +6,6 @@ "DefaultPreset": { "UUID": "{F359CD3B-37E6-4627-B4F6-2DFC2C0E3C1C}", "Name": "Skybox", - "FileMasks": [ - "_skyboxcm" - ], "SourceColor": "Linear", "DestColor": "Linear", "SuppressEngineReduce": true, @@ -24,9 +21,6 @@ "android": { "UUID": "{F359CD3B-37E6-4627-B4F6-2DFC2C0E3C1C}", "Name": "Skybox", - "FileMasks": [ - "_skyboxcm" - ], "SourceColor": "Linear", "DestColor": "Linear", "SuppressEngineReduce": true, @@ -41,9 +35,6 @@ "ios": { "UUID": "{F359CD3B-37E6-4627-B4F6-2DFC2C0E3C1C}", "Name": "Skybox", - "FileMasks": [ - "_skyboxcm" - ], "SourceColor": "Linear", "DestColor": "Linear", "SuppressEngineReduce": true, @@ -58,9 +49,6 @@ "mac": { "UUID": "{F359CD3B-37E6-4627-B4F6-2DFC2C0E3C1C}", "Name": "Skybox", - "FileMasks": [ - "_skyboxcm" - ], "SourceColor": "Linear", "DestColor": "Linear", "SuppressEngineReduce": true, @@ -75,9 +63,6 @@ "provo": { "UUID": "{F359CD3B-37E6-4627-B4F6-2DFC2C0E3C1C}", "Name": "Skybox", - "FileMasks": [ - "_skyboxcm" - ], "SourceColor": "Linear", "DestColor": "Linear", "SuppressEngineReduce": true, diff --git a/Gems/Atom/Asset/ImageProcessingAtom/Config/UserInterface_Compressed.preset b/Gems/Atom/Asset/ImageProcessingAtom/Assets/Config/UserInterface_Compressed.preset similarity index 95% rename from Gems/Atom/Asset/ImageProcessingAtom/Config/UserInterface_Compressed.preset rename to Gems/Atom/Asset/ImageProcessingAtom/Assets/Config/UserInterface_Compressed.preset index 13334de700..7e2c42fa6b 100644 --- a/Gems/Atom/Asset/ImageProcessingAtom/Config/UserInterface_Compressed.preset +++ b/Gems/Atom/Asset/ImageProcessingAtom/Assets/Config/UserInterface_Compressed.preset @@ -9,8 +9,7 @@ "SuppressEngineReduce": true, "PixelFormat": "R8G8B8A8", "SourceColor": "Linear", - "DestColor": "Linear", - "FileMasks": [ "_ui" ] + "DestColor": "Linear" }, "PlatformsPresets": { "android": { diff --git a/Gems/Atom/Asset/ImageProcessingAtom/Config/UserInterface_Lossless.preset b/Gems/Atom/Asset/ImageProcessingAtom/Assets/Config/UserInterface_Lossless.preset similarity index 95% rename from Gems/Atom/Asset/ImageProcessingAtom/Config/UserInterface_Lossless.preset rename to Gems/Atom/Asset/ImageProcessingAtom/Assets/Config/UserInterface_Lossless.preset index 39066b242b..bec6a604ef 100644 --- a/Gems/Atom/Asset/ImageProcessingAtom/Config/UserInterface_Lossless.preset +++ b/Gems/Atom/Asset/ImageProcessingAtom/Assets/Config/UserInterface_Lossless.preset @@ -9,8 +9,7 @@ "SuppressEngineReduce": true, "PixelFormat": "R8G8B8A8", "SourceColor": "Linear", - "DestColor": "Linear", - "FileMasks": [ "_ui" ] + "DestColor": "Linear" }, "PlatformsPresets": { "android": { diff --git a/Gems/Atom/Asset/ImageProcessingAtom/Code/Source/BuilderSettings/BuilderSettingManager.cpp b/Gems/Atom/Asset/ImageProcessingAtom/Code/Source/BuilderSettings/BuilderSettingManager.cpp index a4ba846f1b..487c659ade 100644 --- a/Gems/Atom/Asset/ImageProcessingAtom/Code/Source/BuilderSettings/BuilderSettingManager.cpp +++ b/Gems/Atom/Asset/ImageProcessingAtom/Code/Source/BuilderSettings/BuilderSettingManager.cpp @@ -8,6 +8,7 @@ #include "BuilderSettingManager.h" +#include #include #include #include @@ -17,8 +18,9 @@ #include #include #include -#include #include +#include +#include #include #include @@ -41,13 +43,18 @@ namespace ImageProcessingAtom { - const char* BuilderSettingManager::s_defaultConfigRelativeFolder = "Gems/Atom/Asset/ImageProcessingAtom/Config/"; + const char* BuilderSettingManager::s_defaultConfigRelativeFolder = "Gems/Atom/Asset/ImageProcessingAtom/Assets/Config/"; const char* BuilderSettingManager::s_projectConfigRelativeFolder = "Config/AtomImageBuilder/"; const char* BuilderSettingManager::s_builderSettingFileName = "ImageBuilder.settings"; - const char* BuilderSettingManager::s_presetFileExtension = ".preset"; + const char* BuilderSettingManager::s_presetFileExtension = "preset"; const char FileMaskDelimiter = '_'; + namespace + { + static constexpr const char* const LogWindow = "Image Processing"; + } + #if defined(AZ_TOOLS_EXPAND_FOR_RESTRICTED_PLATFORMS) #define AZ_RESTRICTED_PLATFORM_EXPANSION(CodeName, CODENAME, codename, PrivateName, PRIVATENAME, privatename, PublicName, PUBLICNAME, publicname, PublicAuxName1, PublicAuxName2, PublicAuxName3) \ namespace ImageProcess##PrivateName \ @@ -69,13 +76,15 @@ namespace ImageProcessingAtom if (serialize) { serialize->Class() - ->Version(1) - ->Field("AnalysisFingerprint", &BuilderSettingManager::m_analysisFingerprint) + ->Version(2) ->Field("BuildSettings", &BuilderSettingManager::m_builderSettings) - ->Field("DefaultPresetsByFileMask", &BuilderSettingManager::m_defaultPresetByFileMask) + ->Field("PresetsByFileMask", &BuilderSettingManager::m_presetFilterMap) ->Field("DefaultPreset", &BuilderSettingManager::m_defaultPreset) ->Field("DefaultPresetAlpha", &BuilderSettingManager::m_defaultPresetAlpha) - ->Field("DefaultPresetNonePOT", &BuilderSettingManager::m_defaultPresetNonePOT); + ->Field("DefaultPresetNonePOT", &BuilderSettingManager::m_defaultPresetNonePOT) + // deprecated properties + ->Field("DefaultPresetsByFileMask", &BuilderSettingManager::m_defaultPresetByFileMask) + ->Field("AnalysisFingerprint", &BuilderSettingManager::m_analysisFingerprint); } } @@ -122,7 +131,7 @@ namespace ImageProcessingAtom s_globalInstance.Reset(); } - const PresetSettings* BuilderSettingManager::GetPreset(const PresetName& presetName, const PlatformName& platform, AZStd::string_view* settingsFilePathOut) + const PresetSettings* BuilderSettingManager::GetPreset(const PresetName& presetName, const PlatformName& platform, AZStd::string_view* settingsFilePathOut) const { AZStd::lock_guard lock(m_presetMapLock); auto itr = m_presets.find(presetName); @@ -137,16 +146,36 @@ namespace ImageProcessingAtom return nullptr; } - const BuilderSettings* BuilderSettingManager::GetBuilderSetting(const PlatformName& platform) + AZStd::vector BuilderSettingManager::GetFileMasksForPreset(const PresetName& presetName) const { - if (m_builderSettings.find(platform) != m_builderSettings.end()) + AZStd::vector fileMasks; + + AZStd::lock_guard lock(m_presetMapLock); + for (const auto& mapping:m_presetFilterMap) { - return &m_builderSettings[platform]; + for (const auto& preset : mapping.second) + { + if (preset == presetName) + { + fileMasks.push_back(mapping.first); + break; + } + } + } + return fileMasks; + } + + const BuilderSettings* BuilderSettingManager::GetBuilderSetting(const PlatformName& platform) const + { + auto itr = m_builderSettings.find(platform); + if (itr != m_builderSettings.end()) + { + return &itr->second; } return nullptr; } - const PlatformNameList BuilderSettingManager::GetPlatformList() + const PlatformNameList BuilderSettingManager::GetPlatformList() const { PlatformNameList platforms; @@ -161,12 +190,19 @@ namespace ImageProcessingAtom return platforms; } - const AZStd::map >& BuilderSettingManager::GetPresetFilterMap() + const AZStd::map >& BuilderSettingManager::GetPresetFilterMap() const { AZStd::lock_guard lock(m_presetMapLock); return m_presetFilterMap; } + const AZStd::unordered_set& BuilderSettingManager::GetFullPresetList() const + { + AZStd::lock_guard lock(m_presetMapLock); + AZStd::string noFilter = AZStd::string(); + return m_presetFilterMap.find(noFilter)->second; + } + const PresetName BuilderSettingManager::GetPresetNameFromId(const AZ::Uuid& presetId) { AZStd::lock_guard lock(m_presetMapLock); @@ -188,7 +224,6 @@ namespace ImageProcessingAtom m_presetFilterMap.clear(); m_builderSettings.clear(); m_presets.clear(); - m_defaultPresetByFileMask.clear(); } StringOutcome BuilderSettingManager::LoadConfig() @@ -198,44 +233,53 @@ namespace ImageProcessingAtom auto fileIoBase = AZ::IO::FileIOBase::GetInstance(); if (fileIoBase == nullptr) { - return AZ::Failure(AZStd::string("File IO instance needs to be initialized to resolve ImageProcessing builder file aliases")); + return AZ::Failure( + AZStd::string("File IO instance needs to be initialized to resolve ImageProcessing builder file aliases")); } - // Construct the default setting path - - AZ::IO::FixedMaxPath defaultConfigFolder; if (auto engineRoot = fileIoBase->ResolvePath("@engroot@"); engineRoot.has_value()) { - defaultConfigFolder = *engineRoot; - defaultConfigFolder /= s_defaultConfigRelativeFolder; + m_defaultConfigFolder = *engineRoot; + m_defaultConfigFolder /= s_defaultConfigRelativeFolder; } - AZ::IO::FixedMaxPath projectConfigFolder; if (auto sourceGameRoot = fileIoBase->ResolvePath("@projectroot@"); sourceGameRoot.has_value()) { - projectConfigFolder = *sourceGameRoot; - projectConfigFolder /= s_projectConfigRelativeFolder; + m_projectConfigFolder = *sourceGameRoot; + m_projectConfigFolder /= s_projectConfigRelativeFolder; } AZStd::lock_guard lock(m_presetMapLock); ClearSettings(); - outcome = LoadSettings((projectConfigFolder / s_builderSettingFileName).Native()); - - if (!outcome.IsSuccess()) - { - outcome = LoadSettings((defaultConfigFolder / s_builderSettingFileName).Native()); - } + outcome = LoadSettings(); if (outcome.IsSuccess()) { // Load presets in default folder first, then load from project folder. // The same presets which loaded last will overwrite previous loaded one. - LoadPresets(defaultConfigFolder.Native()); - LoadPresets(projectConfigFolder.Native()); + LoadPresets(m_defaultConfigFolder.Native()); + LoadPresets(m_projectConfigFolder.Native()); + } - // Regenerate file mask mapping after all presets loaded - RegenerateMappings(); + // Collect extra file masks from preset files + CollectFileMasksFromPresets(); + + + if (QCoreApplication::instance()) + { + m_fileWatcher.reset(new QFileSystemWatcher); + // track preset files + // Note, the QT signal would only works for AP but not AssetBuilder + // We use file time stamp to track preset file change in builder's CreateJob + for (auto& preset : m_presets) + { + m_fileWatcher.data()->addPath(QString(preset.second.m_presetFilePath.c_str())); + } + m_fileWatcher.data()->addPath(QString(m_defaultConfigFolder.c_str())); + m_fileWatcher.data()->addPath(QString(m_projectConfigFolder.c_str())); + QObject::connect(m_fileWatcher.data(), &QFileSystemWatcher::fileChanged, this, &BuilderSettingManager::OnFileChanged); + QObject::connect(m_fileWatcher.data(), &QFileSystemWatcher::directoryChanged, this, &BuilderSettingManager::OnFolderChanged); } return outcome; @@ -243,36 +287,84 @@ namespace ImageProcessingAtom void BuilderSettingManager::LoadPresets(AZStd::string_view presetFolder) { - AZStd::lock_guard lock(m_presetMapLock); - QDirIterator it(presetFolder.data(), QStringList() << "*.preset", QDir::Files, QDirIterator::NoIteratorFlags); while (it.hasNext()) { QString filePath = it.next(); - QFileInfo fileInfo = it.fileInfo(); + LoadPreset(filePath.toUtf8().data()); + } + } - MultiplatformPresetSettings preset; - auto result = AZ::JsonSerializationUtils::LoadObjectFromFile(preset, filePath.toUtf8().data()); - if (!result.IsSuccess()) + bool BuilderSettingManager::LoadPreset(const AZStd::string& filePath) + { + QFileInfo fileInfo (filePath.c_str()); + + if (!fileInfo.exists()) + { + return false; + } + + MultiplatformPresetSettings preset; + auto result = AZ::JsonSerializationUtils::LoadObjectFromFile(preset, filePath); + if (!result.IsSuccess()) + { + AZ_Warning(LogWindow, false, "Failed to load preset file %s. Error: %s", + filePath.c_str(), result.GetError().c_str()); + return false; + } + + PresetName presetName(fileInfo.baseName().toUtf8().data()); + + AZ_Warning(LogWindow, presetName == preset.GetPresetName(), "Preset file name '%s' is not" + " same as preset name '%s'. Using preset file name as preset name", + filePath.c_str(), preset.GetPresetName().GetCStr()); + + preset.SetPresetName(presetName); + + m_presets[presetName] = PresetEntry{preset, filePath.c_str(), fileInfo.lastModified()}; + return true; + } + + void BuilderSettingManager::ReloadPreset(const PresetName& presetName) + { + // Find the preset file from project or default config folder + AZStd::string presetFileName = AZStd::string::format("%s.%s", presetName.GetCStr(), s_presetFileExtension); + AZ::IO::FixedMaxPath filePath = m_projectConfigFolder/presetFileName; + QFileInfo fileInfo (filePath.c_str()); + if (!fileInfo.exists()) + { + filePath = (m_defaultConfigFolder/presetFileName).c_str(); + fileInfo = QFileInfo(filePath.c_str()); + } + + AZStd::lock_guard lock(m_presetMapLock); + + //Skip the loading if the file wasn't chagned + if (fileInfo.exists()) + { + if (m_presets.find(presetName) != m_presets.end()) { - AZ_Warning("Image Processing", false, "Failed to load preset file %s. Error: %s", - filePath.toUtf8().data(), result.GetError().c_str()); + if (m_presets[presetName].m_lastModifiedTime == fileInfo.lastModified() + && m_presets[presetName].m_presetFilePath == filePath.c_str()) + { + return; + } } + } - PresetName presetName(fileInfo.baseName().toUtf8().data()); + // remove preset + m_presets.erase(presetName); - AZ_Warning("Image Processing", presetName == preset.GetPresetName(), "Preset file name '%s' is not" - " same as preset name '%s'. Using preset file name as preset name", - filePath.toUtf8().data(), preset.GetPresetName().GetCStr()); - - preset.SetPresetName(presetName); - - m_presets[presetName] = PresetEntry{preset, filePath.toUtf8().data()}; + if (fileInfo.exists()) + { + LoadPreset(filePath.c_str()); } } StringOutcome BuilderSettingManager::LoadConfigFromFolder(AZStd::string_view configFolder) { + AZStd::lock_guard lock(m_presetMapLock); + // Load builder settings AZStd::string settingFilePath = AZStd::string::format("%.*s%s", aznumeric_cast(configFolder.size()), configFolder.data(), s_builderSettingFileName); @@ -282,12 +374,108 @@ namespace ImageProcessingAtom if (result.IsSuccess()) { LoadPresets(configFolder); - RegenerateMappings(); } return result; } + void BuilderSettingManager::ReportDeprecatedSettings() + { + // reported deprecated attributes in image builder settings + if (!m_analysisFingerprint.empty()) + { + AZ_Warning(LogWindow, false, "'AnalysisFingerprint' is deprecated and it should be removed from file [%s]", s_builderSettingFileName); + } + if (!m_defaultPresetByFileMask.empty()) + { + AZ_Warning(LogWindow, false, "'DefaultPresetsByFileMask' is deprecated and it should be removed from file [%s]. Use PresetsByFileMask instead", s_builderSettingFileName); + } + } + + StringOutcome BuilderSettingManager::LoadSettings() + { + // If the project image build setting file exist, it will merge image builder settings from project folder to the settings from default config folder. + bool needMerge = false; + AZStd::string projectSettingFile{ (m_projectConfigFolder / s_builderSettingFileName).Native() }; + + if (AZ::IO::SystemFile::Exists(projectSettingFile.c_str())) + { + needMerge = true; + } + + AZ::Outcome outcome; + AZStd::string defaultSettingFile{ (m_defaultConfigFolder / s_builderSettingFileName).Native() }; + if (needMerge) + { + auto outcome1 = AZ::JsonSerializationUtils::ReadJsonFile(defaultSettingFile); + auto outcome2 = AZ::JsonSerializationUtils::ReadJsonFile(projectSettingFile); + + // return error if it failed to load default settings + if (!outcome1.IsSuccess()) + { + return STRING_OUTCOME_ERROR(outcome1.GetError()); + } + + // if project config was loaded successfully, apply merge patch + rapidjson::Document& originDoc = outcome1.GetValue(); + if (outcome2.IsSuccess()) + { + const rapidjson::Document& patchDoc = outcome2.GetValue(); + AZ::JsonSerializationResult::ResultCode result = + AZ::JsonSerialization::ApplyPatch(originDoc, originDoc.GetAllocator(), patchDoc, AZ::JsonMergeApproach::JsonMergePatch); + + if (result.GetProcessing() == AZ::JsonSerializationResult::Processing::Completed) + { + AZStd::vector outBuffer; + AZ::IO::ByteContainerStream> outStream{ &outBuffer }; + AZ::JsonSerializationUtils::WriteJsonStream(originDoc, outStream); + + outStream.Seek(0, AZ::IO::GenericStream::ST_SEEK_BEGIN); + + outcome = AZ::JsonSerializationUtils::LoadObjectFromStream(*this, outStream); + if (!outcome.IsSuccess()) + { + return STRING_OUTCOME_ERROR(outcome.GetError()); + } + + ReportDeprecatedSettings(); + + + // Generate config file fingerprint + outStream.Seek(0, AZ::IO::GenericStream::ST_SEEK_BEGIN); + AZ::u64 hash = AssetBuilderSDK::GetHashFromIOStream(outStream); + m_analysisFingerprint = AZStd::string::format("%llX", hash); + } + else + { + needMerge = false; + AZ_Warning(LogWindow, false, "Failed to fully merge data into image builder settings. Skipping project build setting file [%s]", projectSettingFile.c_str()); + } + } + else + { + AZ_Warning(LogWindow, false, "Failed to load project setting file [%s]. Skipping", projectSettingFile.c_str()); + } + } + + if (!needMerge) + { + outcome = AZ::JsonSerializationUtils::LoadObjectFromFile(*this, defaultSettingFile); + if (!outcome.IsSuccess()) + { + return STRING_OUTCOME_ERROR(outcome.GetError()); + } + + ReportDeprecatedSettings(); + + // Generate config file fingerprint + AZ::u64 hash = AssetBuilderSDK::GetFileHash(defaultSettingFile.c_str()); + m_analysisFingerprint = AZStd::string::format("%llX", hash); + } + + return STRING_OUTCOME_SUCCESS; + } + StringOutcome BuilderSettingManager::LoadSettings(AZStd::string_view filepath) { AZStd::lock_guard lock(m_presetMapLock); @@ -336,13 +524,13 @@ namespace ImageProcessingAtom return m_analysisFingerprint; } - void BuilderSettingManager::RegenerateMappings() + void BuilderSettingManager::CollectFileMasksFromPresets() { AZStd::lock_guard lock(m_presetMapLock); AZStd::string noFilter = AZStd::string(); - - m_presetFilterMap.clear(); + + AZStd::string extraString; for (const auto& presetIter : m_presets) { @@ -357,22 +545,31 @@ namespace ImageProcessingAtom { if (filemask.empty() || filemask[0] != FileMaskDelimiter) { - AZ_Warning("Image Processing", false, "File mask '%s' is invalid. It must start with '%c'.", filemask.c_str(), FileMaskDelimiter); + AZ_Warning(LogWindow, false, "File mask '%s' is invalid. It must start with '%c'.", filemask.c_str(), FileMaskDelimiter); continue; } else if (filemask.size() < 2) { - AZ_Warning("Image Processing", false, "File mask '%s' is invalid. The '%c' must be followed by at least one other character.", filemask.c_str()); + AZ_Warning(LogWindow, false, "File mask '%s' is invalid. The '%c' must be followed by at least one other character.", filemask.c_str()); continue; } else if (filemask.find(FileMaskDelimiter, 1) != AZStd::string::npos) { - AZ_Warning("Image Processing", false, "File mask '%s' is invalid. It must contain only a single '%c' character.", filemask.c_str(), FileMaskDelimiter); + AZ_Warning(LogWindow, false, "File mask '%s' is invalid. It must contain only a single '%c' character.", filemask.c_str(), FileMaskDelimiter); continue; } + + extraString += (filemask + preset.m_name.GetCStr()); + m_presetFilterMap[filemask].insert(preset.m_name); } } + + if (!extraString.empty()) + { + AZ::u64 hash = AZStd::hash{}(extraString); + m_analysisFingerprint += AZStd::string::format("%llX", hash); + } } void BuilderSettingManager::MetafilePathFromImagePath(AZStd::string_view imagePath, AZStd::string& metafilePath) @@ -419,38 +616,15 @@ namespace ImageProcessingAtom return m_presets.find(presetName) != m_presets.end(); } - PresetName BuilderSettingManager::GetSuggestedPreset(AZStd::string_view imageFilePath, IImageObjectPtr imageFromFile) + PresetName BuilderSettingManager::GetSuggestedPreset(AZStd::string_view imageFilePath) const { PresetName emptyPreset; - //load the image to get its size for later use - IImageObjectPtr image = imageFromFile; - //if the input image is empty we will try to load it from the path - if (imageFromFile == nullptr) - { - image = IImageObjectPtr(LoadImageFromFile(imageFilePath)); - } - - if (image == nullptr) - { - return emptyPreset; - } - //get file mask of this image file AZStd::string fileMask = GetFileMask(imageFilePath); PresetName outPreset = emptyPreset; - //check default presets for some file masks - if (m_defaultPresetByFileMask.find(fileMask) != m_defaultPresetByFileMask.end()) - { - outPreset = m_defaultPresetByFileMask[fileMask]; - if (!IsValidPreset(outPreset)) - { - outPreset = emptyPreset; - } - } - //use the preset filter map to find if (outPreset.IsEmpty() && !fileMask.empty()) { @@ -461,54 +635,21 @@ namespace ImageProcessingAtom } } - const PresetSettings* presetInfo = nullptr; - - if (!outPreset.IsEmpty()) - { - presetInfo = GetPreset(outPreset); - - //special case for cubemap - if (presetInfo && presetInfo->m_cubemapSetting) - { - // If it's not a latitude-longitude map or it doesn't match any cubemap layouts then reset its preset - if (!IsValidLatLongMap(image) && CubemapLayout::GetCubemapLayoutInfo(image) == nullptr) - { - outPreset = emptyPreset; - } - } - } - if (outPreset == emptyPreset) { - if (image->GetAlphaContent() == EAlphaContent::eAlphaContent_Absent) - { - outPreset = m_defaultPreset; - } - else - { - outPreset = m_defaultPresetAlpha; - } + outPreset = m_defaultPreset; } - //get the pixel format for selected preset - presetInfo = GetPreset(outPreset); + return outPreset; + } - if (presetInfo) - { - //valid whether image size work with pixel format - if (CPixelFormats::GetInstance().IsImageSizeValid(presetInfo->m_pixelFormat, - image->GetWidth(0), image->GetHeight(0), false)) - { - return outPreset; - } - else - { - AZ_Warning("Image Processing", false, "Image dimensions are not compatible with preset '%s'. The default preset will be used.", presetInfo->m_name.GetCStr()); - } - } - - //uncompressed one which could be used for almost everything - return m_defaultPresetNonePOT; + AZStd::vector BuilderSettingManager::GetPossiblePresetPaths(const PresetName& presetName) const + { + AZStd::vector paths; + AZStd::string presetFile = AZStd::string::format("%s.preset", presetName.GetCStr()); + paths.push_back((m_defaultConfigFolder / presetFile).c_str()); + paths.push_back((m_projectConfigFolder / presetFile).c_str()); + return paths; } bool BuilderSettingManager::DoesSupportPlatform(AZStd::string_view platformId) @@ -526,18 +667,50 @@ namespace ImageProcessingAtom AZStd::string filePath; if (!AzFramework::StringFunc::Path::Join(outputFolder.data(), fileName.c_str(), filePath)) { - AZ_Warning("Image Processing", false, "Failed to construct path with folder '%.*s' and file: '%s' to save preset", + AZ_Warning(LogWindow, false, "Failed to construct path with folder '%.*s' and file: '%s' to save preset", aznumeric_cast(outputFolder.size()), outputFolder.data(), filePath.c_str()); continue; } auto result = AZ::JsonSerializationUtils::SaveObjectToFile(&presetEntry.m_multiPreset, filePath); if (!result.IsSuccess()) { - AZ_Warning("Image Processing", false, "Failed to save preset '%s' to file '%s'. Error: %s", + AZ_Warning(LogWindow, false, "Failed to save preset '%s' to file '%s'. Error: %s", presetEntry.m_multiPreset.GetDefaultPreset().m_name.GetCStr(), filePath.c_str(), result.GetError().c_str()); } } } + void BuilderSettingManager::OnFileChanged(const QString &path) + { + // handles preset file change + // Note: this signal only works with AP but not AssetBuilder + AZ_TracePrintf(LogWindow, "File changed %s\n", path.toUtf8().data()); + QFileInfo info(path); + // skip if the file is not a preset file + // Note: for .settings file change it's handled when restart AP. + if (info.suffix() != s_presetFileExtension) + { + return; + } + + ReloadPreset(PresetName(info.baseName().toUtf8().data())); + } + + void BuilderSettingManager::OnFolderChanged([[maybe_unused]] const QString &path) + { + // handles new file added or removed + // Note: this signal only works with AP but not AssetBuilder + AZ_TracePrintf(LogWindow, "folder changed %s\n", path.toUtf8().data()); + + AZStd::lock_guard lock(m_presetMapLock); + m_presets.clear(); + LoadPresets(m_defaultConfigFolder.Native()); + LoadPresets(m_projectConfigFolder.Native()); + + for (auto& preset : m_presets) + { + m_fileWatcher.data()->addPath(QString(preset.second.m_presetFilePath.c_str())); + } + } } // namespace ImageProcessingAtom diff --git a/Gems/Atom/Asset/ImageProcessingAtom/Code/Source/BuilderSettings/BuilderSettingManager.h b/Gems/Atom/Asset/ImageProcessingAtom/Code/Source/BuilderSettings/BuilderSettingManager.h index 3bbb71ea43..443b91bc07 100644 --- a/Gems/Atom/Asset/ImageProcessingAtom/Code/Source/BuilderSettings/BuilderSettingManager.h +++ b/Gems/Atom/Asset/ImageProcessingAtom/Code/Source/BuilderSettings/BuilderSettingManager.h @@ -10,10 +10,15 @@ #include #include -#include #include +#include +#include #include +#include +#include +#include + class QSettings; class QString; @@ -36,6 +41,7 @@ namespace ImageProcessingAtom * Each preset setting may have different values on different platform, but they are using same uuid. */ class BuilderSettingManager + : public QObject // required for using QFileSystemWatcher { friend class ImageProcessingTest; @@ -49,17 +55,21 @@ namespace ImageProcessingAtom static void DestroyInstance(); static void Reflect(AZ::ReflectContext* context); - const PresetSettings* GetPreset(const PresetName& presetName, const PlatformName& platform = "", AZStd::string_view* settingsFilePathOut = nullptr); + const PresetSettings* GetPreset(const PresetName& presetName, const PlatformName& platform = "", AZStd::string_view* settingsFilePathOut = nullptr) const; - const BuilderSettings* GetBuilderSetting(const PlatformName& platform); + AZStd::vector GetFileMasksForPreset(const PresetName& presetName) const; + + const BuilderSettings* GetBuilderSetting(const PlatformName& platform) const; //! Return A list of platform supported - const PlatformNameList GetPlatformList(); + const PlatformNameList GetPlatformList() const; //! Return A map of preset settings based on their filemasks. //! @key filemask string, empty string means no filemask //! @value set of preset setting names supporting the specified filemask - const AZStd::map>& GetPresetFilterMap(); + const AZStd::map>& GetPresetFilterMap() const; + + const AZStd::unordered_set& GetFullPresetList() const; //! Find preset name based on the preset id. const PresetName GetPresetNameFromId(const AZ::Uuid& presetId); @@ -68,7 +78,11 @@ namespace ImageProcessingAtom StringOutcome LoadConfig(); //! Load configurations files from a folder which includes builder settings and presets - StringOutcome LoadConfigFromFolder(AZStd::string_view configFolder); + //! Note: this is only used for unit test. Use LoadConfig() for editor or game launcher + StringOutcome LoadConfigFromFolder(AZStd::string_view configFolder); + + //! Reload preset from config folders + void ReloadPreset(const PresetName& presetName); const AZStd::string& GetAnalysisFingerprint() const; @@ -81,7 +95,12 @@ namespace ImageProcessingAtom //! @param imageFilePath: Filepath string of the image file. The function may load the image from the path for better detection //! @param image: an optional image object which can be used for preset selection if there is no match based file mask. //! @return suggested preset name. - PresetName GetSuggestedPreset(AZStd::string_view imageFilePath, IImageObjectPtr image = nullptr); + PresetName GetSuggestedPreset(AZStd::string_view imageFilePath) const; + + //! Get the possible preset config's full file paths + //! This function is only used for setting up image's source dependency if a preset file is missing + //! Otherwise, the preset's file path can be retrieved in GetPreset() function + AZStd::vector GetPossiblePresetPaths(const PresetName& presetName) const; bool IsValidPreset(PresetName presetName) const; @@ -105,25 +124,41 @@ namespace ImageProcessingAtom private: // functions AZ_DISABLE_COPY_MOVE(BuilderSettingManager); + // Write image builder setting to the file specified by filepath StringOutcome WriteSettings(AZStd::string_view filepath); + // Load image builder settings from the file specified by filepath StringOutcome LoadSettings(AZStd::string_view filepath); + // Load merge image builder settings (project and default) + StringOutcome LoadSettings(); + + // report warnings for the deprecated properties in image builder setting data + void ReportDeprecatedSettings(); + // Clear Builder Settings and any cached maps/lists void ClearSettings(); - // Regenerate Builder Settings and any cached maps/lists - void RegenerateMappings(); + // collect file masks + void CollectFileMasksFromPresets(); // Functions to save/load preset from a folder void SavePresets(AZStd::string_view outputFolder); void LoadPresets(AZStd::string_view presetFolder); + // Load a preset to m_presets and return true if success + bool LoadPreset(const AZStd::string& filePath); + + // handle preset files changes + void OnFileChanged(const QString &path); + void OnFolderChanged(const QString &path); + private: // variables struct PresetEntry { MultiplatformPresetSettings m_multiPreset; AZStd::string m_presetFilePath; // Can be used for debug output + QDateTime m_lastModifiedTime; }; // Builder settings for each platform @@ -131,13 +166,13 @@ namespace ImageProcessingAtom AZStd::unordered_map m_presets; - // Cached list of presets mapped by their file masks. + // a list of presets mapped by their file masks. // @Key file mask, use empty string to indicate all presets without filtering // @Value set of preset names that matches the file mask AZStd::map > m_presetFilterMap; - // A mutex to protect when modifying any map in this manager - AZStd::recursive_mutex m_presetMapLock; + // A mutex to protect when modifying any map in this manager + mutable AZStd::recursive_mutex m_presetMapLock; // Default presets for certain file masks AZStd::map m_defaultPresetByFileMask; @@ -153,5 +188,14 @@ namespace ImageProcessingAtom // Image builder's version AZStd::string m_analysisFingerprint; + + // default config folder + AZ::IO::FixedMaxPath m_defaultConfigFolder; + + // project config folder + AZ::IO::FixedMaxPath m_projectConfigFolder; + + // File system watcher to detect preset file changes + QScopedPointer m_fileWatcher; }; } // namespace ImageProcessingAtom diff --git a/Gems/Atom/Asset/ImageProcessingAtom/Code/Source/BuilderSettings/CubemapSettings.h b/Gems/Atom/Asset/ImageProcessingAtom/Code/Source/BuilderSettings/CubemapSettings.h index 9135a0f4d1..77f804b646 100644 --- a/Gems/Atom/Asset/ImageProcessingAtom/Code/Source/BuilderSettings/CubemapSettings.h +++ b/Gems/Atom/Asset/ImageProcessingAtom/Code/Source/BuilderSettings/CubemapSettings.h @@ -26,19 +26,19 @@ namespace ImageProcessingAtom static void Reflect(AZ::ReflectContext* context); // "cm_ftype", cubemap angular filter type: gaussian, cone, disc, cosine, cosine_power, ggx - CubemapFilterType m_filter; + CubemapFilterType m_filter = CubemapFilterType::ggx; // "cm_fangle", base filter angle for cubemap filtering(degrees), 0 - disabled - float m_angle; + float m_angle = 0; // "cm_fmipangle", initial mip filter angle for cubemap filtering(degrees), 0 - disabled - float m_mipAngle; + float m_mipAngle = 0; // "cm_fmipslope", mip filter angle multiplier for cubemap filtering, 1 - default" - float m_mipSlope; + float m_mipSlope = 1; // "cm_edgefixup", cubemap edge fix-up width, 0 - disabled - float m_edgeFixup; + float m_edgeFixup = 0; // generate an IBL specular cubemap bool m_generateIBLSpecular = false; diff --git a/Gems/Atom/Asset/ImageProcessingAtom/Code/Source/BuilderSettings/ImageProcessingDefines.h b/Gems/Atom/Asset/ImageProcessingAtom/Code/Source/BuilderSettings/ImageProcessingDefines.h index e421715995..7c35a0634e 100644 --- a/Gems/Atom/Asset/ImageProcessingAtom/Code/Source/BuilderSettings/ImageProcessingDefines.h +++ b/Gems/Atom/Asset/ImageProcessingAtom/Code/Source/BuilderSettings/ImageProcessingDefines.h @@ -39,7 +39,8 @@ namespace ImageProcessingAtom #define STRING_OUTCOME_ERROR(error) AZ::Failure(AZStd::string(error)) // Common typedefs (with dependent forward-declarations) - typedef AZStd::string PlatformName, FileMask; + typedef AZStd::string PlatformName; + typedef AZStd::string FileMask; typedef AZ::Name PresetName; typedef AZStd::vector PlatformNameVector; typedef AZStd::list PlatformNameList; diff --git a/Gems/Atom/Asset/ImageProcessingAtom/Code/Source/Editor/EditorCommon.cpp b/Gems/Atom/Asset/ImageProcessingAtom/Code/Source/Editor/EditorCommon.cpp index 067faf3dab..3e255dcccc 100644 --- a/Gems/Atom/Asset/ImageProcessingAtom/Code/Source/Editor/EditorCommon.cpp +++ b/Gems/Atom/Asset/ImageProcessingAtom/Code/Source/Editor/EditorCommon.cpp @@ -171,7 +171,7 @@ namespace ImageProcessingAtomEditor if (!preset) { AZ_Warning("Texture Editor", false, "Cannot find preset %s! Will assign a suggested one for the texture.", presetName.GetCStr()); - presetName = BuilderSettingManager::Instance()->GetSuggestedPreset(m_fullPath, m_img); + presetName = BuilderSettingManager::Instance()->GetSuggestedPreset(m_fullPath); for (auto& settingIter : m_settingsMap) { @@ -257,15 +257,22 @@ namespace ImageProcessingAtomEditor // Update input width and height if it's a cubemap if (presetSetting->m_cubemapSetting != nullptr) { - CubemapLayout *srcCubemap = CubemapLayout::CreateCubemapLayout(m_img); - if (srcCubemap == nullptr) + if (IsValidLatLongMap(m_img)) { - return false; + inputWidth = inputWidth/4; + } + else + { + CubemapLayout *srcCubemap = CubemapLayout::CreateCubemapLayout(m_img); + if (srcCubemap == nullptr) + { + return false; + } + inputWidth = srcCubemap->GetFaceSize(); + delete srcCubemap; } - inputWidth = srcCubemap->GetFaceSize(); inputHeight = inputWidth; outResolutionInfo.arrayCount = 6; - delete srcCubemap; } GetOutputExtent(inputWidth, inputHeight, outResolutionInfo.width, outResolutionInfo.height, outResolutionInfo.reduce, &textureSetting, presetSetting); diff --git a/Gems/Atom/Asset/ImageProcessingAtom/Code/Source/Editor/TexturePresetSelectionWidget.cpp b/Gems/Atom/Asset/ImageProcessingAtom/Code/Source/Editor/TexturePresetSelectionWidget.cpp index e50d95b907..cc341c5e31 100644 --- a/Gems/Atom/Asset/ImageProcessingAtom/Code/Source/Editor/TexturePresetSelectionWidget.cpp +++ b/Gems/Atom/Asset/ImageProcessingAtom/Code/Source/Editor/TexturePresetSelectionWidget.cpp @@ -18,6 +18,27 @@ namespace ImageProcessingAtomEditor { using namespace ImageProcessingAtom; + + AZStd::string GetImageFileMask(const AZStd::string& imageFilePath) + { + const char FileMaskDelimiter = '_'; + + //get file name + AZStd::string fileName; + QString lowerFileName = imageFilePath.data(); + lowerFileName = lowerFileName.toLower(); + AzFramework::StringFunc::Path::GetFileName(lowerFileName.toUtf8().constData(), fileName); + + //get the substring from last '_' + size_t lastUnderScore = fileName.find_last_of(FileMaskDelimiter); + if (lastUnderScore != AZStd::string::npos) + { + return fileName.substr(lastUnderScore); + } + + return AZStd::string(); + } + TexturePresetSelectionWidget::TexturePresetSelectionWidget(EditorTextureSetting& textureSetting, QWidget* parent /*= nullptr*/) : QWidget(parent) , m_ui(new Ui::TexturePresetSelectionWidget) @@ -29,33 +50,31 @@ namespace ImageProcessingAtomEditor m_presetList.clear(); auto& presetFilterMap = BuilderSettingManager::Instance()->GetPresetFilterMap(); - AZStd::unordered_set noFilterPresetList; - - // Check if there is any filtered preset list first - for(auto& presetFilter : presetFilterMap) + if (m_listAllPresets) { - if (presetFilter.first.empty()) + m_presetList = BuilderSettingManager::Instance()->GetFullPresetList(); + } + else + { + auto fileMask = GetImageFileMask(m_textureSetting->m_textureName); + auto itr = presetFilterMap.find(fileMask); + if (itr != presetFilterMap.end()) { - noFilterPresetList = presetFilter.second; + m_presetList = itr->second; } - else if (IsMatchingWithFileMask(m_textureSetting->m_textureName, presetFilter.first)) + else { - for(const auto& presetName : presetFilter.second) - { - m_presetList.insert(presetName); - } + m_presetList = BuilderSettingManager::Instance()->GetFullPresetList(); } } - // If no filtered preset list available or should list all presets, use non-filter list - if (m_presetList.size() == 0 || m_listAllPresets) - { - m_presetList = noFilterPresetList; - } + QStringList stringList; foreach (const auto& presetName, m_presetList) { - m_ui->presetComboBox->addItem(QString(presetName.GetCStr())); + stringList.append(QString(presetName.GetCStr())); } + stringList.sort(); + m_ui->presetComboBox->addItems(stringList); // Set current preset const auto& currPreset = m_textureSetting->GetMultiplatformTextureSetting().m_preset; @@ -173,8 +192,9 @@ namespace ImageProcessingAtomEditor AZStd::string conventionText = ""; if (presetSettings) { + auto fileMasks = BuilderSettingManager::Instance()->GetFileMasksForPreset(presetSettings->m_name); int i = 0; - for (const PlatformName& filemask : presetSettings->m_fileMasks) + for (const auto& filemask : fileMasks) { conventionText += i > 0 ? " " + filemask : filemask; i++; diff --git a/Gems/Atom/Asset/ImageProcessingAtom/Code/Source/ImageBuilderComponent.cpp b/Gems/Atom/Asset/ImageProcessingAtom/Code/Source/ImageBuilderComponent.cpp index 90d45ae65a..57596f4a71 100644 --- a/Gems/Atom/Asset/ImageProcessingAtom/Code/Source/ImageBuilderComponent.cpp +++ b/Gems/Atom/Asset/ImageProcessingAtom/Code/Source/ImageBuilderComponent.cpp @@ -221,6 +221,58 @@ namespace ImageProcessingAtom m_isShuttingDown = true; } + PresetName GetImagePreset(const AZStd::string& filepath) + { + // first let preset from asset info + TextureSettings textureSettings; + StringOutcome output = TextureSettings::LoadTextureSetting(filepath, textureSettings); + + if (!textureSettings.m_preset.IsEmpty()) + { + return textureSettings.m_preset; + } + + return BuilderSettingManager::Instance()->GetSuggestedPreset(filepath); + } + + void HandlePresetDependency(PresetName presetName, AZStd::vector& sourceDependencyList) + { + // Reload preset if it was changed + ImageProcessingAtom::BuilderSettingManager::Instance()->ReloadPreset(presetName); + + AZStd::string_view filePath; + auto presetSettings = BuilderSettingManager::Instance()->GetPreset(presetName, /*default platform*/"", &filePath); + + AssetBuilderSDK::SourceFileDependency sourceFileDependency; + sourceFileDependency.m_sourceDependencyType = AssetBuilderSDK::SourceFileDependency::SourceFileDependencyType::Absolute; + + // Need to watch any possibe preset paths + AZStd::vector possiblePresetPaths = BuilderSettingManager::Instance()->GetPossiblePresetPaths(presetName); + for (const auto& path:possiblePresetPaths) + { + sourceFileDependency.m_sourceFileDependencyPath = path; + sourceDependencyList.push_back(sourceFileDependency); + } + + if (presetSettings) + { + // handle special case here + // Cubemap setting may reference some other presets + if (presetSettings->m_cubemapSetting) + { + if (presetSettings->m_cubemapSetting->m_generateIBLDiffuse && !presetSettings->m_cubemapSetting->m_iblDiffusePreset.IsEmpty()) + { + HandlePresetDependency(presetSettings->m_cubemapSetting->m_iblDiffusePreset, sourceDependencyList); + } + + if (presetSettings->m_cubemapSetting->m_generateIBLSpecular && !presetSettings->m_cubemapSetting->m_iblSpecularPreset.IsEmpty()) + { + HandlePresetDependency(presetSettings->m_cubemapSetting->m_iblSpecularPreset, sourceDependencyList); + } + } + } + } + // this happens early on in the file scanning pass // this function should consistently always create the same jobs, and should do no checking whether the job is up to date or not - just be consistent. void ImageBuilderWorker::CreateJobs(const AssetBuilderSDK::CreateJobsRequest& request, AssetBuilderSDK::CreateJobsResponse& response) @@ -242,13 +294,26 @@ namespace ImageProcessingAtom if (ImageProcessingAtom::BuilderSettingManager::Instance()->DoesSupportPlatform(platformInfo.m_identifier)) { AssetBuilderSDK::JobDescriptor descriptor; - descriptor.m_jobKey = ext + " Atom Compile"; + descriptor.m_jobKey = "Image Compile: " + ext; descriptor.SetPlatformIdentifier(platformInfo.m_identifier.c_str()); descriptor.m_critical = false; + descriptor.m_additionalFingerprintInfo = ""; response.m_createJobOutputs.push_back(descriptor); } } + // add source dependency for .assetinfo file + AssetBuilderSDK::SourceFileDependency sourceFileDependency; + sourceFileDependency.m_sourceDependencyType = AssetBuilderSDK::SourceFileDependency::SourceFileDependencyType::Absolute; + sourceFileDependency.m_sourceFileDependencyPath = request.m_sourceFile; + AZ::StringFunc::Path::ReplaceExtension(sourceFileDependency.m_sourceFileDependencyPath, TextureSettings::ExtensionName); + response.m_sourceFileDependencyList.push_back(sourceFileDependency); + + // add source dependencies for .preset files + // Get the preset for this file + auto presetName = GetImagePreset(request.m_sourceFile); + HandlePresetDependency(presetName, response.m_sourceFileDependencyList); + response.m_result = AssetBuilderSDK::CreateJobsResultCode::Success; return; } diff --git a/Gems/Atom/Asset/ImageProcessingAtom/Code/Source/Processing/ImageConvert.cpp b/Gems/Atom/Asset/ImageProcessingAtom/Code/Source/Processing/ImageConvert.cpp index 5b23009cff..defca690a3 100644 --- a/Gems/Atom/Asset/ImageProcessingAtom/Code/Source/Processing/ImageConvert.cpp +++ b/Gems/Atom/Asset/ImageProcessingAtom/Code/Source/Processing/ImageConvert.cpp @@ -11,6 +11,7 @@ #include #include #include +#include #include #include #include @@ -229,12 +230,24 @@ namespace ImageProcessingAtom AZStd::unique_ptr& cubemapSettings = m_input->m_presetSetting.m_cubemapSetting; if (cubemapSettings->m_generateIBLSpecular && !cubemapSettings->m_iblSpecularPreset.IsEmpty()) { - CreateIBLCubemap(cubemapSettings->m_iblSpecularPreset, SpecularCubemapSuffix, m_iblSpecularCubemapImage); + bool success = CreateIBLCubemap(cubemapSettings->m_iblSpecularPreset, SpecularCubemapSuffix, m_iblSpecularCubemapImage); + if (!success) + { + m_isSucceed = false; + m_isFinished = true; + break; + } } if (cubemapSettings->m_generateIBLDiffuse && !cubemapSettings->m_iblDiffusePreset.IsEmpty()) { - CreateIBLCubemap(cubemapSettings->m_iblDiffusePreset, DiffuseCubemapSuffix, m_iblDiffuseCubemapImage); + bool success = CreateIBLCubemap(cubemapSettings->m_iblDiffusePreset, DiffuseCubemapSuffix, m_iblDiffuseCubemapImage); + if (!success) + { + m_isSucceed = false; + m_isFinished = true; + break; + } } } @@ -251,7 +264,12 @@ namespace ImageProcessingAtom { if (m_input->m_presetSetting.m_cubemapSetting->m_requiresConvolve) { - FillCubemapMipmaps(); + bool success = FillCubemapMipmaps(); + if (!success) + { + m_isSucceed = false; + m_isFinished = true; + } } } else @@ -268,9 +286,7 @@ namespace ImageProcessingAtom // get gloss from normal for all mipmaps and save to alpha channel if (m_input->m_presetSetting.m_glossFromNormals) { - bool hasAlpha = (m_alphaContent == EAlphaContent::eAlphaContent_OnlyBlack - || m_alphaContent == EAlphaContent::eAlphaContent_OnlyBlackAndWhite - || m_alphaContent == EAlphaContent::eAlphaContent_Greyscale); + bool hasAlpha = Utils::NeedAlphaChannel(m_alphaContent); m_image->Get()->GlossFromNormals(hasAlpha); // set alpha content so it won't be ignored later. @@ -347,7 +363,11 @@ namespace ImageProcessingAtom } else { - AZ_TracePrintf("Image Processing", "Image converted with preset [%s] [%s] and saved to [%s] (%d bytes) taking %f seconds\n", + + [[maybe_unused]] const PixelFormatInfo* formatInfo = CPixelFormats::GetInstance().GetPixelFormatInfo(m_image->Get()->GetPixelFormat()); + AZ_TracePrintf("Image Processing", "Image [%dx%d] [%s] converted with preset [%s] [%s] and saved to [%s] (%d bytes) taking %f seconds\n", + m_image->Get()->GetWidth(0), m_image->Get()->GetHeight(0), + formatInfo->szName, m_input->m_presetSetting.m_name.GetCStr(), m_input->m_filePath.c_str(), m_input->m_outputFolder.c_str(), sizeTotal, m_processTime); @@ -421,6 +441,17 @@ namespace ImageProcessingAtom outHeight >>= 1; outReduce++; } + + // resize to min texture size if it's smaller + if (outWidth < presetSettings->m_minTextureSize) + { + outWidth = presetSettings->m_minTextureSize; + } + + if (outHeight < presetSettings->m_minTextureSize) + { + outHeight = presetSettings->m_minTextureSize; + } } bool ImageConvertProcess::ConvertToLinear() @@ -647,7 +678,7 @@ namespace ImageProcessingAtom } else if (!CPixelFormats::GetInstance().IsImageSizeValid(dstFmt, dwWidth, dwHeight, false)) { - AZ_Warning("Image Processing", false, "Image size will be scaled for pixel format %s", CPixelFormats::GetInstance().GetPixelFormatInfo(dstFmt)->szName); + AZ_TracePrintf("Image processing", "Image size will be scaled for pixel format %s\n", CPixelFormats::GetInstance().GetPixelFormatInfo(dstFmt)->szName); } #if defined(AZ_TOOLS_EXPAND_FOR_RESTRICTED_PLATFORMS) @@ -758,7 +789,7 @@ namespace ImageProcessingAtom // in very rare user case, an old texture setting file may not have a preset. We fix it over here too. if (textureSettings.m_preset.IsEmpty()) { - textureSettings.m_preset = BuilderSettingManager::Instance()->GetSuggestedPreset(imageFilePath, srcImage); + textureSettings.m_preset = BuilderSettingManager::Instance()->GetSuggestedPreset(imageFilePath); } // Get preset @@ -795,7 +826,7 @@ namespace ImageProcessingAtom return process; } - void ImageConvertProcess::CreateIBLCubemap(PresetName preset, const char* fileNameSuffix, IImageObjectPtr& cubemapImage) + bool ImageConvertProcess::CreateIBLCubemap(PresetName preset, const char* fileNameSuffix, IImageObjectPtr& cubemapImage) { const AZStd::string& platformId = m_input->m_platform; AZStd::string_view filePath; @@ -803,7 +834,7 @@ namespace ImageProcessingAtom if (presetSettings == nullptr) { AZ_Error("Image Processing", false, "Couldn't find preset for IBL cubemap generation"); - return; + return false; } // generate export file name @@ -838,14 +869,14 @@ namespace ImageProcessingAtom if (!imageConvertProcess) { AZ_Error("Image Processing", false, "Failed to create image convert process for the IBL cubemap"); - return; + return false; } imageConvertProcess->ProcessAll(); if (!imageConvertProcess->IsSucceed()) { AZ_Error("Image Processing", false, "Image convert process for the IBL cubemap failed"); - return; + return false; } // append the output products to the job's product list @@ -853,6 +884,7 @@ namespace ImageProcessingAtom // store the output cubemap so it can be accessed by unit tests cubemapImage = imageConvertProcess->m_image->Get(); + return true; } bool ConvertImageFile(const AZStd::string& imageFilePath, const AZStd::string& exportDir, @@ -873,68 +905,6 @@ namespace ImageProcessingAtom return result; } - IImageObjectPtr MergeOutputImageForPreview(IImageObjectPtr image, IImageObjectPtr alphaImage) - { - if (!image) - { - return IImageObjectPtr(); - } - - ImageToProcess imageToProcess(image); - imageToProcess.ConvertFormat(ePixelFormat_R8G8B8A8); - IImageObjectPtr previewImage = imageToProcess.Get(); - - // If there is separate Alpha image, combine it with output - if (alphaImage) - { - // Create pixel operation function for rgb and alpha images - IPixelOperationPtr imageOp = CreatePixelOperation(ePixelFormat_R8G8B8A8); - IPixelOperationPtr alphaOp = CreatePixelOperation(ePixelFormat_A8); - - // Convert the alpha image to A8 first - ImageToProcess imageToProcess2(alphaImage); - imageToProcess2.ConvertFormat(ePixelFormat_A8); - IImageObjectPtr previewImageAlpha = imageToProcess2.Get(); - - const uint32 imageMips = previewImage->GetMipCount(); - [[maybe_unused]] const uint32 alphaMips = previewImageAlpha->GetMipCount(); - - // Get count of bytes per pixel for both rgb and alpha images - uint32 imagePixelBytes = CPixelFormats::GetInstance().GetPixelFormatInfo(ePixelFormat_R8G8B8A8)->bitsPerBlock / 8; - uint32 alphaPixelBytes = CPixelFormats::GetInstance().GetPixelFormatInfo(ePixelFormat_A8)->bitsPerBlock / 8; - - AZ_Assert(imageMips <= alphaMips, "Mip level of alpha image is less than origin image!"); - - // For each mip level, set the alpha value to the image - for (uint32 mipLevel = 0; mipLevel < imageMips; ++mipLevel) - { - const uint32 pixelCount = previewImage->GetPixelCount(mipLevel); - [[maybe_unused]] const uint32 alphaPixelCount = previewImageAlpha->GetPixelCount(mipLevel); - - AZ_Assert(pixelCount == alphaPixelCount, "Pixel count for image and alpha image at mip level %d is not equal!", mipLevel); - - uint8* imageBuf; - uint32 pitch; - previewImage->GetImagePointer(mipLevel, imageBuf, pitch); - - uint8* alphaBuf; - uint32 alphaPitch; - previewImageAlpha->GetImagePointer(mipLevel, alphaBuf, alphaPitch); - - float rAlpha, gAlpha, bAlpha, aAlpha, rImage, gImage, bImage, aImage; - - for (uint32 i = 0; i < pixelCount; ++i, imageBuf += imagePixelBytes, alphaBuf += alphaPixelBytes) - { - alphaOp->GetRGBA(alphaBuf, rAlpha, gAlpha, bAlpha, aAlpha); - imageOp->GetRGBA(imageBuf, rImage, gImage, bImage, aImage); - imageOp->SetRGBA(imageBuf, rImage, gImage, bImage, aAlpha); - } - } - } - - return previewImage; - } - IImageObjectPtr ConvertImageForPreview(IImageObjectPtr image) { if (!image) diff --git a/Gems/Atom/Asset/ImageProcessingAtom/Code/Source/Processing/ImageConvert.h b/Gems/Atom/Asset/ImageProcessingAtom/Code/Source/Processing/ImageConvert.h index fe57b1a89f..ba3d21191f 100644 --- a/Gems/Atom/Asset/ImageProcessingAtom/Code/Source/Processing/ImageConvert.h +++ b/Gems/Atom/Asset/ImageProcessingAtom/Code/Source/Processing/ImageConvert.h @@ -51,9 +51,6 @@ namespace ImageProcessingAtom //Converts the image to a RGBA8 format that can be displayed in a preview UI. IImageObjectPtr ConvertImageForPreview(IImageObjectPtr image); - //Combine image with alpha image if any and output as RGBA8 - IImageObjectPtr MergeOutputImageForPreview(IImageObjectPtr image, IImageObjectPtr alphaImage); - //get output image size and mip count based on the texture setting and preset setting //other helper functions @@ -160,7 +157,7 @@ namespace ImageProcessingAtom bool FillCubemapMipmaps(); //IBL cubemap generation, this creates a separate ImageConvertProcess - void CreateIBLCubemap(PresetName preset, const char* fileNameSuffix, IImageObjectPtr& cubemapImage); + bool CreateIBLCubemap(PresetName preset, const char* fileNameSuffix, IImageObjectPtr& cubemapImage); //convert color space to linear with pixel format rgba32f bool ConvertToLinear(); diff --git a/Gems/Atom/Asset/ImageProcessingAtom/Code/Source/Processing/ImageConvertJob.cpp b/Gems/Atom/Asset/ImageProcessingAtom/Code/Source/Processing/ImageConvertJob.cpp index 0e4521ab24..d81685f0c6 100644 --- a/Gems/Atom/Asset/ImageProcessingAtom/Code/Source/Processing/ImageConvertJob.cpp +++ b/Gems/Atom/Asset/ImageProcessingAtom/Code/Source/Processing/ImageConvertJob.cpp @@ -16,28 +16,14 @@ namespace ImageProcessingAtom { - IImageObjectPtr ImageConvertOutput::GetOutputImage(OutputImageType type) const + IImageObjectPtr ImageConvertOutput::GetOutputImage() const { - if (type < OutputImageType::Count) - { - return m_outputImage[static_cast(type)]; - } - else - { - return IImageObjectPtr(); - } + return m_outputImage; } - void ImageConvertOutput::SetOutputImage(IImageObjectPtr image, OutputImageType type) + void ImageConvertOutput::SetOutputImage(IImageObjectPtr image) { - if (type < OutputImageType::Count) - { - m_outputImage[static_cast(type)] = image; - } - else - { - AZ_Error("ImageProcess", false, "Cannot set output image to %d", type); - } + m_outputImage = image; } void ImageConvertOutput::SetReady(bool ready) @@ -62,10 +48,7 @@ namespace ImageProcessingAtom void ImageConvertOutput::Reset() { - for (int i = 0; i < static_cast(OutputImageType::Count); i++) - { - m_outputImage[i] = nullptr; - } + m_outputImage = nullptr; m_outputReady = false; m_progress = 0.0f; } @@ -109,13 +92,12 @@ namespace ImageProcessingAtom IImageObjectPtr outputImage = m_process->GetOutputImage(); - m_output->SetOutputImage(outputImage, ImageConvertOutput::Base); - if (!IsJobCancelled()) { - // For preview, combine image output with alpha if any + // convert the output image to RGBA format for preview m_output->SetProgress(1.0f / static_cast(m_previewProcessStep)); - m_output->SetOutputImage(outputImage, ImageConvertOutput::Preview); + IImageObjectPtr uncompressedImage = ConvertImageForPreview(outputImage); + m_output->SetOutputImage(uncompressedImage); } m_output->SetReady(true); diff --git a/Gems/Atom/Asset/ImageProcessingAtom/Code/Source/Processing/ImageConvertJob.h b/Gems/Atom/Asset/ImageProcessingAtom/Code/Source/Processing/ImageConvertJob.h index 9baa5dd1b4..ac15d47806 100644 --- a/Gems/Atom/Asset/ImageProcessingAtom/Code/Source/Processing/ImageConvertJob.h +++ b/Gems/Atom/Asset/ImageProcessingAtom/Code/Source/Processing/ImageConvertJob.h @@ -21,16 +21,8 @@ namespace ImageProcessingAtom class ImageConvertOutput { public: - enum OutputImageType - { - Base = 0, // Might contains alpha or not - Alpha, // Separate alpha image - Preview, // Combine base image with alpha if any, format RGBA8 - Count - }; - - IImageObjectPtr GetOutputImage(OutputImageType type) const; - void SetOutputImage(IImageObjectPtr image, OutputImageType type); + IImageObjectPtr GetOutputImage() const; + void SetOutputImage(IImageObjectPtr image); void SetReady(bool ready); bool IsReady() const; float GetProgress() const; @@ -38,7 +30,7 @@ namespace ImageProcessingAtom void Reset(); private: - IImageObjectPtr m_outputImage[OutputImageType::Count]; + IImageObjectPtr m_outputImage; bool m_outputReady = false; float m_progress = 0.0f; }; diff --git a/Gems/Atom/Asset/ImageProcessingAtom/Code/Source/Processing/ImageObjectImpl.cpp b/Gems/Atom/Asset/ImageProcessingAtom/Code/Source/Processing/ImageObjectImpl.cpp index 465d992ef6..758df462ec 100644 --- a/Gems/Atom/Asset/ImageProcessingAtom/Code/Source/Processing/ImageObjectImpl.cpp +++ b/Gems/Atom/Asset/ImageProcessingAtom/Code/Source/Processing/ImageObjectImpl.cpp @@ -183,10 +183,9 @@ namespace ImageProcessingAtom return EAlphaContent::eAlphaContent_Absent; } - //if it's compressed format, return indeterminate. if user really want to know the content, they may convert the format to ARGB8 first if (!CPixelFormats::GetInstance().IsPixelFormatUncompressed(m_pixelFormat)) { - AZ_Assert(false, "the function only works right with uncompressed formats. convert to uncompressed format if you get accurate result"); + AZ_TracePrintf("Image processing", "GetAlphaContent() was called for compressed format\n"); return EAlphaContent::eAlphaContent_Indeterminate; } diff --git a/Gems/Atom/Asset/ImageProcessingAtom/Code/Source/Processing/ImagePreview.cpp b/Gems/Atom/Asset/ImageProcessingAtom/Code/Source/Processing/ImagePreview.cpp index 77a7fbef76..ff7fa911d7 100644 --- a/Gems/Atom/Asset/ImageProcessingAtom/Code/Source/Processing/ImagePreview.cpp +++ b/Gems/Atom/Asset/ImageProcessingAtom/Code/Source/Processing/ImagePreview.cpp @@ -86,7 +86,7 @@ namespace ImageProcessingAtom IImageObjectPtr ImagePreview::GetOutputImage() { - return m_output.GetOutputImage(ImageConvertOutput::Preview); + return m_output.GetOutputImage(); } ImagePreview::~ImagePreview() diff --git a/Gems/Atom/Asset/ImageProcessingAtom/Code/Source/Processing/Utils.cpp b/Gems/Atom/Asset/ImageProcessingAtom/Code/Source/Processing/Utils.cpp index 29ba8c3351..20e1b18e77 100644 --- a/Gems/Atom/Asset/ImageProcessingAtom/Code/Source/Processing/Utils.cpp +++ b/Gems/Atom/Asset/ImageProcessingAtom/Code/Source/Processing/Utils.cpp @@ -385,6 +385,13 @@ namespace ImageProcessingAtom } return true; } + + bool NeedAlphaChannel(EAlphaContent alphaContent) + { + return (alphaContent == EAlphaContent::eAlphaContent_OnlyBlack + || alphaContent == EAlphaContent::eAlphaContent_OnlyBlackAndWhite + || alphaContent == EAlphaContent::eAlphaContent_Greyscale); + } } } // namespace ImageProcessingAtom diff --git a/Gems/Atom/Asset/ImageProcessingAtom/Code/Source/Processing/Utils.h b/Gems/Atom/Asset/ImageProcessingAtom/Code/Source/Processing/Utils.h index d5905eddbc..59503a2366 100644 --- a/Gems/Atom/Asset/ImageProcessingAtom/Code/Source/Processing/Utils.h +++ b/Gems/Atom/Asset/ImageProcessingAtom/Code/Source/Processing/Utils.h @@ -26,5 +26,7 @@ namespace ImageProcessingAtom IImageObjectPtr LoadImageFromImageAsset(const AZ::Data::Asset& asset); bool SaveImageToDdsFile(IImageObjectPtr image, AZStd::string_view filePath); + + bool NeedAlphaChannel(EAlphaContent alphaContent); } } diff --git a/Gems/Atom/Asset/ImageProcessingAtom/Code/Tests/ImageProcessing_Test.cpp b/Gems/Atom/Asset/ImageProcessingAtom/Code/Tests/ImageProcessing_Test.cpp index d0029ffc86..91b0952a06 100644 --- a/Gems/Atom/Asset/ImageProcessingAtom/Code/Tests/ImageProcessing_Test.cpp +++ b/Gems/Atom/Asset/ImageProcessingAtom/Code/Tests/ImageProcessing_Test.cpp @@ -203,7 +203,7 @@ namespace UnitTest m_gemFolder = AZ::Test::GetEngineRootPath() + "/Gems/Atom/Asset/ImageProcessingAtom/"; m_outputFolder = m_gemFolder + AZStd::string("Code/Tests/TestAssets/temp/"); - m_defaultSettingFolder = m_gemFolder + AZStd::string("Config/"); + m_defaultSettingFolder = m_gemFolder + AZStd::string("Assets/Config/"); m_testFileFolder = m_gemFolder + AZStd::string("Code/Tests/TestAssets/"); InitialImageFilenames(); diff --git a/Gems/Atom/Asset/ImageProcessingAtom/Config/ImageBuilder.settings b/Gems/Atom/Asset/ImageProcessingAtom/Config/ImageBuilder.settings deleted file mode 100644 index 466ac4b71d..0000000000 --- a/Gems/Atom/Asset/ImageProcessingAtom/Config/ImageBuilder.settings +++ /dev/null @@ -1,67 +0,0 @@ -{ - "Type": "JsonSerialization", - "Version": 1, - "ClassName": "BuilderSettingManager", - "ClassData": { - "AnalysisFingerprint": "2", - "BuildSettings": { - "android": { - "GlossScale": 16.0, - "GlossBias": 0.0, - "Streaming": false, - "Enable": true - }, - "ios": { - "GlossScale": 16.0, - "GlossBias": 0.0, - "Streaming": false, - "Enable": true - }, - "mac": { - "GlossScale": 16.0, - "GlossBias": 0.0, - "Streaming": false, - "Enable": true - }, - "pc": { - "GlossScale": 16.0, - "GlossBias": 0.0, - "Streaming": false, - "Enable": true - }, - "linux": { - "GlossScale": 16.0, - "GlossBias": 0.0, - "Streaming": false, - "Enable": true - }, - "provo": { - "GlossScale": 16.0, - "GlossBias": 0.0, - "Streaming": false, - "Enable": false - } - }, - "DefaultPresetsByFileMask": { - "_basecolor": "Albedo", - "_diff": "Albedo", - "_diffuse": "Albedo", - "_ddn": "Normals", - "_normal": "Normals", - "_ddna": "NormalsWithSmoothness", - "_glossness": "Reflectance", - "_spec": "Reflectance", - "_specular": "Reflectance", - "_metallic": "Reflectance", - "_refl": "Reflectance", - "_roughness": "Reflectance", - "_ibldiffusecm": "IBLDiffuse", - "_iblskyboxcm": "IBLSkybox", - "_iblspecularcm": "IBLSpecular", - "_skyboxcm": "Skybox" - }, - "DefaultPreset": "Albedo", - "DefaultPresetAlpha": "AlbedoWithGenericAlpha", - "DefaultPresetNonePOT": "ReferenceImage" - } -} diff --git a/Gems/Atom/Asset/ImageProcessingAtom/Config/Reflectance.preset b/Gems/Atom/Asset/ImageProcessingAtom/Config/Reflectance.preset deleted file mode 100644 index 2ac88dca85..0000000000 --- a/Gems/Atom/Asset/ImageProcessingAtom/Config/Reflectance.preset +++ /dev/null @@ -1,157 +0,0 @@ -{ - "Type": "JsonSerialization", - "Version": 1, - "ClassName": "MultiplatformPresetSettings", - "ClassData": { - "DefaultPreset": { - "UUID": "{7A3CC95E-0A0C-4CA1-8357-5712B028B77D}", - "Name": "Reflectance", - "SourceColor": "Linear", - "DestColor": "Linear", - "FileMasks": [ - "_spec", - "_refl", - "_ref", - "_rf", - "_gloss", - "_g", - "_f0", - "_specf0", - "_specular", - "_metal", - "_mtl", - "_m", - "_mt", - "_metalness", - "_metallic", - "_roughness", - "_rough" - ], - "PixelFormat": "BC1", - "IsPowerOf2": true, - "MipMapSetting": { - "MipGenType": "Box" - } - }, - "PlatformsPresets": { - "android": { - "UUID": "{7A3CC95E-0A0C-4CA1-8357-5712B028B77D}", - "Name": "Reflectance", - "SourceColor": "Linear", - "DestColor": "Linear", - "FileMasks": [ - "_spec", - "_refl", - "_ref", - "_rf", - "_gloss", - "_g", - "_f0", - "_specf0", - "_metal", - "_mtl", - "_m", - "_mt", - "_metalness", - "_metallic", - "_roughness", - "_rough" - ], - "PixelFormat": "ASTC_6x6", - "MaxTextureSize": 2048, - "IsPowerOf2": true, - "MipMapSetting": { - "MipGenType": "Box" - } - }, - "ios": { - "UUID": "{7A3CC95E-0A0C-4CA1-8357-5712B028B77D}", - "Name": "Reflectance", - "SourceColor": "Linear", - "DestColor": "Linear", - "FileMasks": [ - "_spec", - "_refl", - "_ref", - "_rf", - "_gloss", - "_g", - "_f0", - "_specf0", - "_metal", - "_mtl", - "_m", - "_mt", - "_metalness", - "_metallic", - "_roughness", - "_rough" - ], - "PixelFormat": "ASTC_6x6", - "MaxTextureSize": 2048, - "IsPowerOf2": true, - "MipMapSetting": { - "MipGenType": "Box" - } - }, - "mac": { - "UUID": "{7A3CC95E-0A0C-4CA1-8357-5712B028B77D}", - "Name": "Reflectance", - "SourceColor": "Linear", - "DestColor": "Linear", - "FileMasks": [ - "_spec", - "_refl", - "_ref", - "_rf", - "_gloss", - "_g", - "_f0", - "_specf0", - "_metal", - "_mtl", - "_m", - "_mt", - "_metalness", - "_metallic", - "_roughness", - "_rough" - ], - "PixelFormat": "BC1", - "IsPowerOf2": true, - "MipMapSetting": { - "MipGenType": "Box" - } - }, - "provo": { - "UUID": "{7A3CC95E-0A0C-4CA1-8357-5712B028B77D}", - "Name": "Reflectance", - "SourceColor": "Linear", - "DestColor": "Linear", - "FileMasks": [ - "_spec", - "_refl", - "_ref", - "_rf", - "_gloss", - "_g", - "_f0", - "_specf0", - "_metal", - "_mtl", - "_m", - "_mt", - "_metalness", - "_metallic", - "_roughness", - "_rough" - ], - "PixelFormat": "BC1", - "IsPowerOf2": true, - "MipMapSetting": { - "MipGenType": "Box" - } - } - } - } -} diff --git a/Gems/Atom/Feature/Common/Assets/Passes/ReflectionScreenSpace.pass b/Gems/Atom/Feature/Common/Assets/Passes/ReflectionScreenSpace.pass index 4972f0f494..d1825be820 100644 --- a/Gems/Atom/Feature/Common/Assets/Passes/ReflectionScreenSpace.pass +++ b/Gems/Atom/Feature/Common/Assets/Passes/ReflectionScreenSpace.pass @@ -34,10 +34,6 @@ } ], "PassRequests": [ - { - "Name": "ReflectionScreenSpaceBlurPass", - "TemplateName": "ReflectionScreenSpaceBlurPassTemplate" - }, { "Name": "ReflectionScreenSpaceTracePass", "TemplateName": "ReflectionScreenSpaceTracePassTemplate", @@ -56,42 +52,65 @@ "Attachment": "NormalInput" } }, - { - "LocalSlot": "DepthStencilInput", - "AttachmentRef": { - "Pass": "Parent", - "Attachment": "DepthStencilInput" - - } - }, { "LocalSlot": "SpecularF0Input", "AttachmentRef": { "Pass": "Parent", "Attachment": "SpecularF0Input" } + }, + { + "LocalSlot": "ReflectionInputOutput", + "AttachmentRef": { + "Pass": "Parent", + "Attachment": "ReflectionInputOutput" + } + } + ] + }, + { + "Name": "ReflectionScreenSpaceBlurPass", + "TemplateName": "ReflectionScreenSpaceBlurPassTemplate", + "Connections": [ + { + "LocalSlot": "DepthInput", + "AttachmentRef": { + "Pass": "Parent", + "Attachment": "DepthStencilInput" + } + }, + { + "LocalSlot": "ScreenSpaceReflectionInputOutput", + "AttachmentRef": { + "Pass": "ReflectionScreenSpaceTracePass", + "Attachment": "ScreenSpaceReflectionOutput" + } + }, + { + "LocalSlot": "DownsampledDepthInputOutput", + "AttachmentRef": { + "Pass": "ReflectionScreenSpaceTracePass", + "Attachment": "DownsampledDepthOutput" + } } ] }, { "Name": "ReflectionScreenSpaceCompositePass", "TemplateName": "ReflectionScreenSpaceCompositePassTemplate", - "ExecuteAfter": [ - "ReflectionScreenSpaceBlurPass" - ], "Connections": [ { - "LocalSlot": "TraceInput", + "LocalSlot": "ReflectionInput", "AttachmentRef": { - "Pass": "ReflectionScreenSpaceTracePass", - "Attachment": "Output" + "Pass": "ReflectionScreenSpaceBlurPass", + "Attachment": "ScreenSpaceReflectionInputOutput" } }, { - "LocalSlot": "PreviousFrameBufferInput", + "LocalSlot": "DownsampledDepthInput", "AttachmentRef": { "Pass": "ReflectionScreenSpaceBlurPass", - "Attachment": "PreviousFrameInputOutput" + "Attachment": "DownsampledDepthInputOutput" } }, { @@ -115,6 +134,13 @@ "Attachment": "DepthStencilInput" } }, + { + "LocalSlot": "PreviousFrameInputOutput", + "AttachmentRef": { + "Pass": "ReflectionScreenSpaceTracePass", + "Attachment": "PreviousFrameInputOutput" + } + }, { "LocalSlot": "DepthStencilInput", "AttachmentRef": { diff --git a/Gems/Atom/Feature/Common/Assets/Passes/ReflectionScreenSpaceBlur.pass b/Gems/Atom/Feature/Common/Assets/Passes/ReflectionScreenSpaceBlur.pass index e2fde2d4ef..a5fd2fdfb1 100644 --- a/Gems/Atom/Feature/Common/Assets/Passes/ReflectionScreenSpaceBlur.pass +++ b/Gems/Atom/Feature/Common/Assets/Passes/ReflectionScreenSpaceBlur.pass @@ -8,34 +8,19 @@ "PassClass": "ReflectionScreenSpaceBlurPass", "Slots": [ { - "Name": "PreviousFrameInputOutput", + "Name": "DepthInput", + "SlotType": "Input", + "ScopeAttachmentUsage": "Shader" + }, + { + "Name": "ScreenSpaceReflectionInputOutput", "SlotType": "InputOutput", "ScopeAttachmentUsage": "Shader" - } - ], - "ImageAttachments": [ + }, { - "Name": "PreviousFrameImage", - "SizeSource": { - "Source": { - "Pass": "Parent", - "Attachment": "SpecularInput" - } - }, - "ImageDescriptor": { - "Format": "R16G16B16A16_FLOAT", - "SharedQueueMask": "Graphics" - }, - "GenerateFullMipChain": true - } - ], - "Connections": [ - { - "LocalSlot": "PreviousFrameInputOutput", - "AttachmentRef": { - "Pass": "This", - "Attachment": "PreviousFrameImage" - } + "Name": "DownsampledDepthInputOutput", + "SlotType": "InputOutput", + "ScopeAttachmentUsage": "DepthStencil" } ] } diff --git a/Gems/Atom/Feature/Common/Assets/Passes/ReflectionScreenSpaceBlurVertical.pass b/Gems/Atom/Feature/Common/Assets/Passes/ReflectionScreenSpaceBlurVertical.pass index a616ed4c8e..af3878cf6b 100644 --- a/Gems/Atom/Feature/Common/Assets/Passes/ReflectionScreenSpaceBlurVertical.pass +++ b/Gems/Atom/Feature/Common/Assets/Passes/ReflectionScreenSpaceBlurVertical.pass @@ -7,6 +7,11 @@ "Name": "ReflectionScreenSpaceBlurVerticalPassTemplate", "PassClass": "ReflectionScreenSpaceBlurChildPass", "Slots": [ + { + "Name": "DepthInput", + "SlotType": "Input", + "ScopeAttachmentUsage": "Shader" + }, { "Name": "Input", "SlotType": "InputOutput", @@ -16,6 +21,20 @@ "Name": "Output", "SlotType": "InputOutput", "ScopeAttachmentUsage": "RenderTarget" + }, + { + "Name": "DownsampledDepthOutput", + "SlotType": "InputOutput", + "ScopeAttachmentUsage": "DepthStencil" + } + ], + "Connections": [ + { + "LocalSlot": "DepthInput", + "AttachmentRef": { + "Pass": "Parent", + "Attachment": "DepthInput" + } } ], "PassData": { diff --git a/Gems/Atom/Feature/Common/Assets/Passes/ReflectionScreenSpaceComposite.pass b/Gems/Atom/Feature/Common/Assets/Passes/ReflectionScreenSpaceComposite.pass index 5443c32406..17b58dbc9e 100644 --- a/Gems/Atom/Feature/Common/Assets/Passes/ReflectionScreenSpaceComposite.pass +++ b/Gems/Atom/Feature/Common/Assets/Passes/ReflectionScreenSpaceComposite.pass @@ -8,12 +8,12 @@ "PassClass": "ReflectionScreenSpaceCompositePass", "Slots": [ { - "Name": "TraceInput", + "Name": "ReflectionInput", "SlotType": "Input", "ScopeAttachmentUsage": "Shader" }, { - "Name": "PreviousFrameBufferInput", + "Name": "DownsampledDepthInput", "SlotType": "Input", "ScopeAttachmentUsage": "Shader" }, @@ -37,6 +37,11 @@ ] } }, + { + "Name": "PreviousFrameInputOutput", + "SlotType": "InputOutput", + "ScopeAttachmentUsage": "Shader" + }, { "Name": "DepthStencilInput", "SlotType": "Input", diff --git a/Gems/Atom/Feature/Common/Assets/Passes/ReflectionScreenSpaceTrace.pass b/Gems/Atom/Feature/Common/Assets/Passes/ReflectionScreenSpaceTrace.pass index 370db1f45a..824d23a046 100644 --- a/Gems/Atom/Feature/Common/Assets/Passes/ReflectionScreenSpaceTrace.pass +++ b/Gems/Atom/Feature/Common/Assets/Passes/ReflectionScreenSpaceTrace.pass @@ -5,7 +5,7 @@ "ClassData": { "PassTemplate": { "Name": "ReflectionScreenSpaceTracePassTemplate", - "PassClass": "FullScreenTriangle", + "PassClass": "ReflectionScreenSpaceTracePass", "Slots": [ { "Name": "DepthStencilTextureInput", @@ -28,24 +28,52 @@ "ScopeAttachmentUsage": "Shader" }, { - "Name": "DepthStencilInput", + "Name": "ReflectionInputOutput", "SlotType": "Input", - "ScopeAttachmentUsage": "DepthStencil", - "ImageViewDesc": { - "AspectFlags": [ - "Stencil" - ] + "ScopeAttachmentUsage": "Shader" + }, + { + "Name": "PreviousFrameInputOutput", + "SlotType": "Input", + "ScopeAttachmentUsage": "Shader" + }, + { + "Name": "ScreenSpaceReflectionOutput", + "SlotType": "Output", + "ScopeAttachmentUsage": "RenderTarget", + "LoadStoreAction": { + "ClearValue": { + "Value": [ + 0.0, + 0.0, + 0.0, + 0.0 + ] + }, + "LoadAction": "Clear" } }, { - "Name": "Output", + "Name": "DownsampledDepthOutput", "SlotType": "Output", - "ScopeAttachmentUsage": "RenderTarget" + "ScopeAttachmentUsage": "DepthStencil", + "LoadStoreAction": { + "ClearValue": { + "Type": "DepthStencil", + "Value": [ + 1.0, + {}, + {}, + {} + ] + }, + "LoadAction": "Clear" + } } ], "ImageAttachments": [ { - "Name": "TraceImage", + "Name": "ScreenSpaceReflectionImage", "SizeSource": { "Source": { "Pass": "This", @@ -56,9 +84,40 @@ "HeightMultiplier": 0.5 } }, - "MultisampleSource": { - "Pass": "This", - "Attachment": "SpecularF0Input" + "ImageDescriptor": { + "Format": "R16G16B16A16_FLOAT", + "MipLevels": "5", + "SharedQueueMask": "Graphics" + } + }, + { + "Name": "DownsampledDepthImage", + "SizeSource": { + "Source": { + "Pass": "Parent", + "Attachment": "DepthStencilInput" + }, + "Multipliers": { + "WidthMultiplier": 0.5, + "HeightMultiplier": 0.5 + } + }, + "FormatSource": { + "Pass": "Parent", + "Attachment": "DepthStencilInput" + }, + "ImageDescriptor": { + "MipLevels": "5", + "SharedQueueMask": "Graphics" + } + }, + { + "Name": "PreviousFrameImage", + "SizeSource": { + "Source": { + "Pass": "Parent", + "Attachment": "SpecularInput" + } }, "ImageDescriptor": { "Format": "R16G16B16A16_FLOAT", @@ -68,15 +127,28 @@ ], "Connections": [ { - "LocalSlot": "Output", + "LocalSlot": "ScreenSpaceReflectionOutput", "AttachmentRef": { "Pass": "This", - "Attachment": "TraceImage" + "Attachment": "ScreenSpaceReflectionImage" + } + }, + { + "LocalSlot": "DownsampledDepthOutput", + "AttachmentRef": { + "Pass": "This", + "Attachment": "DownsampledDepthImage" + } + }, + { + "LocalSlot": "PreviousFrameInputOutput", + "AttachmentRef": { + "Pass": "This", + "Attachment": "PreviousFrameImage" } } ], - "PassData": - { + "PassData": { "$type": "FullscreenTrianglePassData", "ShaderAsset": { "FilePath": "Shaders/Reflections/ReflectionScreenSpaceTrace.shader" diff --git a/Gems/Atom/Feature/Common/Assets/ShaderLib/Atom/Features/Shadow/ProjectedShadow.azsli b/Gems/Atom/Feature/Common/Assets/ShaderLib/Atom/Features/Shadow/ProjectedShadow.azsli index daed3a2921..3b8379e7fa 100644 --- a/Gems/Atom/Feature/Common/Assets/ShaderLib/Atom/Features/Shadow/ProjectedShadow.azsli +++ b/Gems/Atom/Feature/Common/Assets/ShaderLib/Atom/Features/Shadow/ProjectedShadow.azsli @@ -14,6 +14,7 @@ #include #include "BicubicPcfFilters.azsli" #include "Shadow.azsli" +#include "NormalOffsetShadows.azsli" // ProjectedShadow calculates shadowed area projected from a light. class ProjectedShadow @@ -123,6 +124,7 @@ float ProjectedShadow::GetThickness(uint shadowIndex, float3 worldPosition) ProjectedShadow shadow; shadow.m_worldPosition = worldPosition; + shadow.m_normalVector = 0; // The normal vector is used to reduce acne, this is not an issue when using the shadowmap to determine thickness. shadow.m_shadowIndex = shadowIndex; shadow.SetShadowPosition(); return shadow.GetThickness(); @@ -317,8 +319,13 @@ bool ProjectedShadow::IsShadowed(float3 shadowPosition) void ProjectedShadow::SetShadowPosition() { + const float normalBias = ViewSrg::m_projectedShadows[m_shadowIndex].m_normalShadowBias; + const float shadowmapSize = ViewSrg::m_projectedFilterParams[m_shadowIndex].m_shadowmapSize; + const float3 shadowOffset = ComputeNormalShadowOffset(normalBias, m_normalVector, shadowmapSize); const float4x4 depthBiasMatrix = ViewSrg::m_projectedShadows[m_shadowIndex].m_depthBiasMatrix; - float4 shadowPositionHomogeneous = mul(depthBiasMatrix, float4(m_worldPosition, 1)); + + float4 shadowPositionHomogeneous = mul(depthBiasMatrix, float4(m_worldPosition + shadowOffset, 1)); + m_shadowPosition = shadowPositionHomogeneous.xyz / shadowPositionHomogeneous.w; m_bias = ViewSrg::m_projectedShadows[m_shadowIndex].m_bias / shadowPositionHomogeneous.w; diff --git a/Gems/Atom/Feature/Common/Assets/Shaders/Reflections/ReflectionScreenSpaceBlurCommon.azsli b/Gems/Atom/Feature/Common/Assets/Shaders/Reflections/ReflectionScreenSpaceBlurCommon.azsli index 1e4d4af8a2..3d38df2816 100644 --- a/Gems/Atom/Feature/Common/Assets/Shaders/Reflections/ReflectionScreenSpaceBlurCommon.azsli +++ b/Gems/Atom/Feature/Common/Assets/Shaders/Reflections/ReflectionScreenSpaceBlurCommon.azsli @@ -6,11 +6,31 @@ * */ -// 7-tap Gaussian Kernel (Sigma 1.1) -static const uint GaussianKernelSize = 7; -static const int2 TexelOffsetsV[GaussianKernelSize] = {{0, -3}, {0, -2}, {0, -1}, {0, 0}, {0, 1}, {0, 2}, {0, 3}}; -static const int2 TexelOffsetsH[GaussianKernelSize] = {{-3, 0}, {-2, 0}, {-1, 0}, {0, 0}, {1, 0}, {2, 0}, {3, 0}}; -static const float TexelWeights[GaussianKernelSize] = {0.010805f, 0.074929f, 0.238727f, 0.351078f, 0.238727f, 0.074929f, 0.010805f}; +// Gaussian Kernel Radius 9, Sigma 1.8 +static const uint GaussianKernelSize = 19; +static const int2 TexelOffsetsV[GaussianKernelSize] = {{0, -9}, {0, -8}, {0, -7}, {0, -6}, {0, -5}, {0, -4}, {0, -3}, {0, -2}, {0, -1}, {0, 0}, {0, 1}, {0, 2}, {0, 3}, {0, 4}, {0, 5}, {0, 6}, {0, 7}, {0, 8}, {0, 9}}; +static const int2 TexelOffsetsH[GaussianKernelSize] = {{-9, 0}, {-8, 0}, {-7, 0}, {-6, 0}, {-5, 0}, {-4, 0}, {-3, 0}, {-2, 0}, {-1, 0}, {0, 0}, {1, 0}, {2, 0}, {3, 0}, {4, 0}, {5, 0}, {6, 0}, {7, 0}, {8, 0}, {9, 0}}; +static const float TexelWeights[GaussianKernelSize] = { + 0.0000011022801820635918f, + 0.000014295732881160677f, + 0.0001370168487067367f, + 0.0009708086495991633f, + 0.005086391900047703f, + 0.019711193240183777f, + 0.056512463228943335f, + 0.11989501853796679f, + 0.18826323520204147f, + 0.21881694875889543f, + 0.18826323520204147f, + 0.11989501853796679f, + 0.056512463228943335f, + 0.019711193240183777f, + 0.005086391900047703f, + 0.0009708086495991633f, + 0.0001370168487067367f, + 0.000014295732881160677f, + 0.0000011022801820635918f +}; float3 GaussianFilter(uint2 screenCoords, int2 texelOffsets[GaussianKernelSize], RWTexture2D inputImage) { diff --git a/Gems/Atom/Feature/Common/Assets/Shaders/Reflections/ReflectionScreenSpaceBlurVertical.azsl b/Gems/Atom/Feature/Common/Assets/Shaders/Reflections/ReflectionScreenSpaceBlurVertical.azsl index cfc35d10e4..bdc787350e 100644 --- a/Gems/Atom/Feature/Common/Assets/Shaders/Reflections/ReflectionScreenSpaceBlurVertical.azsl +++ b/Gems/Atom/Feature/Common/Assets/Shaders/Reflections/ReflectionScreenSpaceBlurVertical.azsl @@ -10,12 +10,13 @@ #include #include -#include #include +#include #include "ReflectionScreenSpaceBlurCommon.azsli" ShaderResourceGroup PassSrg : SRG_PerPass { + Texture2DMS m_depth; RWTexture2D m_input; RWTexture2D m_output; uint m_imageWidth; @@ -26,13 +27,39 @@ ShaderResourceGroup PassSrg : SRG_PerPass #include // Pixel Shader +struct PSOutput +{ + float4 m_color : SV_Target0; + float m_depth : SV_Depth; +}; + PSOutput MainPS(VSOutput IN) { // vertical blur uses coordinates from the mip0 input image - uint2 coords = IN.m_position.xy * PassSrg::m_outputScale; - float3 result = GaussianFilter(coords, TexelOffsetsV, PassSrg::m_input); + uint2 halfResCoords = IN.m_position.xy * PassSrg::m_outputScale; + float3 result = GaussianFilter(halfResCoords, TexelOffsetsV, PassSrg::m_input); + + // downsample depth, using fullscreen image coordinates + float downsampledDepth = 0; + if (PassSrg::m_input[halfResCoords].w > 0.0f) + { + uint2 fullScreenCoords = halfResCoords * 2; + + for (int y = -2; y < 2; ++y) + { + for (int x = -2; x < 2; ++x) + { + float depth = PassSrg::m_depth.Load(fullScreenCoords + int2(x, y), 0).r; + if (depth > downsampledDepth) + { + downsampledDepth = depth; + } + } + } + } PSOutput OUT; OUT.m_color = float4(result, 1.0f); + OUT.m_depth = downsampledDepth; return OUT; } diff --git a/Gems/Atom/Feature/Common/Assets/Shaders/Reflections/ReflectionScreenSpaceBlurVertical.shader b/Gems/Atom/Feature/Common/Assets/Shaders/Reflections/ReflectionScreenSpaceBlurVertical.shader index dcebb4d2ae..92995bd69f 100644 --- a/Gems/Atom/Feature/Common/Assets/Shaders/Reflections/ReflectionScreenSpaceBlurVertical.shader +++ b/Gems/Atom/Feature/Common/Assets/Shaders/Reflections/ReflectionScreenSpaceBlurVertical.shader @@ -10,7 +10,8 @@ { "Depth" : { - "Enable" : false + "Enable" : true, // required to bind the depth buffer SRV + "CompareFunc" : "Always" } }, diff --git a/Gems/Atom/Feature/Common/Assets/Shaders/Reflections/ReflectionScreenSpaceComposite.azsl b/Gems/Atom/Feature/Common/Assets/Shaders/Reflections/ReflectionScreenSpaceComposite.azsl index a0c31442fa..6cd4ce16f5 100644 --- a/Gems/Atom/Feature/Common/Assets/Shaders/Reflections/ReflectionScreenSpaceComposite.azsl +++ b/Gems/Atom/Feature/Common/Assets/Shaders/Reflections/ReflectionScreenSpaceComposite.azsl @@ -12,17 +12,19 @@ #include #include #include +#include #include #include #include ShaderResourceGroup PassSrg : SRG_PerPass { - Texture2DMS m_trace; - Texture2D m_previousFrame; + Texture2D m_reflection; + Texture2D m_downsampledDepth; Texture2DMS m_normal; // RGB10 = Normal (Encoded), A2 = Flags Texture2DMS m_specularF0; // RGB8 = SpecularF0, A8 = Roughness Texture2DMS m_depth; + Texture2D m_previousFrame; Sampler LinearSampler { @@ -40,6 +42,49 @@ ShaderResourceGroup PassSrg : SRG_PerPass #include +float3 SampleReflection(float2 reflectionUV, float mip, float depth, float3 normal, uint2 invDimensions) +{ + const float DepthTolerance = 0.001f; + + // attempt to trivially accept the downsampled reflection texel + float downsampledDepth = PassSrg::m_downsampledDepth.SampleLevel(PassSrg::LinearSampler, reflectionUV, floor(mip)).r; + if (abs(depth - downsampledDepth) <= DepthTolerance) + { + // use this reflection sample + float3 reflection = PassSrg::m_reflection.SampleLevel(PassSrg::LinearSampler, reflectionUV, mip).rgb; + return reflection; + } + + // neighborhood search surrounding the downsampled texel, searching for the closest matching depth + float closestDepthDelta = 1.0f; + int2 closestOffsetUV = float2(0.0f, 0.0f); + for (int y = -4; y <= 4; ++y) + { + for (int x = -4; x <= 4; ++x) + { + float2 offsetUV = float2(x * invDimensions.x, y * invDimensions.y); + float downsampledDepth = PassSrg::m_downsampledDepth.SampleLevel(PassSrg::LinearSampler, reflectionUV + offsetUV, floor(mip)).r; + float depthDelta = abs(depth - downsampledDepth); + + if (depthDelta <= DepthTolerance) + { + // depth is within tolerance, use this texel + float3 reflection = PassSrg::m_reflection.SampleLevel(PassSrg::LinearSampler, reflectionUV + offsetUV, mip).rgb; + return reflection; + } + + if (closestDepthDelta > depthDelta) + { + closestDepthDelta = depthDelta; + closestOffsetUV = offsetUV; + } + } + } + + float3 reflection = PassSrg::m_reflection.SampleLevel(PassSrg::LinearSampler, reflectionUV + closestOffsetUV, mip).rgb; + return reflection; +} + // Pixel Shader PSOutput MainPS(VSOutput IN, in uint sampleIndex : SV_SampleIndex) { @@ -52,11 +97,21 @@ PSOutput MainPS(VSOutput IN, in uint sampleIndex : SV_SampleIndex) // compute trace image coordinates for the half-res image float2 traceCoords = screenCoords * 0.5f; - // load trace data and check w-component to see if there was a hit - float4 traceData = PassSrg::m_trace.Load(traceCoords, sampleIndex); - if (traceData.w <= 0.0f) + // check reflection data mip0 to see if there was a hit + float4 reflectionData = PassSrg::m_reflection.Load(uint3(traceCoords, 0)); + if (reflectionData.w <= 0.0f) { - // no hit, fallback to the cubemap reflections currently in the reflection buffer + // fallback to the cubemap reflections currently in the reflection buffer + discard; + } + + // load specular and roughness + float4 specularF0 = PassSrg::m_specularF0.Load(screenCoords, sampleIndex); + float roughness = specularF0.a; + const float MaxRoughness = 0.5f; + if (roughness > MaxRoughness) + { + // fallback to the cubemap reflections currently in the reflection buffer discard; } @@ -65,8 +120,9 @@ PSOutput MainPS(VSOutput IN, in uint sampleIndex : SV_SampleIndex) float depth = PassSrg::m_depth.Load(screenCoords, sampleIndex).r; float2 ndcPos = float2(UV.x, 1.0f - UV.y) * 2.0f - 1.0f; float4 projectedPos = float4(ndcPos, depth, 1.0f); - float4 positionWS = mul(ViewSrg::m_viewProjectionInverseMatrix, projectedPos); - positionWS /= positionWS.w; + float4 positionVS = mul(ViewSrg::m_projectionMatrixInverse, projectedPos); + positionVS /= positionVS.w; + float3 positionWS = mul(ViewSrg::m_viewMatrixInverse, positionVS).xyz; // compute ray from camera to surface position float3 cameraToPositionWS = normalize(positionWS.xyz - ViewSrg::m_worldPosition); @@ -74,42 +130,16 @@ PSOutput MainPS(VSOutput IN, in uint sampleIndex : SV_SampleIndex) // retrieve surface normal float4 encodedNormal = PassSrg::m_normal.Load(screenCoords, sampleIndex); float3 normalWS = DecodeNormalSignedOctahedron(encodedNormal.rgb); - - // compute surface specular - float4 specularF0 = PassSrg::m_specularF0.Load(screenCoords, sampleIndex); - float roughness = specularF0.a; float NdotV = dot(normalWS, -cameraToPositionWS); - float3 specular = FresnelSchlickWithRoughness(NdotV, specularF0.rgb, roughness); - // reconstruct the world space position of the trace coordinates - float2 traceUV = saturate(traceData.xy / dimensions); - float traceDepth = PassSrg::m_depth.Load(traceData.xy, sampleIndex).r; - float2 traceNDC = float2(traceUV.x, 1.0f - traceUV.y) * 2.0f - 1.0f; - float4 traceProjectedPos = float4(traceNDC, traceDepth, 1.0f); - float4 tracePositionVS = mul(ViewSrg::m_projectionMatrixInverse, traceProjectedPos); - tracePositionVS /= tracePositionVS.w; - float4 tracePositionWS = mul(ViewSrg::m_viewMatrixInverse, tracePositionVS); - - // reproject to the previous frame image coordinates - float4 tracePrevNDC = mul(ViewSrg::m_viewProjectionPrevMatrix, tracePositionWS); - tracePrevNDC /= tracePrevNDC.w; - float2 tracePrevUV = float2(tracePrevNDC.x, -1.0f * tracePrevNDC.y) * 0.5f + 0.5f; - - // compute the roughness mip to use in the previous frame image + // compute the roughness mip to use in the reflection image // remap the roughness mip into a lower range to more closely match the material roughness values - const float MaxRoughness = 0.5f; float mip = saturate(roughness / MaxRoughness) * PassSrg::m_maxMipLevel; - // sample reflection value from the roughness mip - float4 reflectionColor = float4(PassSrg::m_previousFrame.SampleLevel(PassSrg::LinearSampler, tracePrevUV, mip).rgb, 1.0f); - - // fade rays close to screen edge - const float ScreenFadeDistance = 0.95f; - float2 fadeAmount = max(max(0.0f, traceUV - ScreenFadeDistance), max(0.0f, 1.0f - traceUV - ScreenFadeDistance)); - fadeAmount /= (1.0f - ScreenFadeDistance); - float alpha = 1.0f - max(fadeAmount.x, fadeAmount.y); - + // sample reflection color from the mip chain + float3 reflectionColor = SampleReflection(IN.m_texCoord, mip, depth, normalWS, 1.0f / dimensions); + PSOutput OUT; - OUT.m_color = float4(reflectionColor.rgb * specular, alpha); + OUT.m_color = float4(reflectionColor, reflectionData.w); return OUT; } diff --git a/Gems/Atom/Feature/Common/Assets/Shaders/Reflections/ReflectionScreenSpaceTrace.azsl b/Gems/Atom/Feature/Common/Assets/Shaders/Reflections/ReflectionScreenSpaceTrace.azsl index c95befce05..7c18b7f5de 100644 --- a/Gems/Atom/Feature/Common/Assets/Shaders/Reflections/ReflectionScreenSpaceTrace.azsl +++ b/Gems/Atom/Feature/Common/Assets/Shaders/Reflections/ReflectionScreenSpaceTrace.azsl @@ -10,7 +10,7 @@ #include #include -#include +#include #include #include #include @@ -20,6 +20,18 @@ ShaderResourceGroup PassSrg : SRG_PerPass Texture2DMS m_depth; Texture2DMS m_normal; // RGB10 = Normal (Encoded), A2 = Flags Texture2DMS m_specularF0; // RGB8 = SpecularF0, A8 = Roughness + Texture2DMS m_reflection; + Texture2D m_previousFrame; + + Sampler LinearSampler + { + MinFilter = Linear; + MagFilter = Linear; + MipFilter = Linear; + AddressU = Clamp; + AddressV = Clamp; + AddressW = Clamp; + }; } #include @@ -49,6 +61,12 @@ VSOutput MainVS(VSInput input) } // Pixel Shader +struct PSOutput +{ + float4 m_color : SV_Target0; + float m_depth : SV_Depth; +}; + PSOutput MainPS(VSOutput IN) { // compute screen coords based on a half-res render target @@ -83,16 +101,83 @@ PSOutput MainPS(VSOutput IN) // reflect view ray around surface normal float3 reflectDirVS = normalize(reflect(cameraToPositionVS, normalVS)); + // check to see if the reflected direction is approaching the camera + float rdotv = dot(reflectDirVS, -cameraToPositionVS); + bool fallbackEdge = false; + if (rdotv >= -0.05f) + { + if (rdotv >= 0.0f) + { + // ray points back to camera, fallback to cubemaps + discard; + } + + // ray is approaching the camera direction, but not there yet - trace the reflection and set this + // as a non-reflected pixel, which will prevent artifacts at the boundary + fallbackEdge = true; + } + // trace screenspace rays against the depth buffer to find the screenspace intersection coordinates float4 result = float4(0.0f, 0.0f, 0.0f, 0.0f); float2 hitCoords = float2(0.0f, 0.0f); if (TraceRayScreenSpace(positionVS, reflectDirVS, dimensions, hitCoords)) { - float rdotv = dot(reflectDirVS, cameraToPositionVS); - result = float4(hitCoords, 0.0f, rdotv); + // reconstruct the world space position of the trace coordinates + float2 traceUV = saturate(hitCoords / dimensions); + float traceDepth = PassSrg::m_depth.Load(hitCoords, 0).r; + float2 traceNDC = float2(traceUV.x, 1.0f - traceUV.y) * 2.0f - 1.0f; + float4 traceProjectedPos = float4(traceNDC, traceDepth, 1.0f); + float4 tracePositionVS = mul(ViewSrg::m_projectionMatrixInverse, traceProjectedPos); + tracePositionVS /= tracePositionVS.w; + float4 tracePositionWS = mul(ViewSrg::m_viewMatrixInverse, tracePositionVS); + + // reproject to the previous frame image coordinates + float4 tracePrevNDC = mul(ViewSrg::m_viewProjectionPrevMatrix, tracePositionWS); + tracePrevNDC /= tracePrevNDC.w; + float2 tracePrevUV = float2(tracePrevNDC.x, -1.0f * tracePrevNDC.y) * 0.5f + 0.5f; + + // sample the previous frame image + result.rgb = PassSrg::m_previousFrame.SampleLevel(PassSrg::LinearSampler, tracePrevUV, 0).rgb; + + // apply surface specular + float3 specularF0 = PassSrg::m_specularF0.Load(screenCoords, 0).rgb; + result.rgb *= specularF0; + + // fade rays close to screen edge + const float ScreenFadeDistance = 0.95f; + float2 fadeAmount = max(max(0.0f, traceUV - ScreenFadeDistance), max(0.0f, 1.0f - traceUV - ScreenFadeDistance)); + fadeAmount /= (1.0f - ScreenFadeDistance); + result.a = fallbackEdge ? 0.0f : 1.0f - max(fadeAmount.x, fadeAmount.y); + } + else + { + // ray miss, add in the IBL/probe reflections from the specular pass + float4 positionWS = mul(ViewSrg::m_viewMatrixInverse, positionVS); + float3 cameraToPositionWS = normalize(positionWS - ViewSrg::m_worldPosition); + float3 reflectDirWS = normalize(reflect(cameraToPositionWS, normalWS)); + + result.rgb += PassSrg::m_reflection.Load(screenCoords, 0).rgb; + result.a = fallbackEdge ? 0.0f : 1.0f; + } + + // downsample depth + float downsampledDepth = 0.0f; + for (int y = -2; y < 2; ++y) + { + for (int x = -2; x < 2; ++x) + { + float depth = PassSrg::m_depth.Load(screenCoords + int2(x, y), 0).r; + + // take the closest depth sample (larger depth value due to reverse depth) + if (depth > downsampledDepth) + { + downsampledDepth = depth; + } + } } PSOutput OUT; OUT.m_color = result; + OUT.m_depth = downsampledDepth; return OUT; } diff --git a/Gems/Atom/Feature/Common/Assets/Shaders/Reflections/ReflectionScreenSpaceTrace.shader b/Gems/Atom/Feature/Common/Assets/Shaders/Reflections/ReflectionScreenSpaceTrace.shader index 563e0e3276..3ceabd404a 100644 --- a/Gems/Atom/Feature/Common/Assets/Shaders/Reflections/ReflectionScreenSpaceTrace.shader +++ b/Gems/Atom/Feature/Common/Assets/Shaders/Reflections/ReflectionScreenSpaceTrace.shader @@ -10,7 +10,8 @@ { "Depth" : { - "Enable" : false + "Enable" : true, // required to bind the depth buffer SRV + "CompareFunc" : "Always" } }, diff --git a/Gems/Atom/Feature/Common/Code/Include/Atom/Feature/CoreLights/DiskLightFeatureProcessorInterface.h b/Gems/Atom/Feature/Common/Code/Include/Atom/Feature/CoreLights/DiskLightFeatureProcessorInterface.h index 5aa2dfb800..98220fae15 100644 --- a/Gems/Atom/Feature/Common/Code/Include/Atom/Feature/CoreLights/DiskLightFeatureProcessorInterface.h +++ b/Gems/Atom/Feature/Common/Code/Include/Atom/Feature/CoreLights/DiskLightFeatureProcessorInterface.h @@ -86,6 +86,8 @@ namespace AZ virtual void SetShadowsEnabled(LightHandle handle, bool enabled) = 0; //! Sets the shadow bias virtual void SetShadowBias(LightHandle handle, float bias) = 0; + //! Sets the normal shadow bias + virtual void SetNormalShadowBias(LightHandle handle, float bias) = 0; //! Sets the shadowmap size (width and height) of the light. virtual void SetShadowmapMaxResolution(LightHandle handle, ShadowmapSize shadowmapSize) = 0; //! Specifies filter method of shadows. diff --git a/Gems/Atom/Feature/Common/Code/Include/Atom/Feature/CoreLights/PointLightFeatureProcessorInterface.h b/Gems/Atom/Feature/Common/Code/Include/Atom/Feature/CoreLights/PointLightFeatureProcessorInterface.h index 1a5a776cdf..52b1402b24 100644 --- a/Gems/Atom/Feature/Common/Code/Include/Atom/Feature/CoreLights/PointLightFeatureProcessorInterface.h +++ b/Gems/Atom/Feature/Common/Code/Include/Atom/Feature/CoreLights/PointLightFeatureProcessorInterface.h @@ -74,6 +74,8 @@ namespace AZ virtual void SetFilteringSampleCount(LightHandle handle, uint16_t count) = 0; //! Sets the Esm exponent to use. Higher values produce a steeper falloff in the border areas between light and shadow. virtual void SetEsmExponent(LightHandle handle, float exponent) = 0; + //! Sets the normal shadow bias. Reduces acne by biasing the shadowmap lookup along the geometric normal. + virtual void SetNormalShadowBias(LightHandle handle, float bias) = 0; //! Sets all of the the point data for the provided LightHandle. virtual void SetPointData(LightHandle handle, const PointLightData& data) = 0; }; diff --git a/Gems/Atom/Feature/Common/Code/Include/Atom/Feature/Utils/ModelPreset.h b/Gems/Atom/Feature/Common/Code/Include/Atom/Feature/Utils/ModelPreset.h index 8bd494dfde..2dd4bed264 100644 --- a/Gems/Atom/Feature/Common/Code/Include/Atom/Feature/Utils/ModelPreset.h +++ b/Gems/Atom/Feature/Common/Code/Include/Atom/Feature/Utils/ModelPreset.h @@ -30,7 +30,6 @@ namespace AZ AZStd::string m_displayName; AZ::Data::Asset m_modelAsset; - AZ::Data::Asset m_previewImageAsset; }; using ModelPresetPtr = AZStd::shared_ptr; diff --git a/Gems/Atom/Feature/Common/Code/Source/AuxGeom/AuxGeomBase.h b/Gems/Atom/Feature/Common/Code/Source/AuxGeom/AuxGeomBase.h index fe731f4ad6..b329a35977 100644 --- a/Gems/Atom/Feature/Common/Code/Source/AuxGeom/AuxGeomBase.h +++ b/Gems/Atom/Feature/Common/Code/Source/AuxGeom/AuxGeomBase.h @@ -155,8 +155,10 @@ namespace AZ enum AuxGeomShapeType { ShapeType_Sphere, + ShapeType_Hemisphere, ShapeType_Cone, ShapeType_Cylinder, + ShapeType_CylinderNoEnds, // Cylinder without disks on either end ShapeType_Disk, ShapeType_Quad, diff --git a/Gems/Atom/Feature/Common/Code/Source/AuxGeom/AuxGeomDrawQueue.cpp b/Gems/Atom/Feature/Common/Code/Source/AuxGeom/AuxGeomDrawQueue.cpp index b755a6efee..5cc43e9013 100644 --- a/Gems/Atom/Feature/Common/Code/Source/AuxGeom/AuxGeomDrawQueue.cpp +++ b/Gems/Atom/Feature/Common/Code/Source/AuxGeom/AuxGeomDrawQueue.cpp @@ -314,15 +314,40 @@ namespace AZ AddShape(style, shape); } - void AuxGeomDrawQueue::DrawSphere( - const AZ::Vector3& center, + Matrix3x3 CreateMatrix3x3FromDirection(const AZ::Vector3& direction) + { + Vector3 unitDirection(direction.GetNormalized()); + Vector3 unitOrthogonal(direction.GetOrthogonalVector().GetNormalized()); + Vector3 unitCross(unitOrthogonal.Cross(unitDirection)); + return Matrix3x3::CreateFromColumns(unitOrthogonal, unitDirection, unitCross); + } + + void AuxGeomDrawQueue::DrawSphere(const AZ::Vector3& center, const AZ::Vector3& direction, float radius, const AZ::Color& color, DrawStyle style, DepthTest depthTest, DepthWrite depthWrite, FaceCullMode faceCull, int32_t viewProjOverrideIndex) + { + DrawSphereCommon(center, direction, radius, color, style, depthTest, depthWrite, faceCull, viewProjOverrideIndex, false); + } + + void AuxGeomDrawQueue::DrawSphere(const AZ::Vector3& center, float radius, const AZ::Color& color, DrawStyle style, DepthTest depthTest, DepthWrite depthWrite, FaceCullMode faceCull, int32_t viewProjOverrideIndex) + { + DrawSphereCommon(center, AZ::Vector3::CreateAxisZ(), radius, color, style, depthTest, depthWrite, faceCull, viewProjOverrideIndex, false); + } + + void AuxGeomDrawQueue::DrawHemisphere(const AZ::Vector3& center, const AZ::Vector3& direction, float radius, const AZ::Color& color, DrawStyle style, DepthTest depthTest, DepthWrite depthWrite, FaceCullMode faceCull, int32_t viewProjOverrideIndex) + { + DrawSphereCommon(center, direction, radius, color, style, depthTest, depthWrite, faceCull, viewProjOverrideIndex, true); + } + + void AuxGeomDrawQueue::DrawSphereCommon( + const AZ::Vector3& center, + const AZ::Vector3& direction, float radius, const AZ::Color& color, DrawStyle style, DepthTest depthTest, DepthWrite depthWrite, FaceCullMode faceCull, - int32_t viewProjOverrideIndex) + int32_t viewProjOverrideIndex, + bool isHemisphere) { if (radius <= 0.0f) { @@ -330,12 +355,12 @@ namespace AZ } ShapeBufferEntry shape; - shape.m_shapeType = ShapeType_Sphere; + shape.m_shapeType = isHemisphere ? ShapeType_Hemisphere : ShapeType_Sphere; shape.m_depthRead = ConvertRPIDepthTestFlag(depthTest); shape.m_depthWrite = ConvertRPIDepthWriteFlag(depthWrite); shape.m_faceCullMode = ConvertRPIFaceCullFlag(faceCull); shape.m_color = color; - shape.m_rotationMatrix = Matrix3x3::CreateIdentity(); + shape.m_rotationMatrix = CreateMatrix3x3FromDirection(direction); shape.m_position = center; shape.m_scale = AZ::Vector3(radius, radius, radius); shape.m_pointSize = m_pointSize; @@ -362,13 +387,9 @@ namespace AZ shape.m_faceCullMode = ConvertRPIFaceCullFlag(faceCull); shape.m_color = color; - Vector3 unitDirection(direction.GetNormalized()); - Vector3 unitOrthogonal(direction.GetOrthogonalVector().GetNormalized()); - Vector3 unitCross(unitOrthogonal.Cross(unitDirection)); - // The disk mesh is created with the top of the disk pointing along the positive Y axis. This creates a // rotation so that the top of the disk will point along the given direction vector. - shape.m_rotationMatrix = Matrix3x3::CreateFromColumns(unitOrthogonal, unitDirection, unitCross); + shape.m_rotationMatrix = CreateMatrix3x3FromDirection(direction); shape.m_position = center; shape.m_scale = AZ::Vector3(radius, 1.0f, radius); shape.m_pointSize = m_pointSize; @@ -401,13 +422,7 @@ namespace AZ shape.m_faceCullMode = ConvertRPIFaceCullFlag(faceCull); shape.m_color = color; - Vector3 unitDirection(direction.GetNormalized()); - Vector3 unitOrthogonal(direction.GetOrthogonalVector().GetNormalized()); - Vector3 unitCross(unitOrthogonal.Cross(unitDirection)); - - // The cone mesh is created with the tip of the cone pointing along the positive Y axis. This creates a - // rotation so that the tip of the cone will point along the given direction vector. - shape.m_rotationMatrix = Matrix3x3::CreateFromColumns(unitOrthogonal, unitDirection, unitCross); + shape.m_rotationMatrix = CreateMatrix3x3FromDirection(direction); shape.m_position = center; shape.m_scale = AZ::Vector3(radius, height, radius); shape.m_pointSize = m_pointSize; @@ -416,17 +431,30 @@ namespace AZ AddShape(style, shape); } - void AuxGeomDrawQueue::DrawCylinder( - const AZ::Vector3& center, - const AZ::Vector3& direction, - float radius, - float height, - const AZ::Color& color, - DrawStyle style, - DepthTest depthTest, - DepthWrite depthWrite, - FaceCullMode faceCull, - int32_t viewProjOverrideIndex) + void AuxGeomDrawQueue::DrawCylinder(const AZ::Vector3& center, const AZ::Vector3& direction, float radius, float height, const AZ::Color& color, + DrawStyle style, DepthTest depthTest, DepthWrite depthWrite, FaceCullMode faceCull, int32_t viewProjOverrideIndex) + { + DrawCylinderCommon(center, direction, radius, height, color, style, depthTest, depthWrite, faceCull, viewProjOverrideIndex, true); + } + + void AuxGeomDrawQueue::DrawCylinderNoEnds(const AZ::Vector3& center, const AZ::Vector3& direction, float radius, float height, const AZ::Color& color, + DrawStyle style, DepthTest depthTest, DepthWrite depthWrite, FaceCullMode faceCull, int32_t viewProjOverrideIndex) + { + DrawCylinderCommon(center, direction, radius, height, color, style, depthTest, depthWrite, faceCull, viewProjOverrideIndex, false); + } + + void AuxGeomDrawQueue::DrawCylinderCommon( + const AZ::Vector3& center, + const AZ::Vector3& direction, + float radius, + float height, + const AZ::Color& color, + DrawStyle style, + DepthTest depthTest, + DepthWrite depthWrite, + FaceCullMode faceCull, + int32_t viewProjOverrideIndex, + bool drawEnds) { if (radius <= 0.0f || height <= 0.0f) { @@ -434,19 +462,15 @@ namespace AZ } ShapeBufferEntry shape; - shape.m_shapeType = ShapeType_Cylinder; - shape.m_depthRead = ConvertRPIDepthTestFlag(depthTest); + shape.m_shapeType = drawEnds ? ShapeType_Cylinder : ShapeType_CylinderNoEnds; + shape.m_depthRead = ConvertRPIDepthTestFlag(depthTest); shape.m_depthWrite = ConvertRPIDepthWriteFlag(depthWrite); shape.m_faceCullMode = ConvertRPIFaceCullFlag(faceCull); shape.m_color = color; - Vector3 unitDirection(direction.GetNormalized()); - Vector3 unitOrthogonal(direction.GetOrthogonalVector().GetNormalized()); - Vector3 unitCross(unitOrthogonal.Cross(unitDirection)); - // The cylinder mesh is created with the top end cap of the cylinder facing along the positive Y axis. This creates a // rotation so that the top face of the cylinder will face along the given direction vector. - shape.m_rotationMatrix = Matrix3x3::CreateFromColumns(unitOrthogonal, unitDirection, unitCross); + shape.m_rotationMatrix = CreateMatrix3x3FromDirection(direction); shape.m_position = center; shape.m_scale = AZ::Vector3(radius, height, radius); shape.m_pointSize = m_pointSize; diff --git a/Gems/Atom/Feature/Common/Code/Source/AuxGeom/AuxGeomDrawQueue.h b/Gems/Atom/Feature/Common/Code/Source/AuxGeom/AuxGeomDrawQueue.h index 535a992fe0..7fa1bbdca8 100644 --- a/Gems/Atom/Feature/Common/Code/Source/AuxGeom/AuxGeomDrawQueue.h +++ b/Gems/Atom/Feature/Common/Code/Source/AuxGeom/AuxGeomDrawQueue.h @@ -60,9 +60,12 @@ namespace AZ // Fixed shape draws void DrawQuad(float width, float height, const AZ::Matrix3x4& transform, const AZ::Color& color, DrawStyle style, DepthTest depthTest, DepthWrite depthWrite, FaceCullMode faceCull, int32_t viewProjOverrideIndex) override; void DrawSphere(const AZ::Vector3& center, float radius, const AZ::Color& color, DrawStyle style, DepthTest depthTest, DepthWrite depthWrite, FaceCullMode faceCull, int32_t viewProjOverrideIndex) override; + void DrawSphere(const AZ::Vector3& center, const AZ::Vector3& direction, float radius, const AZ::Color& color, DrawStyle style, DepthTest depthTest, DepthWrite depthWrite, FaceCullMode faceCull, int32_t viewProjOverrideIndex) override; + void DrawHemisphere(const AZ::Vector3& center, const AZ::Vector3& direction, float radius, const AZ::Color& color, DrawStyle style, DepthTest depthTest, DepthWrite depthWrite, FaceCullMode faceCull, int32_t viewProjOverrideIndex) override; void DrawDisk(const AZ::Vector3& center, const AZ::Vector3& direction, float radius, const AZ::Color& color, DrawStyle style, DepthTest depthTest, DepthWrite depthWrite, FaceCullMode faceCull, int32_t viewProjOverrideIndex) override; void DrawCone(const AZ::Vector3& center, const AZ::Vector3& direction, float radius, float height, const AZ::Color& color, DrawStyle style, DepthTest depthTest, DepthWrite depthWrite, FaceCullMode faceCull, int32_t viewProjOverrideIndex) override; void DrawCylinder(const AZ::Vector3& center, const AZ::Vector3& direction, float radius, float height, const AZ::Color& color, DrawStyle style, DepthTest depthTest, DepthWrite depthWrite, FaceCullMode faceCull, int32_t viewProjOverrideIndex) override; + void DrawCylinderNoEnds(const AZ::Vector3& center, const AZ::Vector3& direction, float radius, float height, const AZ::Color& color, DrawStyle style, DepthTest depthTest, DepthWrite depthWrite, FaceCullMode faceCull, int32_t viewProjOverrideIndex) override; void DrawAabb(const AZ::Aabb& aabb, const AZ::Color& color, DrawStyle style, DepthTest depthTest, DepthWrite depthWrite, FaceCullMode faceCull, int32_t viewProjOverrideIndex) override; void DrawAabb(const AZ::Aabb& aabb, const AZ::Matrix3x4& transform, const AZ::Color& color, DrawStyle style, DepthTest depthTest, DepthWrite depthWrite, FaceCullMode faceCull, int32_t viewProjOverrideIndex) override; void DrawObb(const AZ::Obb& obb, const AZ::Vector3& position, const AZ::Color& color, DrawStyle style, DepthTest depthTest, DepthWrite depthWrite, FaceCullMode faceCull, int32_t viewProjOverrideIndex) override; @@ -73,6 +76,9 @@ namespace AZ private: // functions + void DrawCylinderCommon(const AZ::Vector3& center, const AZ::Vector3& direction, float radius, float height, const AZ::Color& color, DrawStyle style, DepthTest depthTest, DepthWrite depthWrite, FaceCullMode faceCull, int32_t viewProjOverrideIndex, bool drawEnds); + void DrawSphereCommon(const AZ::Vector3& center, const AZ::Vector3& direction, float radius, const AZ::Color& color, DrawStyle style, DepthTest depthTest, DepthWrite depthWrite, FaceCullMode faceCull, int32_t viewProjOverrideIndex, bool isHemisphere); + //! Clear the current buffers void ClearCurrentBufferData(); diff --git a/Gems/Atom/Feature/Common/Code/Source/AuxGeom/FixedShapeProcessor.cpp b/Gems/Atom/Feature/Common/Code/Source/AuxGeom/FixedShapeProcessor.cpp index c2ee397b4c..2e7c0759db 100644 --- a/Gems/Atom/Feature/Common/Code/Source/AuxGeom/FixedShapeProcessor.cpp +++ b/Gems/Atom/Feature/Common/Code/Source/AuxGeom/FixedShapeProcessor.cpp @@ -10,6 +10,7 @@ #include "AuxGeomDrawProcessorShared.h" #include +#include #include #include @@ -69,11 +70,13 @@ namespace AZ SetupInputStreamLayout(m_objectStreamLayout[DrawStyle_Solid], RHI::PrimitiveTopology::TriangleList, false); SetupInputStreamLayout(m_objectStreamLayout[DrawStyle_Shaded], RHI::PrimitiveTopology::TriangleList, true); - CreateSphereBuffersAndViews(); + CreateSphereBuffersAndViews(AuxGeomShapeType::ShapeType_Sphere); + CreateSphereBuffersAndViews(AuxGeomShapeType::ShapeType_Hemisphere); CreateQuadBuffersAndViews(); CreateDiskBuffersAndViews(); CreateConeBuffersAndViews(); - CreateCylinderBuffersAndViews(); + CreateCylinderBuffersAndViews(AuxGeomShapeType::ShapeType_Cylinder); + CreateCylinderBuffersAndViews(AuxGeomShapeType::ShapeType_CylinderNoEnds); CreateBoxBuffersAndViews(); // cache scene pointer for RHI::PipelineState creation. @@ -293,8 +296,11 @@ namespace AZ } } - bool FixedShapeProcessor::CreateSphereBuffersAndViews() + bool FixedShapeProcessor::CreateSphereBuffersAndViews(AuxGeomShapeType sphereShapeType) { + AZ_Assert(sphereShapeType == ShapeType_Sphere || sphereShapeType == ShapeType_Hemisphere, + "Trying to create sphere buffers and views with a non-sphere shape type!"); + const uint32_t numSphereLods = 5; struct LodInfo { @@ -311,13 +317,13 @@ namespace AZ { 9, 9, 0.0000f} }}; - auto& m_shape = m_shapes[ShapeType_Sphere]; + auto& m_shape = m_shapes[sphereShapeType]; m_shape.m_numLods = numSphereLods; for (uint32_t lodIndex = 0; lodIndex < numSphereLods; ++lodIndex) { MeshData meshData; - CreateSphereMeshData(meshData, lodInfo[lodIndex].numRings, lodInfo[lodIndex].numSections); + CreateSphereMeshData(meshData, lodInfo[lodIndex].numRings, lodInfo[lodIndex].numSections, sphereShapeType); ObjectBuffers objectBuffers; @@ -334,12 +340,25 @@ namespace AZ return true; } - void FixedShapeProcessor::CreateSphereMeshData(MeshData& meshData, uint32_t numRings, uint32_t numSections) + void FixedShapeProcessor::CreateSphereMeshData(MeshData& meshData, uint32_t numRings, uint32_t numSections, AuxGeomShapeType sphereShapeType) { const float radius = 1.0f; + // calculate "inner" vertices + float sectionAngle(DegToRad(360.0f / static_cast(numSections))); + float ringSlice(DegToRad(180.0f / static_cast(numRings))); + + uint32_t numberOfPoles = 2; + + if (sphereShapeType == ShapeType_Hemisphere) + { + numberOfPoles = 1; + numRings = (numRings + 1) / 2; + ringSlice = DegToRad(90.0f / static_cast(numRings)); + } + // calc required number of vertices/indices/triangles to build a sphere for the given parameters - uint32_t numVertices = (numRings - 1) * numSections + 2; + uint32_t numVertices = (numRings - 1) * numSections + numberOfPoles; // setup buffers auto& positions = meshData.m_positions; @@ -354,30 +373,29 @@ namespace AZ using NormalType = AuxGeomNormal; // 1st pole vertex - positions.push_back(PosType(0.0f, 0.0f, radius)); - normals.push_back(NormalType(0.0f, 0.0f, 1.0f)); + positions.push_back(PosType(0.0f, radius, 0.0f)); + normals.push_back(NormalType(0.0f, 1.0f, 0.0f)); - // calculate "inner" vertices - float sectionAngle(DegToRad(360.0f / static_cast(numSections))); - float ringSlice(DegToRad(180.0f / static_cast(numRings))); - - for (uint32_t ring = 1; ring < numRings; ++ring) + for (uint32_t ring = 1; ring < numRings - numberOfPoles + 2; ++ring) { float w(sinf(ring * ringSlice)); for (uint32_t section = 0; section < numSections; ++section) { float x = radius * cosf(section * sectionAngle) * w; - float y = radius * sinf(section * sectionAngle) * w; - float z = radius * cosf(ring * ringSlice); + float y = radius * cosf(ring * ringSlice); + float z = radius * sinf(section * sectionAngle) * w; Vector3 radialVector(x, y, z); positions.push_back(radialVector); normals.push_back(radialVector.GetNormalized()); } } - // 2nd vertex of pole (for end cap) - positions.push_back(PosType(0.0f, 0.0f, -radius)); - normals.push_back(NormalType(0.0f, 0.0f, -1.0f)); + if (sphereShapeType == ShapeType_Sphere) + { + // 2nd vertex of pole (for end cap) + positions.push_back(PosType(0.0f, -radius, 0.0f)); + normals.push_back(NormalType(0.0f, -1.0f, 0.0f)); + } // point indices { @@ -393,7 +411,8 @@ namespace AZ // line indices { - const uint32_t numEdges = (numRings - 2) * numSections * 2 + 2 * numSections * 2; + // NumEdges = NumRingEdges + NumSectionEdges = (numRings * numSections) + (numRings * numSections) + const uint32_t numEdges = numRings * numSections * 2; const uint32_t numLineIndices = numEdges * 2; // build "inner" faces @@ -401,10 +420,9 @@ namespace AZ indices.clear(); indices.reserve(numLineIndices); - for (uint16_t ring = 0; ring < numRings - 2; ++ring) + for (uint16_t ring = 0; ring < numRings - numberOfPoles + 1; ++ring) { uint16_t firstVertOfThisRing = static_cast(1 + ring * numSections); - uint16_t firstVertOfNextRing = static_cast(1 + (ring + 1) * numSections); for (uint16_t section = 0; section < numSections; ++section) { uint32_t nextSection = (section + 1) % numSections; @@ -414,32 +432,33 @@ namespace AZ indices.push_back(static_cast(firstVertOfThisRing + nextSection)); // line around section - indices.push_back(firstVertOfThisRing + section); - indices.push_back(firstVertOfNextRing + section); + int currentVertexIndex = firstVertOfThisRing + section; + // max 0 will implicitly handle the top pole + int previousVertexIndex = AZStd::max(currentVertexIndex - (int)numSections, 0); + indices.push_back(static_cast(currentVertexIndex)); + indices.push_back(static_cast(previousVertexIndex)); } } - // build faces for end caps (to connect "inner" vertices with poles) - uint16_t firstPoleVert = 0; - uint16_t firstVertOfFirstRing = static_cast(1 + (0) * numSections); - for (uint16_t section = 0; section < numSections; ++section) + if (sphereShapeType == ShapeType_Sphere) { - indices.push_back(firstPoleVert); - indices.push_back(firstVertOfFirstRing + section); - } - - uint16_t lastPoleVert = static_cast((numRings - 1) * numSections + 1); - uint16_t firstVertOfLastRing = static_cast(1 + (numRings - 2) * numSections); - for (uint16_t section = 0; section < numSections; ++section) - { - indices.push_back(firstVertOfLastRing + section); - indices.push_back(lastPoleVert); + // build faces for bottom pole (to connect "inner" vertices with poles) + uint16_t lastPoleVert = static_cast((numRings - 1) * numSections + 1); + uint16_t firstVertOfLastRing = static_cast(1 + (numRings - 2) * numSections); + for (uint16_t section = 0; section < numSections; ++section) + { + indices.push_back(firstVertOfLastRing + section); + indices.push_back(lastPoleVert); + } } } // triangle indices { - const uint32_t numTriangles = (numRings - 2) * numSections * 2 + 2 * numSections; + // NumTriangles = NumTrianglesAtPoles + NumQuads * 2 + // = (numSections * 2) + ((numRings - 2) * numSections * 2) + // = (numSections * 2) * (numRings - 2 + 1) + const uint32_t numTriangles = (numRings - 1) * numSections * 2; const uint32_t numTriangleIndices = numTriangles * 3; // build "inner" faces @@ -447,10 +466,10 @@ namespace AZ indices.clear(); indices.reserve(numTriangleIndices); - for (uint32_t ring = 0; ring < numRings - 2; ++ring) + for (uint32_t ring = 0; ring < numRings - numberOfPoles; ++ring) { uint32_t firstVertOfThisRing = 1 + ring * numSections; - uint32_t firstVertOfNextRing = 1 + (ring + 1) * numSections; + uint32_t firstVertOfNextRing = firstVertOfThisRing + numSections; for (uint32_t section = 0; section < numSections; ++section) { @@ -476,14 +495,17 @@ namespace AZ indices.push_back(static_cast(firstPoleVert)); } - uint32_t lastPoleVert = (numRings - 1) * numSections + 1; - uint32_t firstVertOfLastRing = 1 + (numRings - 2) * numSections; - for (uint32_t section = 0; section < numSections; ++section) + if (sphereShapeType == ShapeType_Sphere) { - uint32_t nextSection = (section + 1) % numSections; - indices.push_back(static_cast(firstVertOfLastRing + nextSection)); - indices.push_back(static_cast(firstVertOfLastRing + section)); - indices.push_back(static_cast(lastPoleVert)); + uint32_t lastPoleVert = (numRings - 1) * numSections + 1; + uint32_t firstVertOfLastRing = 1 + (numRings - 2) * numSections; + for (uint32_t section = 0; section < numSections; ++section) + { + uint32_t nextSection = (section + 1) % numSections; + indices.push_back(static_cast(firstVertOfLastRing + nextSection)); + indices.push_back(static_cast(firstVertOfLastRing + section)); + indices.push_back(static_cast(lastPoleVert)); + } } } } @@ -827,8 +849,11 @@ namespace AZ } } - bool FixedShapeProcessor::CreateCylinderBuffersAndViews() + bool FixedShapeProcessor::CreateCylinderBuffersAndViews(AuxGeomShapeType cylinderShapeType) { + AZ_Assert(cylinderShapeType == ShapeType_Cylinder || cylinderShapeType == ShapeType_CylinderNoEnds, + "Trying to create cylinder buffers and views with a non-cylinder shape type!"); + const uint32_t numCylinderLods = 5; struct LodInfo { @@ -836,21 +861,21 @@ namespace AZ float screenPercentage; }; const AZStd::array lodInfo = - {{ + { { { 38, 0.1000f}, { 22, 0.0100f}, { 14, 0.0010f}, { 10, 0.0001f}, { 8, 0.0000f} - }}; + } }; - auto& m_shape = m_shapes[ShapeType_Cylinder]; + auto& m_shape = m_shapes[cylinderShapeType]; m_shape.m_numLods = numCylinderLods; for (uint32_t lodIndex = 0; lodIndex < numCylinderLods; ++lodIndex) { MeshData meshData; - CreateCylinderMeshData(meshData, lodInfo[lodIndex].numSections); + CreateCylinderMeshData(meshData, lodInfo[lodIndex].numSections, cylinderShapeType); ObjectBuffers objectBuffers; @@ -867,13 +892,25 @@ namespace AZ return true; } - void FixedShapeProcessor::CreateCylinderMeshData(MeshData& meshData, uint32_t numSections) + void FixedShapeProcessor::CreateCylinderMeshData(MeshData& meshData, uint32_t numSections, AuxGeomShapeType cylinderShapeType) { const float radius = 1.0f; const float height = 1.0f; + //uint16_t indexOfBottomCenter = 0; + //uint16_t indexOfBottomStart = 1; + //uint16_t indexOfTopCenter = numSections + 1; + //uint16_t indexOfTopStart = numSections + 2; + uint16_t indexOfSidesStart = static_cast(2 * numSections + 2); + + if (cylinderShapeType == ShapeType_CylinderNoEnds) + { + // We won't draw disks at the ends of the cylinder, so no need to offset side indices + indexOfSidesStart = 0; + } + // calc required number of vertices to build a cylinder for the given parameters - uint32_t numVertices = 4 * numSections + 2; + uint32_t numVertices = indexOfSidesStart + 2 * numSections; // setup buffers auto& positions = meshData.m_positions; @@ -888,8 +925,11 @@ namespace AZ float topHeight = height * 0.5f; // Create caps - CreateDiskMeshData(meshData, numSections, Facing::Down, bottomHeight); - CreateDiskMeshData(meshData, numSections, Facing::Up, topHeight); + if (cylinderShapeType == ShapeType_Cylinder) + { + CreateDiskMeshData(meshData, numSections, Facing::Down, bottomHeight); + CreateDiskMeshData(meshData, numSections, Facing::Up, topHeight); + } // create vertices for side (so normal points out correctly) float sectionAngle(DegToRad(360.0f / (float)numSections)); @@ -906,12 +946,6 @@ namespace AZ normals.push_back(normal); } - //uint16_t indexOfBottomCenter = 0; - //uint16_t indexOfBottomStart = 1; - //uint16_t indexOfTopCenter = numSections + 1; - //uint16_t indexOfTopStart = numSections + 2; - uint16_t indexOfSidesStart = static_cast(2 * numSections + 2); - // build point indices { auto& indices = meshData.m_pointIndices; @@ -930,6 +964,24 @@ namespace AZ indices.push_back(indexOfSidesStart + 2 * section); indices.push_back(indexOfSidesStart + 2 * section + 1); } + + // If we're not drawing the disks at the ends of the cylinder, we still want to + // draw a ring around the end to join the tips of lines we created just above + if (cylinderShapeType == ShapeType_CylinderNoEnds) + { + for (uint16_t section = 0; section < numSections; ++section) + { + uint16_t nextSection = (section + 1) % numSections; + + // line around the bottom cap + indices.push_back(section * 2); + indices.push_back(nextSection * 2); + + // line around the top cap + indices.push_back(section * 2 + 1); + indices.push_back(nextSection * 2 + 1); + } + } } // indices for triangles diff --git a/Gems/Atom/Feature/Common/Code/Source/AuxGeom/FixedShapeProcessor.h b/Gems/Atom/Feature/Common/Code/Source/AuxGeom/FixedShapeProcessor.h index 4007d62f66..958cee3143 100644 --- a/Gems/Atom/Feature/Common/Code/Source/AuxGeom/FixedShapeProcessor.h +++ b/Gems/Atom/Feature/Common/Code/Source/AuxGeom/FixedShapeProcessor.h @@ -138,8 +138,8 @@ namespace AZ Both, }; - bool CreateSphereBuffersAndViews(); - void CreateSphereMeshData(MeshData& meshData, uint32_t numRings, uint32_t numSections); + bool CreateSphereBuffersAndViews(AuxGeomShapeType sphereShapeType); + void CreateSphereMeshData(MeshData& meshData, uint32_t numRings, uint32_t numSections, AuxGeomShapeType sphereShapeType); bool CreateQuadBuffersAndViews(); void CreateQuadMeshDataSide(MeshData& meshData, bool isUp, bool drawLines); @@ -152,8 +152,8 @@ namespace AZ bool CreateConeBuffersAndViews(); void CreateConeMeshData(MeshData& meshData, uint32_t numRings, uint32_t numSections); - bool CreateCylinderBuffersAndViews(); - void CreateCylinderMeshData(MeshData& meshData, uint32_t numSections); + bool CreateCylinderBuffersAndViews(AuxGeomShapeType cylinderShapeType); + void CreateCylinderMeshData(MeshData& meshData, uint32_t numSections, AuxGeomShapeType cylinderShapeType); bool CreateBoxBuffersAndViews(); void CreateBoxMeshData(MeshData& meshData); diff --git a/Gems/Atom/Feature/Common/Code/Source/CommonSystemComponent.cpp b/Gems/Atom/Feature/Common/Code/Source/CommonSystemComponent.cpp index 2e5db39880..c3c189eb62 100644 --- a/Gems/Atom/Feature/Common/Code/Source/CommonSystemComponent.cpp +++ b/Gems/Atom/Feature/Common/Code/Source/CommonSystemComponent.cpp @@ -100,6 +100,7 @@ #include #include #include +#include #include #include #include @@ -292,6 +293,7 @@ namespace AZ passSystem->AddPassCreator(Name("DeferredFogPass"), &DeferredFogPass::Create); // Add Reflection passes + passSystem->AddPassCreator(Name("ReflectionScreenSpaceTracePass"), &Render::ReflectionScreenSpaceTracePass::Create); passSystem->AddPassCreator(Name("ReflectionScreenSpaceBlurPass"), &Render::ReflectionScreenSpaceBlurPass::Create); passSystem->AddPassCreator(Name("ReflectionScreenSpaceBlurChildPass"), &Render::ReflectionScreenSpaceBlurChildPass::Create); passSystem->AddPassCreator(Name("ReflectionScreenSpaceCompositePass"), &Render::ReflectionScreenSpaceCompositePass::Create); diff --git a/Gems/Atom/Feature/Common/Code/Source/CoreLights/DirectionalLightFeatureProcessor.cpp b/Gems/Atom/Feature/Common/Code/Source/CoreLights/DirectionalLightFeatureProcessor.cpp index ce5d3cc363..8a1ff95f29 100644 --- a/Gems/Atom/Feature/Common/Code/Source/CoreLights/DirectionalLightFeatureProcessor.cpp +++ b/Gems/Atom/Feature/Common/Code/Source/CoreLights/DirectionalLightFeatureProcessor.cpp @@ -343,7 +343,6 @@ namespace AZ m_shadowBufferNeedsUpdate = true; m_shadowProperties.GetData(index).m_cameraConfigurations[nullptr] = {}; - m_shadowProperties.GetData(index).m_cameraTransforms[nullptr] = Transform::CreateIdentity(); const LightHandle handle(index); m_shadowingLightHandle = handle; // only the recent light has shadows. @@ -495,20 +494,10 @@ namespace AZ void DirectionalLightFeatureProcessor::SetCameraTransform( LightHandle handle, - const Transform& cameraTransform, - const RPI::RenderPipelineId& renderPipelineId) + const Transform&, + const RPI::RenderPipelineId&) { ShadowProperty& property = m_shadowProperties.GetData(handle.GetIndex()); - - if (RPI::RenderPipeline* renderPipeline = GetParentScene()->GetRenderPipeline(renderPipelineId).get()) - { - const RPI::View* cameraView = renderPipeline->GetDefaultView().get(); - property.m_cameraTransforms[cameraView] = cameraTransform; - } - else - { - property.m_cameraTransforms[nullptr] = cameraTransform; - } property.m_shadowmapViewNeedsUpdate = true; } @@ -934,17 +923,6 @@ namespace AZ return property.m_cameraConfigurations.at(nullptr); } - const Transform& DirectionalLightFeatureProcessor::GetCameraTransform(LightHandle handle, const RPI::View* cameraView) const - { - const ShadowProperty& property = m_shadowProperties.GetData(handle.GetIndex()); - const auto findIt = property.m_cameraTransforms.find(cameraView); - if (findIt != property.m_cameraTransforms.end()) - { - return findIt->second; - } - return property.m_cameraTransforms.at(nullptr); - } - void DirectionalLightFeatureProcessor::UpdateFrustums( LightHandle handle) { @@ -1365,10 +1343,11 @@ namespace AZ // If we used an AABB whose Y-direction range is from a segment, // the depth value on the shadowmap saturated to 0 or 1, // and we could not draw shadow correctly. + const Transform cameraTransform = cameraView->GetCameraTransform(); const Vector3 entireFrustumCenterLight = - lightTransform.GetInverseFast() * (GetCameraTransform(handle, cameraView).TransformPoint(property.m_entireFrustumCenterLocal)); + lightTransform.GetInverseFast() * (cameraTransform.TransformPoint(property.m_entireFrustumCenterLocal)); const float entireCenterY = entireFrustumCenterLight.GetElement(1); - const Vector3 cameraLocationWorld = GetCameraTransform(handle, cameraView).GetTranslation(); + const Vector3 cameraLocationWorld = cameraTransform.GetTranslation(); const Vector3 cameraLocationLight = lightTransformInverse * cameraLocationWorld; // Extend light view frustum by camera depth far in order to avoid shadow lacking behind camera. const float cameraBehindMinY = cameraLocationLight.GetElement(1) - GetCameraConfiguration(handle, cameraView).GetDepthFar(); @@ -1428,8 +1407,8 @@ namespace AZ GetCameraConfiguration(handle, cameraView).GetDepthCenter(depthNear, depthFar), depthFar); - const Vector3 localCenter{ 0.f, depthCenter, 0.f }; - return GetCameraTransform(handle, cameraView).TransformPoint(localCenter); + const Vector3 localCenter{ 0.f, depthCenter, 0.f }; + return cameraView->GetCameraTransform().TransformPoint(localCenter); } float DirectionalLightFeatureProcessor::GetRadius( @@ -1483,7 +1462,7 @@ namespace AZ const ShadowProperty& property = m_shadowProperties.GetData(handle.GetIndex()); const Vector3& boundaryCenter = GetWorldCenterPosition(handle, cameraView, depthNear, depthFar); const CascadeShadowCameraConfiguration& cameraConfiguration = GetCameraConfiguration(handle, cameraView); - const Transform& cameraTransform = GetCameraTransform(handle, cameraView); + const Transform cameraTransform = cameraView->GetCameraTransform(); const Vector3& cameraFwd = cameraTransform.GetBasis(1); const Vector3& cameraUp = cameraTransform.GetBasis(2); const Vector3 cameraToBoundaryCenter = boundaryCenter - cameraTransform.GetTranslation(); diff --git a/Gems/Atom/Feature/Common/Code/Source/CoreLights/DirectionalLightFeatureProcessor.h b/Gems/Atom/Feature/Common/Code/Source/CoreLights/DirectionalLightFeatureProcessor.h index 77f2db38d6..c206a5097f 100644 --- a/Gems/Atom/Feature/Common/Code/Source/CoreLights/DirectionalLightFeatureProcessor.h +++ b/Gems/Atom/Feature/Common/Code/Source/CoreLights/DirectionalLightFeatureProcessor.h @@ -134,9 +134,6 @@ namespace AZ // Default far depth of each cascade. AZStd::array m_defaultFarDepths; - // Transforms of camera who offers view frustum for each camera view. - AZStd::unordered_map m_cameraTransforms; - // Configuration offers shape of the camera view frustum for each camera view. AZStd::unordered_map m_cameraConfigurations; @@ -259,11 +256,6 @@ namespace AZ //! it returns one of the fallback render pipeline ID. const CascadeShadowCameraConfiguration& GetCameraConfiguration(LightHandle handle, const RPI::View* cameraView) const; - //! This returns the camera transform. - //! If it has not been registered for the given camera view. - //! it returns one of the fallback render pipeline ID. - const Transform& GetCameraTransform(LightHandle handle, const RPI::View* cameraView) const; - //! This update view frustum of camera. void UpdateFrustums(LightHandle handle); diff --git a/Gems/Atom/Feature/Common/Code/Source/CoreLights/DiskLightFeatureProcessor.cpp b/Gems/Atom/Feature/Common/Code/Source/CoreLights/DiskLightFeatureProcessor.cpp index acf81ede32..e362ee3afc 100644 --- a/Gems/Atom/Feature/Common/Code/Source/CoreLights/DiskLightFeatureProcessor.cpp +++ b/Gems/Atom/Feature/Common/Code/Source/CoreLights/DiskLightFeatureProcessor.cpp @@ -313,6 +313,11 @@ namespace AZ SetShadowSetting(handle, &ProjectedShadowFeatureProcessor::SetShadowBias, bias); } + void DiskLightFeatureProcessor::SetNormalShadowBias(LightHandle handle, float bias) + { + SetShadowSetting(handle, &ProjectedShadowFeatureProcessor::SetNormalShadowBias, bias); + } + void DiskLightFeatureProcessor::SetShadowmapMaxResolution(LightHandle handle, ShadowmapSize shadowmapSize) { SetShadowSetting(handle, &ProjectedShadowFeatureProcessor::SetShadowmapMaxResolution, shadowmapSize); diff --git a/Gems/Atom/Feature/Common/Code/Source/CoreLights/DiskLightFeatureProcessor.h b/Gems/Atom/Feature/Common/Code/Source/CoreLights/DiskLightFeatureProcessor.h index 275712f84f..bafddacc65 100644 --- a/Gems/Atom/Feature/Common/Code/Source/CoreLights/DiskLightFeatureProcessor.h +++ b/Gems/Atom/Feature/Common/Code/Source/CoreLights/DiskLightFeatureProcessor.h @@ -51,6 +51,7 @@ namespace AZ void SetConeAngles(LightHandle handle, float innerDegrees, float outerDegrees) override; void SetShadowsEnabled(LightHandle handle, bool enabled) override; void SetShadowBias(LightHandle handle, float bias) override; + void SetNormalShadowBias(LightHandle handle, float bias) override; void SetShadowmapMaxResolution(LightHandle handle, ShadowmapSize shadowmapSize) override; void SetShadowFilterMethod(LightHandle handle, ShadowFilterMethod method) override; void SetFilteringSampleCount(LightHandle handle, uint16_t count) override; diff --git a/Gems/Atom/Feature/Common/Code/Source/CoreLights/PointLightFeatureProcessor.cpp b/Gems/Atom/Feature/Common/Code/Source/CoreLights/PointLightFeatureProcessor.cpp index dcf412c35d..c5d6c3bf78 100644 --- a/Gems/Atom/Feature/Common/Code/Source/CoreLights/PointLightFeatureProcessor.cpp +++ b/Gems/Atom/Feature/Common/Code/Source/CoreLights/PointLightFeatureProcessor.cpp @@ -302,5 +302,10 @@ namespace AZ SetShadowSetting(handle, &ProjectedShadowFeatureProcessor::SetEsmExponent, esmExponent); } + void PointLightFeatureProcessor::SetNormalShadowBias(LightHandle handle, float bias) + { + SetShadowSetting(handle, &ProjectedShadowFeatureProcessor::SetNormalShadowBias, bias); + } + } // namespace Render } // namespace AZ diff --git a/Gems/Atom/Feature/Common/Code/Source/CoreLights/PointLightFeatureProcessor.h b/Gems/Atom/Feature/Common/Code/Source/CoreLights/PointLightFeatureProcessor.h index 54cb0303cc..df97fa0a52 100644 --- a/Gems/Atom/Feature/Common/Code/Source/CoreLights/PointLightFeatureProcessor.h +++ b/Gems/Atom/Feature/Common/Code/Source/CoreLights/PointLightFeatureProcessor.h @@ -52,6 +52,7 @@ namespace AZ void SetShadowFilterMethod(LightHandle handle, ShadowFilterMethod method) override; void SetFilteringSampleCount(LightHandle handle, uint16_t count) override; void SetEsmExponent(LightHandle handle, float esmExponent) override; + void SetNormalShadowBias(LightHandle handle, float bias) override; void SetPointData(LightHandle handle, const PointLightData& data) override; const Data::Instance GetLightBuffer() const; diff --git a/Gems/Atom/Feature/Common/Code/Source/ReflectionScreenSpace/ReflectionCopyFrameBufferPass.cpp b/Gems/Atom/Feature/Common/Code/Source/ReflectionScreenSpace/ReflectionCopyFrameBufferPass.cpp index a1858a7e9d..8c5e36e706 100644 --- a/Gems/Atom/Feature/Common/Code/Source/ReflectionScreenSpace/ReflectionCopyFrameBufferPass.cpp +++ b/Gems/Atom/Feature/Common/Code/Source/ReflectionScreenSpace/ReflectionCopyFrameBufferPass.cpp @@ -7,7 +7,7 @@ */ #include "ReflectionCopyFrameBufferPass.h" -#include "ReflectionScreenSpaceBlurPass.h" +#include "ReflectionScreenSpaceTracePass.h" #include #include @@ -28,16 +28,16 @@ namespace AZ void ReflectionCopyFrameBufferPass::BuildInternal() { - RPI::PassFilter passFilter = RPI::PassFilter::CreateWithPassName(AZ::Name("ReflectionScreenSpaceBlurPass"), GetRenderPipeline()); + RPI::PassFilter passFilter = RPI::PassFilter::CreateWithPassName(AZ::Name("ReflectionScreenSpaceTracePass"), GetRenderPipeline()); RPI::PassSystemInterface::Get()->ForEachPass(passFilter, [this](RPI::Pass* pass) -> RPI::PassFilterExecutionFlow { - Render::ReflectionScreenSpaceBlurPass* blurPass = azrtti_cast(pass); - Data::Instance& frameBufferAttachment = blurPass->GetFrameBufferImageAttachment(); + Render::ReflectionScreenSpaceTracePass* tracePass = azrtti_cast(pass); + Data::Instance& frameBufferAttachment = tracePass->GetPreviousFrameImageAttachment(); RPI::PassAttachmentBinding& outputBinding = GetOutputBinding(0); AttachImageToSlot(outputBinding.m_name, frameBufferAttachment); - return RPI::PassFilterExecutionFlow::StopVisitingPasses; + return RPI::PassFilterExecutionFlow::StopVisitingPasses; }); FullscreenTrianglePass::BuildInternal(); diff --git a/Gems/Atom/Feature/Common/Code/Source/ReflectionScreenSpace/ReflectionScreenSpaceBlurPass.cpp b/Gems/Atom/Feature/Common/Code/Source/ReflectionScreenSpace/ReflectionScreenSpaceBlurPass.cpp index edd7ad1013..c0b25697a3 100644 --- a/Gems/Atom/Feature/Common/Code/Source/ReflectionScreenSpace/ReflectionScreenSpaceBlurPass.cpp +++ b/Gems/Atom/Feature/Common/Code/Source/ReflectionScreenSpace/ReflectionScreenSpaceBlurPass.cpp @@ -12,6 +12,7 @@ #include #include #include +#include #include #include #include @@ -79,7 +80,7 @@ namespace AZ horizontalBlurChildDesc.m_passTemplate = blurHorizontalPassTemplate; // add child passes to perform the vertical and horizontal Gaussian blur for each roughness mip level - for (uint32_t mip = 0; mip < m_numBlurMips; ++mip) + for (uint32_t mip = 0; mip < NumMipLevels - 1; ++mip) { // create Vertical blur child passes { @@ -114,35 +115,15 @@ namespace AZ RemoveChildren(); m_flags.m_createChildren = true; - Data::Instance pool = RPI::ImageSystemInterface::Get()->GetSystemAttachmentPool(); - - // retrieve the image attachment from the pass - AZ_Assert(m_ownedAttachments.size() == 1, "ReflectionScreenSpaceBlurPass must have exactly one ImageAttachment defined"); - RPI::Ptr reflectionImageAttachment = m_ownedAttachments[0]; - - // update the image attachment descriptor to sync up size and format - reflectionImageAttachment->Update(); - - // change the lifetime since we want it to live between frames - reflectionImageAttachment->m_lifetime = RHI::AttachmentLifetimeType::Imported; - - // set the bind flags - RHI::ImageDescriptor& imageDesc = reflectionImageAttachment->m_descriptor.m_image; - imageDesc.m_bindFlags |= RHI::ImageBindFlags::Color | RHI::ImageBindFlags::ShaderReadWrite; - - // create the image attachment - RHI::ClearValue clearValue = RHI::ClearValue::CreateVector4Float(0, 0, 0, 0); - m_frameBufferImageAttachment = RPI::AttachmentImage::Create(*pool.get(), imageDesc, Name(reflectionImageAttachment->m_path.GetCStr()), &clearValue, nullptr); - - reflectionImageAttachment->m_path = m_frameBufferImageAttachment->GetAttachmentId(); - reflectionImageAttachment->m_importedResource = m_frameBufferImageAttachment; - - uint32_t mipLevels = reflectionImageAttachment->m_descriptor.m_image.m_mipLevels; + // retrieve the reflection, downsampled normal, and downsampled depth attachments + RPI::PassAttachment* reflectionImageAttachment = GetInputOutputBinding(0).m_attachment.get(); RHI::Size imageSize = reflectionImageAttachment->m_descriptor.m_image.m_size; + RPI::PassAttachment* downsampledDepthImageAttachment = GetInputOutputBinding(1).m_attachment.get(); + // create transient attachments, one for each blur mip level AZStd::vector transientPassAttachments; - for (uint32_t mip = 1; mip <= mipLevels - 1; ++mip) + for (uint32_t mip = 1; mip <= NumMipLevels - 1; ++mip) { RHI::Size mipSize = imageSize.GetReducedMip(mip); @@ -160,8 +141,6 @@ namespace AZ m_ownedAttachments.push_back(transientPassAttachment); } - m_numBlurMips = mipLevels - 1; - // call ParentPass::BuildInternal() first to configure the slots and auto-add the empty bindings, // then we will assign attachments to the bindings ParentPass::BuildInternal(); @@ -170,13 +149,27 @@ namespace AZ uint32_t attachmentIndex = 0; for (auto& verticalBlurChildPass : m_verticalBlurChildPasses) { + // mip0 source input RPI::PassAttachmentBinding& inputAttachmentBinding = verticalBlurChildPass->GetInputOutputBinding(0); inputAttachmentBinding.SetAttachment(reflectionImageAttachment); inputAttachmentBinding.m_connectedBinding = &GetInputOutputBinding(0); + // mipN transient output RPI::PassAttachmentBinding& outputAttachmentBinding = verticalBlurChildPass->GetInputOutputBinding(1); outputAttachmentBinding.SetAttachment(transientPassAttachments[attachmentIndex]); + // setup downsampled depth output + // Note: this is a vertical pass output only, and each vertical child pass writes a specific mip level + uint32_t mipLevel = attachmentIndex + 1; + + // downsampled depth output + RPI::PassAttachmentBinding& downsampledDepthAttachmentBinding = verticalBlurChildPass->GetInputOutputBinding(2); + RHI::ImageViewDescriptor downsampledDepthOutputViewDesc; + downsampledDepthOutputViewDesc.m_mipSliceMin = static_cast(mipLevel); + downsampledDepthOutputViewDesc.m_mipSliceMax = static_cast(mipLevel); + downsampledDepthAttachmentBinding.m_unifiedScopeDesc.SetAsImage(downsampledDepthOutputViewDesc); + downsampledDepthAttachmentBinding.SetAttachment(downsampledDepthImageAttachment); + attachmentIndex++; } diff --git a/Gems/Atom/Feature/Common/Code/Source/ReflectionScreenSpace/ReflectionScreenSpaceBlurPass.h b/Gems/Atom/Feature/Common/Code/Source/ReflectionScreenSpace/ReflectionScreenSpaceBlurPass.h index b7ea98ae25..9548665c8a 100644 --- a/Gems/Atom/Feature/Common/Code/Source/ReflectionScreenSpace/ReflectionScreenSpaceBlurPass.h +++ b/Gems/Atom/Feature/Common/Code/Source/ReflectionScreenSpace/ReflectionScreenSpaceBlurPass.h @@ -29,12 +29,8 @@ namespace AZ //! Creates a new pass without a PassTemplate static RPI::Ptr Create(const RPI::PassDescriptor& descriptor); - //! Returns the frame buffer image attachment used by the ReflectionFrameBufferCopy pass - //! to store the previous frame image - Data::Instance& GetFrameBufferImageAttachment() { return m_frameBufferImageAttachment; } - - //! Returns the number of mip levels in the blur - uint32_t GetNumBlurMips() const { return m_numBlurMips; } + //! The total number of mip levels in the blur (including mip0) + static const uint32_t NumMipLevels = 5; private: explicit ReflectionScreenSpaceBlurPass(const RPI::PassDescriptor& descriptor); @@ -47,9 +43,6 @@ namespace AZ AZStd::vector> m_verticalBlurChildPasses; AZStd::vector> m_horizontalBlurChildPasses; - - Data::Instance m_frameBufferImageAttachment; - uint32_t m_numBlurMips = 0; }; } // namespace RPI } // namespace AZ diff --git a/Gems/Atom/Feature/Common/Code/Source/ReflectionScreenSpace/ReflectionScreenSpaceCompositePass.cpp b/Gems/Atom/Feature/Common/Code/Source/ReflectionScreenSpace/ReflectionScreenSpaceCompositePass.cpp index 1362191691..d27d4d90c9 100644 --- a/Gems/Atom/Feature/Common/Code/Source/ReflectionScreenSpace/ReflectionScreenSpaceCompositePass.cpp +++ b/Gems/Atom/Feature/Common/Code/Source/ReflectionScreenSpace/ReflectionScreenSpaceCompositePass.cpp @@ -26,6 +26,19 @@ namespace AZ { } + bool ReflectionScreenSpaceCompositePass::IsEnabled() const + { + // delay for a few frames to ensure that the previous frame texture is populated + static const uint32_t FrameDelay = 10; + if (m_frameDelayCount < FrameDelay) + { + m_frameDelayCount++; + return false; + } + + return true; + } + void ReflectionScreenSpaceCompositePass::CompileResources([[maybe_unused]] const RHI::FrameGraphCompileContext& context) { if (!m_shaderResourceGroup) @@ -33,22 +46,8 @@ namespace AZ return; } - RPI::PassFilter passFilter = RPI::PassFilter::CreateWithPassName(AZ::Name("ReflectionScreenSpaceBlurPass"), GetRenderPipeline()); - - RPI::PassSystemInterface::Get()->ForEachPass(passFilter, [this](RPI::Pass* pass) -> RPI::PassFilterExecutionFlow - { - Render::ReflectionScreenSpaceBlurPass* blurPass = azrtti_cast(pass); - - // compute the max mip level based on the available mips in the previous frame image, and capping it - // to stay within a range that has reasonable data - const uint32_t MaxNumRoughnessMips = 8; - uint32_t maxMipLevel = AZStd::min(MaxNumRoughnessMips, blurPass->GetNumBlurMips()) - 1; - - auto constantIndex = m_shaderResourceGroup->FindShaderInputConstantIndex(Name("m_maxMipLevel")); - m_shaderResourceGroup->SetConstant(constantIndex, maxMipLevel); - - return RPI::PassFilterExecutionFlow::StopVisitingPasses; - }); + auto constantIndex = m_shaderResourceGroup->FindShaderInputConstantIndex(Name("m_maxMipLevel")); + m_shaderResourceGroup->SetConstant(constantIndex, ReflectionScreenSpaceBlurPass::NumMipLevels - 1); FullscreenTrianglePass::CompileResources(context); } diff --git a/Gems/Atom/Feature/Common/Code/Source/ReflectionScreenSpace/ReflectionScreenSpaceCompositePass.h b/Gems/Atom/Feature/Common/Code/Source/ReflectionScreenSpace/ReflectionScreenSpaceCompositePass.h index c70a21cd1e..03b2834633 100644 --- a/Gems/Atom/Feature/Common/Code/Source/ReflectionScreenSpace/ReflectionScreenSpaceCompositePass.h +++ b/Gems/Atom/Feature/Common/Code/Source/ReflectionScreenSpace/ReflectionScreenSpaceCompositePass.h @@ -34,6 +34,9 @@ namespace AZ // Pass Overrides... void CompileResources(const RHI::FrameGraphCompileContext& context) override; + bool IsEnabled() const override; + + mutable uint32_t m_frameDelayCount = 0; }; } // namespace RPI } // namespace AZ diff --git a/Gems/Atom/Feature/Common/Code/Source/ReflectionScreenSpace/ReflectionScreenSpaceTracePass.cpp b/Gems/Atom/Feature/Common/Code/Source/ReflectionScreenSpace/ReflectionScreenSpaceTracePass.cpp new file mode 100644 index 0000000000..7f6bce8a00 --- /dev/null +++ b/Gems/Atom/Feature/Common/Code/Source/ReflectionScreenSpace/ReflectionScreenSpaceTracePass.cpp @@ -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 + * + */ + +#include "ReflectionScreenSpaceTracePass.h" +#include +#include +#include +#include +#include + +namespace AZ +{ + namespace Render + { + RPI::Ptr ReflectionScreenSpaceTracePass::Create(const RPI::PassDescriptor& descriptor) + { + RPI::Ptr pass = aznew ReflectionScreenSpaceTracePass(descriptor); + return AZStd::move(pass); + } + + ReflectionScreenSpaceTracePass::ReflectionScreenSpaceTracePass(const RPI::PassDescriptor& descriptor) + : RPI::FullscreenTrianglePass(descriptor) + { + } + + void ReflectionScreenSpaceTracePass::BuildInternal() + { + Data::Instance pool = RPI::ImageSystemInterface::Get()->GetSystemAttachmentPool(); + + // retrieve the previous frame image attachment from the pass + AZ_Assert(m_ownedAttachments.size() == 3, "ReflectionScreenSpaceTracePass must have the following attachment images defined: ReflectionImage, DownSampledDepthImage, and PreviousFrameImage"); + RPI::Ptr previousFrameImageAttachment = m_ownedAttachments[2]; + + // update the image attachment descriptor to sync up size and format + previousFrameImageAttachment->Update(); + + // change the lifetime since we want it to live between frames + previousFrameImageAttachment->m_lifetime = RHI::AttachmentLifetimeType::Imported; + + // set the bind flags + RHI::ImageDescriptor& imageDesc = previousFrameImageAttachment->m_descriptor.m_image; + imageDesc.m_bindFlags |= RHI::ImageBindFlags::Color | RHI::ImageBindFlags::ShaderReadWrite; + + // create the image attachment + RHI::ClearValue clearValue = RHI::ClearValue::CreateVector4Float(0, 0, 0, 0); + m_previousFrameImageAttachment = RPI::AttachmentImage::Create(*pool.get(), imageDesc, Name(previousFrameImageAttachment->m_path.GetCStr()), &clearValue, nullptr); + + previousFrameImageAttachment->m_path = m_previousFrameImageAttachment->GetAttachmentId(); + previousFrameImageAttachment->m_importedResource = m_previousFrameImageAttachment; + } + + } // namespace RPI +} // namespace AZ diff --git a/Gems/Atom/Feature/Common/Code/Source/ReflectionScreenSpace/ReflectionScreenSpaceTracePass.h b/Gems/Atom/Feature/Common/Code/Source/ReflectionScreenSpace/ReflectionScreenSpaceTracePass.h new file mode 100644 index 0000000000..b03418bbac --- /dev/null +++ b/Gems/Atom/Feature/Common/Code/Source/ReflectionScreenSpace/ReflectionScreenSpaceTracePass.h @@ -0,0 +1,43 @@ +/* + * 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 + { + //! This pass traces screenspace reflections from the previous frame image. + class ReflectionScreenSpaceTracePass + : public RPI::FullscreenTrianglePass + { + AZ_RPI_PASS(DiffuseProbeGridDownsamplePass); + + public: + AZ_RTTI(Render::ReflectionScreenSpaceTracePass, "{70FD45E9-8363-4AA1-A514-3C24AC975E53}", FullscreenTrianglePass); + AZ_CLASS_ALLOCATOR(Render::ReflectionScreenSpaceTracePass, SystemAllocator, 0); + + //! Creates a new pass without a PassTemplate + static RPI::Ptr Create(const RPI::PassDescriptor& descriptor); + + Data::Instance& GetPreviousFrameImageAttachment() { return m_previousFrameImageAttachment; } + + private: + explicit ReflectionScreenSpaceTracePass(const RPI::PassDescriptor& descriptor); + + // Pass behavior overrides... + virtual void BuildInternal() override; + + Data::Instance m_previousFrameImageAttachment; + }; + } // namespace RPI +} // namespace AZ diff --git a/Gems/Atom/Feature/Common/Code/Source/Shadows/ProjectedShadowFeatureProcessor.cpp b/Gems/Atom/Feature/Common/Code/Source/Shadows/ProjectedShadowFeatureProcessor.cpp index 70ccaa5702..c0cc93d7e0 100644 --- a/Gems/Atom/Feature/Common/Code/Source/Shadows/ProjectedShadowFeatureProcessor.cpp +++ b/Gems/Atom/Feature/Common/Code/Source/Shadows/ProjectedShadowFeatureProcessor.cpp @@ -155,8 +155,9 @@ namespace AZ::Render { AZ_Assert(id.IsValid(), "Invalid ShadowId passed to ProjectedShadowFeatureProcessor::SetNormalShadowBias()."); - ShadowProperty& shadowProperty = GetShadowPropertyFromShadowId(id); - shadowProperty.m_normalShadowBias = normalShadowBias; + ShadowData& shadowData = m_shadowData.GetElement(id.GetIndex()); + shadowData.m_normalShadowBias = normalShadowBias; + m_deviceBufferNeedsUpdate = true; } void ProjectedShadowFeatureProcessor::SetShadowmapMaxResolution(ShadowId id, ShadowmapSize size) diff --git a/Gems/Atom/Feature/Common/Code/Source/Shadows/ProjectedShadowFeatureProcessor.h b/Gems/Atom/Feature/Common/Code/Source/Shadows/ProjectedShadowFeatureProcessor.h index 8939f1845d..a892e77b7f 100644 --- a/Gems/Atom/Feature/Common/Code/Source/Shadows/ProjectedShadowFeatureProcessor.h +++ b/Gems/Atom/Feature/Common/Code/Source/Shadows/ProjectedShadowFeatureProcessor.h @@ -68,7 +68,7 @@ namespace AZ::Render uint32_t m_filteringSampleCount = 0; AZStd::array m_unprojectConstants = { {0, 0} }; float m_bias; - float m_normalShadowBias; + float m_normalShadowBias = 0; float m_esmExponent = 87.0f; float m_padding[3]; }; @@ -79,7 +79,6 @@ namespace AZ::Render ProjectedShadowDescriptor m_desc; RPI::ViewPtr m_shadowmapView; float m_bias = 0.1f; - float m_normalShadowBias = 0.0f; ShadowId m_shadowId; }; diff --git a/Gems/Atom/Feature/Common/Code/Source/Utils/EditorModelPreset.cpp b/Gems/Atom/Feature/Common/Code/Source/Utils/EditorModelPreset.cpp index 63c2fc7150..d636fde2fe 100644 --- a/Gems/Atom/Feature/Common/Code/Source/Utils/EditorModelPreset.cpp +++ b/Gems/Atom/Feature/Common/Code/Source/Utils/EditorModelPreset.cpp @@ -29,7 +29,6 @@ namespace AZ ->Attribute(AZ::Edit::Attributes::AutoExpand, true) ->DataElement(AZ::Edit::UIHandlers::Default, &ModelPreset::m_displayName, "Display Name", "Identifier used for display and selection") ->DataElement(AZ::Edit::UIHandlers::Default, &ModelPreset::m_modelAsset, "Model Asset", "Model asset reference") - ->DataElement(AZ::Edit::UIHandlers::Default, &ModelPreset::m_previewImageAsset, "Preview Image Asset", "Preview image asset reference") ; } } diff --git a/Gems/Atom/Feature/Common/Code/Source/Utils/ModelPreset.cpp b/Gems/Atom/Feature/Common/Code/Source/Utils/ModelPreset.cpp index c684b3cc89..ce8a1680a9 100644 --- a/Gems/Atom/Feature/Common/Code/Source/Utils/ModelPreset.cpp +++ b/Gems/Atom/Feature/Common/Code/Source/Utils/ModelPreset.cpp @@ -24,10 +24,9 @@ namespace AZ if (auto serializeContext = azrtti_cast(context)) { serializeContext->Class() - ->Version(3) + ->Version(4) ->Field("displayName", &ModelPreset::m_displayName) ->Field("modelAsset", &ModelPreset::m_modelAsset) - ->Field("previewImageAsset", &ModelPreset::m_previewImageAsset) ; } @@ -41,7 +40,6 @@ namespace AZ ->Constructor() ->Property("displayName", BehaviorValueProperty(&ModelPreset::m_displayName)) ->Property("modelAsset", BehaviorValueProperty(&ModelPreset::m_modelAsset)) - ->Property("previewImageAsset", BehaviorValueProperty(&ModelPreset::m_previewImageAsset)) ; } } 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 184460b210..3ed2ec8755 100644 --- a/Gems/Atom/Feature/Common/Code/atom_feature_common_files.cmake +++ b/Gems/Atom/Feature/Common/Code/atom_feature_common_files.cmake @@ -275,6 +275,8 @@ set(FILES Source/RayTracing/RayTracingPassData.h Source/ReflectionProbe/ReflectionProbeFeatureProcessor.cpp Source/ReflectionProbe/ReflectionProbe.cpp + Source/ReflectionScreenSpace/ReflectionScreenSpaceTracePass.cpp + Source/ReflectionScreenSpace/ReflectionScreenSpaceTracePass.h Source/ReflectionScreenSpace/ReflectionScreenSpaceBlurPass.cpp Source/ReflectionScreenSpace/ReflectionScreenSpaceBlurPass.h Source/ReflectionScreenSpace/ReflectionScreenSpaceBlurChildPass.cpp diff --git a/Gems/Atom/Feature/Common/Editor/Scripts/ColorGrading/__init__.py b/Gems/Atom/Feature/Common/Editor/Scripts/ColorGrading/__init__.py index d500d6e09c..7e244dcfb2 100644 --- a/Gems/Atom/Feature/Common/Editor/Scripts/ColorGrading/__init__.py +++ b/Gems/Atom/Feature/Common/Editor/Scripts/ColorGrading/__init__.py @@ -163,6 +163,7 @@ _LOGGER.debug('Invoking __init__.py for {0}.'.format({_PACKAGENAME})) # ------------------------------------------------------------------------- +# ------------------------------------------------------------------------- def get_datadir() -> pathlib.Path: """ persistent application data. diff --git a/Gems/Atom/Feature/Common/Editor/Scripts/ColorGrading/capture_displaymapperpassthrough.py b/Gems/Atom/Feature/Common/Editor/Scripts/ColorGrading/capture_displaymapper.py similarity index 65% rename from Gems/Atom/Feature/Common/Editor/Scripts/ColorGrading/capture_displaymapperpassthrough.py rename to Gems/Atom/Feature/Common/Editor/Scripts/ColorGrading/capture_displaymapper.py index 76cdd8450a..bfcdf4c79e 100644 --- a/Gems/Atom/Feature/Common/Editor/Scripts/ColorGrading/capture_displaymapperpassthrough.py +++ b/Gems/Atom/Feature/Common/Editor/Scripts/ColorGrading/capture_displaymapper.py @@ -10,9 +10,7 @@ """Frame capture of the Displaymapper Passthrough (outputs .dds image)""" # ------------------------------------------------------------------------ import logging as _logging -from env_bool import env_bool -# ------------------------------------------------------------------------ _MODULENAME = 'ColorGrading.capture_displaymapperpassthrough' import ColorGrading.initialize @@ -27,25 +25,35 @@ _LOGGER.debug('Initializing: {0}.'.format({_MODULENAME})) import azlmbr.bus import azlmbr.atom -default_passtree = ["Root", +# This requires the level to have the DisplayMapper component added +# and configured to 'Passthrough' +# but now we can capture the parent input +# so this is here for reference for how it previously worked +passtree_displaymapperpassthrough = ["Root", + "MainPipeline_0", + "MainPipeline", + "PostProcessPass", + "LightAdaptation", + "DisplayMapperPass", + "DisplayMapperPassthrough"] + +# we can grad the parent pass input to the displaymapper directly +passtree_default = ["Root", "MainPipeline_0", "MainPipeline", "PostProcessPass", "LightAdaptation", - "DisplayMapperPass", - "DisplayMapperPassthrough"] + "DisplayMapperPass"] -default_path = "FrameCapture\DisplayMapperPassthrough.dds" - -# To Do: we should try to set display mapper to passthrough, -# then back after capture? +default_path = "FrameCapture\DisplayMappeInput.dds" # To Do: we can wrap this, to call from a PySide2 GUI def capture(command="CapturePassAttachment", - passtree=default_passtree, - pass_type="Output", + passtree=passtree_default, + pass_type="Input", output_path=default_path): + """Writes frame capture into project cache""" azlmbr.atom.FrameCaptureRequestBus(azlmbr.bus.Broadcast, command, passtree, diff --git a/Gems/Atom/Feature/Common/Editor/Scripts/ColorGrading/initialize.py b/Gems/Atom/Feature/Common/Editor/Scripts/ColorGrading/initialize.py index ac64ade322..24fcd08f02 100644 --- a/Gems/Atom/Feature/Common/Editor/Scripts/ColorGrading/initialize.py +++ b/Gems/Atom/Feature/Common/Editor/Scripts/ColorGrading/initialize.py @@ -32,10 +32,7 @@ if DCCSI_GDEBUG: DCCSI_LOGLEVEL = int(10) # set up logger with both console and file _logging -if DCCSI_GDEBUG: - _LOGGER = initialize_logger(_PACKAGENAME, log_to_file=True, default_log_level=DCCSI_LOGLEVEL) -else: - _LOGGER = initialize_logger(_PACKAGENAME, log_to_file=False, default_log_level=DCCSI_LOGLEVEL) +_LOGGER = initialize_logger(_PACKAGENAME, log_to_file=DCCSI_GDEBUG, default_log_level=DCCSI_LOGLEVEL) _LOGGER.debug('Initializing: {0}.'.format({_MODULENAME})) @@ -46,7 +43,7 @@ if DCCSI_DEV_MODE: APPDATA = get_datadir() # os APPDATA APPDATA_WING = Path(APPDATA, f"Wing Pro {DCCSI_WING_VERSION_MAJOR}").resolve() if APPDATA_WING.exists(): - site.addsitedir(pathlib.PureWindowsPath(APPDATA_WING).as_posix()) + site.addsitedir(APPDATA_WING.resolve()) import wingdbstub as debugger try: debugger.Ensure() @@ -75,8 +72,7 @@ def start(): try: _O3DE_DEV = Path(os.getenv('O3DE_DEV')) - _O3DE_DEV = _O3DE_DEV.resolve() - os.environ['O3DE_DEV'] = pathlib.PureWindowsPath(_O3DE_DEV).as_posix() + os.environ['O3DE_DEV'] = _O3DE_DEV.as_posix() _LOGGER.debug(f'O3DE_DEV is: {_O3DE_DEV}') except EnvironmentError as e: _LOGGER.error('O3DE engineroot not set or found') @@ -86,23 +82,22 @@ def start(): _TAG_LY_BUILD_PATH = os.getenv('TAG_LY_BUILD_PATH', 'build') _DEFAULT_BIN_PATH = Path(str(_O3DE_DEV), _TAG_LY_BUILD_PATH, 'bin', 'profile') _O3DE_BIN_PATH = Path(os.getenv('O3DE_BIN_PATH', _DEFAULT_BIN_PATH)) - _O3DE_BIN_PATH = _O3DE_BIN_PATH.resolve() - os.environ['O3DE_BIN_PATH'] = pathlib.PureWindowsPath(_O3DE_BIN_PATH).as_posix() + os.environ['O3DE_BIN_PATH'] = _O3DE_BIN_PATH.as_posix() _LOGGER.debug(f'O3DE_BIN_PATH is: {_O3DE_BIN_PATH}') - site.addsitedir(pathlib.PureWindowsPath(_O3DE_BIN_PATH).as_posix()) + site.addsitedir(_O3DE_BIN_PATH.resolve()) except EnvironmentError as e: _LOGGER.error('O3DE bin folder not set or found') raise e if running_editor: _O3DE_DEV = Path(os.getenv('O3DE_DEV', Path(azlmbr.paths.engroot))) - os.environ['O3DE_DEV'] = pathlib.PureWindowsPath(_O3DE_DEV).as_posix() + os.environ['O3DE_DEV'] = _O3DE_DEV.as_posix() _LOGGER.debug(_O3DE_DEV) _O3DE_BIN_PATH = Path(str(_O3DE_DEV),Path(azlmbr.paths.executableFolder)) _O3DE_BIN = Path(os.getenv('O3DE_BIN', _O3DE_BIN_PATH.resolve())) - os.environ['O3DE_BIN'] = pathlib.PureWindowsPath(_O3DE_BIN).as_posix() + os.environ['O3DE_BIN'] = _O3DE_BIN_PATH.as_posix() _LOGGER.debug(_O3DE_BIN) diff --git a/Gems/Atom/Feature/Common/Tools/ColorGrading/cmdline/CMD_ColorGradingTools.bat b/Gems/Atom/Feature/Common/Tools/ColorGrading/cmdline/CMD_ColorGradingTools.bat index 56021c0801..89dd86be80 100644 --- a/Gems/Atom/Feature/Common/Tools/ColorGrading/cmdline/CMD_ColorGradingTools.bat +++ b/Gems/Atom/Feature/Common/Tools/ColorGrading/cmdline/CMD_ColorGradingTools.bat @@ -34,15 +34,15 @@ SETLOCAL ENABLEDELAYEDEXPANSION IF EXIST "%~dp0User_Env.bat" CALL %~dp0User_Env.bat :: Initialize env -echo +echo. echo ... calling Env_Core.bat CALL %~dp0\Env_Core.bat -echo +echo. echo ... calling Env_Python.bat CALL %~dp0\Env_Python.bat -echo +echo. echo ... calling Env_Tools.bat CALL %~dp0\Env_Tools.bat diff --git a/Gems/Atom/Feature/Common/Tools/ColorGrading/cmdline/Env_Python.bat b/Gems/Atom/Feature/Common/Tools/ColorGrading/cmdline/Env_Python.bat index fc4afc964e..ffb34b06e5 100644 --- a/Gems/Atom/Feature/Common/Tools/ColorGrading/cmdline/Env_Python.bat +++ b/Gems/Atom/Feature/Common/Tools/ColorGrading/cmdline/Env_Python.bat @@ -27,37 +27,19 @@ echo ~ O3DE Color Grading Python Env ... echo _____________________________________________________________________ echo. -:: Python Version -:: Ideally these are set to match the O3DE python distribution -:: \python\runtime -IF "%DCCSI_PY_VERSION_MAJOR%"=="" (set DCCSI_PY_VERSION_MAJOR=3) -echo DCCSI_PY_VERSION_MAJOR = %DCCSI_PY_VERSION_MAJOR% - -:: PY version Major -IF "%DCCSI_PY_VERSION_MINOR%"=="" (set DCCSI_PY_VERSION_MINOR=7) -echo DCCSI_PY_VERSION_MINOR = %DCCSI_PY_VERSION_MINOR% - -IF "%DCCSI_PY_VERSION_RELEASE%"=="" (set DCCSI_PY_VERSION_RELEASE=10) -echo DCCSI_PY_VERSION_RELEASE = %DCCSI_PY_VERSION_RELEASE% - -:: shared location for 64bit python 3.7 DEV location -:: this defines a DCCsi sandbox for lib site-packages by version -:: \Gems\AtomLyIntegration\TechnicalArt\DccScriptingInterface\3rdParty\Python\Lib -set DCCSI_PYTHON_PATH=%DCCSIG_PATH%\3rdParty\Python -echo DCCSI_PYTHON_PATH = %DCCSI_PYTHON_PATH% - -:: add access to a Lib location that matches the py version (example: 3.7.x) -:: switch this for other python versions like maya (2.7.x) -IF "%DCCSI_PYTHON_LIB_PATH%"=="" (set DCCSI_PYTHON_LIB_PATH=%DCCSI_PYTHON_PATH%\Lib\%DCCSI_PY_VERSION_MAJOR%.x\%DCCSI_PY_VERSION_MAJOR%.%DCCSI_PY_VERSION_MINOR%.x\site-packages) -echo DCCSI_PYTHON_LIB_PATH = %DCCSI_PYTHON_LIB_PATH% - -:: add to the PATH -SET PATH=%DCCSI_PYTHON_LIB_PATH%;%PATH% - :: shared location for default O3DE python location set DCCSI_PYTHON_INSTALL=%O3DE_DEV%\Python echo DCCSI_PYTHON_INSTALL = %DCCSI_PYTHON_INSTALL% +:: Warning, many DCC tools (like Maya) include thier own versioned python interpretter. +:: Some apps may not operate correctly if PYTHONHOME is set/propogated. +:: This is definitely the case with Maya, doing so causes Maya to not boot. +FOR /F "tokens=* USEBACKQ" %%F IN (`%DCCSI_PYTHON_INSTALL%\python.cmd %DCCSI_PYTHON_INSTALL%\get_python_path.py`) DO (SET PYTHONHOME=%%F) +echo PYTHONHOME - is now the folder containing O3DE python executable +echo PYTHONHOME = %PYTHONHOME% + +SET PYTHON=%PYTHONHOME%\python.exe + :: location for O3DE python 3.7 location set DCCSI_PY_BASE=%DCCSI_PYTHON_INSTALL%\python.cmd echo DCCSI_PY_BASE = %DCCSI_PY_BASE% @@ -65,10 +47,7 @@ echo DCCSI_PY_BASE = %DCCSI_PY_BASE% :: ide and debugger plug set DCCSI_PY_DEFAULT=%DCCSI_PY_BASE% -IF "%DCCSI_PY_REV%"=="" (set DCCSI_PY_REV=rev2) -IF "%DCCSI_PY_PLATFORM%"=="" (set DCCSI_PY_PLATFORM=windows) - -set DCCSI_PY_IDE=%DCCSI_PYTHON_INSTALL%\runtime\python-%DCCSI_PY_VERSION_MAJOR%.%DCCSI_PY_VERSION_MINOR%.%DCCSI_PY_VERSION_RELEASE%-%DCCSI_PY_REV%-%DCCSI_PY_PLATFORM%\python +set DCCSI_PY_IDE=%PYTHONHOME% echo DCCSI_PY_IDE = %DCCSI_PY_IDE% :: Wing and other IDEs probably prefer access directly to the python.exe @@ -91,11 +70,6 @@ SET PATH=%DCCSI_PYTHON_INSTALL%;%DCCSI_PY_IDE%;%DCCSI_PY_IDE_PACKAGES%;%DCCSI_PY set PYTHONPATH=%DCCSIG_PATH%;%DCCSI_PYTHON_LIB_PATH%;%O3DE_BIN_PATH%;%DCCSI_COLORGRADING_SCRIPTS%;%DCCSI_FEATURECOMMON_SCRIPTS%;%PYTHONPATH% echo PYTHONPATH = %PYTHONPATH% -:: used for debugging in WingIDE (but needs to be here) -IF "%TAG_USERNAME%"=="" (set TAG_USERNAME=NOT_SET) -echo TAG_USERNAME = %TAG_USERNAME% -IF "%TAG_USERNAME%"=="NOT_SET" (echo Add TAG_USERNAME to User_Env.bat) - :: Set flag so we don't initialize dccsi environment twice SET O3DE_ENV_PY_INIT=1 GOTO END_OF_FILE diff --git a/Gems/Atom/Feature/Common/Tools/ColorGrading/cmdline/User_Env.bat.template b/Gems/Atom/Feature/Common/Tools/ColorGrading/cmdline/User_Env.bat.template index 973d6d5afd..7ab970c98e 100644 --- a/Gems/Atom/Feature/Common/Tools/ColorGrading/cmdline/User_Env.bat.template +++ b/Gems/Atom/Feature/Common/Tools/ColorGrading/cmdline/User_Env.bat.template @@ -25,11 +25,6 @@ SET TAG_LY_BUILD_PATH=build SET DCCSI_GDEBUG=True SET DCCSI_DEV_MODE=True -:: set the your user name here for windows path -SET TAG_USERNAME=NOT_SET -SET DCCSI_PY_REV=rev1 -SET DCCSI_PY_PLATFORM=windows - :: Set flag so we don't initialize dccsi environment twice SET O3DE_USER_ENV_INIT=1 GOTO END_OF_FILE diff --git a/Gems/Atom/RPI/Assets/Textures/Defaults/Missing.png b/Gems/Atom/RPI/Assets/Textures/Defaults/Missing.png index 3e9bc68ea5..198d034892 100644 --- a/Gems/Atom/RPI/Assets/Textures/Defaults/Missing.png +++ b/Gems/Atom/RPI/Assets/Textures/Defaults/Missing.png @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:28c3cfd8958813b4b539738bfff589731da0aeec5b3376558f377da2ebe973ff -size 5455 +oid sha256:7028c8db4f935f23aa4396668278a67691d92fe345cc9d417a9f47bd9a4af32b +size 8130 diff --git a/Gems/Atom/RPI/Assets/Textures/Defaults/Missing.png.assetinfo b/Gems/Atom/RPI/Assets/Textures/Defaults/Missing.png.assetinfo new file mode 100644 index 0000000000..264a7f2a25 --- /dev/null +++ b/Gems/Atom/RPI/Assets/Textures/Defaults/Missing.png.assetinfo @@ -0,0 +1,91 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Gems/Atom/RPI/Assets/Textures/Defaults/Processing.png b/Gems/Atom/RPI/Assets/Textures/Defaults/Processing.png index 914499d6e7..14c3ec76b0 100644 --- a/Gems/Atom/RPI/Assets/Textures/Defaults/Processing.png +++ b/Gems/Atom/RPI/Assets/Textures/Defaults/Processing.png @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:8a0935be7347d695ed1716d030b5bae68153a88239b0ff15f67f900ac90be442 -size 5038 +oid sha256:a7d94b9c0a77741736b93d8ed4d2b22bc9ae4cf649f3d8b3f10cbaf595a3ed31 +size 8336 diff --git a/Gems/Atom/RPI/Assets/Textures/Defaults/Processing.png.assetinfo b/Gems/Atom/RPI/Assets/Textures/Defaults/Processing.png.assetinfo new file mode 100644 index 0000000000..4a234ef9f3 --- /dev/null +++ b/Gems/Atom/RPI/Assets/Textures/Defaults/Processing.png.assetinfo @@ -0,0 +1,148 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Gems/Atom/RPI/Assets/Textures/Defaults/ProcessingFailed.png b/Gems/Atom/RPI/Assets/Textures/Defaults/ProcessingFailed.png index 558b16b96e..aafdcc2681 100644 --- a/Gems/Atom/RPI/Assets/Textures/Defaults/ProcessingFailed.png +++ b/Gems/Atom/RPI/Assets/Textures/Defaults/ProcessingFailed.png @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:bb243cd6d6414b4e95eab919fa94193b57825902b8d09f40ce3f334d829e74e2 -size 6286 +oid sha256:3bbd45e3ef81850da81d1cc01775930a53c424e64e287b00990af3e7e6a682ba +size 9701 diff --git a/Gems/Atom/RPI/Assets/Textures/Defaults/ProcessingFailed.png.assetinfo b/Gems/Atom/RPI/Assets/Textures/Defaults/ProcessingFailed.png.assetinfo new file mode 100644 index 0000000000..747ce3e0e2 --- /dev/null +++ b/Gems/Atom/RPI/Assets/Textures/Defaults/ProcessingFailed.png.assetinfo @@ -0,0 +1,148 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Gems/Atom/RPI/Code/Include/Atom/RPI.Edit/Common/AssetUtils.h b/Gems/Atom/RPI/Code/Include/Atom/RPI.Edit/Common/AssetUtils.h index bd11965ffa..f758019cfb 100644 --- a/Gems/Atom/RPI/Code/Include/Atom/RPI.Edit/Common/AssetUtils.h +++ b/Gems/Atom/RPI/Code/Include/Atom/RPI.Edit/Common/AssetUtils.h @@ -12,6 +12,7 @@ #include #include +#include namespace AZ { @@ -21,21 +22,24 @@ namespace AZ { // Declarations... - Outcome MakeAssetId(const AZStd::string& sourcePath, uint32_t productSubId); + // Note that these functions default to TraceLevel::Error to preserve legacy behavior of these APIs. It would be nice to make the default match + // RPI.Reflect/Asset/AssetUtils.h which is TraceLevel::Warning, but we are close to a release so it isn't worth the risk at this time. - Outcome MakeAssetId(const AZStd::string& originatingSourcePath, const AZStd::string& referencedSourceFilePath, uint32_t productSubId); + Outcome MakeAssetId(const AZStd::string& sourcePath, uint32_t productSubId, TraceLevel reporting = TraceLevel::Error); + + Outcome MakeAssetId(const AZStd::string& originatingSourcePath, const AZStd::string& referencedSourceFilePath, uint32_t productSubId, TraceLevel reporting = TraceLevel::Error); template - Outcome> LoadAsset(const AZStd::string& sourcePath, uint32_t productSubId = 0); + Outcome> LoadAsset(const AZStd::string& sourcePath, uint32_t productSubId = 0, TraceLevel reporting = TraceLevel::Error); template - Outcome> LoadAsset(const AZStd::string& originatingSourcePath, const AZStd::string& referencedSourceFilePath, uint32_t productSubId = 0); + Outcome> LoadAsset(const AZStd::string& originatingSourcePath, const AZStd::string& referencedSourceFilePath, uint32_t productSubId = 0, TraceLevel reporting = TraceLevel::Error); template - Outcome> LoadAsset(const AZ::Data::AssetId& assetId, const char* sourcePathForDebug); + Outcome> LoadAsset(const AZ::Data::AssetId& assetId, const char* sourcePathForDebug, TraceLevel reporting = TraceLevel::Error); template - Outcome> LoadAsset(const AZ::Data::AssetId& assetId); + Outcome> LoadAsset(const AZ::Data::AssetId& assetId, TraceLevel reporting = TraceLevel::Error); //! Attempts to resolve the full path to a product asset given its ID AZStd::string GetProductPathByAssetId(const AZ::Data::AssetId& assetId); @@ -65,12 +69,12 @@ namespace AZ // Definitions... template - Outcome> LoadAsset(const AZStd::string& sourcePath, uint32_t productSubId) + Outcome> LoadAsset(const AZStd::string& sourcePath, uint32_t productSubId, TraceLevel reporting) { - auto assetId = MakeAssetId(sourcePath, productSubId); + auto assetId = MakeAssetId(sourcePath, productSubId, reporting); if (assetId.IsSuccess()) { - return LoadAsset(assetId.GetValue(), sourcePath.c_str()); + return LoadAsset(assetId.GetValue(), sourcePath.c_str(), reporting); } else { @@ -79,20 +83,20 @@ namespace AZ } template - Outcome> LoadAsset(const AZStd::string& originatingSourcePath, const AZStd::string& referencedSourceFilePath, uint32_t productSubId) + Outcome> LoadAsset(const AZStd::string& originatingSourcePath, const AZStd::string& referencedSourceFilePath, uint32_t productSubId, TraceLevel reporting) { AZStd::string resolvedPath = ResolvePathReference(originatingSourcePath, referencedSourceFilePath); - return LoadAsset(resolvedPath, productSubId); + return LoadAsset(resolvedPath, productSubId, reporting); } template - Outcome> LoadAsset(const AZ::Data::AssetId& assetId) + Outcome> LoadAsset(const AZ::Data::AssetId& assetId, TraceLevel reporting) { - return LoadAsset(assetId, nullptr); + return LoadAsset(assetId, nullptr, reporting); } template - Outcome> LoadAsset(const AZ::Data::AssetId& assetId, [[maybe_unused]] const char* sourcePathForDebug) + Outcome> LoadAsset(const AZ::Data::AssetId& assetId, [[maybe_unused]] const char* sourcePathForDebug, TraceLevel reporting) { if (nullptr == AZ::IO::FileIOBase::GetInstance()->GetAlias("@products@")) { @@ -111,11 +115,11 @@ namespace AZ } else { - AZ_Error("AssetUtils", false, "Could not load %s [Source='%s' Cache='%s' AssetID=%s] ", + AssetUtilsInternal::ReportIssue(reporting, AZStd::string::format("Could not load %s [Source='%s' Cache='%s' AssetID=%s] ", AzTypeInfo::Name(), sourcePathForDebug ? sourcePathForDebug : "", asset.GetHint().empty() ? "" : asset.GetHint().c_str(), - assetId.ToString().c_str()); + assetId.ToString().c_str()).c_str()); return AZ::Failure(); } diff --git a/Gems/Atom/RPI/Code/Include/Atom/RPI.Edit/Material/MaterialUtils.h b/Gems/Atom/RPI/Code/Include/Atom/RPI.Edit/Material/MaterialUtils.h index d12e848a02..c1183c7aa1 100644 --- a/Gems/Atom/RPI/Code/Include/Atom/RPI.Edit/Material/MaterialUtils.h +++ b/Gems/Atom/RPI/Code/Include/Atom/RPI.Edit/Material/MaterialUtils.h @@ -28,7 +28,18 @@ namespace AZ namespace MaterialUtils { - Outcome> GetImageAssetReference(AZStd::string_view materialSourceFilePath, const AZStd::string imageFilePath); + enum class GetImageAssetResult + { + Empty, //! No image was actually requested, the path was empty + Found, //! The requested asset was found + Missing //! The requested asset was not found, and a placeholder asset was used instead + }; + + //! Finds an ImageAsset referenced by a material file (or a placeholder) + //! @param imageAsset the resulting ImageAsset + //! @param materialSourceFilePath the full path to a material source file that is referenfing an image file + //! @param imageFilePath the path to an image source file, which could be relative to the asset root or relative to the material file + GetImageAssetResult GetImageAssetReference(Data::Asset& imageAsset, AZStd::string_view materialSourceFilePath, const AZStd::string imageFilePath); //! Resolve an enum to a uint32_t given its name and definition array (in MaterialPropertyDescriptor). //! @param propertyDescriptor it contains the definition of all enum names in an array. diff --git a/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/AuxGeom/AuxGeomDraw.h b/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/AuxGeom/AuxGeomDraw.h index 474d0d5b9e..29b127407e 100644 --- a/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/AuxGeom/AuxGeomDraw.h +++ b/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/AuxGeom/AuxGeomDraw.h @@ -147,6 +147,30 @@ namespace AZ //! @param viewProjOverrideIndex Which view projection override entry to use, -1 if unused virtual void DrawSphere( const AZ::Vector3& center, float radius, const AZ::Color& color, DrawStyle style = DrawStyle::Shaded, DepthTest depthTest = DepthTest::On, DepthWrite depthWrite = DepthWrite::On, FaceCullMode faceCull = FaceCullMode::Back, int32_t viewProjOverrideIndex = -1) = 0; + //! Draw a sphere. + //! @param center The center of the sphere. + //! @param direction The direction vector. The Pole of the hemisphere will point along this vector. + //! @param radius The radius. + //! @param color The color to draw the sphere. + //! @param style The draw style (point, wireframe, solid, shaded etc). + //! @param depthTest If depth testing should be enabled + //! @param depthWrite If depth writing should be enabled + //! @param faceCull Which (if any) facing triangles should be culled + //! @param viewProjOverrideIndex Which view projection override entry to use, -1 if unused + virtual void DrawSphere(const AZ::Vector3& center, const AZ::Vector3& direction, float radius, const AZ::Color& color, DrawStyle style = DrawStyle::Shaded, DepthTest depthTest = DepthTest::On, DepthWrite depthWrite = DepthWrite::On, FaceCullMode faceCull = FaceCullMode::Back, int32_t viewProjOverrideIndex = -1) = 0; + + //! Draw a hemisphere. + //! @param center The center of the sphere. + //! @param direction The direction vector. The Pole of the hemisphere will point along this vector. + //! @param radius The radius. + //! @param color The color to draw the sphere. + //! @param style The draw style (point, wireframe, solid, shaded etc). + //! @param depthTest If depth testing should be enabled + //! @param depthWrite If depth writing should be enabled + //! @param faceCull Which (if any) facing triangles should be culled + //! @param viewProjOverrideIndex Which view projection override entry to use, -1 if unused + virtual void DrawHemisphere( const AZ::Vector3& center, const AZ::Vector3& direction, float radius, const AZ::Color& color, DrawStyle style = DrawStyle::Shaded, DepthTest depthTest = DepthTest::On, DepthWrite depthWrite = DepthWrite::On, FaceCullMode faceCull = FaceCullMode::Back, int32_t viewProjOverrideIndex = -1) = 0; + //! Draw a disk. //! @param center The center of the disk. //! @param direction The direction vector. The disk will be orthogonal this vector. @@ -172,7 +196,7 @@ namespace AZ //! @param viewProjOverrideIndex Which view projection override entry to use, -1 if unused virtual void DrawCone(const AZ::Vector3& center, const AZ::Vector3& direction, float radius, float height, const AZ::Color& color, DrawStyle style = DrawStyle::Shaded, DepthTest depthTest = DepthTest::On, DepthWrite depthWrite = DepthWrite::On, FaceCullMode faceCull = FaceCullMode::Back, int32_t viewProjOverrideIndex = -1) = 0; - //! Draw a cylinder. + //! Draw a cylinder (with flat disks on the end). //! @param center The center of the base circle. //! @param direction The direction vector. The top end cap of the cylinder will face along this vector. //! @param radius The radius. @@ -185,6 +209,19 @@ namespace AZ //! @param viewProjOverrideIndex Which view projection override entry to use, -1 if unused virtual void DrawCylinder(const AZ::Vector3& center, const AZ::Vector3& direction, float radius, float height, const AZ::Color& color, DrawStyle style = DrawStyle::Shaded, DepthTest depthTest = DepthTest::On, DepthWrite depthWrite = DepthWrite::On, FaceCullMode faceCull = FaceCullMode::Back, int32_t viewProjOverrideIndex = -1) = 0; + //! Draw a cylinder without flat disk on the end. + //! @param center The center of the base circle. + //! @param direction The direction vector. The top end cap of the cylinder will face along this vector. + //! @param radius The radius. + //! @param height The height of the cylinder. + //! @param color The color to draw the cylinder. + //! @param style The draw style (point, wireframe, solid, shaded etc). + //! @param depthTest If depth testing should be enabled + //! @param depthWrite If depth writing should be enabled + //! @param faceCull Which (if any) facing triangles should be culled + //! @param viewProjOverrideIndex Which view projection override entry to use, -1 if unused + virtual void DrawCylinderNoEnds(const AZ::Vector3& center, const AZ::Vector3& direction, float radius, float height, const AZ::Color& color, DrawStyle style = DrawStyle::Shaded, DepthTest depthTest = DepthTest::On, DepthWrite depthWrite = DepthWrite::On, FaceCullMode faceCull = FaceCullMode::Back, int32_t viewProjOverrideIndex = -1) = 0; + //! Draw an axis-aligned bounding box with no transform. //! @param aabb The AABB (typically the bounding box of a set of world space points). //! @param color The color to draw the box. diff --git a/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/Image/ImageSystemInterface.h b/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/Image/ImageSystemInterface.h index f567881c50..920b763bc3 100644 --- a/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/Image/ImageSystemInterface.h +++ b/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/Image/ImageSystemInterface.h @@ -29,6 +29,14 @@ namespace AZ Count }; + namespace DefaultImageAssetPaths + { + static constexpr char DefaultFallback[] = "textures/defaults/defaultfallback.png.streamingimage"; + static constexpr char Processing[] = "textures/defaults/processing.png.streamingimage"; + static constexpr char ProcessingFailed[] = "textures/defaults/processingfailed.png.streamingimage"; + static constexpr char Missing[] = "textures/defaults/missing.png.streamingimage"; + } + class ImageSystemInterface { public: diff --git a/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/View.h b/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/View.h index cdaf59ff75..eb3592944d 100644 --- a/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/View.h +++ b/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/View.h @@ -92,6 +92,8 @@ namespace AZ const AZ::Matrix4x4& GetViewToWorldMatrix() const; const AZ::Matrix4x4& GetViewToClipMatrix() const; const AZ::Matrix4x4& GetWorldToClipMatrix() const; + const AZ::Matrix4x4& GetClipToWorldMatrix() const; + //! Get the camera's world transform, converted from the viewToWorld matrix's native y-up to z-up AZ::Transform GetCameraTransform() const; @@ -130,17 +132,22 @@ namespace AZ //! Returns the masked occlusion culling interface MaskedOcclusionCulling* GetMaskedOcclusionCulling(); + //! This is called by RenderPipeline when this view is added to the pipeline. + void OnAddToRenderPipeline(); + private: View() = delete; View(const AZ::Name& name, UsageFlags usage); - //! Sorts the finalized draw lists in this view void SortFinalizedDrawLists(); //! Sorts a drawList using the sort function from a pass with the corresponding drawListTag void SortDrawList(RHI::DrawList& drawList, RHI::DrawListTag tag); + //! Attempt to create a shader resource group. + void TryCreateShaderResourceGroup(); + AZ::Name m_name; UsageFlags m_usageFlags; diff --git a/Gems/Atom/RPI/Code/Source/RPI.Builders/Material/MaterialBuilder.cpp b/Gems/Atom/RPI/Code/Source/RPI.Builders/Material/MaterialBuilder.cpp index e9cebf29c7..f11b2f94ac 100644 --- a/Gems/Atom/RPI/Code/Source/RPI.Builders/Material/MaterialBuilder.cpp +++ b/Gems/Atom/RPI/Code/Source/RPI.Builders/Material/MaterialBuilder.cpp @@ -63,11 +63,21 @@ namespace AZ { BusDisconnect(); } + + bool MaterialBuilder::ReportMaterialAssetWarningsAsErrors() const + { + bool warningsAsErrors = false; + if (auto settingsRegistry = AZ::SettingsRegistry::Get(); settingsRegistry != nullptr) + { + settingsRegistry->Get(warningsAsErrors, "/O3DE/Atom/RPI/MaterialBuilder/WarningsAsErrors"); + } + return warningsAsErrors; + } //! Adds all relevant dependencies for a referenced source file, considering that the path might be relative to the original file location or a full asset path. //! This will usually include multiple source dependencies and a single job dependency, but will include only source dependencies if the file is not found. //! Note the AssetBuilderSDK::JobDependency::m_platformIdentifier will not be set by this function. The calling code must set this value before passing back - //! to the AssetBuilderSDK::CreateJobsResponse. If isOrderedOnceForMaterialTypes is true and the dependency is a materialtype file, the job dependency type + //! to the AssetBuilderSDK::CreateJobsResponse. If isOrderedOnceForMaterialTypes is true and the dependency is a .materialtype file, the job dependency type //! will be set to JobDependencyType::OrderOnce. void AddPossibleDependencies(AZStd::string_view currentFilePath, AZStd::string_view referencedParentPath, @@ -277,8 +287,8 @@ namespace AZ return materialTypeAssetOutcome.GetValue(); } - - AZ::Data::Asset CreateMaterialAsset(AZStd::string_view materialSourceFilePath, const rapidjson::Value& json) + + AZ::Data::Asset MaterialBuilder::CreateMaterialAsset(AZStd::string_view materialSourceFilePath, const rapidjson::Value& json) const { auto material = LoadSourceData(json, materialSourceFilePath); @@ -292,7 +302,7 @@ namespace AZ return {}; } - auto materialAssetOutcome = material.GetValue().CreateMaterialAsset(Uuid::CreateRandom(), materialSourceFilePath, true); + auto materialAssetOutcome = material.GetValue().CreateMaterialAsset(Uuid::CreateRandom(), materialSourceFilePath, ReportMaterialAssetWarningsAsErrors()); if (!materialAssetOutcome.IsSuccess()) { return {}; diff --git a/Gems/Atom/RPI/Code/Source/RPI.Builders/Material/MaterialBuilder.h b/Gems/Atom/RPI/Code/Source/RPI.Builders/Material/MaterialBuilder.h index afb0789dcf..4fa5f3cf10 100644 --- a/Gems/Atom/RPI/Code/Source/RPI.Builders/Material/MaterialBuilder.h +++ b/Gems/Atom/RPI/Code/Source/RPI.Builders/Material/MaterialBuilder.h @@ -9,6 +9,8 @@ #pragma once #include +#include +#include namespace AZ { @@ -37,6 +39,9 @@ namespace AZ private: + AZ::Data::Asset CreateMaterialAsset(AZStd::string_view materialSourceFilePath, const rapidjson::Value& json) const; + bool ReportMaterialAssetWarningsAsErrors() const; + bool m_isShuttingDown = false; }; diff --git a/Gems/Atom/RPI/Code/Source/RPI.Edit/Common/AssetUtils.cpp b/Gems/Atom/RPI/Code/Source/RPI.Edit/Common/AssetUtils.cpp index c940ef808b..e2877aa163 100644 --- a/Gems/Atom/RPI/Code/Source/RPI.Edit/Common/AssetUtils.cpp +++ b/Gems/Atom/RPI/Code/Source/RPI.Edit/Common/AssetUtils.cpp @@ -10,6 +10,7 @@ #include #include #include +#include namespace AZ { @@ -46,6 +47,12 @@ namespace AZ AZStd::string ResolvePathReference(const AZStd::string& originatingSourceFilePath, const AZStd::string& referencedSourceFilePath) { + // The IsAbsolute part prevents "second join parameter is an absolute path" warnings in StringFunc::Path::Join below + if (referencedSourceFilePath.empty() || AZ::IO::PathView{referencedSourceFilePath}.IsAbsolute()) + { + return referencedSourceFilePath; + } + AZStd::string normalizedReferencedPath = referencedSourceFilePath; AzFramework::StringFunc::Path::Normalize(normalizedReferencedPath); @@ -113,7 +120,7 @@ namespace AZ return results; } - Outcome MakeAssetId(const AZStd::string& sourcePath, uint32_t productSubId) + Outcome MakeAssetId(const AZStd::string& sourcePath, uint32_t productSubId, TraceLevel reporting) { bool assetFound = false; AZ::Data::AssetInfo sourceInfo; @@ -122,7 +129,7 @@ namespace AZ if (!assetFound) { - AZ_Error("AssetUtils", false, "Could not find asset [%s]", sourcePath.c_str()); + AssetUtilsInternal::ReportIssue(reporting, AZStd::string::format("Could not find asset [%s]", sourcePath.c_str()).c_str()); return AZ::Failure(); } else @@ -131,10 +138,10 @@ namespace AZ } } - Outcome MakeAssetId(const AZStd::string& originatingSourcePath, const AZStd::string& referencedSourceFilePath, uint32_t productSubId) + Outcome MakeAssetId(const AZStd::string& originatingSourcePath, const AZStd::string& referencedSourceFilePath, uint32_t productSubId, TraceLevel reporting) { AZStd::string resolvedPath = ResolvePathReference(originatingSourcePath, referencedSourceFilePath); - return MakeAssetId(resolvedPath, productSubId); + return MakeAssetId(resolvedPath, productSubId, reporting); } } // namespace AssetUtils } // namespace RPI diff --git a/Gems/Atom/RPI/Code/Source/RPI.Edit/Material/MaterialSourceData.cpp b/Gems/Atom/RPI/Code/Source/RPI.Edit/Material/MaterialSourceData.cpp index fd073bbae4..4351213c22 100644 --- a/Gems/Atom/RPI/Code/Source/RPI.Edit/Material/MaterialSourceData.cpp +++ b/Gems/Atom/RPI/Code/Source/RPI.Edit/Material/MaterialSourceData.cpp @@ -304,7 +304,7 @@ namespace AZ MaterialPropertyId propertyId{ group.first, property.first }; if (!property.second.m_value.IsValid()) { - AZ_Warning("Material source data", false, "Source data for material property value is invalid."); + materialAssetCreator.ReportWarning("Source data for material property value is invalid."); } else { @@ -318,22 +318,20 @@ namespace AZ { case MaterialPropertyDataType::Image: { - Outcome> imageAssetResult = MaterialUtils::GetImageAssetReference( - materialSourceFilePath, property.second.m_value.GetValue()); + Data::Asset imageAsset; - if (imageAssetResult.IsSuccess()) + MaterialUtils::GetImageAssetResult result = MaterialUtils::GetImageAssetReference( + imageAsset, materialSourceFilePath, property.second.m_value.GetValue()); + + if (result == MaterialUtils::GetImageAssetResult::Missing) { - auto& imageAsset = imageAssetResult.GetValue(); - // Load referenced images when load material - imageAsset.SetAutoLoadBehavior(Data::AssetLoadBehavior::PreLoad); - materialAssetCreator.SetPropertyValue(propertyId.GetFullName(), imageAsset); - } - else - { - materialAssetCreator.ReportError( + materialAssetCreator.ReportWarning( "Material property '%s': Could not find the image '%s'", propertyId.GetFullName().GetCStr(), property.second.m_value.GetValue().data()); } + + imageAsset.SetAutoLoadBehavior(Data::AssetLoadBehavior::PreLoad); + materialAssetCreator.SetPropertyValue(propertyId.GetFullName(), imageAsset); } break; case MaterialPropertyDataType::Enum: diff --git a/Gems/Atom/RPI/Code/Source/RPI.Edit/Material/MaterialTypeSourceData.cpp b/Gems/Atom/RPI/Code/Source/RPI.Edit/Material/MaterialTypeSourceData.cpp index d5551e89ae..d8e6c156be 100644 --- a/Gems/Atom/RPI/Code/Source/RPI.Edit/Material/MaterialTypeSourceData.cpp +++ b/Gems/Atom/RPI/Code/Source/RPI.Edit/Material/MaterialTypeSourceData.cpp @@ -451,20 +451,21 @@ namespace AZ { case MaterialPropertyDataType::Image: { - auto imageAssetResult = MaterialUtils::GetImageAssetReference( - materialTypeSourceFilePath, property.m_value.GetValue()); + Data::Asset imageAsset; - if (imageAssetResult) - { - auto imageAsset = imageAssetResult.GetValue(); - materialTypeAssetCreator.SetPropertyValue(propertyId.GetFullName(), imageAsset); - } - else + MaterialUtils::GetImageAssetResult result = MaterialUtils::GetImageAssetReference( + imageAsset, materialTypeSourceFilePath, property.m_value.GetValue()); + + if (result == MaterialUtils::GetImageAssetResult::Missing) { materialTypeAssetCreator.ReportError( "Material property '%s': Could not find the image '%s'", propertyId.GetFullName().GetCStr(), property.m_value.GetValue().data()); } + else + { + materialTypeAssetCreator.SetPropertyValue(propertyId.GetFullName(), imageAsset); + } } break; case MaterialPropertyDataType::Enum: diff --git a/Gems/Atom/RPI/Code/Source/RPI.Edit/Material/MaterialUtils.cpp b/Gems/Atom/RPI/Code/Source/RPI.Edit/Material/MaterialUtils.cpp index 90ce9e66ce..7fff8d81bc 100644 --- a/Gems/Atom/RPI/Code/Source/RPI.Edit/Material/MaterialUtils.cpp +++ b/Gems/Atom/RPI/Code/Source/RPI.Edit/Material/MaterialUtils.cpp @@ -28,25 +28,36 @@ namespace AZ { namespace MaterialUtils { - Outcome> GetImageAssetReference(AZStd::string_view materialSourceFilePath, const AZStd::string imageFilePath) + GetImageAssetResult GetImageAssetReference(Data::Asset& imageAsset, AZStd::string_view materialSourceFilePath, const AZStd::string imageFilePath) { + imageAsset = {}; + if (imageFilePath.empty()) { // The image value was present but specified an empty string, meaning the texture asset should be explicitly cleared. - return AZ::Success(Data::Asset()); + return GetImageAssetResult::Empty; } else { - Outcome imageAssetId = AssetUtils::MakeAssetId(materialSourceFilePath, imageFilePath, StreamingImageAsset::GetImageAssetSubId()); + // We use TraceLevel::None because fallback textures are available and we'll return GetImageAssetResult::Missing below in that case. + // Callers of GetImageAssetReference will be responsible for logging warnings or errors as needed. + + Outcome imageAssetId = AssetUtils::MakeAssetId(materialSourceFilePath, imageFilePath, StreamingImageAsset::GetImageAssetSubId(), AssetUtils::TraceLevel::None); + if (!imageAssetId.IsSuccess()) { - return AZ::Failure(); - } - else - { - Data::Asset unloadedImageAssetReference(imageAssetId.GetValue(), azrtti_typeid(), imageFilePath); - return AZ::Success(unloadedImageAssetReference); + // When the AssetId cannot be found, we don't want to outright fail, because the runtime has mechanisms for displaying fallback textures which gives the + // user a better recovery workflow. On the other hand we can't just provide an empty/invalid Asset because that would be interpreted as simply + // no value was present and result in using no texture, and this would amount to a silent failure. + // So we use a randomly generated (well except for the "BADA55E7" bit ;) UUID which the runtime and tools will interpret as a missing asset and represent + // it as such. + static const Uuid InvalidAssetPlaceholderId = "{BADA55E7-1A1D-4940-B655-9D08679BD62F}"; + imageAsset = Data::Asset{InvalidAssetPlaceholderId, azrtti_typeid(), imageFilePath}; + return GetImageAssetResult::Missing; } + + imageAsset = Data::Asset{imageAssetId.GetValue(), azrtti_typeid(), imageFilePath}; + return GetImageAssetResult::Found; } } diff --git a/Gems/Atom/RPI/Code/Source/RPI.Public/RenderPipeline.cpp b/Gems/Atom/RPI/Code/Source/RPI.Public/RenderPipeline.cpp index 8d4303f187..062eaf02bd 100644 --- a/Gems/Atom/RPI/Code/Source/RPI.Public/RenderPipeline.cpp +++ b/Gems/Atom/RPI/Code/Source/RPI.Public/RenderPipeline.cpp @@ -178,6 +178,10 @@ namespace AZ pipelineViews.m_views.resize(1); } ViewPtr previousView = pipelineViews.m_views[0]; + if (view) + { + view->OnAddToRenderPipeline(); + } pipelineViews.m_views[0] = view; if (previousView) @@ -238,6 +242,7 @@ namespace AZ pipelineViews.m_type = PipelineViewType::Transient; } view->SetPassesByDrawList(&pipelineViews.m_passesByDrawList); + view->OnAddToRenderPipeline(); pipelineViews.m_views.push_back(view); } } diff --git a/Gems/Atom/RPI/Code/Source/RPI.Public/View.cpp b/Gems/Atom/RPI/Code/Source/RPI.Public/View.cpp index 8c1e38ba58..4ad8dae41c 100644 --- a/Gems/Atom/RPI/Code/Source/RPI.Public/View.cpp +++ b/Gems/Atom/RPI/Code/Source/RPI.Public/View.cpp @@ -47,18 +47,14 @@ namespace AZ { AZ_Assert(!name.IsEmpty(), "invalid name"); - // Set default matrixes. + // Set default matrices SetWorldToViewMatrix(AZ::Matrix4x4::CreateIdentity()); AZ::Matrix4x4 viewToClipMatrix; AZ::MakePerspectiveFovMatrixRH(viewToClipMatrix, AZ::Constants::HalfPi, 1, 0.1f, 1000.f, true); SetViewToClipMatrix(viewToClipMatrix); - Data::Asset viewSrgShaderAsset = RPISystemInterface::Get()->GetCommonShaderAssetForSrgs(); + TryCreateShaderResourceGroup(); - if (viewSrgShaderAsset.IsReady()) - { - m_shaderResourceGroup = ShaderResourceGroup::Create(viewSrgShaderAsset, RPISystemInterface::Get()->GetViewSrgLayout()->GetName()); - } #if AZ_TRAIT_MASKED_OCCLUSION_CULLING_SUPPORTED m_maskedOcclusionCulling = MaskedOcclusionCulling::Create(); m_maskedOcclusionCulling->SetResolution(MaskedSoftwareOcclusionCullingWidth, MaskedSoftwareOcclusionCullingHeight); @@ -125,6 +121,7 @@ namespace AZ m_worldToViewMatrix = worldToView; m_worldToClipMatrix = m_viewToClipMatrix * m_worldToViewMatrix; + m_clipToWorldMatrix = m_worldToClipMatrix.GetInverseFull(); m_onWorldToViewMatrixChange.Signal(m_worldToViewMatrix); m_onWorldToClipMatrixChange.Signal(m_worldToClipMatrix); @@ -162,6 +159,7 @@ namespace AZ m_worldToViewMatrix = m_viewToWorldMatrix.GetInverseFast(); m_worldToClipMatrix = m_viewToClipMatrix * m_worldToViewMatrix; + m_clipToWorldMatrix = m_worldToClipMatrix.GetInverseFull(); // Only signal an update when there is a change, otherwise this might block // user input from changing the value. @@ -177,6 +175,7 @@ namespace AZ m_viewToClipMatrix = viewToClip; m_worldToClipMatrix = m_viewToClipMatrix * m_worldToViewMatrix; + m_clipToWorldMatrix = m_worldToClipMatrix.GetInverseFull(); // Update z depth constant simultaneously // zNear -> n, zFar -> f @@ -227,6 +226,11 @@ namespace AZ return m_worldToClipMatrix; } + const AZ::Matrix4x4& View::GetClipToWorldMatrix() const + { + return m_clipToWorldMatrix; + } + bool View::HasDrawListTag(RHI::DrawListTag drawListTag) { return drawListTag.IsValid() && m_drawListMask[drawListTag.GetIndex()]; @@ -361,16 +365,19 @@ namespace AZ { if (m_clipSpaceOffset.IsZero()) { - Matrix4x4 worldToClipPrevMatrix = m_viewToClipPrevMatrix * m_worldToViewPrevMatrix; - m_shaderResourceGroup->SetConstant(m_worldToClipPrevMatrixConstantIndex, worldToClipPrevMatrix); - m_shaderResourceGroup->SetConstant(m_viewProjectionMatrixConstantIndex, m_worldToClipMatrix); - m_shaderResourceGroup->SetConstant(m_projectionMatrixConstantIndex, m_viewToClipMatrix); - m_shaderResourceGroup->SetConstant(m_clipToWorldMatrixConstantIndex, m_clipToWorldMatrix); - m_shaderResourceGroup->SetConstant(m_projectionMatrixInverseConstantIndex, m_viewToClipMatrix.GetInverseFull()); + if (m_shaderResourceGroup) + { + Matrix4x4 worldToClipPrevMatrix = m_viewToClipPrevMatrix * m_worldToViewPrevMatrix; + m_shaderResourceGroup->SetConstant(m_worldToClipPrevMatrixConstantIndex, worldToClipPrevMatrix); + m_shaderResourceGroup->SetConstant(m_viewProjectionMatrixConstantIndex, m_worldToClipMatrix); + m_shaderResourceGroup->SetConstant(m_projectionMatrixConstantIndex, m_viewToClipMatrix); + m_shaderResourceGroup->SetConstant(m_clipToWorldMatrixConstantIndex, m_clipToWorldMatrix); + m_shaderResourceGroup->SetConstant(m_projectionMatrixInverseConstantIndex, m_viewToClipMatrix.GetInverseFull()); + } } else { - // Offset the current and previous frame clip matricies + // Offset the current and previous frame clip matrices Matrix4x4 offsetViewToClipMatrix = m_viewToClipMatrix; offsetViewToClipMatrix.SetElement(0, 2, m_clipSpaceOffset.GetX()); offsetViewToClipMatrix.SetElement(1, 2, m_clipSpaceOffset.GetY()); @@ -379,27 +386,33 @@ namespace AZ offsetViewToClipPrevMatrix.SetElement(0, 2, m_clipSpaceOffset.GetX()); offsetViewToClipPrevMatrix.SetElement(1, 2, m_clipSpaceOffset.GetY()); - // Build other matricies dependent on the view to clip matricies + // Build other matrices dependent on the view to clip matrices Matrix4x4 offsetWorldToClipMatrix = offsetViewToClipMatrix * m_worldToViewMatrix; Matrix4x4 offsetWorldToClipPrevMatrix = offsetViewToClipPrevMatrix * m_worldToViewPrevMatrix; Matrix4x4 offsetClipToViewMatrix = offsetViewToClipMatrix.GetInverseFull(); Matrix4x4 offsetClipToWorldMatrix = m_viewToWorldMatrix * offsetClipToViewMatrix; - - m_shaderResourceGroup->SetConstant(m_worldToClipPrevMatrixConstantIndex, offsetWorldToClipPrevMatrix); - m_shaderResourceGroup->SetConstant(m_viewProjectionMatrixConstantIndex, offsetWorldToClipMatrix); - m_shaderResourceGroup->SetConstant(m_projectionMatrixConstantIndex, offsetViewToClipMatrix); - m_shaderResourceGroup->SetConstant(m_clipToWorldMatrixConstantIndex, offsetClipToWorldMatrix); - m_shaderResourceGroup->SetConstant(m_projectionMatrixInverseConstantIndex, offsetViewToClipMatrix.GetInverseFull()); + + if (m_shaderResourceGroup) + { + m_shaderResourceGroup->SetConstant(m_worldToClipPrevMatrixConstantIndex, offsetWorldToClipPrevMatrix); + m_shaderResourceGroup->SetConstant(m_viewProjectionMatrixConstantIndex, offsetWorldToClipMatrix); + m_shaderResourceGroup->SetConstant(m_projectionMatrixConstantIndex, offsetViewToClipMatrix); + m_shaderResourceGroup->SetConstant(m_clipToWorldMatrixConstantIndex, offsetClipToWorldMatrix); + m_shaderResourceGroup->SetConstant(m_projectionMatrixInverseConstantIndex, offsetViewToClipMatrix.GetInverseFull()); + } } - m_shaderResourceGroup->SetConstant(m_worldPositionConstantIndex, m_position); - m_shaderResourceGroup->SetConstant(m_viewMatrixConstantIndex, m_worldToViewMatrix); - m_shaderResourceGroup->SetConstant(m_viewMatrixInverseConstantIndex, m_worldToViewMatrix.GetInverseFull()); - m_shaderResourceGroup->SetConstant(m_zConstantsConstantIndex, m_nearZ_farZ_farZTimesNearZ_farZMinusNearZ); - m_shaderResourceGroup->SetConstant(m_unprojectionConstantsIndex, m_unprojectionConstants); + if (m_shaderResourceGroup) + { + m_shaderResourceGroup->SetConstant(m_worldPositionConstantIndex, m_position); + m_shaderResourceGroup->SetConstant(m_viewMatrixConstantIndex, m_worldToViewMatrix); + m_shaderResourceGroup->SetConstant(m_viewMatrixInverseConstantIndex, m_worldToViewMatrix.GetInverseFull()); + m_shaderResourceGroup->SetConstant(m_zConstantsConstantIndex, m_nearZ_farZ_farZTimesNearZ_farZMinusNearZ); + m_shaderResourceGroup->SetConstant(m_unprojectionConstantsIndex, m_unprojectionConstants); - m_shaderResourceGroup->Compile(); + m_shaderResourceGroup->Compile(); + } m_viewToClipPrevMatrix = m_viewToClipMatrix; m_worldToViewPrevMatrix = m_worldToViewMatrix; @@ -418,5 +431,30 @@ namespace AZ { return m_maskedOcclusionCulling; } + + void View::TryCreateShaderResourceGroup() + { + if (!m_shaderResourceGroup) + { + if (auto rpiSystemInterface = RPISystemInterface::Get()) + { + if (Data::Asset viewSrgShaderAsset = rpiSystemInterface->GetCommonShaderAssetForSrgs(); + viewSrgShaderAsset.IsReady()) + { + m_shaderResourceGroup = + ShaderResourceGroup::Create(viewSrgShaderAsset, rpiSystemInterface->GetViewSrgLayout()->GetName()); + } + } + } + } + + void View::OnAddToRenderPipeline() + { + TryCreateShaderResourceGroup(); + if (!m_shaderResourceGroup) + { + AZ_Warning("RPI::View", false, "Shader Resource Group failed to initialize"); + } + } } // namespace RPI } // namespace AZ diff --git a/Gems/Atom/RPI/Code/Source/RPI.Reflect/Image/StreamingImageAssetHandler.cpp b/Gems/Atom/RPI/Code/Source/RPI.Reflect/Image/StreamingImageAssetHandler.cpp index fd04635da3..dd16c565e7 100644 --- a/Gems/Atom/RPI/Code/Source/RPI.Reflect/Image/StreamingImageAssetHandler.cpp +++ b/Gems/Atom/RPI/Code/Source/RPI.Reflect/Image/StreamingImageAssetHandler.cpp @@ -7,6 +7,7 @@ */ #include +#include #include #include @@ -52,7 +53,7 @@ namespace AZ missingAssetStatus, &AzFramework::AssetSystem::AssetSystemRequests::GetAssetStatusById, asset.GetId().m_guid); // Determine which fallback image to use - const char* relativePath = "textures/defaults/defaultfallback.png.streamingimage"; + const char* relativePath = DefaultImageAssetPaths::DefaultFallback; bool useDebugFallbackImages = true; if (auto settingsRegistry = AZ::SettingsRegistry::Get(); settingsRegistry != nullptr) @@ -66,15 +67,15 @@ namespace AZ { case AzFramework::AssetSystem::AssetStatus::AssetStatus_Queued: case AzFramework::AssetSystem::AssetStatus::AssetStatus_Compiling: - relativePath = "textures/defaults/processing.png.streamingimage"; + relativePath = DefaultImageAssetPaths::Processing; break; case AzFramework::AssetSystem::AssetStatus::AssetStatus_Failed: - relativePath = "textures/defaults/processingfailed.png.streamingimage"; + relativePath = DefaultImageAssetPaths::ProcessingFailed; break; case AzFramework::AssetSystem::AssetStatus::AssetStatus_Missing: case AzFramework::AssetSystem::AssetStatus::AssetStatus_Unknown: case AzFramework::AssetSystem::AssetStatus::AssetStatus_Compiled: - relativePath = "textures/defaults/missing.png.streamingimage"; + relativePath = DefaultImageAssetPaths::Missing; break; } } 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 d1017139fc..b74305613e 100644 --- a/Gems/Atom/RPI/Code/Source/RPI.Reflect/Material/MaterialPropertyValue.cpp +++ b/Gems/Atom/RPI/Code/Source/RPI.Reflect/Material/MaterialPropertyValue.cpp @@ -118,12 +118,16 @@ namespace AZ else if (value.is>()) { result.m_value = Data::Asset( - AZStd::any_cast>(value).GetId(), azrtti_typeid()); + AZStd::any_cast>(value).GetId(), + azrtti_typeid(), + AZStd::any_cast>(value).GetHint()); } else if (value.is>()) { result.m_value = Data::Asset( - AZStd::any_cast>(value).GetId(), azrtti_typeid()); + AZStd::any_cast>(value).GetId(), + azrtti_typeid(), + AZStd::any_cast>(value).GetHint()); } else if (value.is>()) { diff --git a/Gems/Atom/RPI/Code/Tests/Common/RPITestFixture.cpp b/Gems/Atom/RPI/Code/Tests/Common/RPITestFixture.cpp index 5343c295d8..8c685656ba 100644 --- a/Gems/Atom/RPI/Code/Tests/Common/RPITestFixture.cpp +++ b/Gems/Atom/RPI/Code/Tests/Common/RPITestFixture.cpp @@ -69,6 +69,19 @@ namespace UnitTest assetPath /= "Cache"; AZ::IO::FileIOBase::GetInstance()->SetAlias("@products@", assetPath.c_str()); + // Remark, AZ::Utils::GetProjectPath() is not used when defining "user" folder, + // instead We use AZ::Test::GetEngineRootPath();. + // Reason: + // When running unit tests, using AZ::Utils::GetProjectPath() will resolve to something like: + // "/data/workspace/o3de/build/linux/External/Atom-9a4d112b/RPI/Code/Cache" + // The ShaderMetricSystem.cpp writes to the @user@ folder and the following runtime error occurs: + // "You may not alter data inside the asset cache. Please check the call stack and consider writing into the source asset folder instead." + // "Attempted write location: /data/workspace/o3de/build/linux/External/Atom-9a4d112b/RPI/Code/Cache/user/shadermetrics.json" + // To avoid the error We use AZ::Test::GetEngineRootPath(); + AZ::IO::Path userPath = AZ::Test::GetEngineRootPath(); + userPath /= "user"; + AZ::IO::FileIOBase::GetInstance()->SetAlias("@user@", userPath.c_str()); + m_jsonRegistrationContext = AZStd::make_unique(); m_jsonSystemComponent = AZStd::make_unique(); m_jsonSystemComponent->Reflect(m_jsonRegistrationContext.get()); diff --git a/Gems/Atom/RPI/Code/Tests/Material/MaterialSourceDataTests.cpp b/Gems/Atom/RPI/Code/Tests/Material/MaterialSourceDataTests.cpp index fa8eed35de..d4bf3e5eaa 100644 --- a/Gems/Atom/RPI/Code/Tests/Material/MaterialSourceDataTests.cpp +++ b/Gems/Atom/RPI/Code/Tests/Material/MaterialSourceDataTests.cpp @@ -625,23 +625,6 @@ namespace UnitTest // We use local functions to easily start a new MaterialAssetCreator for each test case because // the AssetCreator would just skip subsequent operations after the first failure is detected. - auto expectError = [](AZStd::function setOneBadInput, [[maybe_unused]] uint32_t expectedAsserts = 2) - { - MaterialSourceData sourceData; - - sourceData.m_materialType = "@exefolder@/Temp/test.materialtype"; - - AddPropertyGroup(sourceData, "general"); - - setOneBadInput(sourceData); - - AZ_TEST_START_ASSERTTEST; - auto materialAssetOutcome = sourceData.CreateMaterialAsset(Uuid::CreateRandom(), "", false); - AZ_TEST_STOP_ASSERTTEST(expectedAsserts); // Usually one for the initial error, and one for when End() is called - - EXPECT_FALSE(materialAssetOutcome.IsSuccess()); - }; - auto expectWarning = [](AZStd::function setOneBadInput, [[maybe_unused]] uint32_t expectedAsserts = 1) { MaterialSourceData sourceData; @@ -692,10 +675,10 @@ namespace UnitTest }); // Missing image reference - expectError([](MaterialSourceData& materialSourceData) + expectWarning([](MaterialSourceData& materialSourceData) { AddProperty(materialSourceData, "general", "MyImage", AZStd::string("doesNotExist.streamingimage")); - }, 3); // Expect a 3rd error because AssetUtils reports its own assertion failure + }); } diff --git a/Gems/Atom/RPI/Code/Tests/Material/MaterialTests.cpp b/Gems/Atom/RPI/Code/Tests/Material/MaterialTests.cpp index 9c3e08ee08..61999d808e 100644 --- a/Gems/Atom/RPI/Code/Tests/Material/MaterialTests.cpp +++ b/Gems/Atom/RPI/Code/Tests/Material/MaterialTests.cpp @@ -888,4 +888,43 @@ namespace UnitTest EXPECT_EQ(indexFromOldName, indexFromNewName); } + template + void CheckPropertyValueRoundTrip(const T& value) + { + AZ::RPI::MaterialPropertyValue materialPropertyValue{value}; + AZStd::any anyValue{value}; + AZ::RPI::MaterialPropertyValue materialPropertyValueFromAny = MaterialPropertyValue::FromAny(anyValue); + AZ::RPI::MaterialPropertyValue materialPropertyValueFromRoundTrip = MaterialPropertyValue::FromAny(MaterialPropertyValue::ToAny(materialPropertyValue)); + + EXPECT_EQ(materialPropertyValue, materialPropertyValueFromAny); + EXPECT_EQ(materialPropertyValue, materialPropertyValueFromRoundTrip); + + if (materialPropertyValue.Is>()) + { + EXPECT_EQ(materialPropertyValue.GetValue>().GetHint(), materialPropertyValueFromAny.GetValue>().GetHint()); + EXPECT_EQ(materialPropertyValue.GetValue>().GetHint(), materialPropertyValueFromRoundTrip.GetValue>().GetHint()); + } + } + + TEST_F(MaterialTests, TestMaterialPropertyValueAsAny) + { + CheckPropertyValueRoundTrip(true); + CheckPropertyValueRoundTrip(false); + CheckPropertyValueRoundTrip(7); + CheckPropertyValueRoundTrip(8u); + CheckPropertyValueRoundTrip(9.0f); + CheckPropertyValueRoundTrip(AZ::Vector2(1.0f, 2.0f)); + CheckPropertyValueRoundTrip(AZ::Vector3(1.0f, 2.0f, 3.0f)); + CheckPropertyValueRoundTrip(AZ::Vector4(1.0f, 2.0f, 3.0f, 4.0f)); + CheckPropertyValueRoundTrip(AZ::Color(1.0f, 2.0f, 3.0f, 4.0f)); + CheckPropertyValueRoundTrip(Data::Asset{}); + CheckPropertyValueRoundTrip(Data::Asset{}); + CheckPropertyValueRoundTrip(Data::Asset{}); + CheckPropertyValueRoundTrip(Data::Asset{Uuid::CreateRandom(), azrtti_typeid(), "TestAssetPath.png"}); + CheckPropertyValueRoundTrip(Data::Asset{Uuid::CreateRandom(), azrtti_typeid(), "TestAssetPath.png"}); + CheckPropertyValueRoundTrip(Data::Asset{Uuid::CreateRandom(), azrtti_typeid(), "TestAssetPath.png"}); + CheckPropertyValueRoundTrip(m_testImageAsset); + CheckPropertyValueRoundTrip(Data::Instance{m_testImage}); + CheckPropertyValueRoundTrip(AZStd::string{"hello"}); + } } diff --git a/Gems/Atom/Tools/AtomToolsFramework/Code/CMakeLists.txt b/Gems/Atom/Tools/AtomToolsFramework/Code/CMakeLists.txt index 40c8d7956e..e7e8208722 100644 --- a/Gems/Atom/Tools/AtomToolsFramework/Code/CMakeLists.txt +++ b/Gems/Atom/Tools/AtomToolsFramework/Code/CMakeLists.txt @@ -42,6 +42,7 @@ ly_add_target( Gem::Atom_RHI.Reflect Gem::Atom_Feature_Common.Static Gem::Atom_Bootstrap.Headers + Gem::ImageProcessingAtom.Headers ) ly_add_target( @@ -60,6 +61,8 @@ ly_add_target( BUILD_DEPENDENCIES PRIVATE Gem::AtomToolsFramework.Static + RUNTIME_DEPENDENCIES + Gem::ImageProcessingAtom.Editor ) ################################################################################ @@ -80,6 +83,7 @@ if(PAL_TRAIT_BUILD_TESTS_SUPPORTED) PRIVATE AZ::AzTest AZ::AzTestShared + AZ::AzFrameworkTestShared Gem::AtomToolsFramework.Static Gem::Atom_Utils.TestUtils.Static ) diff --git a/Gems/Atom/Tools/AtomToolsFramework/Code/Include/AtomToolsFramework/Debug/TraceRecorder.h b/Gems/Atom/Tools/AtomToolsFramework/Code/Include/AtomToolsFramework/Debug/TraceRecorder.h index 96a8728a43..fc19aea2d3 100644 --- a/Gems/Atom/Tools/AtomToolsFramework/Code/Include/AtomToolsFramework/Debug/TraceRecorder.h +++ b/Gems/Atom/Tools/AtomToolsFramework/Code/Include/AtomToolsFramework/Debug/TraceRecorder.h @@ -26,6 +26,21 @@ namespace AtomToolsFramework //! Get the combined output of all messages AZStd::string GetDump() const; + //! Return the number of OnAssert calls + size_t GetAssertCount() const; + + //! Return the number of OnException calls + size_t GetExceptionCount() const; + + //! Return the number of OnError calls, and includes OnAssert and OnException if @includeHigher is true + size_t GetErrorCount(bool includeHigher = false) const; + + //! Return the number of OnWarning calls, and includes higher categories if @includeHigher is true + size_t GetWarningCount(bool includeHigher = false) const; + + //! Return the number of OnPrintf calls, and includes higher categories if @includeHigher is true + size_t GetPrintfCount(bool includeHigher = false) const; + private: ////////////////////////////////////////////////////////////////////////// // AZ::Debug::TraceMessageBus::Handler overrides... @@ -38,5 +53,11 @@ namespace AtomToolsFramework size_t m_maxMessageCount = std::numeric_limits::max(); AZStd::list m_messages; + + size_t m_assertCount = 0; + size_t m_exceptionCount = 0; + size_t m_errorCount = 0; + size_t m_warningCount = 0; + size_t m_printfCount = 0; }; } // namespace AtomToolsFramework diff --git a/Gems/Atom/Tools/AtomToolsFramework/Code/Include/AtomToolsFramework/Util/MaterialPropertyUtil.h b/Gems/Atom/Tools/AtomToolsFramework/Code/Include/AtomToolsFramework/Util/MaterialPropertyUtil.h index 08f59f9e0b..d27f2403a1 100644 --- a/Gems/Atom/Tools/AtomToolsFramework/Code/Include/AtomToolsFramework/Util/MaterialPropertyUtil.h +++ b/Gems/Atom/Tools/AtomToolsFramework/Code/Include/AtomToolsFramework/Util/MaterialPropertyUtil.h @@ -49,6 +49,7 @@ namespace AtomToolsFramework //! @param propertyValue the value being converted before saving bool ConvertToExportFormat( const AZStd::string& exportPath, + [[maybe_unused]] const AZ::Name& propertyId, const AZ::RPI::MaterialTypeSourceData::PropertyDefinition& propertyDefinition, AZ::RPI::MaterialPropertyValue& propertyValue); diff --git a/Gems/Atom/Tools/AtomToolsFramework/Code/Include/AtomToolsFramework/Util/Util.h b/Gems/Atom/Tools/AtomToolsFramework/Code/Include/AtomToolsFramework/Util/Util.h index 1ad6f69961..ab2b8b46c0 100644 --- a/Gems/Atom/Tools/AtomToolsFramework/Code/Include/AtomToolsFramework/Util/Util.h +++ b/Gems/Atom/Tools/AtomToolsFramework/Code/Include/AtomToolsFramework/Util/Util.h @@ -8,8 +8,9 @@ #pragma once -#include #include +#include +#include #include AZ_PUSH_DISABLE_WARNING(4251 4800, "-Wunknown-warning-option") // disable warnings spawned by QT @@ -18,11 +19,24 @@ AZ_PUSH_DISABLE_WARNING(4251 4800, "-Wunknown-warning-option") // disable warnin #include AZ_POP_DISABLE_WARNING +class QImage; + namespace AtomToolsFramework { + template + T GetSettingOrDefault(AZStd::string_view path, const T& defaultValue) + { + T result; + auto settingsRegistry = AZ::SettingsRegistry::Get(); + return (settingsRegistry && settingsRegistry->Get(result, path)) ? result : defaultValue; + } + + using LoadImageAsyncCallback = AZStd::function; + void LoadImageAsync(const AZStd::string& path, LoadImageAsyncCallback callback); + QFileInfo GetSaveFileInfo(const QString& initialPath); QFileInfo GetOpenFileInfo(const AZStd::vector& assetTypes); QFileInfo GetUniqueFileInfo(const QString& initialPath); QFileInfo GetDuplicationFileInfo(const QString& initialPath); bool LaunchTool(const QString& baseName, const QString& extension, const QStringList& arguments); -} +} // namespace AtomToolsFramework diff --git a/Gems/Atom/Tools/AtomToolsFramework/Code/Include/AtomToolsFramework/Viewport/ModularViewportCameraController.h b/Gems/Atom/Tools/AtomToolsFramework/Code/Include/AtomToolsFramework/Viewport/ModularViewportCameraController.h index 1200cb3d79..45c5394fd8 100644 --- a/Gems/Atom/Tools/AtomToolsFramework/Code/Include/AtomToolsFramework/Viewport/ModularViewportCameraController.h +++ b/Gems/Atom/Tools/AtomToolsFramework/Code/Include/AtomToolsFramework/Viewport/ModularViewportCameraController.h @@ -112,15 +112,16 @@ namespace AtomToolsFramework void UpdateViewport(const AzFramework::ViewportControllerUpdateEvent& event) override; // ModularViewportCameraControllerRequestBus overrides ... - void InterpolateToTransform(const AZ::Transform& worldFromLocal) override; - AZ::Transform GetReferenceFrame() const override; - void SetReferenceFrame(const AZ::Transform& worldFromLocal) override; - void ClearReferenceFrame() override; + bool InterpolateToTransform(const AZ::Transform& worldFromLocal) override; + bool IsInterpolating() const override; + void StartTrackingTransform(const AZ::Transform& worldFromLocal) override; + void StopTrackingTransform() override; + bool IsTrackingTransform() const override; private: - //! Update the reference frame after a change has been made to the camera - //! view without updating the internal camera via user input. - void RefreshReferenceFrame(); + //! Combine the current camera transform with any potential roll from the tracked + //! transform (this is usually zero). + AZ::Transform CombinedCameraTransform() const; //! The current mode the camera controller is in. enum class CameraMode @@ -141,21 +142,21 @@ namespace AtomToolsFramework AzFramework::Camera m_camera; //!< The current camera state (pitch/yaw/position/look-distance). AzFramework::Camera m_targetCamera; //!< The target (next) camera state that m_camera is catching up to. AzFramework::Camera m_previousCamera; //!< The state of the camera from the previous frame. - AZStd::optional m_storedCamera; //!< A potentially stored camera for when a custom reference frame is set. + AZStd::optional m_storedCamera; //!< A potentially stored camera for when a transform is being tracked. AzFramework::CameraSystem m_cameraSystem; //!< The camera system responsible for managing all CameraInputs. AzFramework::CameraProps m_cameraProps; //!< Camera properties to control rotate and translate smoothness. CameraControllerPriorityFn m_priorityFn; //!< Controls at what priority the camera controller should respond to events. CameraAnimation m_cameraAnimation; //!< Camera animation state (used during CameraMode::Animation). CameraMode m_cameraMode = CameraMode::Control; //!< The current mode the camera is operating in. - //! An additional reference frame the camera can operate in (identity has no effect). - AZ::Transform m_referenceFrameOverride = AZ::Transform::CreateIdentity(); - //! Flag to prevent circular updates of the camera transform (while the viewport transform is being updated internally). - bool m_updatingTransformInternally = false; + float m_roll = 0.0f; //!< The current amount of roll to be applied to the camera. + float m_targetRoll = 0.0f; //!< The target amount of roll to be applied to the camera (current will move towards this). //! Listen for camera view changes outside of the camera controller. AZ::RPI::ViewportContext::MatrixChangedEvent::Handler m_cameraViewMatrixChangeHandler; //! The current instance of the modular camera viewport context. AZStd::unique_ptr m_modularCameraViewportContext; + //! Flag to prevent circular updates of the camera transform (while the viewport transform is being updated internally). + bool m_updatingTransformInternally = false; }; //! Placeholder implementation for ModularCameraViewportContext (useful for verifying the interface). diff --git a/Gems/Atom/Tools/AtomToolsFramework/Code/Include/AtomToolsFramework/Viewport/ModularViewportCameraControllerRequestBus.h b/Gems/Atom/Tools/AtomToolsFramework/Code/Include/AtomToolsFramework/Viewport/ModularViewportCameraControllerRequestBus.h index ab397692e4..4422751d6b 100644 --- a/Gems/Atom/Tools/AtomToolsFramework/Code/Include/AtomToolsFramework/Viewport/ModularViewportCameraControllerRequestBus.h +++ b/Gems/Atom/Tools/AtomToolsFramework/Code/Include/AtomToolsFramework/Viewport/ModularViewportCameraControllerRequestBus.h @@ -23,23 +23,31 @@ namespace AtomToolsFramework class ModularViewportCameraControllerRequests : public AZ::EBusTraits { public: + static inline constexpr float InterpolateToTransformDuration = 1.0f; + using BusIdType = AzFramework::ViewportId; static const AZ::EBusAddressPolicy AddressPolicy = AZ::EBusAddressPolicy::ById; static const AZ::EBusHandlerPolicy HandlerPolicy = AZ::EBusHandlerPolicy::Single; //! Begin a smooth transition of the camera to the requested transform. //! @param worldFromLocal The transform of where the camera should end up. - virtual void InterpolateToTransform(const AZ::Transform& worldFromLocal) = 0; + //! @return Returns true if the call began an interpolation and false otherwise. Calls to InterpolateToTransform + //! will have no effect if an interpolation is currently in progress. + virtual bool InterpolateToTransform(const AZ::Transform& worldFromLocal) = 0; - //! Return the current reference frame. - //! @note If a reference frame has not been set or a frame has been cleared, this is just the identity. - virtual AZ::Transform GetReferenceFrame() const = 0; + //! Returns if the camera is currently interpolating to a new transform. + virtual bool IsInterpolating() const = 0; - //! Set a new reference frame other than the identity for the camera controller. - virtual void SetReferenceFrame(const AZ::Transform& worldFromLocal) = 0; + //! Start tracking a transform. + //! Store the current camera transform and move to the next camera transform. + virtual void StartTrackingTransform(const AZ::Transform& worldFromLocal) = 0; - //! Clear the current reference frame to restore the identity. - virtual void ClearReferenceFrame() = 0; + //! Stop tracking the set transform. + //! The previously stored camera transform is restored. + virtual void StopTrackingTransform() = 0; + + //! Return if the tracking transform is set. + virtual bool IsTrackingTransform() const = 0; protected: ~ModularViewportCameraControllerRequests() = default; 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 8233658ded..5216f511cb 100644 --- a/Gems/Atom/Tools/AtomToolsFramework/Code/Include/AtomToolsFramework/Viewport/RenderViewportWidget.h +++ b/Gems/Atom/Tools/AtomToolsFramework/Code/Include/AtomToolsFramework/Viewport/RenderViewportWidget.h @@ -21,6 +21,7 @@ #include #include #include +#include namespace AtomToolsFramework { @@ -30,8 +31,8 @@ namespace AtomToolsFramework //! @see AZ::RPI::ViewportContext for Atom's API for setting up class RenderViewportWidget : public QWidget - , public AzToolsFramework::ViewportInteraction::ViewportInteractionRequestBus::Handler , public AzToolsFramework::ViewportInteraction::ViewportMouseCursorRequestBus::Handler + , public AzToolsFramework::ViewportInteraction::ViewportInteractionRequests , public AzFramework::WindowRequestBus::Handler , protected AzFramework::InputChannelEventListener , protected AZ::TickBus::Handler @@ -90,11 +91,11 @@ namespace AtomToolsFramework //! Input processing is enabled by default. void SetInputProcessingEnabled(bool enabled); - // AzToolsFramework::ViewportInteraction::ViewportInteractionRequestBus::Handler overrides ... + // ViewportInteractionRequests overrides ... AzFramework::CameraState GetCameraState() override; AzFramework::ScreenPoint ViewportWorldToScreen(const AZ::Vector3& worldPosition) override; - AZStd::optional ViewportScreenToWorld(const AzFramework::ScreenPoint& screenPosition, float depth) override; - AZStd::optional ViewportScreenToWorldRay( + AZ::Vector3 ViewportScreenToWorld(const AzFramework::ScreenPoint& screenPosition) override; + AzToolsFramework::ViewportInteraction::ProjectedViewportRay ViewportScreenToWorldRay( const AzFramework::ScreenPoint& screenPosition) override; float DeviceScalingFactor() override; @@ -149,5 +150,7 @@ namespace AtomToolsFramework AZ::ScriptTimePoint m_time; // Maps our internal Qt events into AzFramework InputChannels for our ViewportControllerList. AzToolsFramework::QtEventToAzInputMapper* m_inputChannelMapper = nullptr; + // Implementation of ViewportInteractionRequests (handles viewport picking operations). + AZStd::unique_ptr m_viewportInteractionImpl; }; } //namespace AtomToolsFramework diff --git a/Gems/Atom/Tools/AtomToolsFramework/Code/Include/AtomToolsFramework/Viewport/ViewportInteractionImpl.h b/Gems/Atom/Tools/AtomToolsFramework/Code/Include/AtomToolsFramework/Viewport/ViewportInteractionImpl.h new file mode 100644 index 0000000000..b6ad6e17d1 --- /dev/null +++ b/Gems/Atom/Tools/AtomToolsFramework/Code/Include/AtomToolsFramework/Viewport/ViewportInteractionImpl.h @@ -0,0 +1,48 @@ +/* + * 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 AtomToolsFramework +{ + //! A concrete implementation of the ViewportInteractionRequestBus. + //! Primarily concerned with picking (screen to world and world to screen transformations). + class ViewportInteractionImpl + : public AzToolsFramework::ViewportInteraction::ViewportInteractionRequestBus::Handler + , private AZ::RPI::ViewportContextIdNotificationBus::Handler + { + public: + explicit ViewportInteractionImpl(AZ::RPI::ViewPtr viewPtr); + + void Connect(AzFramework::ViewportId viewportId); + void Disconnect(); + + // ViewportInteractionRequestBus overrides ... + AzFramework::CameraState GetCameraState() override; + AzFramework::ScreenPoint ViewportWorldToScreen(const AZ::Vector3& worldPosition) override; + AZ::Vector3 ViewportScreenToWorld(const AzFramework::ScreenPoint& screenPosition) override; + AzToolsFramework::ViewportInteraction::ProjectedViewportRay ViewportScreenToWorldRay( + const AzFramework::ScreenPoint& screenPosition) override; + float DeviceScalingFactor() override; + + AZStd::function m_screenSizeFn; //! Callback to determine the screen size. + AZStd::function m_deviceScalingFactorFn; //! Callback to determine the device scaling factor. + + private: + // ViewportContextIdNotificationBus overrides ... + void OnViewportDefaultViewChanged(AZ::RPI::ViewPtr view) override; + + AZ::RPI::ViewPtr m_viewPtr; + }; +} // namespace AtomToolsFramework diff --git a/Gems/Atom/Tools/AtomToolsFramework/Code/Source/Application/AtomToolsApplication.cpp b/Gems/Atom/Tools/AtomToolsFramework/Code/Source/Application/AtomToolsApplication.cpp index a63a5e6b46..0f21dcb70e 100644 --- a/Gems/Atom/Tools/AtomToolsFramework/Code/Source/Application/AtomToolsApplication.cpp +++ b/Gems/Atom/Tools/AtomToolsFramework/Code/Source/Application/AtomToolsApplication.cpp @@ -79,12 +79,18 @@ namespace AtomToolsFramework m_styleManager.reset(new AzQtComponents::StyleManager(this)); m_styleManager->initialize(this, engineRootPath); - connect(&m_timer, &QTimer::timeout, this, [&]() + m_timer.setInterval(1); + connect(&m_timer, &QTimer::timeout, this, [this]() { this->PumpSystemEventLoopUntilEmpty(); this->Tick(); }); + connect(this, &QGuiApplication::applicationStateChanged, this, [this]() + { + // Limit the update interval when not in focus to reduce power consumption and interference with other applications + this->m_timer.setInterval((applicationState() & Qt::ApplicationActive) ? 1 : 32); + }); } AtomToolsApplication ::~AtomToolsApplication() diff --git a/Gems/Atom/Tools/AtomToolsFramework/Code/Source/Debug/TraceRecorder.cpp b/Gems/Atom/Tools/AtomToolsFramework/Code/Source/Debug/TraceRecorder.cpp index 3fd069ff0b..5f8c8b9004 100644 --- a/Gems/Atom/Tools/AtomToolsFramework/Code/Source/Debug/TraceRecorder.cpp +++ b/Gems/Atom/Tools/AtomToolsFramework/Code/Source/Debug/TraceRecorder.cpp @@ -31,6 +31,7 @@ namespace AtomToolsFramework bool TraceRecorder::OnAssert(const char* message) { + ++m_assertCount; if (m_messages.size() < m_maxMessageCount) { m_messages.push_back(AZStd::string::format("Assert: %s", message)); @@ -40,6 +41,7 @@ namespace AtomToolsFramework bool TraceRecorder::OnException(const char* message) { + ++m_exceptionCount; if (m_messages.size() < m_maxMessageCount) { m_messages.push_back(AZStd::string::format("Exception: %s", message)); @@ -49,6 +51,7 @@ namespace AtomToolsFramework bool TraceRecorder::OnError(const char* /*window*/, const char* message) { + ++m_errorCount; if (m_messages.size() < m_maxMessageCount) { m_messages.push_back(AZStd::string::format("Error: %s", message)); @@ -58,6 +61,7 @@ namespace AtomToolsFramework bool TraceRecorder::OnWarning(const char* /*window*/, const char* message) { + ++m_warningCount; if (m_messages.size() < m_maxMessageCount) { m_messages.push_back(AZStd::string::format("Warning: %s", message)); @@ -67,11 +71,58 @@ namespace AtomToolsFramework bool TraceRecorder::OnPrintf(const char* /*window*/, const char* message) { + ++m_printfCount; if (m_messages.size() < m_maxMessageCount) { m_messages.push_back(AZStd::string::format("%s", message)); } return false; +} + + size_t TraceRecorder::GetAssertCount() const + { + return m_assertCount; + } + + size_t TraceRecorder::GetExceptionCount() const + { + return m_exceptionCount; + } + + size_t TraceRecorder::GetErrorCount(bool includeHigher) const + { + if (includeHigher) + { + return m_errorCount + GetAssertCount() + GetExceptionCount(); + } + else + { + return m_errorCount; + } + } + + size_t TraceRecorder::GetWarningCount(bool includeHigher) const + { + if (includeHigher) + { + return m_warningCount + GetErrorCount(true); + } + else + { + return m_warningCount; + } + } + + size_t TraceRecorder::GetPrintfCount(bool includeHigher) const + { + if (includeHigher) + { + return m_printfCount + GetWarningCount(true); + } + else + { + return m_printfCount; + } } } // namespace AtomToolsFramework diff --git a/Gems/Atom/Tools/AtomToolsFramework/Code/Source/Document/AtomToolsDocumentSystemComponent.cpp b/Gems/Atom/Tools/AtomToolsFramework/Code/Source/Document/AtomToolsDocumentSystemComponent.cpp index 00de2a7c4c..3a392c1413 100644 --- a/Gems/Atom/Tools/AtomToolsFramework/Code/Source/Document/AtomToolsDocumentSystemComponent.cpp +++ b/Gems/Atom/Tools/AtomToolsFramework/Code/Source/Document/AtomToolsDocumentSystemComponent.cpp @@ -495,8 +495,6 @@ namespace AtomToolsFramework return AZ::Uuid::CreateNull(); } - traceRecorder.GetDump().clear(); - bool openResult = false; AtomToolsDocumentRequestBus::EventResult(openResult, documentId, &AtomToolsDocumentRequestBus::Events::Open, requestedPath); if (!openResult) @@ -507,6 +505,12 @@ namespace AtomToolsFramework AtomToolsDocumentSystemRequestBus::Broadcast(&AtomToolsDocumentSystemRequestBus::Events::DestroyDocument, documentId); return AZ::Uuid::CreateNull(); } + else if (traceRecorder.GetWarningCount(true) > 0) + { + QMessageBox::warning( + QApplication::activeWindow(), QString("Document opened with warnings"), + QString("Warnings encountered: \n%1\n\n%2").arg(requestedPath.c_str()).arg(traceRecorder.GetDump().c_str())); + } return documentId; } diff --git a/Gems/Atom/Tools/AtomToolsFramework/Code/Source/Util/MaterialPropertyUtil.cpp b/Gems/Atom/Tools/AtomToolsFramework/Code/Source/Util/MaterialPropertyUtil.cpp index c49cd3fafb..3ffd8efa6e 100644 --- a/Gems/Atom/Tools/AtomToolsFramework/Code/Source/Util/MaterialPropertyUtil.cpp +++ b/Gems/Atom/Tools/AtomToolsFramework/Code/Source/Util/MaterialPropertyUtil.cpp @@ -167,6 +167,7 @@ namespace AtomToolsFramework bool ConvertToExportFormat( const AZStd::string& exportPath, + [[maybe_unused]] const AZ::Name& propertyId, const AZ::RPI::MaterialTypeSourceData::PropertyDefinition& propertyDefinition, AZ::RPI::MaterialPropertyValue& propertyValue) { @@ -175,7 +176,7 @@ namespace AtomToolsFramework const uint32_t index = propertyValue.GetValue(); if (index >= propertyDefinition.m_enumValues.size()) { - AZ_Error("AtomToolsFramework", false, "Invalid value for material enum property: '%s'.", propertyDefinition.m_name.c_str()); + AZ_Error("AtomToolsFramework", false, "Invalid value for material enum property: '%s'.", propertyId.GetCStr()); return false; } @@ -186,18 +187,33 @@ namespace AtomToolsFramework // Image asset references must be converted from asset IDs to a relative source file path if (propertyDefinition.m_dataType == AZ::RPI::MaterialPropertyDataType::Image) { + AZStd::string imagePath; + AZ::Data::AssetId imageAssetId; + if (propertyValue.Is>()) { const auto& imageAsset = propertyValue.GetValue>(); - const auto& imagePath = AZ::RPI::AssetUtils::GetSourcePathByAssetId(imageAsset.GetId()); - propertyValue = GetExteralReferencePath(exportPath, imagePath); - return true; + imageAssetId = imageAsset.GetId(); } if (propertyValue.Is>()) { const auto& image = propertyValue.GetValue>(); - const auto& imagePath = image ? AZ::RPI::AssetUtils::GetSourcePathByAssetId(image->GetAssetId()) : ""; + if (image) + { + imageAssetId = image->GetAssetId(); + } + } + + imagePath = AZ::RPI::AssetUtils::GetSourcePathByAssetId(imageAssetId); + + if (imageAssetId.IsValid() && imagePath.empty()) + { + AZ_Error("AtomToolsFramework", false, "Image asset could not be found for property: '%s'.", propertyId.GetCStr()); + return false; + } + else + { propertyValue = GetExteralReferencePath(exportPath, imagePath); return true; } diff --git a/Gems/Atom/Tools/AtomToolsFramework/Code/Source/Util/Util.cpp b/Gems/Atom/Tools/AtomToolsFramework/Code/Source/Util/Util.cpp index d3bce34af3..cd50c10e23 100644 --- a/Gems/Atom/Tools/AtomToolsFramework/Code/Source/Util/Util.cpp +++ b/Gems/Atom/Tools/AtomToolsFramework/Code/Source/Util/Util.cpp @@ -6,15 +6,18 @@ * */ +#include +#include #include #include +#include #include #include #include #include +#include #include #include -#include AZ_PUSH_DISABLE_WARNING(4251 4800, "-Wunknown-warning-option") // disable warnings spawned by QT #include @@ -24,6 +27,36 @@ AZ_POP_DISABLE_WARNING namespace AtomToolsFramework { + void LoadImageAsync(const AZStd::string& path, LoadImageAsyncCallback callback) + { + AZ::Job* job = AZ::CreateJobFunction( + [path, callback]() + { + ImageProcessingAtom::IImageObjectPtr imageObject; + ImageProcessingAtom::ImageProcessingRequestBus::BroadcastResult( + imageObject, &ImageProcessingAtom::ImageProcessingRequests::LoadImagePreview, path); + + if (imageObject) + { + AZ::u8* imageBuf = nullptr; + AZ::u32 pitch = 0; + AZ::u32 mip = 0; + imageObject->GetImagePointer(mip, imageBuf, pitch); + const AZ::u32 width = imageObject->GetWidth(mip); + const AZ::u32 height = imageObject->GetHeight(mip); + + QImage image(imageBuf, width, height, pitch, QImage::Format_RGBA8888); + + if (callback) + { + callback(image); + } + } + }, + true); + job->Start(); + } + QFileInfo GetSaveFileInfo(const QString& initialPath) { const QFileInfo initialFileInfo(initialPath); diff --git a/Gems/Atom/Tools/AtomToolsFramework/Code/Source/Viewport/ModularViewportCameraController.cpp b/Gems/Atom/Tools/AtomToolsFramework/Code/Source/Viewport/ModularViewportCameraController.cpp index a92bfdbcdb..179ccd9fd8 100644 --- a/Gems/Atom/Tools/AtomToolsFramework/Code/Source/Viewport/ModularViewportCameraController.cpp +++ b/Gems/Atom/Tools/AtomToolsFramework/Code/Source/Viewport/ModularViewportCameraController.cpp @@ -12,6 +12,7 @@ #include #include #include +#include #include #include #include @@ -175,16 +176,12 @@ namespace AtomToolsFramework // ignore these updates if the camera is being updated internally if (!m_updatingTransformInternally) { - if (m_storedCamera.has_value()) - { - // if an external change occurs ensure we update the stored reference frame if one is set - RefreshReferenceFrame(); - return; - } - m_previousCamera = m_targetCamera; - UpdateCameraFromTransform(m_targetCamera, m_modularCameraViewportContext->GetCameraTransform()); - m_camera = m_targetCamera; + + const AZ::Transform transform = m_modularCameraViewportContext->GetCameraTransform(); + const AZ::Vector3 eulerAngles = AzFramework::EulerAngles(AZ::Matrix3x3::CreateFromTransform(transform)); + UpdateCameraFromTranslationAndRotation(m_targetCamera, transform.GetTranslation(), eulerAngles); + m_targetRoll = eulerAngles.GetY(); } }; @@ -227,7 +224,9 @@ namespace AtomToolsFramework { m_targetCamera = m_cameraSystem.StepCamera(m_targetCamera, event.m_deltaTime.count()); m_camera = AzFramework::SmoothCamera(m_camera, m_targetCamera, m_cameraProps, event.m_deltaTime.count()); - m_modularCameraViewportContext->SetCameraTransform(m_referenceFrameOverride * m_camera.Transform()); + m_roll = AzFramework::SmoothValue(m_targetRoll, m_roll, m_cameraProps.m_rotateSmoothnessFn(), event.m_deltaTime.count()); + + m_modularCameraViewportContext->SetCameraTransform(CombinedCameraTransform()); } else if (m_cameraMode == CameraMode::Animation) { @@ -236,7 +235,10 @@ namespace AtomToolsFramework return t * t * t * (t * (t * 6.0f - 15.0f) + 10.0f); }; - m_cameraAnimation.m_time = AZ::GetClamp(m_cameraAnimation.m_time + event.m_deltaTime.count(), 0.0f, 1.0f); + m_cameraAnimation.m_time = AZ::GetClamp( + m_cameraAnimation.m_time + + (event.m_deltaTime.count() / ModularViewportCameraControllerRequests::InterpolateToTransformDuration), + 0.0f, 1.0f); const auto& [transformStart, transformEnd, animationTime] = m_cameraAnimation; @@ -250,6 +252,7 @@ namespace AtomToolsFramework m_camera.m_yaw = eulerAngles.GetZ(); m_camera.m_pivot = current.GetTranslation(); m_camera.m_offset = AZ::Vector3::CreateZero(); + m_targetRoll = eulerAngles.GetY(); m_targetCamera = m_camera; m_modularCameraViewportContext->SetCameraTransform(current); @@ -257,55 +260,59 @@ namespace AtomToolsFramework if (animationTime >= 1.0f) { m_cameraMode = CameraMode::Control; - RefreshReferenceFrame(); } } m_updatingTransformInternally = false; } - void ModularViewportCameraControllerInstance::InterpolateToTransform(const AZ::Transform& worldFromLocal) + bool ModularViewportCameraControllerInstance::InterpolateToTransform(const AZ::Transform& worldFromLocal) { - m_cameraMode = CameraMode::Animation; - m_cameraAnimation = CameraAnimation{ m_referenceFrameOverride * m_camera.Transform(), worldFromLocal, 0.0f }; + if (!IsInterpolating()) + { + m_cameraMode = CameraMode::Animation; + m_cameraAnimation = CameraAnimation{ CombinedCameraTransform(), worldFromLocal, 0.0f }; + + return true; + } + + return false; } - AZ::Transform ModularViewportCameraControllerInstance::GetReferenceFrame() const + bool ModularViewportCameraControllerInstance::IsInterpolating() const { - return m_referenceFrameOverride; + return m_cameraMode == CameraMode::Animation; } - void ModularViewportCameraControllerInstance::SetReferenceFrame(const AZ::Transform& worldFromLocal) + void ModularViewportCameraControllerInstance::StartTrackingTransform(const AZ::Transform& worldFromLocal) { if (!m_storedCamera.has_value()) { m_storedCamera = m_previousCamera; } - m_referenceFrameOverride = worldFromLocal; - m_targetCamera.m_pitch = 0.0f; - m_targetCamera.m_yaw = 0.0f; + const auto angles = AzFramework::EulerAngles(AZ::Matrix3x3::CreateFromQuaternion(worldFromLocal.GetRotation())); + m_targetCamera.m_pitch = angles.GetX(); + m_targetCamera.m_yaw = angles.GetZ(); m_targetCamera.m_offset = AZ::Vector3::CreateZero(); - m_targetCamera.m_pivot = AZ::Vector3::CreateZero(); - m_camera = m_targetCamera; + m_targetCamera.m_pivot = worldFromLocal.GetTranslation(); + m_targetRoll = angles.GetY(); } - void ModularViewportCameraControllerInstance::ClearReferenceFrame() + void ModularViewportCameraControllerInstance::StopTrackingTransform() { - m_referenceFrameOverride = AZ::Transform::CreateIdentity(); - if (m_storedCamera.has_value()) { m_targetCamera = m_storedCamera.value(); - m_camera = m_targetCamera; + m_targetRoll = 0.0f; } m_storedCamera.reset(); } - void ModularViewportCameraControllerInstance::RefreshReferenceFrame() + bool ModularViewportCameraControllerInstance::IsTrackingTransform() const { - m_referenceFrameOverride = m_modularCameraViewportContext->GetCameraTransform() * m_camera.Transform().GetInverse(); + return m_storedCamera.has_value(); } AZ::Transform PlaceholderModularCameraViewportContextImpl::GetCameraTransform() const @@ -324,4 +331,9 @@ namespace AtomToolsFramework { handler.Connect(m_viewMatrixChangedEvent); } + + AZ::Transform ModularViewportCameraControllerInstance::CombinedCameraTransform() const + { + return m_camera.Transform() * AZ::Transform::CreateFromMatrix3x3(AZ::Matrix3x3::CreateRotationY(m_targetRoll)); + } } // namespace AtomToolsFramework diff --git a/Gems/Atom/Tools/AtomToolsFramework/Code/Source/Viewport/RenderViewportWidget.cpp b/Gems/Atom/Tools/AtomToolsFramework/Code/Source/Viewport/RenderViewportWidget.cpp index bed4778e8e..759f939382 100644 --- a/Gems/Atom/Tools/AtomToolsFramework/Code/Source/Viewport/RenderViewportWidget.cpp +++ b/Gems/Atom/Tools/AtomToolsFramework/Code/Source/Viewport/RenderViewportWidget.cpp @@ -75,7 +75,11 @@ namespace AtomToolsFramework m_defaultCamera = AZ::RPI::View::CreateView(cameraName, AZ::RPI::View::UsageFlags::UsageCamera); AZ::Interface::Get()->PushView(m_viewportContext->GetName(), m_defaultCamera); - AzToolsFramework::ViewportInteraction::ViewportInteractionRequestBus::Handler::BusConnect(GetId()); + m_viewportInteractionImpl = AZStd::make_unique(m_defaultCamera); + m_viewportInteractionImpl->m_deviceScalingFactorFn = [this] { return aznumeric_cast(devicePixelRatioF()); }; + m_viewportInteractionImpl->m_screenSizeFn = [this] { return AzFramework::ScreenSize(width(), height()); }; + m_viewportInteractionImpl->Connect(id); + AzToolsFramework::ViewportInteraction::ViewportMouseCursorRequestBus::Handler::BusConnect(GetId()); AzFramework::InputChannelEventListener::Connect(); AZ::TickBus::Handler::BusConnect(); @@ -107,7 +111,7 @@ namespace AtomToolsFramework AZ::TickBus::Handler::BusDisconnect(); AzFramework::InputChannelEventListener::Disconnect(); AzToolsFramework::ViewportInteraction::ViewportMouseCursorRequestBus::Handler::BusDisconnect(); - AzToolsFramework::ViewportInteraction::ViewportInteractionRequestBus::Handler::BusDisconnect(); + m_viewportInteractionImpl->Disconnect(); } void RenderViewportWidget::LockRenderTargetSize(uint32_t width, uint32_t height) @@ -290,77 +294,23 @@ namespace AtomToolsFramework AzFramework::CameraState RenderViewportWidget::GetCameraState() { - AZ::RPI::ViewPtr currentView = m_viewportContext->GetDefaultView(); - if (currentView == nullptr) - { - return {}; - } - - // Build camera state from Atom camera transforms - AzFramework::CameraState cameraState = AzFramework::CreateCameraFromWorldFromViewMatrix( - currentView->GetViewToWorldMatrix(), - AZ::Vector2{aznumeric_cast(width()), aznumeric_cast(height())} - ); - AzFramework::SetCameraClippingVolumeFromPerspectiveFovMatrixRH(cameraState, currentView->GetViewToClipMatrix()); - - // Convert from Z-up - AZStd::swap(cameraState.m_forward, cameraState.m_up); - cameraState.m_forward = -cameraState.m_forward; - - return cameraState; + return m_viewportInteractionImpl->GetCameraState(); } AzFramework::ScreenPoint RenderViewportWidget::ViewportWorldToScreen(const AZ::Vector3& worldPosition) { - if (AZ::RPI::ViewPtr currentView = m_viewportContext->GetDefaultView(); - currentView == nullptr) - { - return AzFramework::ScreenPoint(0, 0); - } - - return AzFramework::WorldToScreen(worldPosition, GetCameraState()); + return m_viewportInteractionImpl->ViewportWorldToScreen(worldPosition); } - AZStd::optional RenderViewportWidget::ViewportScreenToWorld(const AzFramework::ScreenPoint& screenPosition, float depth) + AZ::Vector3 RenderViewportWidget::ViewportScreenToWorld(const AzFramework::ScreenPoint& screenPosition) { - const auto& cameraProjection = m_viewportContext->GetCameraProjectionMatrix(); - const auto& cameraView = m_viewportContext->GetCameraViewMatrix(); - - const AZ::Vector4 normalizedScreenPosition { - screenPosition.m_x * 2.f / width() - 1.0f, - (height() - screenPosition.m_y) * 2.f / height() - 1.0f, - 1.f - depth, // [GFX TODO] [ATOM-1501] Currently we always assume reverse depth - 1.f - }; - - AZ::Matrix4x4 worldFromScreen = cameraProjection * cameraView; - worldFromScreen.InvertFull(); - - const AZ::Vector4 projectedPosition = worldFromScreen * normalizedScreenPosition; - if (projectedPosition.GetW() == 0.0f) - { - return {}; - } - - return projectedPosition.GetAsVector3() / projectedPosition.GetW(); + return m_viewportInteractionImpl->ViewportScreenToWorld(screenPosition); } - AZStd::optional RenderViewportWidget::ViewportScreenToWorldRay( + AzToolsFramework::ViewportInteraction::ProjectedViewportRay RenderViewportWidget::ViewportScreenToWorldRay( const AzFramework::ScreenPoint& screenPosition) { - auto pos0 = ViewportScreenToWorld(screenPosition, 0.f); - auto pos1 = ViewportScreenToWorld(screenPosition, 1.f); - if (!pos0.has_value() || !pos1.has_value()) - { - return {}; - } - - pos0 = m_viewportContext->GetDefaultView()->GetViewToWorldMatrix().GetTranslation(); - AZ::Vector3 rayOrigin = pos0.value(); - AZ::Vector3 rayDirection = pos1.value() - pos0.value(); - rayDirection.Normalize(); - - return AzToolsFramework::ViewportInteraction::ProjectedViewportRay{rayOrigin, rayDirection}; + return m_viewportInteractionImpl->ViewportScreenToWorldRay(screenPosition); } float RenderViewportWidget::DeviceScalingFactor() diff --git a/Gems/Atom/Tools/AtomToolsFramework/Code/Source/Viewport/ViewportInteractionImpl.cpp b/Gems/Atom/Tools/AtomToolsFramework/Code/Source/Viewport/ViewportInteractionImpl.cpp new file mode 100644 index 0000000000..1a015c167c --- /dev/null +++ b/Gems/Atom/Tools/AtomToolsFramework/Code/Source/Viewport/ViewportInteractionImpl.cpp @@ -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 + * + */ + +#include +#include + +namespace AtomToolsFramework +{ + ViewportInteractionImpl::ViewportInteractionImpl(AZ::RPI::ViewPtr viewPtr) + : m_viewPtr(AZStd::move(viewPtr)) + { + } + + void ViewportInteractionImpl::Connect(const AzFramework::ViewportId viewportId) + { + AzToolsFramework::ViewportInteraction::ViewportInteractionRequestBus::Handler::BusConnect(viewportId); + AZ::RPI::ViewportContextIdNotificationBus::Handler::BusConnect(viewportId); + } + + void ViewportInteractionImpl::Disconnect() + { + AZ::RPI::ViewportContextIdNotificationBus::Handler::BusDisconnect(); + AzToolsFramework::ViewportInteraction::ViewportInteractionRequestBus::Handler::BusDisconnect(); + } + + AzFramework::CameraState ViewportInteractionImpl::GetCameraState() + { + // build camera state from atom camera transforms + AzFramework::CameraState cameraState = + AzFramework::CreateDefaultCamera(m_viewPtr->GetCameraTransform(), AzFramework::Vector2FromScreenSize(m_screenSizeFn())); + AzFramework::SetCameraClippingVolumeFromPerspectiveFovMatrixRH(cameraState, m_viewPtr->GetViewToClipMatrix()); + return cameraState; + } + + AzFramework::ScreenPoint ViewportInteractionImpl::ViewportWorldToScreen(const AZ::Vector3& worldPosition) + { + return AzFramework::WorldToScreen(worldPosition, GetCameraState()); + } + + AZ::Vector3 ViewportInteractionImpl::ViewportScreenToWorld(const AzFramework::ScreenPoint& screenPosition) + { + return AzFramework::ScreenToWorld(screenPosition, GetCameraState()); + } + + AzToolsFramework::ViewportInteraction::ProjectedViewportRay ViewportInteractionImpl::ViewportScreenToWorldRay( + const AzFramework::ScreenPoint& screenPosition) + { + const AzFramework::CameraState cameraState = GetCameraState(); + const AZ::Vector3 rayOrigin = AzFramework::ScreenToWorld(screenPosition, cameraState); + const AZ::Vector3 rayDirection = (rayOrigin - cameraState.m_position).GetNormalized(); + return AzToolsFramework::ViewportInteraction::ProjectedViewportRay{ rayOrigin, rayDirection }; + } + + float ViewportInteractionImpl::DeviceScalingFactor() + { + return m_deviceScalingFactorFn(); + } + + void ViewportInteractionImpl::OnViewportDefaultViewChanged(AZ::RPI::ViewPtr view) + { + m_viewPtr = AZStd::move(view); + } +} // namespace AtomToolsFramework diff --git a/Gems/Atom/Tools/AtomToolsFramework/Code/Tests/AtomToolsFrameworkTest.cpp b/Gems/Atom/Tools/AtomToolsFramework/Code/Tests/AtomToolsFrameworkTest.cpp index df16cfbc43..3124372bd2 100644 --- a/Gems/Atom/Tools/AtomToolsFramework/Code/Tests/AtomToolsFrameworkTest.cpp +++ b/Gems/Atom/Tools/AtomToolsFramework/Code/Tests/AtomToolsFrameworkTest.cpp @@ -12,16 +12,25 @@ namespace UnitTest { + class AtomToolsFrameworkTestEnvironment : public AZ::Test::ITestEnvironment + { + protected: + void SetupEnvironment() override + { + AZ::AllocatorInstance::Create(); + } + + void TeardownEnvironment() override + { + AZ::AllocatorInstance::Destroy(); + } + }; + class AtomToolsFrameworkTest : public ::testing::Test { protected: void SetUp() override { - if (!AZ::AllocatorInstance::IsReady()) - { - AZ::AllocatorInstance::Create(AZ::SystemAllocator::Descriptor()); - } - m_assetSystemStub.Activate(); RegisterSourceAsset("objects/upgrades/materials/supercondor.material"); @@ -38,11 +47,6 @@ namespace UnitTest void TearDown() override { m_assetSystemStub.Deactivate(); - - if (AZ::AllocatorInstance::IsReady()) - { - AZ::AllocatorInstance::Destroy(); - } } void RegisterSourceAsset(const AZStd::string& path) @@ -73,5 +77,5 @@ namespace UnitTest ASSERT_EQ(AtomToolsFramework::GetExteralReferencePath("d:/project/assets/objects/upgrades/materials/supercondor.material", "d:/project/assets/materials/condor.material", 0), "materials/condor.material"); } - AZ_UNIT_TEST_HOOK(DEFAULT_UNIT_TEST_ENV); + AZ_UNIT_TEST_HOOK(new AtomToolsFrameworkTestEnvironment); } // namespace UnitTest diff --git a/Gems/Atom/Tools/AtomToolsFramework/Code/Tests/ViewportInteractionImplTests.cpp b/Gems/Atom/Tools/AtomToolsFramework/Code/Tests/ViewportInteractionImplTests.cpp new file mode 100644 index 0000000000..2dfe4f7c29 --- /dev/null +++ b/Gems/Atom/Tools/AtomToolsFramework/Code/Tests/ViewportInteractionImplTests.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 +#include +#include + +namespace UnitTest +{ + class ViewportInteractionImplFixture : public ::testing::Test + { + public: + static inline constexpr AzFramework::ViewportId TestViewportId = 1234; + static inline constexpr AzFramework::ScreenSize ScreenDimensions = AzFramework::ScreenSize(1280, 720); + + static AzFramework::ScreenPoint ScreenCenter() + { + const auto halfScreenDimensions = ScreenDimensions * 0.5f; + return AzFramework::ScreenPoint(halfScreenDimensions.m_width, halfScreenDimensions.m_height); + } + + void SetUp() override + { + AZ::NameDictionary::Create(); + + m_view = AZ::RPI::View::CreateView(AZ::Name("TestView"), AZ::RPI::View::UsageCamera); + + const auto aspectRatio = aznumeric_cast(ScreenDimensions.m_width) / aznumeric_cast(ScreenDimensions.m_height); + + AZ::Matrix4x4 viewToClipMatrix; + AZ::MakePerspectiveFovMatrixRH(viewToClipMatrix, AZ::DegToRad(60.0f), aspectRatio, 0.1f, 1000.f, true); + m_view->SetViewToClipMatrix(viewToClipMatrix); + + m_viewportInteractionImpl = AZStd::make_unique(m_view); + + m_viewportInteractionImpl->m_deviceScalingFactorFn = [] + { + return 1.0f; + }; + m_viewportInteractionImpl->m_screenSizeFn = [] + { + return ScreenDimensions; + }; + + m_viewportInteractionImpl->Connect(TestViewportId); + } + + void TearDown() override + { + m_viewportInteractionImpl->Disconnect(); + m_viewportInteractionImpl.reset(); + + m_view.reset(); + + AZ::NameDictionary::Destroy(); + } + + AZ::RPI::ViewPtr m_view; + AZStd::unique_ptr m_viewportInteractionImpl; + }; + + // transform a point from screen space to world space, and then from world space back to screen space + AzFramework::ScreenPoint ScreenToWorldToScreen( + const AzFramework::ScreenPoint& screenPoint, + AzToolsFramework::ViewportInteraction::ViewportInteractionRequests& viewportInteractionRequests) + { + const auto worldResult = viewportInteractionRequests.ViewportScreenToWorld(screenPoint); + return viewportInteractionRequests.ViewportWorldToScreen(worldResult); + } + + TEST_F(ViewportInteractionImplFixture, ViewportInteractionRequestsMapsFromScreenToWorldAndBack) + { + using AzFramework::ScreenPoint; + + m_view->SetCameraTransform(AZ::Matrix3x4::CreateFromMatrix3x3AndTranslation( + AZ::Matrix3x3::CreateRotationZ(AZ::DegToRad(90.0f)), AZ::Vector3(10.0f, 0.0f, 5.0f))); + + { + const auto expectedScreenPoint = ScreenPoint{ 600, 450 }; + const auto resultScreenPoint = ScreenToWorldToScreen(expectedScreenPoint, *m_viewportInteractionImpl); + EXPECT_EQ(resultScreenPoint, expectedScreenPoint); + } + + { + auto expectedScreenPoint = ScreenCenter(); + const auto resultScreenPoint = ScreenToWorldToScreen(expectedScreenPoint, *m_viewportInteractionImpl); + EXPECT_EQ(resultScreenPoint, expectedScreenPoint); + } + + { + const auto expectedScreenPoint = ScreenPoint{ 0, 0 }; + const auto resultScreenPoint = ScreenToWorldToScreen(expectedScreenPoint, *m_viewportInteractionImpl); + EXPECT_EQ(resultScreenPoint, expectedScreenPoint); + } + + { + const auto expectedScreenPoint = ScreenPoint{ ScreenDimensions.m_width, ScreenDimensions.m_height }; + const auto resultScreenPoint = ScreenToWorldToScreen(expectedScreenPoint, *m_viewportInteractionImpl); + EXPECT_EQ(resultScreenPoint, expectedScreenPoint); + } + } + + TEST_F(ViewportInteractionImplFixture, ScreenToWorldReturnsPositionOnNearClipPlaneInWorldSpace) + { + m_view->SetCameraTransform(AZ::Matrix3x4::CreateFromMatrix3x3AndTranslation( + AZ::Matrix3x3::CreateRotationZ(AZ::DegToRad(-90.0f)), AZ::Vector3(20.0f, 0.0f, 0.0f))); + + const auto worldResult = m_viewportInteractionImpl->ViewportScreenToWorld(ScreenCenter()); + EXPECT_THAT(worldResult, IsClose(AZ::Vector3(20.1f, 0.0f, 0.0f))); + } + + // note: values produced by reproducing in the editor viewport + TEST_F(ViewportInteractionImplFixture, WorldToScreenGivesExpectedScreenCoordinates) + { + using AzFramework::ScreenPoint; + + { + m_view->SetCameraTransform(AZ::Matrix3x4::CreateFromMatrix3x3AndTranslation( + AZ::Matrix3x3::CreateRotationZ(AZ::DegToRad(160.0f)) * AZ::Matrix3x3::CreateRotationX(AZ::DegToRad(-18.0f)), + AZ::Vector3(-21.0f, 2.5f, 6.0f))); + + const auto screenResult = m_viewportInteractionImpl->ViewportWorldToScreen(AZ::Vector3(-21.0f, -1.5f, 5.0f)); + EXPECT_EQ(screenResult, ScreenPoint(420, 326)); + } + + { + m_view->SetCameraTransform(AZ::Matrix3x4::CreateFromMatrix3x3AndTranslation( + AZ::Matrix3x3::CreateRotationZ(AZ::DegToRad(175.0f)) * AZ::Matrix3x3::CreateRotationX(AZ::DegToRad(-90.0f)), + AZ::Vector3(-10.0f, -11.0f, 2.5f))); + + const auto screenResult = m_viewportInteractionImpl->ViewportWorldToScreen(AZ::Vector3(-10.0f, -10.5f, 0.5f)); + EXPECT_EQ(screenResult, ScreenPoint(654, 515)); + } + + { + m_view->SetCameraTransform(AZ::Matrix3x4::CreateFromMatrix3x3AndTranslation( + AZ::Matrix3x3::CreateRotationZ(AZ::DegToRad(70.0f)) * AZ::Matrix3x3::CreateRotationX(AZ::DegToRad(65.0f)), + AZ::Vector3(-22.5f, -10.0f, 1.5f))); + + const auto screenResult = m_viewportInteractionImpl->ViewportWorldToScreen(AZ::Vector3(-23.0f, -9.5f, 3.0f)); + EXPECT_EQ(screenResult, ScreenPoint(754, 340)); + } + } + + TEST_F(ViewportInteractionImplFixture, ScreenToWorldRayGivesGivesExpectedOriginAndDirection) + { + using AzFramework::ScreenPoint; + + m_view->SetCameraTransform(AZ::Matrix3x4::CreateFromMatrix3x3AndTranslation( + AZ::Matrix3x3::CreateRotationZ(AZ::DegToRad(34.0f)) * AZ::Matrix3x3::CreateRotationX(AZ::DegToRad(-24.0f)), + AZ::Vector3(-9.3f, -9.8f, 4.0f))); + + const auto ray = m_viewportInteractionImpl->ViewportScreenToWorldRay(ScreenPoint(832, 226)); + + float unused; + auto intersection = AZ::Intersect::IntersectRaySphere(ray.origin, ray.direction, AZ::Vector3(-14.0f, 5.7f, 0.75f), 0.5f, unused); + + EXPECT_EQ(intersection, AZ::Intersect::SphereIsectTypes::ISECT_RAY_SPHERE_ISECT); + } + + TEST_F(ViewportInteractionImplFixture, ViewportInteractionRequestsReturnsNewViewWhenItIsChanged) + { + // Given + const auto primaryViewTransform = AZ::Matrix3x4::CreateFromMatrix3x3AndTranslation( + AZ::Matrix3x3::CreateRotationZ(AZ::DegToRad(90.0f)) * AZ::Matrix3x3::CreateRotationX(AZ::DegToRad(-45.0f)), + AZ::Vector3(-10.0f, -15.0f, 20.0f)); + + m_view->SetCameraTransform(primaryViewTransform); + + AZ::RPI::ViewPtr secondaryView = AZ::RPI::View::CreateView(AZ::Name("SecondaryView"), AZ::RPI::View::UsageCamera); + + const auto secondaryViewTransform = AZ::Matrix3x4::CreateFromMatrix3x3AndTranslation( + AZ::Matrix3x3::CreateRotationZ(AZ::DegToRad(-90.0f)) * AZ::Matrix3x3::CreateRotationX(AZ::DegToRad(30.0f)), + AZ::Vector3(-50.0f, -25.0f, 10.0f)); + + secondaryView->SetCameraTransform(secondaryViewTransform); + + // When + AZ::RPI::ViewportContextIdNotificationBus::Event( + TestViewportId, &AZ::RPI::ViewportContextIdNotificationBus::Events::OnViewportDefaultViewChanged, secondaryView); + + // retrieve updated camera transform + AzFramework::CameraState cameraState; + AzToolsFramework::ViewportInteraction::ViewportInteractionRequestBus::EventResult( + cameraState, TestViewportId, &AzToolsFramework::ViewportInteraction::ViewportInteractionRequestBus::Events::GetCameraState); + + const auto cameraMatrix = AzFramework::CameraTransform(cameraState); + const auto cameraTransform = AZ::Matrix3x4::CreateFromMatrix3x3AndTranslation( + AZ::Matrix3x3::CreateFromMatrix4x4(cameraMatrix), cameraMatrix.GetTranslation()); + + // Then + // camera transform matches that of the secondary view + EXPECT_THAT(cameraTransform, IsClose(secondaryViewTransform)); + } +} // namespace UnitTest diff --git a/Gems/Atom/Tools/AtomToolsFramework/Code/atomtoolsframework_files.cmake b/Gems/Atom/Tools/AtomToolsFramework/Code/atomtoolsframework_files.cmake index a2446cebcc..3ddcc05245 100644 --- a/Gems/Atom/Tools/AtomToolsFramework/Code/atomtoolsframework_files.cmake +++ b/Gems/Atom/Tools/AtomToolsFramework/Code/atomtoolsframework_files.cmake @@ -28,6 +28,7 @@ set(FILES Include/AtomToolsFramework/Util/MaterialPropertyUtil.h Include/AtomToolsFramework/Util/Util.h Include/AtomToolsFramework/Viewport/RenderViewportWidget.h + Include/AtomToolsFramework/Viewport/ViewportInteractionImpl.h Include/AtomToolsFramework/Viewport/ModularViewportCameraController.h Include/AtomToolsFramework/Viewport/ModularViewportCameraControllerRequestBus.h Include/AtomToolsFramework/Window/AtomToolsMainWindow.h @@ -55,6 +56,7 @@ set(FILES Source/Util/Util.cpp Source/Viewport/RenderViewportWidget.cpp Source/Viewport/ModularViewportCameraController.cpp + Source/Viewport/ViewportInteractionImpl.cpp Source/Window/AtomToolsMainWindow.cpp Source/Window/AtomToolsMainWindowSystemComponent.cpp Source/Window/AtomToolsMainWindowSystemComponent.h diff --git a/Gems/Atom/Tools/AtomToolsFramework/Code/atomtoolsframework_tests_files.cmake b/Gems/Atom/Tools/AtomToolsFramework/Code/atomtoolsframework_tests_files.cmake index bd9ad9b3d8..a071d29f47 100644 --- a/Gems/Atom/Tools/AtomToolsFramework/Code/atomtoolsframework_tests_files.cmake +++ b/Gems/Atom/Tools/AtomToolsFramework/Code/atomtoolsframework_tests_files.cmake @@ -8,4 +8,5 @@ set(FILES Tests/AtomToolsFrameworkTest.cpp + Tests/ViewportInteractionImplTests.cpp ) \ No newline at end of file diff --git a/Gems/Atom/Tools/MaterialEditor/Code/CMakeLists.txt b/Gems/Atom/Tools/MaterialEditor/Code/CMakeLists.txt index d585e81162..99beb721d6 100644 --- a/Gems/Atom/Tools/MaterialEditor/Code/CMakeLists.txt +++ b/Gems/Atom/Tools/MaterialEditor/Code/CMakeLists.txt @@ -60,7 +60,6 @@ ly_add_target( Gem::AtomToolsFramework.Editor Gem::Atom_RPI.Public Gem::Atom_Feature_Common.Public - Gem::ImageProcessingAtom.Headers ) ly_add_target( @@ -113,7 +112,6 @@ ly_add_target( RUNTIME_DEPENDENCIES Gem::AtomToolsFramework.Editor Gem::EditorPythonBindings.Editor - Gem::ImageProcessingAtom.Editor ) ly_set_gem_variant_to_load(TARGETS MaterialEditor VARIANTS Tools) diff --git a/Gems/Atom/Tools/MaterialEditor/Code/Include/Atom/Viewport/MaterialViewportRequestBus.h b/Gems/Atom/Tools/MaterialEditor/Code/Include/Atom/Viewport/MaterialViewportRequestBus.h index e859d6a433..e37512127c 100644 --- a/Gems/Atom/Tools/MaterialEditor/Code/Include/Atom/Viewport/MaterialViewportRequestBus.h +++ b/Gems/Atom/Tools/MaterialEditor/Code/Include/Atom/Viewport/MaterialViewportRequestBus.h @@ -62,15 +62,6 @@ namespace MaterialEditor //! Get set of lighting preset names virtual MaterialViewportPresetNameSet GetLightingPresetNames() const = 0; - //! Set lighting preset preview image - //! @param preset used to set preview image - //! @param preview image - virtual void SetLightingPresetPreview(AZ::Render::LightingPresetPtr preset, const QImage& image) = 0; - - //! Get lighting preset preview image - //! @param preset used to find preview image - virtual QImage GetLightingPresetPreview(AZ::Render::LightingPresetPtr preset) const = 0; - //! Get model preset last save path //! @param preset to lookup last save path virtual AZStd::string GetLightingPresetLastSavePath(AZ::Render::LightingPresetPtr preset) const = 0; @@ -108,15 +99,6 @@ namespace MaterialEditor //! Get set of model preset names virtual MaterialViewportPresetNameSet GetModelPresetNames() const = 0; - //! Set model preset preview image - //! @param preset used to set preview image - //! @param preview image - virtual void SetModelPresetPreview(AZ::Render::ModelPresetPtr preset, const QImage& image) = 0; - - //! Get model preset preview image - //! @param preset used to find preview image - virtual QImage GetModelPresetPreview(AZ::Render::ModelPresetPtr preset) const = 0; - //! Get model preset last save path //! @param preset to lookup last save path virtual AZStd::string GetModelPresetLastSavePath(AZ::Render::ModelPresetPtr preset) const = 0; diff --git a/Gems/Atom/Tools/MaterialEditor/Code/Source/Document/MaterialDocument.cpp b/Gems/Atom/Tools/MaterialEditor/Code/Source/Document/MaterialDocument.cpp index 8635d1eb3e..2d7768feec 100644 --- a/Gems/Atom/Tools/MaterialEditor/Code/Source/Document/MaterialDocument.cpp +++ b/Gems/Atom/Tools/MaterialEditor/Code/Source/Document/MaterialDocument.cpp @@ -12,6 +12,7 @@ #include #include #include +#include #include #include #include @@ -594,7 +595,7 @@ namespace MaterialEditor MaterialPropertyValue propertyValue = AtomToolsFramework::ConvertToRuntimeType(it->second.GetValue()); if (propertyValue.IsValid()) { - if (!AtomToolsFramework::ConvertToExportFormat(exportPath, propertyDefinition, propertyValue)) + if (!AtomToolsFramework::ConvertToExportFormat(exportPath, propertyId.GetFullName(), propertyDefinition, propertyValue)) { AZ_Error("MaterialDocument", false, "Material document property could not be converted: '%s' in '%s'.", propertyId.GetFullName().GetCStr(), m_absolutePath.c_str()); result = false; @@ -708,6 +709,8 @@ namespace MaterialEditor AZ_Error("MaterialDocument", false, "Material document extension not supported: '%s'.", m_absolutePath.c_str()); return false; } + + const bool elevateWarnings = false; // In order to support automation, general usability, and 'save as' functionality, the user must not have to wait // for their JSON file to be cooked by the asset processor before opening or editing it. @@ -716,7 +719,7 @@ namespace MaterialEditor // Long term, the material document should not be concerned with assets at all. The viewport window should be the // only thing concerned with assets or instances. auto materialAssetResult = - m_materialSourceData.CreateMaterialAssetFromSourceData(Uuid::CreateRandom(), m_absolutePath, true, true, &m_sourceDependencies); + m_materialSourceData.CreateMaterialAssetFromSourceData(Uuid::CreateRandom(), m_absolutePath, elevateWarnings, true, &m_sourceDependencies); if (!materialAssetResult) { AZ_Error("MaterialDocument", false, "Material asset could not be created from source data: '%s'.", m_absolutePath.c_str()); @@ -754,7 +757,7 @@ namespace MaterialEditor AZ_Error("MaterialDocument", false, "Material parent asset ID could not be created: '%s'.", m_materialSourceData.m_parentMaterial.c_str()); return false; } - + auto parentMaterialAssetResult = parentMaterialSourceData.CreateMaterialAssetFromSourceData( parentMaterialAssetIdResult.GetValue(), m_materialSourceData.m_parentMaterial, true, true); if (!parentMaterialAssetResult) diff --git a/Gems/Atom/Tools/MaterialEditor/Code/Source/Viewport/MaterialViewportComponent.cpp b/Gems/Atom/Tools/MaterialEditor/Code/Source/Viewport/MaterialViewportComponent.cpp index a8f41917f9..c8df123d0d 100644 --- a/Gems/Atom/Tools/MaterialEditor/Code/Source/Viewport/MaterialViewportComponent.cpp +++ b/Gems/Atom/Tools/MaterialEditor/Code/Source/Viewport/MaterialViewportComponent.cpp @@ -6,61 +6,26 @@ * */ -#include -#include -#include -#include -#include - -#include -#include -#include -#include -#include - -#include -#include -#include - -#include -#include - -#include - -#include -#include #include #include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include namespace MaterialEditor { - using LoadImageAsyncCallback = AZStd::function; - void LoadImageAsync(const AZStd::string& path, LoadImageAsyncCallback callback) - { - AZ::Job* job = AZ::CreateJobFunction([path, callback]() { - ImageProcessingAtom::IImageObjectPtr imageObject; - ImageProcessingAtom::ImageProcessingRequestBus::BroadcastResult(imageObject, &ImageProcessingAtom::ImageProcessingRequests::LoadImagePreview, path); - - if (imageObject) - { - AZ::u8* imageBuf = nullptr; - AZ::u32 pitch = 0; - AZ::u32 mip = 0; - imageObject->GetImagePointer(mip, imageBuf, pitch); - const AZ::u32 width = imageObject->GetWidth(mip); - const AZ::u32 height = imageObject->GetHeight(mip); - - QImage image(imageBuf, width, height, pitch, QImage::Format_RGBA8888); - - if (callback) - { - callback(image); - } - } - }, true); - job->Start(); - } - MaterialViewportComponent::MaterialViewportComponent() { } @@ -162,12 +127,6 @@ namespace MaterialEditor m_viewportSettings = AZ::UserSettings::CreateFind(AZ::Crc32("MaterialViewportSettings"), AZ::UserSettings::CT_GLOBAL); - m_lightingPresetPreviewImageDefault = QImage(180, 90, QImage::Format::Format_RGBA8888); - m_lightingPresetPreviewImageDefault.fill(Qt::GlobalColor::black); - - m_modelPresetPreviewImageDefault = QImage(90, 90, QImage::Format::Format_RGBA8888); - m_modelPresetPreviewImageDefault.fill(Qt::GlobalColor::black); - MaterialViewportRequestBus::Handler::BusConnect(); AzFramework::AssetCatalogEventBus::Handler::BusConnect(); } @@ -177,12 +136,10 @@ namespace MaterialEditor AzFramework::AssetCatalogEventBus::Handler::BusDisconnect(); MaterialViewportRequestBus::Handler::BusDisconnect(); - m_lightingPresetPreviewImages.clear(); m_lightingPresetVector.clear(); m_lightingPresetLastSavePathMap.clear(); m_lightingPresetSelection.reset(); - m_modelPresetPreviewImages.clear(); m_modelPresetVector.clear(); m_modelPresetLastSavePathMap.clear(); m_modelPresetSelection.reset(); @@ -286,14 +243,6 @@ namespace MaterialEditor SelectLightingPreset(presetPtr); } - const auto& imagePath = AZ::RPI::AssetUtils::GetSourcePathByAssetId(presetPtr->m_skyboxImageAsset.GetId()); - LoadImageAsync(imagePath, [presetPtr](const QImage& image) { - QImage imageScaled = image.scaled(180, 90, Qt::AspectRatioMode::KeepAspectRatio); - AZ::TickBus::QueueFunction([presetPtr, imageScaled]() { - MaterialViewportRequestBus::Broadcast(&MaterialViewportRequestBus::Events::SetLightingPresetPreview, presetPtr, imageScaled); - }); - }); - return presetPtr; } @@ -353,17 +302,6 @@ namespace MaterialEditor return names; } - void MaterialViewportComponent::SetLightingPresetPreview(AZ::Render::LightingPresetPtr preset, const QImage& image) - { - m_lightingPresetPreviewImages[preset] = image; - } - - QImage MaterialViewportComponent::GetLightingPresetPreview(AZ::Render::LightingPresetPtr preset) const - { - auto imageItr = m_lightingPresetPreviewImages.find(preset); - return imageItr != m_lightingPresetPreviewImages.end() ? imageItr->second : m_lightingPresetPreviewImageDefault; - } - AZStd::string MaterialViewportComponent::GetLightingPresetLastSavePath(AZ::Render::LightingPresetPtr preset) const { auto pathItr = m_lightingPresetLastSavePathMap.find(preset); @@ -382,14 +320,6 @@ namespace MaterialEditor SelectModelPreset(presetPtr); } - const auto& imagePath = AZ::RPI::AssetUtils::GetSourcePathByAssetId(presetPtr->m_previewImageAsset.GetId()); - LoadImageAsync(imagePath, [presetPtr](const QImage& image) { - QImage imageScaled = image.scaled(90, 90, Qt::AspectRatioMode::KeepAspectRatio); - AZ::TickBus::QueueFunction([presetPtr, imageScaled]() { - MaterialViewportRequestBus::Broadcast(&MaterialViewportRequestBus::Events::SetModelPresetPreview, presetPtr, imageScaled); - }); - }); - return presetPtr; } @@ -449,17 +379,6 @@ namespace MaterialEditor return names; } - void MaterialViewportComponent::SetModelPresetPreview(AZ::Render::ModelPresetPtr preset, const QImage& image) - { - m_modelPresetPreviewImages[preset] = image; - } - - QImage MaterialViewportComponent::GetModelPresetPreview(AZ::Render::ModelPresetPtr preset) const - { - auto imageItr = m_modelPresetPreviewImages.find(preset); - return imageItr != m_modelPresetPreviewImages.end() ? imageItr->second : m_modelPresetPreviewImageDefault; - } - AZStd::string MaterialViewportComponent::GetModelPresetLastSavePath(AZ::Render::ModelPresetPtr preset) const { auto pathItr = m_modelPresetLastSavePathMap.find(preset); diff --git a/Gems/Atom/Tools/MaterialEditor/Code/Source/Viewport/MaterialViewportComponent.h b/Gems/Atom/Tools/MaterialEditor/Code/Source/Viewport/MaterialViewportComponent.h index 12475bb113..a4f94c3546 100644 --- a/Gems/Atom/Tools/MaterialEditor/Code/Source/Viewport/MaterialViewportComponent.h +++ b/Gems/Atom/Tools/MaterialEditor/Code/Source/Viewport/MaterialViewportComponent.h @@ -58,8 +58,6 @@ namespace MaterialEditor void SelectLightingPreset(AZ::Render::LightingPresetPtr preset) override; void SelectLightingPresetByName(const AZStd::string& name) override; MaterialViewportPresetNameSet GetLightingPresetNames() const override; - void SetLightingPresetPreview(AZ::Render::LightingPresetPtr preset, const QImage& image) override; - QImage GetLightingPresetPreview(AZ::Render::LightingPresetPtr preset) const override; AZStd::string GetLightingPresetLastSavePath(AZ::Render::LightingPresetPtr preset) const override; AZ::Render::ModelPresetPtr AddModelPreset(const AZ::Render::ModelPreset& preset) override; @@ -70,8 +68,6 @@ namespace MaterialEditor void SelectModelPreset(AZ::Render::ModelPresetPtr preset) override; void SelectModelPresetByName(const AZStd::string& name) override; MaterialViewportPresetNameSet GetModelPresetNames() const override; - void SetModelPresetPreview(AZ::Render::ModelPresetPtr preset, const QImage& image) override; - QImage GetModelPresetPreview(AZ::Render::ModelPresetPtr preset) const override; AZStd::string GetModelPresetLastSavePath(AZ::Render::ModelPresetPtr preset) const override; void SetShadowCatcherEnabled(bool enable) override; @@ -97,12 +93,6 @@ namespace MaterialEditor AZ::Render::ModelPresetPtrVector m_modelPresetVector; AZ::Render::ModelPresetPtr m_modelPresetSelection; - AZStd::map m_lightingPresetPreviewImages; - AZStd::map m_modelPresetPreviewImages; - - QImage m_lightingPresetPreviewImageDefault; - QImage m_modelPresetPreviewImageDefault; - mutable AZStd::map m_lightingPresetLastSavePathMap; mutable AZStd::map m_modelPresetLastSavePathMap; diff --git a/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/PresetBrowserDialogs/LightingPresetBrowserDialog.cpp b/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/PresetBrowserDialogs/LightingPresetBrowserDialog.cpp index 72bf7fe003..f8ad038a85 100644 --- a/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/PresetBrowserDialogs/LightingPresetBrowserDialog.cpp +++ b/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/PresetBrowserDialogs/LightingPresetBrowserDialog.cpp @@ -7,6 +7,7 @@ */ #include +#include #include #include #include @@ -27,13 +28,16 @@ namespace MaterialEditor MaterialViewportRequestBus::BroadcastResult(presets, &MaterialViewportRequestBus::Events::GetLightingPresets); AZStd::sort(presets.begin(), presets.end(), [](const auto& a, const auto& b) { return a->m_displayName < b->m_displayName; }); + const int itemSize = aznumeric_cast( + AtomToolsFramework::GetSettingOrDefault("/O3DE/Atom/MaterialEditor/PresetBrowserDialog/LightingItemSize", 180)); + QListWidgetItem* selectedItem = nullptr; for (const auto& preset : presets) { - QImage image; - MaterialViewportRequestBus::BroadcastResult(image, &MaterialViewportRequestBus::Events::GetLightingPresetPreview, preset); - - QListWidgetItem* item = CreateListItem(preset->m_displayName.c_str(), image); + AZStd::string path; + MaterialViewportRequestBus::BroadcastResult(path, &MaterialViewportRequestBus::Events::GetLightingPresetLastSavePath, preset); + QListWidgetItem* item = CreateListItem( + preset->m_displayName.c_str(), AZ::RPI::AssetUtils::MakeAssetId(path, 0).GetValue(), QSize(itemSize, itemSize)); m_listItemToPresetMap[item] = preset; diff --git a/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/PresetBrowserDialogs/ModelPresetBrowserDialog.cpp b/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/PresetBrowserDialogs/ModelPresetBrowserDialog.cpp index c1936cde35..f5a1677462 100644 --- a/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/PresetBrowserDialogs/ModelPresetBrowserDialog.cpp +++ b/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/PresetBrowserDialogs/ModelPresetBrowserDialog.cpp @@ -27,13 +27,13 @@ namespace MaterialEditor MaterialViewportRequestBus::BroadcastResult(presets, &MaterialViewportRequestBus::Events::GetModelPresets); AZStd::sort(presets.begin(), presets.end(), [](const auto& a, const auto& b) { return a->m_displayName < b->m_displayName; }); + const int itemSize = aznumeric_cast( + AtomToolsFramework::GetSettingOrDefault("/O3DE/Atom/MaterialEditor/PresetBrowserDialog/ModelItemSize", 90)); + QListWidgetItem* selectedItem = nullptr; for (const auto& preset : presets) { - QImage image; - MaterialViewportRequestBus::BroadcastResult(image, &MaterialViewportRequestBus::Events::GetModelPresetPreview, preset); - - QListWidgetItem* item = CreateListItem(preset->m_displayName.c_str(), image); + QListWidgetItem* item = CreateListItem(preset->m_displayName.c_str(), preset->m_modelAsset.GetId(), QSize(itemSize, itemSize)); m_listItemToPresetMap[item] = preset; diff --git a/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/PresetBrowserDialogs/PresetBrowserDialog.cpp b/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/PresetBrowserDialogs/PresetBrowserDialog.cpp index d3aa6350f0..f2bb84dff6 100644 --- a/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/PresetBrowserDialogs/PresetBrowserDialog.cpp +++ b/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/PresetBrowserDialogs/PresetBrowserDialog.cpp @@ -12,11 +12,16 @@ #include #include #include +#include +#include +#include +#include #include #include #include #include +#include namespace MaterialEditor { @@ -41,35 +46,51 @@ namespace MaterialEditor m_ui->m_presetList->setGridSize(QSize(0, 0)); m_ui->m_presetList->setWrapping(true); - QObject::connect(m_ui->m_presetList, &QListWidget::currentItemChanged, [this]() { SelectCurrentPreset(); }); + QObject::connect(m_ui->m_presetList, &QListWidget::currentItemChanged, [this](){ SelectCurrentPreset(); }); } - QListWidgetItem* PresetBrowserDialog::CreateListItem(const QString& title, const QImage& image) + QListWidgetItem* PresetBrowserDialog::CreateListItem(const QString& title, const AZ::Data::AssetId& assetId, const QSize& size) { + const int itemBorder = aznumeric_cast( + AtomToolsFramework::GetSettingOrDefault("/O3DE/Atom/MaterialEditor/PresetBrowserDialog/ItemBorder", 4)); + const int itemSpacing = aznumeric_cast( + AtomToolsFramework::GetSettingOrDefault("/O3DE/Atom/MaterialEditor/PresetBrowserDialog/ItemSpacing", 10)); + const int headerHeight = aznumeric_cast( + AtomToolsFramework::GetSettingOrDefault("/O3DE/Atom/MaterialEditor/PresetBrowserDialog/HeaderHeight", 15)); + const QSize gridSize = m_ui->m_presetList->gridSize(); - m_ui->m_presetList->setGridSize( - QSize(AZStd::max(gridSize.width(), image.width() + 10), AZStd::max(gridSize.height(), image.height() + 10))); + m_ui->m_presetList->setGridSize(QSize( + AZStd::max(gridSize.width(), size.width() + itemSpacing), + AZStd::max(gridSize.height(), size.height() + itemSpacing + headerHeight))); QListWidgetItem* item = new QListWidgetItem(m_ui->m_presetList); item->setData(Qt::UserRole, title); - item->setSizeHint(image.size() + QSize(4, 4)); + item->setSizeHint(size + QSize(itemBorder, itemBorder + headerHeight)); m_ui->m_presetList->addItem(item); - QLabel* previewImage = new QLabel(m_ui->m_presetList); - previewImage->setFixedSize(image.size()); - previewImage->setMargin(0); - previewImage->setPixmap(QPixmap::fromImage(image)); - previewImage->updateGeometry(); + QWidget* itemWidget = new QWidget(m_ui->m_presetList); + itemWidget->setLayout(new QVBoxLayout(itemWidget)); + itemWidget->layout()->setSpacing(0); + itemWidget->layout()->setMargin(0); - AzQtComponents::ElidingLabel* previewLabel = new AzQtComponents::ElidingLabel(previewImage); - previewLabel->setText(title); - previewLabel->setFixedSize(QSize(image.width(), 15)); - previewLabel->setMargin(0); - previewLabel->setStyleSheet("background-color: rgb(35, 35, 35)"); - AzQtComponents::Text::addPrimaryStyle(previewLabel); - AzQtComponents::Text::addLabelStyle(previewLabel); + AzQtComponents::ElidingLabel* header = new AzQtComponents::ElidingLabel(itemWidget); + header->setText(title); + header->setFixedSize(QSize(size.width(), headerHeight)); + header->setMargin(0); + header->setStyleSheet("background-color: rgb(35, 35, 35)"); + AzQtComponents::Text::addPrimaryStyle(header); + AzQtComponents::Text::addLabelStyle(header); + itemWidget->layout()->addWidget(header); - m_ui->m_presetList->setItemWidget(item, previewImage); + AzToolsFramework::Thumbnailer::ThumbnailWidget* thumbnail = new AzToolsFramework::Thumbnailer::ThumbnailWidget(itemWidget); + thumbnail->setFixedSize(size); + thumbnail->SetThumbnailKey( + MAKE_TKEY(AzToolsFramework::AssetBrowser::ProductThumbnailKey, assetId), + AzToolsFramework::Thumbnailer::ThumbnailContext::DefaultContext); + thumbnail->updateGeometry(); + itemWidget->layout()->addWidget(thumbnail); + + m_ui->m_presetList->setItemWidget(item, itemWidget); return item; } @@ -79,15 +100,15 @@ namespace MaterialEditor m_ui->m_searchWidget->setReadOnly(false); m_ui->m_searchWidget->setContextMenuPolicy(Qt::CustomContextMenu); AzQtComponents::LineEdit::applySearchStyle(m_ui->m_searchWidget); - connect(m_ui->m_searchWidget, &QLineEdit::textChanged, this, [this]() { ApplySearchFilter(); }); - connect(m_ui->m_searchWidget, &QWidget::customContextMenuRequested, this, [this](const QPoint& pos) { ShowSearchMenu(pos); }); + connect(m_ui->m_searchWidget, &QLineEdit::textChanged, this, [this](){ ApplySearchFilter(); }); + connect(m_ui->m_searchWidget, &QWidget::customContextMenuRequested, this, [this](const QPoint& pos){ ShowSearchMenu(pos); }); } void PresetBrowserDialog::SetupDialogButtons() { connect(m_ui->m_buttonBox, &QDialogButtonBox::accepted, this, &QDialog::accept); connect(m_ui->m_buttonBox, &QDialogButtonBox::rejected, this, &QDialog::reject); - connect(this, &QDialog::rejected, this, [this]() { SelectInitialPreset(); }); + connect(this, &QDialog::rejected, this, [this](){ SelectInitialPreset(); }); } void PresetBrowserDialog::ApplySearchFilter() diff --git a/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/PresetBrowserDialogs/PresetBrowserDialog.h b/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/PresetBrowserDialogs/PresetBrowserDialog.h index ee01737352..20e049f6f8 100644 --- a/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/PresetBrowserDialogs/PresetBrowserDialog.h +++ b/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/PresetBrowserDialogs/PresetBrowserDialog.h @@ -9,12 +9,12 @@ #pragma once #if !defined(Q_MOC_RUN) +#include #include - #include #endif -#include +#include class QImage; class QListWidgetItem; @@ -32,7 +32,7 @@ namespace MaterialEditor protected: void SetupPresetList(); - QListWidgetItem* CreateListItem(const QString& title, const QImage& image); + QListWidgetItem* CreateListItem(const QString& title, const AZ::Data::AssetId& assetId, const QSize& size); void SetupSearchWidget(); void SetupDialogButtons(); diff --git a/Gems/AtomLyIntegration/AtomBridge/Code/Source/AtomDebugDisplayViewportInterface.cpp b/Gems/AtomLyIntegration/AtomBridge/Code/Source/AtomDebugDisplayViewportInterface.cpp index 12e4ccd8ad..39cc2f63b2 100644 --- a/Gems/AtomLyIntegration/AtomBridge/Code/Source/AtomDebugDisplayViewportInterface.cpp +++ b/Gems/AtomLyIntegration/AtomBridge/Code/Source/AtomDebugDisplayViewportInterface.cpp @@ -1016,6 +1016,55 @@ namespace AZ::AtomBridge } } + void AtomDebugDisplayViewportInterface::DrawWireCylinderNoEnds(const AZ::Vector3& center, const AZ::Vector3& axis, float radius, float height) + { + if (m_auxGeomPtr) + { + const float scale = GetCurrentTransform().RetrieveScale().GetMaxElement(); + const AZ::Vector3 worldCenter = ToWorldSpacePosition(center); + const AZ::Vector3 worldAxis = ToWorldSpaceVector(axis); + m_auxGeomPtr->DrawCylinderNoEnds( + worldCenter, + worldAxis, + scale * radius, + scale * height, + m_rendState.m_color, + AZ::RPI::AuxGeomDraw::DrawStyle::Line, + m_rendState.m_depthTest, + m_rendState.m_depthWrite, + m_rendState.m_faceCullMode, + m_rendState.m_viewProjOverrideIndex + ); + } + } + + void AtomDebugDisplayViewportInterface::DrawSolidCylinderNoEnds( + const AZ::Vector3& center, + const AZ::Vector3& axis, + float radius, + float height, + bool drawShaded) + { + if (m_auxGeomPtr) + { + const float scale = GetCurrentTransform().RetrieveScale().GetMaxElement(); + const AZ::Vector3 worldCenter = ToWorldSpacePosition(center); + const AZ::Vector3 worldAxis = ToWorldSpaceVector(axis); + m_auxGeomPtr->DrawCylinderNoEnds( + worldCenter, + worldAxis, + scale * radius, + scale * height, + m_rendState.m_color, + drawShaded ? AZ::RPI::AuxGeomDraw::DrawStyle::Shaded : AZ::RPI::AuxGeomDraw::DrawStyle::Solid, + m_rendState.m_depthTest, + m_rendState.m_depthWrite, + m_rendState.m_faceCullMode, + m_rendState.m_viewProjOverrideIndex + ); + } + } + void AtomDebugDisplayViewportInterface::DrawWireCapsule( const AZ::Vector3& center, const AZ::Vector3& axis, @@ -1025,83 +1074,24 @@ namespace AZ::AtomBridge if (m_auxGeomPtr && radius > FLT_EPSILON && axis.GetLengthSq() > FLT_EPSILON) { AZ::Vector3 axisNormalized = axis.GetNormalizedEstimate(); - SingleColorStaticSizeLineHelper<(16+1) * 5> lines; // 360/22.5 = 16, 5 possible calls to CreateArbitraryAxisArc - AZ::Vector3 radiusV3 = AZ::Vector3(radius); - float stepAngle = DegToRad(22.5f); - float Deg0 = DegToRad(0.0f); + const float scale = GetCurrentTransform().RetrieveScale().GetMaxElement(); + const AZ::Vector3 worldCenter = ToWorldSpacePosition(center); + const AZ::Vector3 worldAxis = ToWorldSpaceVector(axis); - // Draw cylinder part (or just a circle around the middle) + // Draw cylinder part (if cylinder height is too small, ignore cylinder and just draw both hemispheres) if (heightStraightSection > FLT_EPSILON) { - DrawWireCylinder(center, axis, radius, heightStraightSection); - } - else - { - float Deg360 = DegToRad(360.0f); - CreateArbitraryAxisArc( - lines, - stepAngle, - Deg0, - Deg360, - center, - radiusV3, - axisNormalized - ); + DrawWireCylinderNoEnds(worldCenter, worldAxis, scale * radius, scale * heightStraightSection); } - float Deg90 = DegToRad(90.0f); - float Deg180 = DegToRad(180.0f); - - AZ::Vector3 ortho1Normalized, ortho2Normalized; - CalcBasisVectors(axisNormalized, ortho1Normalized, ortho2Normalized); AZ::Vector3 centerToTopCircleCenter = axisNormalized * heightStraightSection * 0.5f; - AZ::Vector3 topCenter = center + centerToTopCircleCenter; - AZ::Vector3 bottomCenter = center - centerToTopCircleCenter; - // Draw top cap as two criss-crossing 180deg arcs - CreateArbitraryAxisArc( - lines, - stepAngle, - Deg90, - Deg90 + Deg180, - topCenter, - radiusV3, - ortho1Normalized - ); + // Top hemisphere + DrawWireHemisphere(center + centerToTopCircleCenter, worldAxis, scale * radius); - CreateArbitraryAxisArc( - lines, - stepAngle, - Deg180, - Deg180 + Deg180, - topCenter, - radiusV3, - ortho2Normalized - ); - - // Draw bottom cap - CreateArbitraryAxisArc( - lines, - stepAngle, - -Deg90, - -Deg90 + Deg180, - bottomCenter, - radiusV3, - ortho1Normalized - ); - - CreateArbitraryAxisArc( - lines, - stepAngle, - Deg0, - Deg0 + Deg180, - bottomCenter, - radiusV3, - ortho2Normalized - ); - - lines.Draw(m_auxGeomPtr, m_rendState); + // Bottom hemisphere + DrawWireHemisphere(center - centerToTopCircleCenter, -worldAxis, scale * radius); } } @@ -1148,6 +1138,25 @@ namespace AZ::AtomBridge } } + void AtomDebugDisplayViewportInterface::DrawWireHemisphere(const AZ::Vector3& pos, const AZ::Vector3& axis, float radius) + { + if (m_auxGeomPtr) + { + const float scale = GetCurrentTransform().RetrieveScale().GetMaxElement(); + m_auxGeomPtr->DrawHemisphere( + ToWorldSpacePosition(pos), + axis, + scale * radius, + m_rendState.m_color, + AZ::RPI::AuxGeomDraw::DrawStyle::Line, + m_rendState.m_depthTest, + m_rendState.m_depthWrite, + m_rendState.m_faceCullMode, + m_rendState.m_viewProjOverrideIndex + ); + } + } + void AtomDebugDisplayViewportInterface::DrawWireDisk(const AZ::Vector3& pos, const AZ::Vector3& dir, float radius) { if (m_auxGeomPtr) @@ -1353,9 +1362,8 @@ namespace AZ::AtomBridge // if 2d draw need to project pos to screen first AzFramework::TextDrawParameters params; AZ::RPI::ViewportContextPtr viewportContext = GetViewportContext(); - const auto dpiScaleFactor = viewportContext->GetDpiScalingFactor(); params.m_drawViewportId = viewportContext->GetId(); // get the viewport ID so default viewport works - params.m_position = AZ::Vector3(x * dpiScaleFactor, y * dpiScaleFactor, 1.0f); + params.m_position = AZ::Vector3(x, y, 1.0f); params.m_color = m_rendState.m_color; params.m_scale = AZ::Vector2(size); params.m_hAlign = center ? AzFramework::TextHorizontalAlignment::Center : AzFramework::TextHorizontalAlignment::Left; //! Horizontal text alignment diff --git a/Gems/AtomLyIntegration/AtomBridge/Code/Source/AtomDebugDisplayViewportInterface.h b/Gems/AtomLyIntegration/AtomBridge/Code/Source/AtomDebugDisplayViewportInterface.h index 5f902c5884..7f7af9bbcb 100644 --- a/Gems/AtomLyIntegration/AtomBridge/Code/Source/AtomDebugDisplayViewportInterface.h +++ b/Gems/AtomLyIntegration/AtomBridge/Code/Source/AtomDebugDisplayViewportInterface.h @@ -168,9 +168,12 @@ namespace AZ::AtomBridge void DrawSolidCone(const AZ::Vector3& pos, const AZ::Vector3& dir, float radius, float height, bool drawShaded) override; void DrawWireCylinder(const AZ::Vector3& center, const AZ::Vector3& axis, float radius, float height) override; void DrawSolidCylinder(const AZ::Vector3& center, const AZ::Vector3& axis, float radius, float height, bool drawShaded) override; + void DrawWireCylinderNoEnds(const AZ::Vector3& center, const AZ::Vector3& axis, float radius, float height) override; + void DrawSolidCylinderNoEnds(const AZ::Vector3& center, const AZ::Vector3& axis, float radius, float height, bool drawShaded) override; void DrawWireCapsule(const AZ::Vector3& center, const AZ::Vector3& axis, float radius, float heightStraightSection) override; void DrawWireSphere(const AZ::Vector3& pos, float radius) override; void DrawWireSphere(const AZ::Vector3& pos, const AZ::Vector3 radius) override; + void DrawWireHemisphere(const AZ::Vector3& pos, const AZ::Vector3& axis, float radius) override; void DrawWireDisk(const AZ::Vector3& pos, const AZ::Vector3& dir, float radius) override; void DrawBall(const AZ::Vector3& pos, float radius, bool drawShaded) override; void DrawDisk(const AZ::Vector3& pos, const AZ::Vector3& dir, float radius) override; diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Include/AtomLyIntegration/CommonFeatures/CoreLights/AreaLightBus.h b/Gems/AtomLyIntegration/CommonFeatures/Code/Include/AtomLyIntegration/CommonFeatures/CoreLights/AreaLightBus.h index 72c4ef97a8..b9c62e6fe2 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Include/AtomLyIntegration/CommonFeatures/CoreLights/AreaLightBus.h +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Include/AtomLyIntegration/CommonFeatures/CoreLights/AreaLightBus.h @@ -132,6 +132,13 @@ namespace AZ //! Sets the Esm exponent. Higher values produce a steeper falloff between light and shadow. virtual void SetEsmExponent(float exponent) = 0; + //! Reduces acne by biasing the shadowmap lookup along the geometric normal. + //! @return Returns the amount of bias to apply. + virtual float GetNormalShadowBias() const = 0; + + //! Reduces acne by biasing the shadowmap lookup along the geometric normal. + //! @param normalShadowBias Sets the amount of normal shadow bias to apply. + virtual void SetNormalShadowBias(float normalShadowBias) = 0; }; //! The EBus for requests to for setting and getting light component properties. diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Include/AtomLyIntegration/CommonFeatures/CoreLights/AreaLightComponentConfig.h b/Gems/AtomLyIntegration/CommonFeatures/Code/Include/AtomLyIntegration/CommonFeatures/CoreLights/AreaLightComponentConfig.h index c76c922385..130e066e1a 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Include/AtomLyIntegration/CommonFeatures/CoreLights/AreaLightComponentConfig.h +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Include/AtomLyIntegration/CommonFeatures/CoreLights/AreaLightComponentConfig.h @@ -57,6 +57,7 @@ namespace AZ // Shadows (only used for supported shapes) bool m_enableShadow = false; float m_bias = 0.1f; + float m_normalShadowBias = 0.0f; ShadowmapSize m_shadowmapMaxSize = ShadowmapSize::Size256; ShadowFilterMethod m_shadowFilterMethod = ShadowFilterMethod::None; uint16_t m_filteringSampleCount = 12; diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/CoreLights/AreaLightComponentConfig.cpp b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/CoreLights/AreaLightComponentConfig.cpp index f0418a5024..91f8f1aa36 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/CoreLights/AreaLightComponentConfig.cpp +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/CoreLights/AreaLightComponentConfig.cpp @@ -34,6 +34,7 @@ namespace AZ // Shadows ->Field("Enable Shadow", &AreaLightComponentConfig::m_enableShadow) ->Field("Shadow Bias", &AreaLightComponentConfig::m_bias) + ->Field("Normal Shadow Bias", &AreaLightComponentConfig::m_normalShadowBias) ->Field("Shadowmap Max Size", &AreaLightComponentConfig::m_shadowmapMaxSize) ->Field("Shadow Filter Method", &AreaLightComponentConfig::m_shadowFilterMethod) ->Field("Filtering Sample Count", &AreaLightComponentConfig::m_filteringSampleCount) diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/CoreLights/AreaLightComponentController.cpp b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/CoreLights/AreaLightComponentController.cpp index 36cb2a7f5a..7668477690 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/CoreLights/AreaLightComponentController.cpp +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/CoreLights/AreaLightComponentController.cpp @@ -70,6 +70,8 @@ namespace AZ::Render ->Event("SetEnableShadow", &AreaLightRequestBus::Events::SetEnableShadow) ->Event("GetShadowBias", &AreaLightRequestBus::Events::GetShadowBias) ->Event("SetShadowBias", &AreaLightRequestBus::Events::SetShadowBias) + ->Event("GetNormalShadowBias", &AreaLightRequestBus::Events::GetNormalShadowBias) + ->Event("SetNormalShadowBias", &AreaLightRequestBus::Events::SetNormalShadowBias) ->Event("GetShadowmapMaxSize", &AreaLightRequestBus::Events::GetShadowmapMaxSize) ->Event("SetShadowmapMaxSize", &AreaLightRequestBus::Events::SetShadowmapMaxSize) ->Event("GetShadowFilterMethod", &AreaLightRequestBus::Events::GetShadowFilterMethod) @@ -91,6 +93,7 @@ namespace AZ::Render ->VirtualProperty("ShadowsEnabled", "GetEnableShadow", "SetEnableShadow") ->VirtualProperty("ShadowBias", "GetShadowBias", "SetShadowBias") + ->VirtualProperty("NormalShadowBias", "GetNormalShadowBias", "SetNormalShadowBias") ->VirtualProperty("ShadowmapMaxSize", "GetShadowmapMaxSize", "SetShadowmapMaxSize") ->VirtualProperty("ShadowFilterMethod", "GetShadowFilterMethod", "SetShadowFilterMethod") ->VirtualProperty("FilteringSampleCount", "GetFilteringSampleCount", "SetFilteringSampleCount") @@ -302,6 +305,7 @@ namespace AZ::Render if (m_configuration.m_enableShadow) { m_lightShapeDelegate->SetShadowBias(m_configuration.m_bias); + m_lightShapeDelegate->SetNormalShadowBias(m_configuration.m_normalShadowBias); m_lightShapeDelegate->SetShadowmapMaxSize(m_configuration.m_shadowmapMaxSize); m_lightShapeDelegate->SetShadowFilterMethod(m_configuration.m_shadowFilterMethod); m_lightShapeDelegate->SetFilteringSampleCount(m_configuration.m_filteringSampleCount); @@ -474,6 +478,20 @@ namespace AZ::Render } } + void AreaLightComponentController::SetNormalShadowBias(float bias) + { + m_configuration.m_normalShadowBias = bias; + if (m_lightShapeDelegate) + { + m_lightShapeDelegate->SetNormalShadowBias(bias); + } + } + + float AreaLightComponentController::GetNormalShadowBias() const + { + return m_configuration.m_normalShadowBias; + } + ShadowmapSize AreaLightComponentController::GetShadowmapMaxSize() const { return m_configuration.m_shadowmapMaxSize; diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/CoreLights/AreaLightComponentController.h b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/CoreLights/AreaLightComponentController.h index cc6223e7e5..81299a0372 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/CoreLights/AreaLightComponentController.h +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/CoreLights/AreaLightComponentController.h @@ -86,6 +86,8 @@ namespace AZ void SetFilteringSampleCount(uint32_t count) override; float GetEsmExponent() const override; void SetEsmExponent(float exponent) override; + float GetNormalShadowBias() const override; + void SetNormalShadowBias(float bias) override; void HandleDisplayEntityViewport( const AzFramework::ViewportInfo& viewportInfo, diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/CoreLights/DiskLightDelegate.cpp b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/CoreLights/DiskLightDelegate.cpp index dfb6cf6946..f060018099 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/CoreLights/DiskLightDelegate.cpp +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/CoreLights/DiskLightDelegate.cpp @@ -138,6 +138,14 @@ namespace AZ::Render } } + void DiskLightDelegate::SetNormalShadowBias(float bias) + { + if (GetShadowsEnabled() && GetLightHandle().IsValid()) + { + GetFeatureProcessor()->SetNormalShadowBias(GetLightHandle(), bias); + } + } + void DiskLightDelegate::SetShadowmapMaxSize(ShadowmapSize size) { if (GetShadowsEnabled() && GetLightHandle().IsValid()) diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/CoreLights/DiskLightDelegate.h b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/CoreLights/DiskLightDelegate.h index 2be782c69c..c19a8d37ae 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/CoreLights/DiskLightDelegate.h +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/CoreLights/DiskLightDelegate.h @@ -46,6 +46,7 @@ namespace AZ void SetShadowFilterMethod(ShadowFilterMethod method) override; void SetFilteringSampleCount(uint32_t count) override; void SetEsmExponent(float exponent) override; + void SetNormalShadowBias(float bias) override; private: diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/CoreLights/EditorAreaLightComponent.cpp b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/CoreLights/EditorAreaLightComponent.cpp index db46434d9a..02c9f77436 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/CoreLights/EditorAreaLightComponent.cpp +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/CoreLights/EditorAreaLightComponent.cpp @@ -136,7 +136,7 @@ namespace AZ ->Attribute(Edit::Attributes::Min, 0.0f) ->Attribute(Edit::Attributes::Max, 100.0f) ->Attribute(Edit::Attributes::SoftMin, 0.0f) - ->Attribute(Edit::Attributes::SoftMax, 2.0f) + ->Attribute(Edit::Attributes::SoftMax, 10.0f) ->Attribute(Edit::Attributes::ChangeNotify, Edit::PropertyRefreshLevels::ValuesOnly) ->Attribute(Edit::Attributes::Visibility, &AreaLightComponentConfig::SupportsShadows) ->Attribute(Edit::Attributes::ReadOnly, &AreaLightComponentConfig::ShadowsDisabled) @@ -171,7 +171,16 @@ namespace AZ ->Attribute(Edit::Attributes::ChangeNotify, Edit::PropertyRefreshLevels::ValuesOnly) ->Attribute(Edit::Attributes::Visibility, &AreaLightComponentConfig::SupportsShadows) ->Attribute(Edit::Attributes::ReadOnly, &AreaLightComponentConfig::IsEsmDisabled) - ; + ->DataElement( + Edit::UIHandlers::Slider, &AreaLightComponentConfig::m_normalShadowBias, "Normal Shadow Bias\n", + "Reduces acne by biasing the shadowmap lookup along the geometric normal.\n" + "If this is 0, no biasing is applied.") + ->Attribute(Edit::Attributes::Min, 0.f) + ->Attribute(Edit::Attributes::Max, 10.0f) + ->Attribute(Edit::Attributes::ChangeNotify, Edit::PropertyRefreshLevels::ValuesOnly) + ->Attribute(Edit::Attributes::Visibility, &AreaLightComponentConfig::SupportsShadows) + ->Attribute(Edit::Attributes::ReadOnly, &AreaLightComponentConfig::ShadowsDisabled) + ; } } diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/CoreLights/LightDelegateBase.h b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/CoreLights/LightDelegateBase.h index 336c67f55d..8b096b0367 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/CoreLights/LightDelegateBase.h +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/CoreLights/LightDelegateBase.h @@ -58,7 +58,8 @@ namespace AZ void SetShadowFilterMethod([[maybe_unused]] ShadowFilterMethod method) override {}; void SetFilteringSampleCount([[maybe_unused]] uint32_t count) override {}; void SetEsmExponent([[maybe_unused]] float esmExponent) override{}; - + void SetNormalShadowBias([[maybe_unused]] float bias) override{}; + protected: void InitBase(EntityId entityId); diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/CoreLights/LightDelegateInterface.h b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/CoreLights/LightDelegateInterface.h index 9bb8188898..40ffaf392d 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/CoreLights/LightDelegateInterface.h +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/CoreLights/LightDelegateInterface.h @@ -79,6 +79,8 @@ namespace AZ virtual void SetFilteringSampleCount(uint32_t count) = 0; //! Sets the Esm exponent to use. Higher values produce a steeper falloff between light and shadow. virtual void SetEsmExponent(float exponent) = 0; + //! Sets the normal bias. Reduces acne by biasing the shadowmap lookup along the geometric normal. + virtual void SetNormalShadowBias(float bias) = 0; }; } // namespace Render } // namespace AZ diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/CoreLights/SphereLightDelegate.cpp b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/CoreLights/SphereLightDelegate.cpp index 661b0c6b25..f2e1f41008 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/CoreLights/SphereLightDelegate.cpp +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/CoreLights/SphereLightDelegate.cpp @@ -107,4 +107,13 @@ namespace AZ::Render GetFeatureProcessor()->SetEsmExponent(GetLightHandle(), esmExponent); } } + + void SphereLightDelegate::SetNormalShadowBias(float bias) + { + if (GetShadowsEnabled() && GetLightHandle().IsValid()) + { + GetFeatureProcessor()->SetNormalShadowBias(GetLightHandle(), bias); + } + } + } // namespace AZ::Render diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/CoreLights/SphereLightDelegate.h b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/CoreLights/SphereLightDelegate.h index 8bdee2442a..bad00e597c 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/CoreLights/SphereLightDelegate.h +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/CoreLights/SphereLightDelegate.h @@ -36,6 +36,7 @@ namespace AZ void SetShadowFilterMethod(ShadowFilterMethod method) override; void SetFilteringSampleCount(uint32_t count) override; void SetEsmExponent(float esmExponent) override; + void SetNormalShadowBias(float bias) override; private: diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Material/EditorMaterialComponentUtil.cpp b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Material/EditorMaterialComponentUtil.cpp index 0fd7b7164d..d3e125426c 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Material/EditorMaterialComponentUtil.cpp +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Material/EditorMaterialComponentUtil.cpp @@ -134,7 +134,7 @@ namespace AZ propertyValue = AZ::RPI::MaterialPropertyValue::FromAny(propertyOverrideItr->second); } - if (!AtomToolsFramework::ConvertToExportFormat(path, propertyDefinition, propertyValue)) + if (!AtomToolsFramework::ConvertToExportFormat(path, propertyId.GetFullName(), propertyDefinition, propertyValue)) { AZ_Error("AZ::Render::EditorMaterialComponentUtil", false, "Failed to export: %s", path.c_str()); result = false; diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/SharedPreview/SharedPreviewContent.cpp b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/SharedPreview/SharedPreviewContent.cpp index 91b6d2b02a..8bc9c5ac7d 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/SharedPreview/SharedPreviewContent.cpp +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/SharedPreview/SharedPreviewContent.cpp @@ -163,9 +163,9 @@ namespace AZ m_modelAsset->GetAabb().GetAsSphere(center, radius); } - const auto distance = radius + NearDist; - const auto cameraRotation = Quaternion::CreateFromAxisAngle(Vector3::CreateAxisZ(), CameraRotationAngle); - const auto cameraPosition = center + cameraRotation.TransformVector(Vector3(0.0f, distance, 0.0f)); + const auto distance = fabsf(radius / sinf(FieldOfView)) + NearDist; + const auto cameraRotation = Quaternion::CreateFromAxisAngle(Vector3::CreateAxisX(), -CameraRotationAngle); + const auto cameraPosition = center + cameraRotation.TransformVector(-Vector3::CreateAxisY() * distance); const auto cameraTransform = Transform::CreateLookAt(cameraPosition, center); m_view->SetCameraTransform(Matrix3x4::CreateFromTransform(cameraTransform)); } diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/SharedPreview/SharedPreviewContent.h b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/SharedPreview/SharedPreviewContent.h index 7308aa19bc..dfab7a8630 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/SharedPreview/SharedPreviewContent.h +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/SharedPreview/SharedPreviewContent.h @@ -51,7 +51,7 @@ namespace AZ static constexpr float NearDist = 0.001f; static constexpr float FarDist = 100.0f; static constexpr float FieldOfView = Constants::HalfPi; - static constexpr float CameraRotationAngle = Constants::QuarterPi / 2.0f; + static constexpr float CameraRotationAngle = Constants::QuarterPi / 3.0f; RPI::ScenePtr m_scene; RPI::ViewPtr m_view; diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/SharedPreview/SharedPreviewUtils.cpp b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/SharedPreview/SharedPreviewUtils.cpp index c2988cf53d..d0e288d239 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/SharedPreview/SharedPreviewUtils.cpp +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/SharedPreview/SharedPreviewUtils.cpp @@ -9,9 +9,11 @@ #include #include #include +#include #include #include #include +#include #include namespace AZ @@ -20,45 +22,64 @@ namespace AZ { namespace SharedPreviewUtils { - Data::AssetId GetAssetId( - AzToolsFramework::Thumbnailer::SharedThumbnailKey key, - const Data::AssetType& assetType, - const Data::AssetId& defaultAssetId) + AZStd::unordered_set GetSupportedAssetTypes() { + return { RPI::AnyAsset::RTTI_Type(), RPI::MaterialAsset::RTTI_Type(), RPI::ModelAsset::RTTI_Type() }; + } + + bool IsSupportedAssetType(AzToolsFramework::Thumbnailer::SharedThumbnailKey key) + { + return GetSupportedAssetInfo(key).m_assetId.IsValid(); + } + + AZ::Data::AssetInfo GetSupportedAssetInfo(AzToolsFramework::Thumbnailer::SharedThumbnailKey key) + { + const auto& supportedTypeIds = GetSupportedAssetTypes(); + // if it's a source thumbnail key, find first product with a matching asset type auto sourceKey = azrtti_cast(key.data()); if (sourceKey) { bool foundIt = false; - AZStd::vector productsAssetInfo; + AZStd::vector productsAssetInfo; AzToolsFramework::AssetSystemRequestBus::BroadcastResult( foundIt, &AzToolsFramework::AssetSystemRequestBus::Events::GetAssetsProducedBySourceUUID, sourceKey->GetSourceUuid(), productsAssetInfo); - if (!foundIt) - { - return defaultAssetId; - } - auto assetInfoIt = AZStd::find_if( - productsAssetInfo.begin(), productsAssetInfo.end(), - [&assetType](const Data::AssetInfo& assetInfo) - { - return assetInfo.m_assetType == assetType; - }); - if (assetInfoIt == productsAssetInfo.end()) - { - return defaultAssetId; - } - return assetInfoIt->m_assetId; + for (const auto& assetInfo : productsAssetInfo) + { + if (supportedTypeIds.find(assetInfo.m_assetType) != supportedTypeIds.end()) + { + return assetInfo; + } + } + return AZ::Data::AssetInfo(); } // if it's a product thumbnail key just return its assetId + AZ::Data::AssetInfo assetInfo; auto productKey = azrtti_cast(key.data()); - if (productKey && productKey->GetAssetType() == assetType) + if (productKey && supportedTypeIds.find(productKey->GetAssetType()) != supportedTypeIds.end()) { - return productKey->GetAssetId(); + AZ::Data::AssetCatalogRequestBus::BroadcastResult( + assetInfo, &AZ::Data::AssetCatalogRequestBus::Events::GetAssetInfoById, productKey->GetAssetId()); } - return defaultAssetId; + return assetInfo; + } + + AZ::Data::AssetId GetSupportedAssetId(AzToolsFramework::Thumbnailer::SharedThumbnailKey key, const AZ::Data::AssetId& defaultAssetId) + { + const AZ::Data::AssetInfo assetInfo = GetSupportedAssetInfo(key); + return assetInfo.m_assetId.IsValid() ? assetInfo.m_assetId : defaultAssetId; + } + + AZ::Data::AssetId GetAssetIdForProductPath(const AZStd::string_view productPath) + { + if (!productPath.empty()) + { + return AZ::RPI::AssetUtils::GetAssetIdForProductPath(productPath.data()); + } + return AZ::Data::AssetId(); } QString WordWrap(const QString& string, int maxLength) @@ -85,32 +106,6 @@ namespace AZ } return result; } - - AZStd::unordered_set GetSupportedAssetTypes() - { - return { RPI::AnyAsset::RTTI_Type(), RPI::MaterialAsset::RTTI_Type(), RPI::ModelAsset::RTTI_Type() }; - } - - bool IsSupportedAssetType(AzToolsFramework::Thumbnailer::SharedThumbnailKey key) - { - for (const AZ::Uuid& typeId : SharedPreviewUtils::GetSupportedAssetTypes()) - { - const AZ::Data::AssetId& assetId = SharedPreviewUtils::GetAssetId(key, typeId); - if (assetId.IsValid()) - { - if (typeId == RPI::AnyAsset::RTTI_Type()) - { - AZ::Data::AssetInfo assetInfo; - AZ::Data::AssetCatalogRequestBus::BroadcastResult( - assetInfo, &AZ::Data::AssetCatalogRequestBus::Events::GetAssetInfoById, assetId); - return AzFramework::StringFunc::EndsWith(assetInfo.m_relativePath.c_str(), "lightingpreset.azasset"); - } - return true; - } - } - - return false; - } } // namespace SharedPreviewUtils } // namespace LyIntegration } // namespace AZ diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/SharedPreview/SharedPreviewUtils.h b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/SharedPreview/SharedPreviewUtils.h index 6c5d83d22a..28c9809d6d 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/SharedPreview/SharedPreviewUtils.h +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/SharedPreview/SharedPreviewUtils.h @@ -8,9 +8,9 @@ #pragma once -#include - #if !defined(Q_MOC_RUN) +#include +#include #include #endif @@ -20,21 +20,25 @@ namespace AZ { namespace SharedPreviewUtils { - //! Get assetId by assetType that belongs to either source or product thumbnail key - Data::AssetId GetAssetId( - AzToolsFramework::Thumbnailer::SharedThumbnailKey key, - const Data::AssetType& assetType, - const Data::AssetId& defaultAssetId = {}); - - //! Word wrap function for previewer QLabel, since by default it does not break long words such as filenames, so manual word - //! wrap needed - QString WordWrap(const QString& string, int maxLength); - //! Get the set of all asset types supported by the shared preview AZStd::unordered_set GetSupportedAssetTypes(); //! Determine if a thumbnail key has an asset supported by the shared preview bool IsSupportedAssetType(AzToolsFramework::Thumbnailer::SharedThumbnailKey key); + + //! Get assetInfo of source or product thumbnail key if asset type is supported by the shared preview + AZ::Data::AssetInfo GetSupportedAssetInfo(AzToolsFramework::Thumbnailer::SharedThumbnailKey key); + + //! Get assetId of source or product thumbnail key if asset type is supported by the shared preview + AZ::Data::AssetId GetSupportedAssetId( + AzToolsFramework::Thumbnailer::SharedThumbnailKey key, const AZ::Data::AssetId& defaultAssetId = {}); + + //! Wraps AZ::RPI::AssetUtils::GetAssetIdForProductPath to handle empty productPath + AZ::Data::AssetId GetAssetIdForProductPath(const AZStd::string_view productPath); + + //! Inserts new line characters into a string whenever the maximum number of characters per line is exceeded + QString WordWrap(const QString& string, int maxLength); + } // namespace SharedPreviewUtils } // namespace LyIntegration } // namespace AZ diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/SharedPreview/SharedThumbnail.cpp b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/SharedPreview/SharedThumbnail.cpp index 5d82bac139..d07c4577e8 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/SharedPreview/SharedThumbnail.cpp +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/SharedPreview/SharedThumbnail.cpp @@ -22,18 +22,13 @@ namespace AZ ////////////////////////////////////////////////////////////////////////// SharedThumbnail::SharedThumbnail(AzToolsFramework::Thumbnailer::SharedThumbnailKey key) : Thumbnail(key) + , m_assetInfo(SharedPreviewUtils::GetSupportedAssetInfo(key)) { - for (const AZ::Uuid& typeId : SharedPreviewUtils::GetSupportedAssetTypes()) + if (m_assetInfo.m_assetId.IsValid()) { - const AZ::Data::AssetId& assetId = SharedPreviewUtils::GetAssetId(key, typeId); - if (assetId.IsValid()) - { - m_assetId = assetId; - m_typeId = typeId; - AzToolsFramework::Thumbnailer::ThumbnailerRendererNotificationBus::Handler::BusConnect(key); - AzFramework::AssetCatalogEventBus::Handler::BusConnect(); - return; - } + AzToolsFramework::Thumbnailer::ThumbnailerRendererNotificationBus::Handler::BusConnect(key); + AzFramework::AssetCatalogEventBus::Handler::BusConnect(); + return; } AZ_Error("SharedThumbnail", false, "Failed to find matching assetId for the thumbnailKey."); @@ -43,7 +38,9 @@ namespace AZ void SharedThumbnail::LoadThread() { AzToolsFramework::Thumbnailer::ThumbnailerRendererRequestBus::QueueEvent( - m_typeId, &AzToolsFramework::Thumbnailer::ThumbnailerRendererRequests::RenderThumbnail, m_key, SharedThumbnailSize); + m_assetInfo.m_assetType, &AzToolsFramework::Thumbnailer::ThumbnailerRendererRequests::RenderThumbnail, m_key, + SharedThumbnailSize); + // wait for response from thumbnail renderer m_renderWait.acquire(); } @@ -68,7 +65,7 @@ namespace AZ void SharedThumbnail::OnCatalogAssetChanged([[maybe_unused]] const AZ::Data::AssetId& assetId) { - if (m_assetId == assetId && m_state == State::Ready) + if (m_assetInfo.m_assetId == assetId && m_state == State::Ready) { m_state = State::Unloaded; Load(); diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/SharedPreview/SharedThumbnail.h b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/SharedPreview/SharedThumbnail.h index dee433e0bb..2d4b17a09e 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/SharedPreview/SharedThumbnail.h +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/SharedPreview/SharedThumbnail.h @@ -43,8 +43,7 @@ namespace AZ void OnCatalogAssetChanged(const AZ::Data::AssetId& assetId) override; AZStd::binary_semaphore m_renderWait; - Data::AssetId m_assetId; - AZ::Uuid m_typeId; + Data::AssetInfo m_assetInfo; }; //! Cache configuration for shared thumbnails diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/SharedPreview/SharedThumbnailRenderer.cpp b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/SharedPreview/SharedThumbnailRenderer.cpp index c43ba5f1cf..4ee75e3436 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/SharedPreview/SharedThumbnailRenderer.cpp +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/SharedPreview/SharedThumbnailRenderer.cpp @@ -8,6 +8,7 @@ #include #include +#include #include #include #include @@ -20,9 +21,9 @@ namespace AZ { SharedThumbnailRenderer::SharedThumbnailRenderer() { - m_defaultModelAsset.Create(DefaultModelAssetId, true); - m_defaultMaterialAsset.Create(DefaultMaterialAssetId, true); - m_defaultLightingPresetAsset.Create(DefaultLightingPresetAssetId, true); + m_defaultModelAsset.Create(SharedPreviewUtils::GetAssetIdForProductPath(DefaultModelPath), true); + m_defaultMaterialAsset.Create(SharedPreviewUtils::GetAssetIdForProductPath(DefaultMaterialPath), true); + m_defaultLightingPresetAsset.Create(SharedPreviewUtils::GetAssetIdForProductPath(DefaultLightingPresetPath), true); for (const AZ::Uuid& typeId : SharedPreviewUtils::GetSupportedAssetTypes()) { @@ -37,17 +38,66 @@ namespace AZ SystemTickBus::Handler::BusDisconnect(); } + SharedThumbnailRenderer::ThumbnailConfig SharedThumbnailRenderer::GetThumbnailConfig( + AzToolsFramework::Thumbnailer::SharedThumbnailKey thumbnailKey) + { + ThumbnailConfig thumbnailConfig; + + const auto assetInfo = SharedPreviewUtils::GetSupportedAssetInfo(thumbnailKey); + if (assetInfo.m_assetType == RPI::ModelAsset::RTTI_Type()) + { + static constexpr const char* MaterialAssetPathSetting = + "/O3DE/Atom/CommonFeature/SharedPreview/ModelAssetType/MaterialAssetPath"; + static constexpr const char* LightingAssetPathSetting = + "/O3DE/Atom/CommonFeature/SharedPreview/ModelAssetType/LightingAssetPath"; + + thumbnailConfig.m_modelId = assetInfo.m_assetId; + thumbnailConfig.m_materialId = SharedPreviewUtils::GetAssetIdForProductPath( + AtomToolsFramework::GetSettingOrDefault(MaterialAssetPathSetting, DefaultMaterialPath)); + thumbnailConfig.m_lightingId = SharedPreviewUtils::GetAssetIdForProductPath( + AtomToolsFramework::GetSettingOrDefault(LightingAssetPathSetting, DefaultLightingPresetPath)); + } + else if (assetInfo.m_assetType == RPI::MaterialAsset::RTTI_Type()) + { + static constexpr const char* ModelAssetPathSetting = + "/O3DE/Atom/CommonFeature/SharedPreview/MaterialAssetType/ModelAssetPath"; + static constexpr const char* LightingAssetPathSetting = + "/O3DE/Atom/CommonFeature/SharedPreview/MaterialAssetType/LightingAssetPath"; + + thumbnailConfig.m_modelId = SharedPreviewUtils::GetAssetIdForProductPath( + AtomToolsFramework::GetSettingOrDefault(ModelAssetPathSetting, DefaultModelPath)); + thumbnailConfig.m_materialId = assetInfo.m_assetId; + thumbnailConfig.m_lightingId = SharedPreviewUtils::GetAssetIdForProductPath( + AtomToolsFramework::GetSettingOrDefault(LightingAssetPathSetting, DefaultLightingPresetPath)); + } + else if (assetInfo.m_assetType == RPI::AnyAsset::RTTI_Type()) + { + static constexpr const char* ModelAssetPathSetting = + "/O3DE/Atom/CommonFeature/SharedPreview/LightingAssetType/ModelAssetPath"; + static constexpr const char* MaterialAssetPathSetting = + "/O3DE/Atom/CommonFeature/SharedPreview/LightingAssetType/MaterialAssetPath"; + + thumbnailConfig.m_modelId = SharedPreviewUtils::GetAssetIdForProductPath( + AtomToolsFramework::GetSettingOrDefault(ModelAssetPathSetting, DefaultModelPath)); + thumbnailConfig.m_materialId = SharedPreviewUtils::GetAssetIdForProductPath( + AtomToolsFramework::GetSettingOrDefault(MaterialAssetPathSetting, "materials/reflectionprobe/reflectionprobevisualization.azmaterial")); + thumbnailConfig.m_lightingId = assetInfo.m_assetId; + } + + return thumbnailConfig; + } + void SharedThumbnailRenderer::RenderThumbnail(AzToolsFramework::Thumbnailer::SharedThumbnailKey thumbnailKey, int thumbnailSize) { if (auto previewRenderer = AZ::Interface::Get()) { + const auto& thumbnailConfig = GetThumbnailConfig(thumbnailKey); + previewRenderer->AddCaptureRequest( { thumbnailSize, AZStd::make_shared( previewRenderer->GetScene(), previewRenderer->GetView(), previewRenderer->GetEntityContextId(), - SharedPreviewUtils::GetAssetId(thumbnailKey, RPI::ModelAsset::RTTI_Type(), DefaultModelAssetId), - SharedPreviewUtils::GetAssetId(thumbnailKey, RPI::MaterialAsset::RTTI_Type(), DefaultMaterialAssetId), - SharedPreviewUtils::GetAssetId(thumbnailKey, RPI::AnyAsset::RTTI_Type(), DefaultLightingPresetAssetId), + thumbnailConfig.m_modelId, thumbnailConfig.m_materialId, thumbnailConfig.m_lightingId, Render::MaterialPropertyOverrideMap()), [thumbnailKey]() { diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/SharedPreview/SharedThumbnailRenderer.h b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/SharedPreview/SharedThumbnailRenderer.h index 4db7728109..2166ac49e7 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/SharedPreview/SharedThumbnailRenderer.h +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/SharedPreview/SharedThumbnailRenderer.h @@ -33,6 +33,15 @@ namespace AZ ~SharedThumbnailRenderer(); private: + struct ThumbnailConfig + { + Data::AssetId m_modelId; + Data::AssetId m_materialId; + Data::AssetId m_lightingId; + }; + + ThumbnailConfig GetThumbnailConfig(AzToolsFramework::Thumbnailer::SharedThumbnailKey thumbnailKey); + //! ThumbnailerRendererRequestsBus::Handler interface overrides... void RenderThumbnail(AzToolsFramework::Thumbnailer::SharedThumbnailKey thumbnailKey, int thumbnailSize) override; bool Installed() const override; @@ -42,15 +51,12 @@ namespace AZ // Default assets to be kept loaded and used for rendering if not overridden static constexpr const char* DefaultLightingPresetPath = "lightingpresets/thumbnail.lightingpreset.azasset"; - const Data::AssetId DefaultLightingPresetAssetId = AZ::RPI::AssetUtils::GetAssetIdForProductPath(DefaultLightingPresetPath); Data::Asset m_defaultLightingPresetAsset; static constexpr const char* DefaultModelPath = "models/sphere.azmodel"; - const Data::AssetId DefaultModelAssetId = AZ::RPI::AssetUtils::GetAssetIdForProductPath(DefaultModelPath); Data::Asset m_defaultModelAsset; static constexpr const char* DefaultMaterialPath = ""; - const Data::AssetId DefaultMaterialAssetId; Data::Asset m_defaultMaterialAsset; }; } // namespace LyIntegration diff --git a/Gems/Camera/Code/Source/ViewportCameraSelectorWindow.cpp b/Gems/Camera/Code/Source/ViewportCameraSelectorWindow.cpp index dc091db9e5..eb1fd9890c 100644 --- a/Gems/Camera/Code/Source/ViewportCameraSelectorWindow.cpp +++ b/Gems/Camera/Code/Source/ViewportCameraSelectorWindow.cpp @@ -7,14 +7,14 @@ */ #include "ViewportCameraSelectorWindow.h" #include "ViewportCameraSelectorWindow_Internals.h" -#include -#include -#include -#include -#include -#include #include #include +#include +#include +#include +#include +#include +#include namespace Qt { @@ -64,12 +64,14 @@ namespace Camera CameraListModel::CameraListModel(QWidget* myParent) : QAbstractListModel(myParent) { + m_lastActiveCamera = AZ::EntityId(); m_cameraItems.push_back(AZ::EntityId()); CameraNotificationBus::Handler::BusConnect(); } CameraListModel::~CameraListModel() { + m_firstEntry = true; // set the view entity id back to Invalid, thus enabling the editor camera EditorCameraRequests::Bus::Broadcast(&EditorCameraRequests::SetViewFromEntityPerspective, AZ::EntityId()); @@ -98,11 +100,13 @@ namespace Camera { // If the camera entity is not an editor camera entity, don't add it to the list. // This occurs when we're in simulation mode. + + //We reset the m_firstEntry value so we can update m_lastActiveCamera when we remove from the cameras list + m_firstEntry = true; + bool isEditorEntity = false; AzToolsFramework::EditorEntityContextRequestBus::BroadcastResult( - isEditorEntity, - &AzToolsFramework::EditorEntityContextRequests::IsEditorEntity, - cameraId); + isEditorEntity, &AzToolsFramework::EditorEntityContextRequests::IsEditorEntity, cameraId); if (!isEditorEntity) { return; @@ -111,11 +115,25 @@ namespace Camera beginInsertRows(QModelIndex(), rowCount(), rowCount()); m_cameraItems.push_back(cameraId); endInsertRows(); + + if (m_lastActiveCamera.IsValid() && m_lastActiveCamera == cameraId) + { + Camera::CameraRequestBus::Event(cameraId, &Camera::CameraRequestBus::Events::MakeActiveView); + } } void CameraListModel::OnCameraRemoved(const AZ::EntityId& cameraId) { - auto cameraIt = AZStd::find_if(m_cameraItems.begin(), m_cameraItems.end(), + //Check it is the first time we remove a camera from the list before any other addition + //So we don't end up with the wrong camera ID. + if (m_firstEntry) + { + CameraSystemRequestBus::BroadcastResult(m_lastActiveCamera, &CameraSystemRequestBus::Events::GetActiveCamera); + m_firstEntry = false; + } + + auto cameraIt = AZStd::find_if( + m_cameraItems.begin(), m_cameraItems.end(), [&cameraId](const CameraListItem& entry) { return entry.m_cameraId == cameraId; @@ -162,7 +180,12 @@ namespace Camera // use the stylesheet for elements in a set where one item must be selected at all times setProperty("class", "SingleRequiredSelection"); - connect(m_cameraList, &CameraListModel::rowsInserted, this, [sortedProxyModel](const QModelIndex&, int, int) { sortedProxyModel->sortColumn(); }); + connect( + m_cameraList, &CameraListModel::rowsInserted, this, + [sortedProxyModel](const QModelIndex&, int, int) + { + sortedProxyModel->sortColumn(); + }); // highlight the current selected camera entity AZ::EntityId currentSelection; @@ -188,7 +211,8 @@ namespace Camera QScopedValueRollback rb(m_ignoreViewportViewEntityChanged, true); AZ::EntityId entityId = selectionModel()->currentIndex().data(Qt::CameraIdRole).value(); - EditorCameraRequests::Bus::Broadcast(&EditorCameraRequests::SetViewAndMovementLockFromEntityPerspective, entityId, lockCameraMovement); + EditorCameraRequests::Bus::Broadcast( + &EditorCameraRequests::SetViewAndMovementLockFromEntityPerspective, entityId, lockCameraMovement); } } @@ -220,7 +244,9 @@ namespace Camera } // swallow mouse move events so we can disable sloppy selection - void ViewportCameraSelectorWindow::mouseMoveEvent(QMouseEvent*) {} + void ViewportCameraSelectorWindow::mouseMoveEvent(QMouseEvent*) + { + } // double click selects the entity void ViewportCameraSelectorWindow::mouseDoubleClickEvent([[maybe_unused]] QMouseEvent* event) @@ -228,11 +254,13 @@ namespace Camera AZ::EntityId entityId = selectionModel()->currentIndex().data(Qt::CameraIdRole).value(); if (entityId.IsValid()) { - AzToolsFramework::ToolsApplicationRequestBus::Broadcast(&AzToolsFramework::ToolsApplicationRequestBus::Events::SetSelectedEntities, AzToolsFramework::EntityIdList { entityId }); + AzToolsFramework::ToolsApplicationRequestBus::Broadcast( + &AzToolsFramework::ToolsApplicationRequestBus::Events::SetSelectedEntities, AzToolsFramework::EntityIdList{ entityId }); } else { - AzToolsFramework::ToolsApplicationRequestBus::Broadcast(&AzToolsFramework::ToolsApplicationRequestBus::Events::SetSelectedEntities, AzToolsFramework::EntityIdList {}); + AzToolsFramework::ToolsApplicationRequestBus::Broadcast( + &AzToolsFramework::ToolsApplicationRequestBus::Events::SetSelectedEntities, AzToolsFramework::EntityIdList{}); } } @@ -290,7 +318,10 @@ namespace Camera : QWidget(parent) { setLayout(new QVBoxLayout(this)); - auto label = new QLabel("Select the camera you wish to view and navigate through. Closing this window will return you to the default editor camera.", this); + auto label = new QLabel( + "Select the camera you wish to view and navigate through. Closing this window will return you to the default editor " + "camera.", + this); label->setWordWrap(true); layout()->addWidget(label); layout()->addWidget(new ViewportCameraSelectorWindow(this)); @@ -309,6 +340,8 @@ namespace Camera viewOptions.isPreview = true; viewOptions.showInMenu = true; viewOptions.preferedDockingArea = Qt::DockWidgetArea::LeftDockWidgetArea; - AzToolsFramework::EditorRequestBus::Broadcast(&AzToolsFramework::EditorRequestBus::Events::RegisterViewPane, s_viewportCameraSelectorName, "Viewport", viewOptions, &Internal::CreateNewSelectionWindow); + AzToolsFramework::EditorRequestBus::Broadcast( + &AzToolsFramework::EditorRequestBus::Events::RegisterViewPane, s_viewportCameraSelectorName, "Viewport", viewOptions, + &Internal::CreateNewSelectionWindow); } } // namespace Camera diff --git a/Gems/Camera/Code/Source/ViewportCameraSelectorWindow_Internals.h b/Gems/Camera/Code/Source/ViewportCameraSelectorWindow_Internals.h index b07ae7789f..21f316b83d 100644 --- a/Gems/Camera/Code/Source/ViewportCameraSelectorWindow_Internals.h +++ b/Gems/Camera/Code/Source/ViewportCameraSelectorWindow_Internals.h @@ -58,6 +58,11 @@ namespace Camera private: AZStd::vector m_cameraItems; AZ::EntityId m_sequenceCameraEntityId; + AZ::EntityId m_lastActiveCamera; + + //Value to check that is the first time that we remove a camera before adding a new one. + //So we can update m_lastActiveCamera properly + bool m_firstEntry = true; }; struct ViewportCameraSelectorWindow diff --git a/Gems/GraphCanvas/Code/StaticLib/GraphCanvas/Widgets/NodePalette/TreeItems/NodePaletteTreeItem.cpp b/Gems/GraphCanvas/Code/StaticLib/GraphCanvas/Widgets/NodePalette/TreeItems/NodePaletteTreeItem.cpp index cbdfbfcf0c..bce17c6348 100644 --- a/Gems/GraphCanvas/Code/StaticLib/GraphCanvas/Widgets/NodePalette/TreeItems/NodePaletteTreeItem.cpp +++ b/Gems/GraphCanvas/Code/StaticLib/GraphCanvas/Widgets/NodePalette/TreeItems/NodePaletteTreeItem.cpp @@ -9,6 +9,10 @@ #include +AZ_PUSH_DISABLE_WARNING(4244 4251 4800, "-Wunknown-warning-option") +#include +AZ_POP_DISABLE_WARNING + namespace GraphCanvas { //////////////////////// @@ -19,7 +23,6 @@ namespace GraphCanvas NodePaletteTreeItem::NodePaletteTreeItem(AZStd::string_view name, EditorId editorId) : GraphCanvas::GraphCanvasTreeItem() - , m_errorIcon(":/GraphCanvasEditorResources/toast_error_icon.png") , m_editorId(editorId) , m_name(QString::fromUtf8(name.data(), static_cast(name.size()))) , m_selected(false) @@ -88,7 +91,7 @@ namespace GraphCanvas case Qt::DecorationRole: if (HasError()) { - return m_errorIcon; + return QIcon(":/GraphCanvasEditorResources/toast_error_icon.png"); } break; default: diff --git a/Gems/GraphCanvas/Code/StaticLib/GraphCanvas/Widgets/NodePalette/TreeItems/NodePaletteTreeItem.h b/Gems/GraphCanvas/Code/StaticLib/GraphCanvas/Widgets/NodePalette/TreeItems/NodePaletteTreeItem.h index 3dad6fed0a..4259caf69b 100644 --- a/Gems/GraphCanvas/Code/StaticLib/GraphCanvas/Widgets/NodePalette/TreeItems/NodePaletteTreeItem.h +++ b/Gems/GraphCanvas/Code/StaticLib/GraphCanvas/Widgets/NodePalette/TreeItems/NodePaletteTreeItem.h @@ -9,10 +9,6 @@ #include -AZ_PUSH_DISABLE_WARNING(4244 4251 4800, "-Wunknown-warning-option") -#include -AZ_POP_DISABLE_WARNING - #include #include #include @@ -117,7 +113,6 @@ namespace GraphCanvas private: // Error Display - QIcon m_errorIcon; QString m_errorString; AZStd::string m_styleOverride; diff --git a/Gems/LmbrCentral/Assets/Editor/Icons/Components/AxisAlignedBoxShape.svg b/Gems/LmbrCentral/Assets/Editor/Icons/Components/AxisAlignedBoxShape.svg new file mode 100644 index 0000000000..0f3982d713 --- /dev/null +++ b/Gems/LmbrCentral/Assets/Editor/Icons/Components/AxisAlignedBoxShape.svg @@ -0,0 +1,3 @@ + + + diff --git a/Gems/LmbrCentral/Assets/Editor/Icons/Components/Viewport/AxisAlignedBoxShape.svg b/Gems/LmbrCentral/Assets/Editor/Icons/Components/Viewport/AxisAlignedBoxShape.svg new file mode 100644 index 0000000000..51f0be0572 --- /dev/null +++ b/Gems/LmbrCentral/Assets/Editor/Icons/Components/Viewport/AxisAlignedBoxShape.svg @@ -0,0 +1,16 @@ + + + + + + + + + + + + + + + + diff --git a/Gems/LmbrCentral/Code/Source/Ai/EditorNavigationAreaComponent.cpp b/Gems/LmbrCentral/Code/Source/Ai/EditorNavigationAreaComponent.cpp index f723918cf3..ed707ee9b3 100644 --- a/Gems/LmbrCentral/Code/Source/Ai/EditorNavigationAreaComponent.cpp +++ b/Gems/LmbrCentral/Code/Source/Ai/EditorNavigationAreaComponent.cpp @@ -47,6 +47,7 @@ namespace LmbrCentral { editContext->Class("Navigation Area", "Navigation Area configuration") ->ClassElement(AZ::Edit::ClassElements::EditorData, "") + ->Attribute(AZ::Edit::Attributes::AddableByUser, false) ->Attribute(AZ::Edit::Attributes::Category, "AI") ->Attribute(AZ::Edit::Attributes::Icon, "Icons/Components/NavigationArea.svg") ->Attribute(AZ::Edit::Attributes::ViewportIcon, "Icons/Components/Viewport/NavigationArea.svg") diff --git a/Gems/LmbrCentral/Code/Source/Ai/EditorNavigationSeedComponent.cpp b/Gems/LmbrCentral/Code/Source/Ai/EditorNavigationSeedComponent.cpp index 47999dbd4b..8d8727e314 100644 --- a/Gems/LmbrCentral/Code/Source/Ai/EditorNavigationSeedComponent.cpp +++ b/Gems/LmbrCentral/Code/Source/Ai/EditorNavigationSeedComponent.cpp @@ -32,6 +32,7 @@ namespace LmbrCentral editContext->Class("Navigation Seed", "Determines reachable navigation nodes") ->ClassElement(AZ::Edit::ClassElements::EditorData, "") ->Attribute(AZ::Edit::Attributes::AppearsInAddComponentMenu, AZ_CRC("Game", 0x232b318c)) + ->Attribute(AZ::Edit::Attributes::AddableByUser, false) ->Attribute(AZ::Edit::Attributes::Category, "AI") ->Attribute(AZ::Edit::Attributes::Icon, "Icons/Components/NavigationSeed.svg") ->Attribute(AZ::Edit::Attributes::ViewportIcon, "Icons/Components/Viewport/NavigationSeed.svg") diff --git a/Gems/LmbrCentral/Code/Source/Ai/NavigationComponent.cpp b/Gems/LmbrCentral/Code/Source/Ai/NavigationComponent.cpp index 500d5c17da..9798307d51 100644 --- a/Gems/LmbrCentral/Code/Source/Ai/NavigationComponent.cpp +++ b/Gems/LmbrCentral/Code/Source/Ai/NavigationComponent.cpp @@ -120,6 +120,7 @@ namespace LmbrCentral editContext->Class( "Navigation", "The Navigation component provides basic pathfinding and pathfollowing services to an entity") ->ClassElement(AZ::Edit::ClassElements::EditorData, "") + ->Attribute(AZ::Edit::Attributes::AddableByUser, false) ->Attribute(AZ::Edit::Attributes::Category, "AI") ->Attribute(AZ::Edit::Attributes::Icon, "Icons/Components/Navigation.svg") ->Attribute(AZ::Edit::Attributes::ViewportIcon, "Icons/Components/Viewport/Navigation.svg") diff --git a/Gems/LmbrCentral/Code/Source/Scripting/TagComponent.cpp b/Gems/LmbrCentral/Code/Source/Scripting/TagComponent.cpp index f2701473f3..7eb3c62b5d 100644 --- a/Gems/LmbrCentral/Code/Source/Scripting/TagComponent.cpp +++ b/Gems/LmbrCentral/Code/Source/Scripting/TagComponent.cpp @@ -92,7 +92,7 @@ namespace LmbrCentral ; behaviorContext->EBus("TagGlobalRequestBus") - ->Event("RequestTaggedEntities", &TagGlobalRequestBus::Events::RequestTaggedEntities) + ->Event("Get Entity By Tag", &TagGlobalRequestBus::Events::RequestTaggedEntities, "RequestTaggedEntities") ; behaviorContext->EBus("TagComponentNotificationsBus") diff --git a/Gems/LmbrCentral/Code/Source/Shape/EditorAxisAlignedBoxShapeComponent.cpp b/Gems/LmbrCentral/Code/Source/Shape/EditorAxisAlignedBoxShapeComponent.cpp index c833677b1d..f78f2f048d 100644 --- a/Gems/LmbrCentral/Code/Source/Shape/EditorAxisAlignedBoxShapeComponent.cpp +++ b/Gems/LmbrCentral/Code/Source/Shape/EditorAxisAlignedBoxShapeComponent.cpp @@ -36,8 +36,8 @@ namespace LmbrCentral "Axis Aligned Box Shape", "The Axis Aligned Box Shape component creates a box around the associated entity") ->ClassElement(AZ::Edit::ClassElements::EditorData, "") ->Attribute(AZ::Edit::Attributes::Category, "Shape") - ->Attribute(AZ::Edit::Attributes::Icon, "Icons/Components/Box_Shape.svg") - ->Attribute(AZ::Edit::Attributes::ViewportIcon, "Icons/Components/Viewport/Box_Shape.svg") + ->Attribute(AZ::Edit::Attributes::Icon, "Editor/Icons/Components/AxisAlignedBoxShape.svg") + ->Attribute(AZ::Edit::Attributes::ViewportIcon, "Editor/Icons/Components/Viewport/AxisAlignedBoxShape.svg") ->Attribute(AZ::Edit::Attributes::AppearsInAddComponentMenu, AZ_CRC_CE("Game")) ->Attribute(AZ::Edit::Attributes::AutoExpand, true) ->Attribute(AZ::Edit::Attributes::HelpPageURL, "https://o3de.org/docs/user-guide/components/reference/shape/axis-aligned-box-shape/") diff --git a/Gems/LyShine/Code/Editor/EditorWindow.cpp b/Gems/LyShine/Code/Editor/EditorWindow.cpp index a4ad4d7043..7b60474ed5 100644 --- a/Gems/LyShine/Code/Editor/EditorWindow.cpp +++ b/Gems/LyShine/Code/Editor/EditorWindow.cpp @@ -8,6 +8,7 @@ #include "EditorCommon.h" #include "CanvasHelpers.h" #include "AssetDropHelpers.h" +#include #include #include #include @@ -697,15 +698,36 @@ bool EditorWindow::SaveCanvasToXml(UiCanvasMetadata& canvasMetadata, bool forceA else if (recentFiles.size() > 0) { dir = Path::GetPath(recentFiles.front()); - dir.append(canvasMetadata.m_canvasDisplayName.c_str()); } // Else go to the default canvas directory else { dir = FileHelpers::GetAbsoluteDir(UICANVASEDITOR_CANVAS_DIRECTORY); - dir.append(canvasMetadata.m_canvasDisplayName.c_str()); } + // Make sure the directory exists. If not, walk up the directory path until we find one that does + // so that we will have a consistent 'starting folder' in the 'AzQtComponents::FileDialog::GetSaveFileName' call + // across different platforms. + AZ::IO::FixedMaxPath dirPath(dir.toUtf8().constData()); + + while (!AZ::IO::SystemFile::IsDirectory(dirPath.c_str())) + { + AZ::IO::PathView parentPath = dirPath.ParentPath(); + if (parentPath == dirPath) + { + // We've reach the root path, need to break out whether or not + // the root path exists + break; + } + else + { + dirPath = parentPath; + } + } + // Append the default filename + dirPath /= canvasMetadata.m_canvasDisplayName; + dir = QString::fromUtf8(dirPath.c_str(), static_cast(dirPath.Native().size())); + QString filename = AzQtComponents::FileDialog::GetSaveFileName(nullptr, QString(), dir, diff --git a/Gems/PhysX/Assets/Editor/Icons/Components/PhysXHeightfieldCollider.svg b/Gems/PhysX/Assets/Editor/Icons/Components/PhysXHeightfieldCollider.svg new file mode 100644 index 0000000000..f616a26381 --- /dev/null +++ b/Gems/PhysX/Assets/Editor/Icons/Components/PhysXHeightfieldCollider.svg @@ -0,0 +1,3 @@ + + + diff --git a/Gems/PhysX/Assets/Editor/Icons/Components/Viewport/PhysXHeightfieldCollider.svg b/Gems/PhysX/Assets/Editor/Icons/Components/Viewport/PhysXHeightfieldCollider.svg new file mode 100644 index 0000000000..fbfed18e46 --- /dev/null +++ b/Gems/PhysX/Assets/Editor/Icons/Components/Viewport/PhysXHeightfieldCollider.svg @@ -0,0 +1,16 @@ + + + + + + + + + + + + + + + + diff --git a/Gems/PhysX/Code/Editor/EditorJointConfiguration.cpp b/Gems/PhysX/Code/Editor/EditorJointConfiguration.cpp index 02e684de63..166c44de22 100644 --- a/Gems/PhysX/Code/Editor/EditorJointConfiguration.cpp +++ b/Gems/PhysX/Code/Editor/EditorJointConfiguration.cpp @@ -11,6 +11,7 @@ #include #include #include +#include namespace { @@ -213,7 +214,7 @@ namespace PhysX if (auto* serializeContext = azrtti_cast(context)) { serializeContext->Class() - ->Version(4, &EditorJointConfig::VersionConverter) + ->Version(5, &EditorJointConfig::VersionConverter) ->Field("Local Position", &EditorJointConfig::m_localPosition) ->Field("Local Rotation", &EditorJointConfig::m_localRotation) ->Field("Parent Entity", &EditorJointConfig::m_leadEntity) @@ -228,6 +229,12 @@ namespace PhysX if (auto* editContext = serializeContext->GetEditContext()) { + editContext->Enum("Joint Display Setup State", "Options for displaying joint setup.") + ->Value("Never", EditorJointConfig::DisplaySetupState::Never) + ->Value("Selected", EditorJointConfig::DisplaySetupState::Selected) + ->Value("Always", EditorJointConfig::DisplaySetupState::Always) + ; + editContext->Class( "PhysX Joint Configuration", "") ->ClassElement(AZ::Edit::ClassElements::EditorData, "") @@ -244,8 +251,11 @@ namespace PhysX ->Attribute(AZ::Edit::Attributes::ChangeNotify, &EditorJointConfig::ValidateLeadEntityId) ->DataElement(0, &PhysX::EditorJointConfig::m_selfCollide, "Lead-Follower Collide" , "When active, the lead and follower pair will collide with each other.") - ->DataElement(0, &PhysX::EditorJointConfig::m_displayJointSetup, "Display Setup in Viewport" - , "Display joint setup in the viewport.") + ->DataElement( + AZ::Edit::UIHandlers::ComboBox, &PhysX::EditorJointConfig::m_displayJointSetup, "Display Setup in Viewport" + , "Never = Not shown." + "Select = Show setup display when entity is selected." + "Always = Always show setup display.") ->Attribute(AZ::Edit::Attributes::ReadOnly, &EditorJointConfig::IsInComponentMode) ->DataElement(0, &PhysX::EditorJointConfig::m_selectLeadOnSnap, "Select Lead on Snap" , "Select lead entity on snap to position in component mode.") @@ -306,6 +316,23 @@ namespace PhysX m_followerEntity); } + bool EditorJointConfig::ShowSetupDisplay() const + { + switch(m_displayJointSetup) + { + case DisplaySetupState::Always: + return true; + case DisplaySetupState::Selected: + { + bool showSetup = false; + AzToolsFramework::EditorEntityInfoRequestBus::EventResult( + showSetup, m_followerEntity, &AzToolsFramework::EditorEntityInfoRequests::IsSelected); + return showSetup; + } + } + return false; + } + bool EditorJointConfig::IsInComponentMode() const { return m_inComponentMode; @@ -343,6 +370,31 @@ namespace PhysX } } + // convert m_displayJointSetup from a bool to the enum with the option Never,Selected,Always show joint setup helpers. + if (classElement.GetVersion() <= 4) + { + // get the current bool setting and remove it. + bool oldSetting = false; + const int displayJointSetupIndex = classElement.FindElement(AZ_CRC_CE("Display Debug")); + if (displayJointSetupIndex >= 0) + { + AZ::SerializeContext::DataElementNode& elementNode = classElement.GetSubElement(displayJointSetupIndex); + elementNode.GetData(oldSetting); + classElement.RemoveElement(displayJointSetupIndex); + } + + //if the old setting was on set it to 'Selected'. otherwise 'Never' + if (oldSetting) + { + classElement.AddElementWithData(context, "Display Debug", EditorJointConfig::DisplaySetupState::Selected); + } + else + { + classElement.AddElementWithData(context, "Display Debug", EditorJointConfig::DisplaySetupState::Never); + } + } + + return result; } diff --git a/Gems/PhysX/Code/Editor/EditorJointConfiguration.h b/Gems/PhysX/Code/Editor/EditorJointConfiguration.h index 89ab31e4a7..f3dcd4afed 100644 --- a/Gems/PhysX/Code/Editor/EditorJointConfiguration.h +++ b/Gems/PhysX/Code/Editor/EditorJointConfiguration.h @@ -100,12 +100,21 @@ namespace PhysX AZ_TYPE_INFO(EditorJointConfig, "{8A966D65-CA97-4786-A13C-ACAA519D97EA}"); static void Reflect(AZ::ReflectContext* context); + enum class DisplaySetupState : AZ::u8 + { + Never = 0, + Selected, + Always + }; + void SetLeadEntityId(AZ::EntityId leadEntityId); JointGenericProperties ToGenericProperties() const; JointComponentConfiguration ToGameTimeConfig() const; + bool ShowSetupDisplay() const; + bool m_breakable = false; - bool m_displayJointSetup = false; + DisplaySetupState m_displayJointSetup = DisplaySetupState::Selected; bool m_inComponentMode = false; bool m_selectLeadOnSnap = true; bool m_selfCollide = false; @@ -129,3 +138,8 @@ namespace PhysX }; } // namespace PhysX + +namespace AZ +{ + AZ_TYPE_INFO_SPECIALIZE(PhysX::EditorJointConfig::DisplaySetupState, "{17EBE6BD-289A-4326-8A24-DCE3B7FEC51E}"); +} // namespace AZ diff --git a/Gems/PhysX/Code/Source/EditorBallJointComponent.cpp b/Gems/PhysX/Code/Source/EditorBallJointComponent.cpp index fa71fa0061..d7065a869d 100644 --- a/Gems/PhysX/Code/Source/EditorBallJointComponent.cpp +++ b/Gems/PhysX/Code/Source/EditorBallJointComponent.cpp @@ -215,7 +215,7 @@ namespace PhysX { EditorJointComponent::DisplayEntityViewport(viewportInfo, debugDisplay); - if (!m_config.m_displayJointSetup && + if (!m_config.ShowSetupDisplay() && !m_config.m_inComponentMode) { return; diff --git a/Gems/PhysX/Code/Source/EditorHeightfieldColliderComponent.cpp b/Gems/PhysX/Code/Source/EditorHeightfieldColliderComponent.cpp index 0f09258524..fb0a38fa18 100644 --- a/Gems/PhysX/Code/Source/EditorHeightfieldColliderComponent.cpp +++ b/Gems/PhysX/Code/Source/EditorHeightfieldColliderComponent.cpp @@ -34,8 +34,8 @@ namespace PhysX "PhysX Heightfield Collider", "Creates geometry in the PhysX simulation based on an attached heightfield component") ->ClassElement(AZ::Edit::ClassElements::EditorData, "") ->Attribute(AZ::Edit::Attributes::Category, "PhysX") - ->Attribute(AZ::Edit::Attributes::Icon, "Icons/Components/PhysXCollider.svg") - ->Attribute(AZ::Edit::Attributes::ViewportIcon, "Icons/Components/Viewport/PhysXCollider.svg") + ->Attribute(AZ::Edit::Attributes::Icon, "Editor/Icons/Components/PhysXHeightfieldCollider.svg") + ->Attribute(AZ::Edit::Attributes::ViewportIcon, "Editor/Icons/Components/Viewport/PhysXHeightfieldCollider.svg") ->Attribute(AZ::Edit::Attributes::AppearsInAddComponentMenu, AZ_CRC_CE("Game")) ->Attribute( AZ::Edit::Attributes::HelpPageURL, "https://o3de.org/docs/user-guide/components/reference/physx/heightfield-collider/") diff --git a/Gems/PhysX/Code/Source/EditorHingeJointComponent.cpp b/Gems/PhysX/Code/Source/EditorHingeJointComponent.cpp index 1b575074e2..f009c990b4 100644 --- a/Gems/PhysX/Code/Source/EditorHingeJointComponent.cpp +++ b/Gems/PhysX/Code/Source/EditorHingeJointComponent.cpp @@ -211,7 +211,7 @@ namespace PhysX { EditorJointComponent::DisplayEntityViewport(viewportInfo, debugDisplay); - if (!m_config.m_displayJointSetup && + if (!m_config.ShowSetupDisplay() && !m_config.m_inComponentMode) { return; diff --git a/Gems/PhysX/Code/Source/PhysXCharacters/API/CharacterUtils.cpp b/Gems/PhysX/Code/Source/PhysXCharacters/API/CharacterUtils.cpp index 4ed2825cc2..46f4c04880 100644 --- a/Gems/PhysX/Code/Source/PhysXCharacters/API/CharacterUtils.cpp +++ b/Gems/PhysX/Code/Source/PhysXCharacters/API/CharacterUtils.cpp @@ -344,6 +344,55 @@ namespace PhysX bool isAcceleration = true; return physx::PxD6JointDrive(stiffness, damping, forceLimit, isAcceleration); } + + AZStd::vector ComputeHierarchyDepths(const AZStd::vector& parentIndices) + { + const size_t numNodes = parentIndices.size(); + AZStd::vector nodeDepths(numNodes); + for (size_t nodeIndex = 0; nodeIndex < numNodes; nodeIndex++) + { + nodeDepths[nodeIndex] = { -1, nodeIndex }; + } + + for (size_t nodeIndex = 0; nodeIndex < numNodes; nodeIndex++) + { + if (nodeDepths[nodeIndex].m_depth != -1) + { + continue; + } + int depth = -1; // initial depth value for this node + int ancestorDepth = 0; // the depth of the first ancestor we find when iteratively visiting parents + bool ancestorFound = false; // whether we have found either an ancestor which already has a depth value, or the root + size_t currentIndex = nodeIndex; + while (!ancestorFound) + { + depth++; + if (depth > numNodes) + { + AZ_Error("PhysX Ragdoll", false, "Loop detected in hierarchy depth computation."); + return nodeDepths; + } + const size_t parentIndex = parentIndices[currentIndex]; + + if (parentIndex >= numNodes || nodeDepths[currentIndex].m_depth != -1) + { + ancestorFound = true; + ancestorDepth = (nodeDepths[currentIndex].m_depth != -1) ? nodeDepths[currentIndex].m_depth : 0; + } + + currentIndex = parentIndex; + } + + currentIndex = nodeIndex; + for (int i = depth; i >= 0; i--) + { + nodeDepths[currentIndex] = { ancestorDepth + i, currentIndex }; + currentIndex = parentIndices[currentIndex]; + } + } + + return nodeDepths; + } } // namespace Characters } // namespace Utils } // namespace PhysX diff --git a/Gems/PhysX/Code/Source/PhysXCharacters/API/CharacterUtils.h b/Gems/PhysX/Code/Source/PhysXCharacters/API/CharacterUtils.h index 0f51a5d9b9..245dc01abd 100644 --- a/Gems/PhysX/Code/Source/PhysXCharacters/API/CharacterUtils.h +++ b/Gems/PhysX/Code/Source/PhysXCharacters/API/CharacterUtils.h @@ -49,6 +49,18 @@ namespace PhysX //! @param forceLimit The upper limit on the force the joint can apply to reach its target. //! @return The created joint drive. physx::PxD6JointDrive CreateD6JointDrive(float strength, float dampingRatio, float forceLimit); + + //! Contains information about a node in a hierarchy and how deep it is in the hierarchy relative to the root. + struct DepthData + { + int m_depth = -1; //!< Depth of the joint in the hierarchy. The root has depth 0, its children depth 1, and so on. + size_t m_index = 0; // ComputeHierarchyDepths(const AZStd::vector& parentIndices); } // namespace Characters } // namespace Utils } // namespace PhysX diff --git a/Gems/PhysX/Code/Source/PhysXCharacters/Components/RagdollComponent.cpp b/Gems/PhysX/Code/Source/PhysXCharacters/Components/RagdollComponent.cpp index 57972fea3e..7615a175d1 100644 --- a/Gems/PhysX/Code/Source/PhysXCharacters/Components/RagdollComponent.cpp +++ b/Gems/PhysX/Code/Source/PhysXCharacters/Components/RagdollComponent.cpp @@ -7,20 +7,20 @@ */ #include -#include #include -#include #include +#include +#include #include +#include #include #include -#include +#include #include namespace PhysX { - bool RagdollComponent::VersionConverter(AZ::SerializeContext& context, - AZ::SerializeContext::DataElementNode& classElement) + bool RagdollComponent::VersionConverter(AZ::SerializeContext& context, AZ::SerializeContext::DataElementNode& classElement) { // The element "PhysXRagdoll" was changed from a shared pointer to a unique pointer, but a version converter was // not added at the time. This means there may be serialized data with either the shared or unique pointer, but @@ -76,13 +76,13 @@ namespace PhysX ->Field("EnableJointProjection", &RagdollComponent::m_enableJointProjection) ->Field("ProjectionLinearTol", &RagdollComponent::m_jointProjectionLinearTolerance) ->Field("ProjectionAngularTol", &RagdollComponent::m_jointProjectionAngularToleranceDegrees) - ; + ->Field("EnableMassRatioClamping", &RagdollComponent::m_enableMassRatioClamping) + ->Field("MaxMassRatio", &RagdollComponent::m_maxMassRatio); AZ::EditContext* editContext = serializeContext->GetEditContext(); if (editContext) { - editContext->Class( - "PhysX Ragdoll", "Creates a PhysX ragdoll simulation for an animation actor.") + editContext->Class("PhysX Ragdoll", "Creates a PhysX ragdoll simulation for an animation actor.") ->ClassElement(AZ::Edit::ClassElements::EditorData, "") ->Attribute(AZ::Edit::Attributes::Category, "PhysX") ->Attribute(AZ::Edit::Attributes::Icon, "Icons/Components/PhysXRagdoll.svg") @@ -90,34 +90,49 @@ namespace PhysX ->Attribute(AZ::Edit::Attributes::AppearsInAddComponentMenu, AZ_CRC("Game", 0x232b318c)) ->Attribute(AZ::Edit::Attributes::HelpPageURL, "https://o3de.org/docs/user-guide/components/reference/physx/ragdoll/") ->Attribute(AZ::Edit::Attributes::AutoExpand, true) - ->DataElement(AZ::Edit::UIHandlers::Default, &RagdollComponent::m_positionIterations, "Position Iteration Count", + ->DataElement( + AZ::Edit::UIHandlers::Default, &RagdollComponent::m_positionIterations, "Position Iteration Count", "The frequency at which ragdoll collider positions are resolved. Higher values can increase fidelity but decrease " "performance. Very high values might introduce instability.") ->Attribute(AZ::Edit::Attributes::Min, 1) ->Attribute(AZ::Edit::Attributes::Max, 255) - ->DataElement(AZ::Edit::UIHandlers::Default, &RagdollComponent::m_velocityIterations, "Velocity Iteration Count", + ->DataElement( + AZ::Edit::UIHandlers::Default, &RagdollComponent::m_velocityIterations, "Velocity Iteration Count", "The frequency at which ragdoll collider velocities are resolved. Higher values can increase fidelity but decrease " "performance. Very high values might introduce instability.") ->Attribute(AZ::Edit::Attributes::Min, 1) ->Attribute(AZ::Edit::Attributes::Max, 255) - ->DataElement(AZ::Edit::UIHandlers::Default, &RagdollComponent::m_enableJointProjection, - "Enable Joint Projection", "When active, preserves joint constraints in volatile simulations. " + ->DataElement( + AZ::Edit::UIHandlers::Default, &RagdollComponent::m_enableJointProjection, "Enable Joint Projection", + "When active, preserves joint constraints in volatile simulations. " "Might not be physically correct in all simulations.") ->Attribute(AZ::Edit::Attributes::ChangeNotify, AZ::Edit::PropertyRefreshLevels::EntireTree) - ->DataElement(AZ::Edit::UIHandlers::Default, &RagdollComponent::m_jointProjectionLinearTolerance, + ->DataElement( + AZ::Edit::UIHandlers::Default, &RagdollComponent::m_jointProjectionLinearTolerance, "Joint Projection Linear Tolerance", "Maximum linear joint error. Projection is applied to linear joint errors above this value.") ->Attribute(AZ::Edit::Attributes::Min, 0.0f) ->Attribute(AZ::Edit::Attributes::Step, 1e-3f) ->Attribute(AZ::Edit::Attributes::Visibility, &RagdollComponent::IsJointProjectionVisible) - ->DataElement(AZ::Edit::UIHandlers::Default, &RagdollComponent::m_jointProjectionAngularToleranceDegrees, + ->DataElement( + AZ::Edit::UIHandlers::Default, &RagdollComponent::m_jointProjectionAngularToleranceDegrees, "Joint Projection Angular Tolerance", "Maximum angular joint error. Projection is applied to angular joint errors above this value.") ->Attribute(AZ::Edit::Attributes::Min, 0.0f) ->Attribute(AZ::Edit::Attributes::Step, 0.1f) ->Attribute(AZ::Edit::Attributes::Suffix, " degrees") ->Attribute(AZ::Edit::Attributes::Visibility, &RagdollComponent::IsJointProjectionVisible) - ; + ->DataElement( + AZ::Edit::UIHandlers::Default, &RagdollComponent::m_enableMassRatioClamping, "Enable Mass Ratio Clamping", + "When active, ragdoll node mass values may be overridden to avoid unstable mass ratios.") + ->Attribute(AZ::Edit::Attributes::ChangeNotify, AZ::Edit::PropertyRefreshLevels::EntireTree) + ->DataElement( + AZ::Edit::UIHandlers::Default, &RagdollComponent::m_maxMassRatio, "Maximum Mass Ratio", + "The mass of the child body of a joint may be clamped to avoid its ratio with the parent " + "body mass exceeding this threshold.") + ->Attribute(AZ::Edit::Attributes::Min, 1.0f) + ->Attribute(AZ::Edit::Attributes::Step, 0.1f) + ->Attribute(AZ::Edit::Attributes::Visibility, &RagdollComponent::IsMaxMassRatioVisible); } } @@ -126,11 +141,16 @@ namespace PhysX } } - bool RagdollComponent::IsJointProjectionVisible() + bool RagdollComponent::IsJointProjectionVisible() const { return m_enableJointProjection; } + bool RagdollComponent::IsMaxMassRatioVisible() const + { + return m_enableMassRatioClamping; + } + // AZ::Component void RagdollComponent::Init() { @@ -272,7 +292,6 @@ namespace PhysX return ragdoll->IsSimulated(); } return false; - } AZ::Aabb RagdollComponent::GetAabb() const @@ -318,20 +337,19 @@ namespace PhysX if (numNodes == 0) { - AZ_Error("PhysX Ragdoll Component", false, - "Ragdoll configuration has 0 nodes, ragdoll will not be created for entity \"%s\".", + AZ_Error( + "PhysX Ragdoll Component", false, "Ragdoll configuration has 0 nodes, ragdoll will not be created for entity \"%s\".", GetEntity()->GetName().c_str()); return; } - ragdollConfiguration.m_parentIndices.resize(numNodes); for (size_t nodeIndex = 0; nodeIndex < numNodes; nodeIndex++) { AZStd::string parentName; AZStd::string nodeName = ragdollConfiguration.m_nodes[nodeIndex].m_debugName; - AzFramework::CharacterPhysicsDataRequestBus::EventResult(parentName, GetEntityId(), - &AzFramework::CharacterPhysicsDataRequests::GetParentNodeName, nodeName); + AzFramework::CharacterPhysicsDataRequestBus::EventResult( + parentName, GetEntityId(), &AzFramework::CharacterPhysicsDataRequests::GetParentNodeName, nodeName); AZ::Outcome parentIndex = Utils::Characters::GetNodeIndex(ragdollConfiguration, parentName); ragdollConfiguration.m_parentIndices[nodeIndex] = parentIndex ? parentIndex.GetValue() : SIZE_MAX; @@ -339,8 +357,8 @@ namespace PhysX } Physics::RagdollState bindPose; - AzFramework::CharacterPhysicsDataRequestBus::EventResult(bindPose, GetEntityId(), - &AzFramework::CharacterPhysicsDataRequests::GetBindPose, ragdollConfiguration); + AzFramework::CharacterPhysicsDataRequestBus::EventResult( + bindPose, GetEntityId(), &AzFramework::CharacterPhysicsDataRequests::GetBindPose, ragdollConfiguration); AZ::Transform entityTransform = AZ::Transform::CreateIdentity(); AZ::TransformBus::EventResult(entityTransform, GetEntityId(), &AZ::TransformBus::Events::GetWorldTM); @@ -354,13 +372,12 @@ namespace PhysX m_ragdollHandle = sceneInterface->AddSimulatedBody(m_attachedSceneHandle, &ragdollConfiguration); } auto* ragdoll = GetPhysXRagdoll(); - if (ragdoll == nullptr || - m_ragdollHandle == AzPhysics::InvalidSimulatedBodyHandle) + if (ragdoll == nullptr || m_ragdollHandle == AzPhysics::InvalidSimulatedBodyHandle) { AZ_Error("PhysX Ragdoll Component", false, "Failed to create ragdoll."); return; } - + for (size_t nodeIndex = 0; nodeIndex < numNodes; nodeIndex++) { if (physx::PxRigidDynamic* pxRigidBody = ragdoll->GetPxRigidDynamic(nodeIndex)) @@ -389,17 +406,63 @@ namespace PhysX } } + // If mass ratio clamping is enabled, iterate out from the root and clamp mass values + if (m_enableMassRatioClamping) + { + const float maxMassRatio = AZStd::GetMax(1.0f + AZ::Constants::FloatEpsilon, m_maxMassRatio); + + // figure out the depth of each node in the tree, so that nodes can be visited from the root outwards + AZStd::vector nodeDepths = + Utils::Characters::ComputeHierarchyDepths(ragdollConfiguration.m_parentIndices); + + AZStd::sort( + nodeDepths.begin(), nodeDepths.end(), + [](const Utils::Characters::DepthData& d1, const Utils::Characters::DepthData& d2) + { + return d1.m_depth < d2.m_depth; + }); + + bool massesClamped = false; + for (const auto& nodeDepth : nodeDepths) + { + const size_t nodeIndex = nodeDepth.m_index; + const size_t parentIndex = ragdollConfiguration.m_parentIndices[nodeIndex]; + if (parentIndex < numNodes) + { + AzPhysics::RigidBody& nodeRigidBody = ragdoll->GetNode(nodeIndex)->GetRigidBody(); + const float originalMass = nodeRigidBody.GetMass(); + const float parentMass = ragdoll->GetNode(parentIndex)->GetRigidBody().GetMass(); + const float minMass = parentMass / maxMassRatio; + const float maxMass = parentMass; + if (originalMass < minMass || originalMass > maxMass) + { + const float clampedMass = AZStd::clamp(originalMass, minMass, maxMass); + nodeRigidBody.SetMass(clampedMass); + massesClamped = true; + if (!AZ::IsClose(originalMass, 0.0f)) + { + // scale the inertia proportionally to how the mass was modified + auto pxRigidBody = static_cast(nodeRigidBody.GetNativePointer()); + pxRigidBody->setMassSpaceInertiaTensor(clampedMass / originalMass * pxRigidBody->getMassSpaceInertiaTensor()); + } + } + } + } + + AZ_WarningOnce("PhysX Ragdoll", !massesClamped, + "Mass values for ragdoll on entity \"%s\" were modified based on max mass ratio setting to avoid instability.", + GetEntity()->GetName().c_str()); + } + AzFramework::RagdollPhysicsRequestBus::Handler::BusConnect(GetEntityId()); AzPhysics::SimulatedBodyComponentRequestsBus::Handler::BusConnect(GetEntityId()); - AzFramework::RagdollPhysicsNotificationBus::Event(GetEntityId(), - &AzFramework::RagdollPhysicsNotifications::OnRagdollActivated); + AzFramework::RagdollPhysicsNotificationBus::Event(GetEntityId(), &AzFramework::RagdollPhysicsNotifications::OnRagdollActivated); } void RagdollComponent::DestroyRagdoll() { - if (m_ragdollHandle != AzPhysics::InvalidSimulatedBodyHandle && - m_attachedSceneHandle != AzPhysics::InvalidSceneHandle) + if (m_ragdollHandle != AzPhysics::InvalidSimulatedBodyHandle && m_attachedSceneHandle != AzPhysics::InvalidSceneHandle) { AzFramework::RagdollPhysicsRequestBus::Handler::BusDisconnect(); AzFramework::RagdollPhysicsNotificationBus::Event( @@ -421,8 +484,7 @@ namespace PhysX const Ragdoll* RagdollComponent::GetPhysXRagdollConst() const { - if (m_ragdollHandle == AzPhysics::InvalidSimulatedBodyHandle || - m_attachedSceneHandle == AzPhysics::InvalidSceneHandle) + if (m_ragdollHandle == AzPhysics::InvalidSimulatedBodyHandle || m_attachedSceneHandle == AzPhysics::InvalidSceneHandle) { return nullptr; } diff --git a/Gems/PhysX/Code/Source/PhysXCharacters/Components/RagdollComponent.h b/Gems/PhysX/Code/Source/PhysXCharacters/Components/RagdollComponent.h index 63dd1354dd..3ef59bf623 100644 --- a/Gems/PhysX/Code/Source/PhysXCharacters/Components/RagdollComponent.h +++ b/Gems/PhysX/Code/Source/PhysXCharacters/Components/RagdollComponent.h @@ -103,7 +103,8 @@ namespace PhysX Ragdoll* GetPhysXRagdoll(); const Ragdoll* GetPhysXRagdollConst() const; - bool IsJointProjectionVisible(); + bool IsJointProjectionVisible() const; + bool IsMaxMassRatioVisible() const; AzPhysics::SimulatedBodyHandle m_ragdollHandle = AzPhysics::InvalidSimulatedBodyHandle; AzPhysics::SceneHandle m_attachedSceneHandle = AzPhysics::InvalidSceneHandle; @@ -119,5 +120,9 @@ namespace PhysX float m_jointProjectionLinearTolerance = 1e-3f; /// Angular joint error (in degrees) above which projection will be applied. float m_jointProjectionAngularToleranceDegrees = 1.0f; + /// Allows ragdoll node mass values to be overridden to avoid unstable mass ratios. + bool m_enableMassRatioClamping = false; + /// If mass ratio clamping is enabled, masses will be clamped to within this ratio. + float m_maxMassRatio = 2.0f; }; } // namespace PhysX diff --git a/Gems/PhysX/Code/Tests/RagdollTests.cpp b/Gems/PhysX/Code/Tests/RagdollTests.cpp index 30e9400790..ff4637fd6e 100644 --- a/Gems/PhysX/Code/Tests/RagdollTests.cpp +++ b/Gems/PhysX/Code/Tests/RagdollTests.cpp @@ -367,4 +367,19 @@ namespace PhysX float minZ = ragdoll->GetAabb().GetMin().GetZ(); EXPECT_NEAR(minZ, 0.0f, 0.05f); } + + TEST(ComputeHierarchyDepthsTest, DepthValuesCorrect) + { + AZStd::vector parentIndices = + { 3, 5, AZStd::numeric_limits::max(), 1, 2, 9, 7, 4, 0, 6, 11, 12, 5, 14, 15, 16, 5, 18, 19, 4, 21, 22, 4 }; + + const AZStd::vector nodeDepths = Utils::Characters::ComputeHierarchyDepths(parentIndices); + + std::vector expectedDepths = { 8, 6, 0, 7, 1, 5, 3, 2, 9, 4, 8, 7, 6, 9, 8, 7, 6, 4, 3, 2, 4, 3, 2 }; + + for (size_t i = 0; i < parentIndices.size(); i++) + { + EXPECT_EQ(nodeDepths[i].m_depth, expectedDepths[i]); + } + } } // namespace PhysX diff --git a/Gems/QtForPython/Code/CMakeLists.txt b/Gems/QtForPython/Code/CMakeLists.txt index 48ce5c02d3..da763978a6 100644 --- a/Gems/QtForPython/Code/CMakeLists.txt +++ b/Gems/QtForPython/Code/CMakeLists.txt @@ -21,7 +21,8 @@ ly_add_target( NAME QtForPython.Editor.Static STATIC NAMESPACE Gem FILES_CMAKE - qtforpython_editor_${PAL_PLATFORM_NAME_LOWERCASE}_files.cmake + qtforpython_editor_files.cmake + ${CMAKE_CURRENT_SOURCE_DIR}/Source/Platform/${PAL_PLATFORM_NAME}/qtforpython_editor_${PAL_PLATFORM_NAME_LOWERCASE}_files.cmake PLATFORM_INCLUDE_FILES ${common_source_dir}/${PAL_TRAIT_COMPILER_ID}/qtforpython_${PAL_TRAIT_COMPILER_ID_LOWERCASE}.cmake INCLUDE_DIRECTORIES @@ -45,6 +46,9 @@ ly_add_target( NAMESPACE Gem FILES_CMAKE qtforpython_shared_files.cmake + INCLUDE_DIRECTORIES + PRIVATE + ${CMAKE_CURRENT_SOURCE_DIR}/Source/Platform/${PAL_PLATFORM_NAME} BUILD_DEPENDENCIES PRIVATE Gem::QtForPython.Editor.Static diff --git a/Gems/QtForPython/Code/Source/Platform/Linux/InitializeEmbeddedPyside2.h b/Gems/QtForPython/Code/Source/Platform/Linux/InitializeEmbeddedPyside2.h new file mode 100644 index 0000000000..f27b54810f --- /dev/null +++ b/Gems/QtForPython/Code/Source/Platform/Linux/InitializeEmbeddedPyside2.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 + +namespace QtForPython +{ + const char* s_libPythonLibraryFile = "libpython3.7m.so.1.0"; + const char* s_libPyside2LibraryFile = "libpyside2.abi3.so.5.14"; + const char* s_libShibokenLibraryFile = "libshiboken2.abi3.so.5.14"; + + class InitializeEmbeddedPyside2 + { + public: + InitializeEmbeddedPyside2() + { + m_libPythonLibraryFile = InitializeEmbeddedPyside2::LoadModule(s_libPythonLibraryFile); + m_libPyside2LibraryFile = InitializeEmbeddedPyside2::LoadModule(s_libPyside2LibraryFile); + m_libShibokenLibraryFile = InitializeEmbeddedPyside2::LoadModule(s_libShibokenLibraryFile); + } + virtual ~InitializeEmbeddedPyside2() + { + InitializeEmbeddedPyside2::UnloadModule(m_libShibokenLibraryFile); + InitializeEmbeddedPyside2::UnloadModule(m_libPyside2LibraryFile); + InitializeEmbeddedPyside2::UnloadModule(m_libPythonLibraryFile); + } + + private: + static void* LoadModule(const char* moduleToLoad) + { + void* moduleHandle = dlopen(moduleToLoad, RTLD_NOW | RTLD_GLOBAL); + if (!moduleHandle) + { + const char* loadError = dlerror(); + AZ_Error("QtForPython", false, "Unable to load python library %s for Pyside2: %s", moduleToLoad, + loadError ? loadError : "Unknown Error"); + } + return moduleHandle; + } + + static void UnloadModule(void* moduleHandle) + { + if (moduleHandle) + { + dlclose(moduleHandle); + } + } + + void* m_libPythonLibraryFile; + void* m_libPyside2LibraryFile; + void* m_libShibokenLibraryFile; + }; +} // namespace QtForPython diff --git a/Gems/QtForPython/Code/Source/Platform/Linux/PAL_linux.cmake b/Gems/QtForPython/Code/Source/Platform/Linux/PAL_linux.cmake index 236043e893..789d2afae2 100644 --- a/Gems/QtForPython/Code/Source/Platform/Linux/PAL_linux.cmake +++ b/Gems/QtForPython/Code/Source/Platform/Linux/PAL_linux.cmake @@ -6,4 +6,4 @@ # # -set(PAL_TRAIT_BUILD_QTFORPYTHON_SUPPORTED FALSE) +set(PAL_TRAIT_BUILD_QTFORPYTHON_SUPPORTED TRUE) diff --git a/Gems/QtForPython/Code/Source/Platform/Linux/qtforpython_editor_linux_files.cmake b/Gems/QtForPython/Code/Source/Platform/Linux/qtforpython_editor_linux_files.cmake new file mode 100644 index 0000000000..54c588a247 --- /dev/null +++ b/Gems/QtForPython/Code/Source/Platform/Linux/qtforpython_editor_linux_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 + InitializeEmbeddedPyside2.h +) diff --git a/Gems/QtForPython/Code/Source/Platform/Mac/InitializeEmbeddedPyside2.h b/Gems/QtForPython/Code/Source/Platform/Mac/InitializeEmbeddedPyside2.h new file mode 100644 index 0000000000..819764620b --- /dev/null +++ b/Gems/QtForPython/Code/Source/Platform/Mac/InitializeEmbeddedPyside2.h @@ -0,0 +1,18 @@ +/* + * Copyright (c) Contributors to the Open 3D Engine Project. + * For complete copyright and license terms please see the LICENSE at the root of this distribution. + * + * SPDX-License-Identifier: Apache-2.0 OR MIT + * + */ +#pragma once + +namespace QtForPython +{ + class InitializeEmbeddedPyside2 + { + public: + InitializeEmbeddedPyside2() = default; + virtual ~InitializeEmbeddedPyside2() = default; + }; +} // namespace QtForPython diff --git a/Gems/QtForPython/Code/Source/Platform/Mac/qtforpython_editor_macos_files.cmake b/Gems/QtForPython/Code/Source/Platform/Mac/qtforpython_editor_macos_files.cmake new file mode 100644 index 0000000000..54c588a247 --- /dev/null +++ b/Gems/QtForPython/Code/Source/Platform/Mac/qtforpython_editor_macos_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 + InitializeEmbeddedPyside2.h +) diff --git a/Gems/QtForPython/Code/Source/Platform/Windows/InitializeEmbeddedPyside2.h b/Gems/QtForPython/Code/Source/Platform/Windows/InitializeEmbeddedPyside2.h new file mode 100644 index 0000000000..819764620b --- /dev/null +++ b/Gems/QtForPython/Code/Source/Platform/Windows/InitializeEmbeddedPyside2.h @@ -0,0 +1,18 @@ +/* + * Copyright (c) Contributors to the Open 3D Engine Project. + * For complete copyright and license terms please see the LICENSE at the root of this distribution. + * + * SPDX-License-Identifier: Apache-2.0 OR MIT + * + */ +#pragma once + +namespace QtForPython +{ + class InitializeEmbeddedPyside2 + { + public: + InitializeEmbeddedPyside2() = default; + virtual ~InitializeEmbeddedPyside2() = default; + }; +} // namespace QtForPython diff --git a/Gems/QtForPython/Code/Source/Platform/Windows/qtforpython_editor_windows_files.cmake b/Gems/QtForPython/Code/Source/Platform/Windows/qtforpython_editor_windows_files.cmake new file mode 100644 index 0000000000..54c588a247 --- /dev/null +++ b/Gems/QtForPython/Code/Source/Platform/Windows/qtforpython_editor_windows_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 + InitializeEmbeddedPyside2.h +) diff --git a/Gems/QtForPython/Code/Source/QtForPythonModule.cpp b/Gems/QtForPython/Code/Source/QtForPythonModule.cpp index 1ed79310b4..ad39d0b82c 100644 --- a/Gems/QtForPython/Code/Source/QtForPythonModule.cpp +++ b/Gems/QtForPython/Code/Source/QtForPythonModule.cpp @@ -8,13 +8,17 @@ #include #include +#include #include +#include "InitializeEmbeddedPyside2.h" + namespace QtForPython { class QtForPythonModule : public AZ::Module + , private InitializeEmbeddedPyside2 { public: AZ_RTTI(QtForPythonModule, "{81545CD5-79FA-47CE-96F2-1A9C5D59B4B9}", AZ::Module); @@ -22,11 +26,13 @@ namespace QtForPython QtForPythonModule() : AZ::Module() + , InitializeEmbeddedPyside2() { m_descriptors.insert(m_descriptors.end(), { QtForPythonSystemComponent::CreateDescriptor(), }); } + ~QtForPythonModule() override = default; /** * Add required SystemComponents to the SystemEntity. diff --git a/Gems/QtForPython/Code/Source/QtForPythonSystemComponent.cpp b/Gems/QtForPython/Code/Source/QtForPythonSystemComponent.cpp index 83a158dd18..240beff78e 100644 --- a/Gems/QtForPython/Code/Source/QtForPythonSystemComponent.cpp +++ b/Gems/QtForPython/Code/Source/QtForPythonSystemComponent.cpp @@ -203,10 +203,6 @@ namespace QtForPython { QtBootstrapParameters params; -#if !defined(Q_OS_WIN) -#error Unsupported OS platform for this QtForPython gem -#endif - params.m_mainWindowId = 0; using namespace AzToolsFramework; QWidget* activeWindow = nullptr; diff --git a/Gems/QtForPython/Code/qtforpython_editor_macos_files.cmake b/Gems/QtForPython/Code/Source/qtforpython_editor_files.cmake similarity index 100% rename from Gems/QtForPython/Code/qtforpython_editor_macos_files.cmake rename to Gems/QtForPython/Code/Source/qtforpython_editor_files.cmake diff --git a/Gems/QtForPython/Code/qtforpython_editor_windows_files.cmake b/Gems/QtForPython/Code/qtforpython_editor_files.cmake similarity index 100% rename from Gems/QtForPython/Code/qtforpython_editor_windows_files.cmake rename to Gems/QtForPython/Code/qtforpython_editor_files.cmake diff --git a/Gems/ScriptCanvas/Code/Editor/View/Widgets/NodePalette/NodePaletteModel.cpp b/Gems/ScriptCanvas/Code/Editor/View/Widgets/NodePalette/NodePaletteModel.cpp index 947c49cd78..f128537e1a 100644 --- a/Gems/ScriptCanvas/Code/Editor/View/Widgets/NodePalette/NodePaletteModel.cpp +++ b/Gems/ScriptCanvas/Code/Editor/View/Widgets/NodePalette/NodePaletteModel.cpp @@ -877,6 +877,7 @@ namespace ScriptCanvasEditor void NodePaletteModel::RepopulateModel() { + AZ_PROFILE_FUNCTION(ScriptCanvas); ClearRegistry(); PopulateNodePaletteModel((*this)); diff --git a/Gems/ScriptCanvas/Code/Editor/View/Windows/MainWindow.cpp b/Gems/ScriptCanvas/Code/Editor/View/Windows/MainWindow.cpp index 1ad8b58317..e61b015aae 100644 --- a/Gems/ScriptCanvas/Code/Editor/View/Windows/MainWindow.cpp +++ b/Gems/ScriptCanvas/Code/Editor/View/Windows/MainWindow.cpp @@ -428,6 +428,8 @@ namespace ScriptCanvasEditor , m_closeCurrentGraphAfterSave(false) , m_styleManager(ScriptCanvasEditor::AssetEditorId, "ScriptCanvas/StyleSheet/graphcanvas_style.json") { + AZ_PROFILE_FUNCTION(ScriptCanvas); + VariablePaletteRequestBus::Handler::BusConnect(); GraphCanvas::AssetEditorAutomationRequestBus::Handler::BusConnect(ScriptCanvasEditor::AssetEditorId); diff --git a/Gems/Terrain/Assets/Editor/Icons/Components/TerrainHeight.svg b/Gems/Terrain/Assets/Editor/Icons/Components/TerrainHeight.svg index 57835e9c20..78af20cc2d 100644 --- a/Gems/Terrain/Assets/Editor/Icons/Components/TerrainHeight.svg +++ b/Gems/Terrain/Assets/Editor/Icons/Components/TerrainHeight.svg @@ -1,7 +1,5 @@ - - - icon / Environmental / Terrain Height - - - - \ No newline at end of file + + + + + diff --git a/Gems/Terrain/Assets/Editor/Icons/Components/TerrainLayerSpawner.svg b/Gems/Terrain/Assets/Editor/Icons/Components/TerrainLayerSpawner.svg index df73d78276..ad7403d976 100644 --- a/Gems/Terrain/Assets/Editor/Icons/Components/TerrainLayerSpawner.svg +++ b/Gems/Terrain/Assets/Editor/Icons/Components/TerrainLayerSpawner.svg @@ -1,7 +1,5 @@ - - - icon / Environmental / Generate Terrian - - - - \ No newline at end of file + + + + + diff --git a/Gems/Terrain/Assets/Editor/Icons/Components/TerrainMacroMaterial.svg b/Gems/Terrain/Assets/Editor/Icons/Components/TerrainMacroMaterial.svg new file mode 100644 index 0000000000..9a694bfbf7 --- /dev/null +++ b/Gems/Terrain/Assets/Editor/Icons/Components/TerrainMacroMaterial.svg @@ -0,0 +1,3 @@ + + + diff --git a/Gems/Terrain/Assets/Editor/Icons/Components/TerrainPhysicsCollider.svg b/Gems/Terrain/Assets/Editor/Icons/Components/TerrainPhysicsCollider.svg new file mode 100644 index 0000000000..56ffb05464 --- /dev/null +++ b/Gems/Terrain/Assets/Editor/Icons/Components/TerrainPhysicsCollider.svg @@ -0,0 +1,3 @@ + + + diff --git a/Gems/Terrain/Assets/Editor/Icons/Components/TerrainSurfaceGradientList.svg b/Gems/Terrain/Assets/Editor/Icons/Components/TerrainSurfaceGradientList.svg new file mode 100644 index 0000000000..c4e8ce79d2 --- /dev/null +++ b/Gems/Terrain/Assets/Editor/Icons/Components/TerrainSurfaceGradientList.svg @@ -0,0 +1,3 @@ + + + diff --git a/Gems/Terrain/Assets/Editor/Icons/Components/TerrainSurfaceMaterials.svg b/Gems/Terrain/Assets/Editor/Icons/Components/TerrainSurfaceMaterials.svg new file mode 100644 index 0000000000..5a25cb3be9 --- /dev/null +++ b/Gems/Terrain/Assets/Editor/Icons/Components/TerrainSurfaceMaterials.svg @@ -0,0 +1,3 @@ + + + diff --git a/Gems/Terrain/Assets/Editor/Icons/Components/TerrainWorld.svg b/Gems/Terrain/Assets/Editor/Icons/Components/TerrainWorld.svg index c6388d6215..f3c17f66e4 100644 --- a/Gems/Terrain/Assets/Editor/Icons/Components/TerrainWorld.svg +++ b/Gems/Terrain/Assets/Editor/Icons/Components/TerrainWorld.svg @@ -1,8 +1,5 @@ - - - icon / Environmental / Terrain Refactor - - - - - \ No newline at end of file + + + + + diff --git a/Gems/Terrain/Assets/Editor/Icons/Components/TerrainWorldDebugger.svg b/Gems/Terrain/Assets/Editor/Icons/Components/TerrainWorldDebugger.svg index bd1512afda..b128d0f316 100644 --- a/Gems/Terrain/Assets/Editor/Icons/Components/TerrainWorldDebugger.svg +++ b/Gems/Terrain/Assets/Editor/Icons/Components/TerrainWorldDebugger.svg @@ -1,8 +1,5 @@ - - - icon / Environmental / Terrain World Debugger - - - - - \ No newline at end of file + + + + + diff --git a/Gems/Terrain/Assets/Editor/Icons/Components/TerrainWorldRenderer.svg b/Gems/Terrain/Assets/Editor/Icons/Components/TerrainWorldRenderer.svg index ab3716ad5d..de97c005fc 100644 --- a/Gems/Terrain/Assets/Editor/Icons/Components/TerrainWorldRenderer.svg +++ b/Gems/Terrain/Assets/Editor/Icons/Components/TerrainWorldRenderer.svg @@ -1,8 +1,5 @@ - - - icon / Environmental / Terrain World Renderer - - - - - \ No newline at end of file + + + + + diff --git a/Gems/Terrain/Assets/Editor/Icons/Components/Viewport/TerrainHeight.svg b/Gems/Terrain/Assets/Editor/Icons/Components/Viewport/TerrainHeight.svg index b87a0b4d7e..87a2d199bd 100644 --- a/Gems/Terrain/Assets/Editor/Icons/Components/Viewport/TerrainHeight.svg +++ b/Gems/Terrain/Assets/Editor/Icons/Components/Viewport/TerrainHeight.svg @@ -1,25 +1,22 @@ - - - icon / Environmental / Terrain Height - box - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file + + + + + + + + + + + + + + + + + + + + + + diff --git a/Gems/Terrain/Assets/Editor/Icons/Components/Viewport/TerrainLayerSpawner.svg b/Gems/Terrain/Assets/Editor/Icons/Components/Viewport/TerrainLayerSpawner.svg index c078d32fe5..a89186819f 100644 --- a/Gems/Terrain/Assets/Editor/Icons/Components/Viewport/TerrainLayerSpawner.svg +++ b/Gems/Terrain/Assets/Editor/Icons/Components/Viewport/TerrainLayerSpawner.svg @@ -1,25 +1,22 @@ - - - icon / Environmental / Generate Terrian - box - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file + + + + + + + + + + + + + + + + + + + + + + diff --git a/Gems/Terrain/Assets/Editor/Icons/Components/Viewport/TerrainMacroMaterial.svg b/Gems/Terrain/Assets/Editor/Icons/Components/Viewport/TerrainMacroMaterial.svg new file mode 100644 index 0000000000..177469e46e --- /dev/null +++ b/Gems/Terrain/Assets/Editor/Icons/Components/Viewport/TerrainMacroMaterial.svg @@ -0,0 +1,16 @@ + + + + + + + + + + + + + + + + diff --git a/Gems/Terrain/Assets/Editor/Icons/Components/Viewport/TerrainPhysicsCollider.svg b/Gems/Terrain/Assets/Editor/Icons/Components/Viewport/TerrainPhysicsCollider.svg new file mode 100644 index 0000000000..302e585f6e --- /dev/null +++ b/Gems/Terrain/Assets/Editor/Icons/Components/Viewport/TerrainPhysicsCollider.svg @@ -0,0 +1,16 @@ + + + + + + + + + + + + + + + + diff --git a/Gems/Terrain/Assets/Editor/Icons/Components/Viewport/TerrainSurfaceGradientList.svg b/Gems/Terrain/Assets/Editor/Icons/Components/Viewport/TerrainSurfaceGradientList.svg new file mode 100644 index 0000000000..19cb144936 --- /dev/null +++ b/Gems/Terrain/Assets/Editor/Icons/Components/Viewport/TerrainSurfaceGradientList.svg @@ -0,0 +1,16 @@ + + + + + + + + + + + + + + + + diff --git a/Gems/Terrain/Assets/Editor/Icons/Components/Viewport/TerrainSurfaceMaterials.svg b/Gems/Terrain/Assets/Editor/Icons/Components/Viewport/TerrainSurfaceMaterials.svg new file mode 100644 index 0000000000..5179f61867 --- /dev/null +++ b/Gems/Terrain/Assets/Editor/Icons/Components/Viewport/TerrainSurfaceMaterials.svg @@ -0,0 +1,21 @@ + + + + + + + + + + + + + + + + + + + + + diff --git a/Gems/Terrain/Assets/Editor/Icons/Components/Viewport/TerrainWorld.svg b/Gems/Terrain/Assets/Editor/Icons/Components/Viewport/TerrainWorld.svg index 2aee65f2a8..5466395141 100644 --- a/Gems/Terrain/Assets/Editor/Icons/Components/Viewport/TerrainWorld.svg +++ b/Gems/Terrain/Assets/Editor/Icons/Components/Viewport/TerrainWorld.svg @@ -1,25 +1,22 @@ - - - icon / Environmental / Terrain Refactor - box - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file + + + + + + + + + + + + + + + + + + + + + + diff --git a/Gems/Terrain/Assets/Editor/Icons/Components/Viewport/TerrainWorldDebugger.svg b/Gems/Terrain/Assets/Editor/Icons/Components/Viewport/TerrainWorldDebugger.svg index 1b729ab73f..ea9935fefb 100644 --- a/Gems/Terrain/Assets/Editor/Icons/Components/Viewport/TerrainWorldDebugger.svg +++ b/Gems/Terrain/Assets/Editor/Icons/Components/Viewport/TerrainWorldDebugger.svg @@ -1,25 +1,22 @@ - - - icon / Environmental / Terrain World Debugger - box - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file + + + + + + + + + + + + + + + + + + + + + + diff --git a/Gems/Terrain/Assets/Editor/Icons/Components/Viewport/TerrainWorldRenderer.svg b/Gems/Terrain/Assets/Editor/Icons/Components/Viewport/TerrainWorldRenderer.svg index 4287508f10..af235047db 100644 --- a/Gems/Terrain/Assets/Editor/Icons/Components/Viewport/TerrainWorldRenderer.svg +++ b/Gems/Terrain/Assets/Editor/Icons/Components/Viewport/TerrainWorldRenderer.svg @@ -1,25 +1,22 @@ - - - icon / Environmental / Terrain World Renderer - box - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file + + + + + + + + + + + + + + + + + + + + + + diff --git a/Gems/Terrain/Assets/Materials/Terrain/DefaultPbrTerrain.material b/Gems/Terrain/Assets/Materials/Terrain/DefaultPbrTerrain.material index d2acc2516a..7cf249a10d 100644 --- a/Gems/Terrain/Assets/Materials/Terrain/DefaultPbrTerrain.material +++ b/Gems/Terrain/Assets/Materials/Terrain/DefaultPbrTerrain.material @@ -2,23 +2,5 @@ "description": "", "materialType": "PbrTerrain.materialtype", "parentMaterial": "", - "propertyLayoutVersion": 1, - "properties": { - "baseColor": { - "color": [ 0.18, 0.18, 0.18 ], - "useTexture": false - }, - "normal": - { - "useTexture": false - }, - "roughness": - { - "useTexture": false - }, - "specularF0": - { - "useTexture": false - } - } + "propertyLayoutVersion": 1 } diff --git a/Gems/Terrain/Code/Source/EditorComponents/EditorTerrainPhysicsColliderComponent.h b/Gems/Terrain/Code/Source/EditorComponents/EditorTerrainPhysicsColliderComponent.h index d2254161a0..924426c262 100644 --- a/Gems/Terrain/Code/Source/EditorComponents/EditorTerrainPhysicsColliderComponent.h +++ b/Gems/Terrain/Code/Source/EditorComponents/EditorTerrainPhysicsColliderComponent.h @@ -25,8 +25,8 @@ namespace Terrain static constexpr auto s_categoryName = "Terrain"; static constexpr auto s_componentName = "Terrain Physics Heightfield Collider"; static constexpr auto s_componentDescription = "Provides terrain data to a physics collider in the form of a heightfield and surface->material mapping."; - static constexpr auto s_icon = "Editor/Icons/Components/TerrainLayerSpawner.svg"; - static constexpr auto s_viewportIcon = "Editor/Icons/Components/Viewport/TerrainLayerSpawner.svg"; + static constexpr auto s_icon = "Editor/Icons/Components/TerrainPhysicsCollider.svg"; + static constexpr auto s_viewportIcon = "Editor/Icons/Components/Viewport/TerrainPhysicsCollider.svg"; static constexpr auto s_helpUrl = ""; }; } diff --git a/Gems/Terrain/Code/Source/EditorComponents/EditorTerrainSurfaceGradientListComponent.h b/Gems/Terrain/Code/Source/EditorComponents/EditorTerrainSurfaceGradientListComponent.h index e2c5f1b280..3cf9e7fc47 100644 --- a/Gems/Terrain/Code/Source/EditorComponents/EditorTerrainSurfaceGradientListComponent.h +++ b/Gems/Terrain/Code/Source/EditorComponents/EditorTerrainSurfaceGradientListComponent.h @@ -25,8 +25,8 @@ namespace Terrain static constexpr const char* const s_categoryName = "Terrain"; static constexpr const char* const s_componentName = "Terrain Surface Gradient List"; static constexpr const char* const s_componentDescription = "Provides a mapping between gradients and surface tags for use by the terrain system."; - static constexpr const char* const s_icon = "Editor/Icons/Components/TerrainLayerSpawner.svg"; - static constexpr const char* const s_viewportIcon = "Editor/Icons/Components/Viewport/TerrainLayerSpawner.svg"; + static constexpr const char* const s_icon = "Editor/Icons/Components/TerrainSurfaceGradientList.svg"; + static constexpr const char* const s_viewportIcon = "Editor/Icons/Components/Viewport/TerrainSurfaceGradientList.svg"; static constexpr const char* const s_helpUrl = ""; }; } diff --git a/Gems/Terrain/Code/Source/TerrainRenderer/EditorComponents/EditorTerrainMacroMaterialComponent.h b/Gems/Terrain/Code/Source/TerrainRenderer/EditorComponents/EditorTerrainMacroMaterialComponent.h index a2fddf5768..67897b7dec 100644 --- a/Gems/Terrain/Code/Source/TerrainRenderer/EditorComponents/EditorTerrainMacroMaterialComponent.h +++ b/Gems/Terrain/Code/Source/TerrainRenderer/EditorComponents/EditorTerrainMacroMaterialComponent.h @@ -25,8 +25,8 @@ namespace Terrain static constexpr const char* const s_categoryName = "Terrain"; static constexpr const char* const s_componentName = "Terrain Macro Material"; static constexpr const char* const s_componentDescription = "Provides a macro material for a region to the terrain renderer"; - static constexpr const char* const s_icon = "Editor/Icons/Components/TerrainLayerRenderer.svg"; - static constexpr const char* const s_viewportIcon = "Editor/Icons/Components/Viewport/TerrainLayerRenderer.svg"; + static constexpr const char* const s_icon = "Editor/Icons/Components/TerrainMacroMaterial.svg"; + static constexpr const char* const s_viewportIcon = "Editor/Icons/Components/Viewport/TerrainMacroMaterial.svg"; static constexpr const char* const s_helpUrl = ""; }; } diff --git a/Gems/Terrain/Code/Source/TerrainRenderer/EditorComponents/EditorTerrainSurfaceMaterialsListComponent.h b/Gems/Terrain/Code/Source/TerrainRenderer/EditorComponents/EditorTerrainSurfaceMaterialsListComponent.h index f0d03a6082..7fe8c82522 100644 --- a/Gems/Terrain/Code/Source/TerrainRenderer/EditorComponents/EditorTerrainSurfaceMaterialsListComponent.h +++ b/Gems/Terrain/Code/Source/TerrainRenderer/EditorComponents/EditorTerrainSurfaceMaterialsListComponent.h @@ -25,8 +25,8 @@ namespace Terrain static constexpr const char* const s_categoryName = "Terrain"; static constexpr const char* const s_componentName = "Terrain Surface Materials List"; static constexpr const char* const s_componentDescription = "Provides a mapping between surface tags and render materials."; - static constexpr const char* const s_icon = "Editor/Icons/Components/TerrainHeight.svg"; - static constexpr const char* const s_viewportIcon = "Editor/Icons/Components/Viewport/TerrainHeight.svg"; + static constexpr const char* const s_icon = "Editor/Icons/Components/TerrainSurfaceMaterials.svg"; + static constexpr const char* const s_viewportIcon = "Editor/Icons/Components/Viewport/TerrainSurfaceMaterials.svg"; static constexpr const char* const s_helpUrl = ""; }; } diff --git a/Templates/CMakeLists.txt b/Templates/CMakeLists.txt index 9735907a6a..5f5d561a9f 100644 --- a/Templates/CMakeLists.txt +++ b/Templates/CMakeLists.txt @@ -14,5 +14,6 @@ ly_install_directory( DefaultGem DefaultProject MinimalProject + GemRepo VERBATIM ) diff --git a/Templates/GemRepo/Template/gem.json b/Templates/GemRepo/Template/gem.json new file mode 100644 index 0000000000..292681b2b5 --- /dev/null +++ b/Templates/GemRepo/Template/gem.json @@ -0,0 +1,19 @@ +{ + "gem_name": "${Name}Gem", + "display_name": "${Name}Gem", + "license": "What license ${Name}Gem uses goes here: i.e. Apache-2.0 Or MIT", + "license_url": "", + "origin": "The primary repo for ${Name}Gem goes here: i.e. http://www.mydomain.com", + "summary": "A short description of ${Name}Gem which is zipped up in an archive named gem.zip in the root of the Gem Repo. Though not required, it is recommended that the sha256 of the gem.zip file should be placed in the sha256 field of this gem.json so the download can be verified.", + "origin_uri": "${RepoURI}/gem.zip", + "sha256": "", + "type": "Code", + "canonical_tags": [ + "Gem" + ], + "user_tags": [ + "${Name}Gem" + ], + "icon_path": "preview.png", + "requirements": "" +} diff --git a/Templates/GemRepo/Template/repo.json b/Templates/GemRepo/Template/repo.json new file mode 100644 index 0000000000..2af1fcfd2a --- /dev/null +++ b/Templates/GemRepo/Template/repo.json @@ -0,0 +1,11 @@ +{ + "repo_name":"${Name}", + "origin":"Origin for the ${Name} Gem Repository", + "repo_uri": "${RepoURI}", + "summary": "A Gem Repository with a single Gem in the root of the repository.", + "additional_info": "Additional info for ${Name}", + "last_updated": "", + "gems": [ + "${RepoURI}" + ] +} diff --git a/Templates/GemRepo/preview.png b/Templates/GemRepo/preview.png new file mode 100644 index 0000000000..78a2a735d2 --- /dev/null +++ b/Templates/GemRepo/preview.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:6ae503ec99c8358991dc3c6e50737844d3602b81a49abbbed7d697d7238547c0 +size 28026 diff --git a/Templates/GemRepo/template.json b/Templates/GemRepo/template.json new file mode 100644 index 0000000000..88123a9dae --- /dev/null +++ b/Templates/GemRepo/template.json @@ -0,0 +1,27 @@ +{ + "template_name": "GemRepo", + "origin": "The primary repo for GemRepo goes here: i.e. http://www.mydomain.com", + "license": "What license GemRepo uses goes here: i.e. https://opensource.org/licenses/MIT", + "display_name": "GemRepo", + "summary": "A Gem Repository that contains a single Gem.", + "canonical_tags": [], + "user_tags": [ + "GemRepo" + ], + "icon_path": "preview.png", + "copyFiles": [ + { + "file": "gem.json", + "origin": "gem.json", + "isTemplated": true, + "isOptional": false + }, + { + "file": "repo.json", + "origin": "repo.json", + "isTemplated": true, + "isOptional": false + } + ], + "createDirectories": [] +} diff --git a/cmake/3rdParty/Platform/Linux/BuiltInPackages_linux.cmake b/cmake/3rdParty/Platform/Linux/BuiltInPackages_linux.cmake index af46fd14e0..3ad49c6d7a 100644 --- a/cmake/3rdParty/Platform/Linux/BuiltInPackages_linux.cmake +++ b/cmake/3rdParty/Platform/Linux/BuiltInPackages_linux.cmake @@ -46,3 +46,4 @@ ly_associate_package(PACKAGE_NAME squish-ccr-deb557d-rev1-linux ly_associate_package(PACKAGE_NAME astc-encoder-3.2-rev2-linux TARGETS astc-encoder PACKAGE_HASH 71549d1ca9e4d48391b92a89ea23656d3393810e6777879f6f8a9def2db1610c) 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) +ly_associate_package(PACKAGE_NAME pyside2-5.15.2-rev2-linux TARGETS pyside2 PACKAGE_HASH 7589c397c8224d0c3ad691ff02e1afd55d9a1f9de1967c14eb8105dd2b0c4dd1) diff --git a/cmake/SettingsRegistry.cmake b/cmake/SettingsRegistry.cmake index c677aba7cf..e8c14ac8a0 100644 --- a/cmake/SettingsRegistry.cmake +++ b/cmake/SettingsRegistry.cmake @@ -33,6 +33,34 @@ set(gems_json_template [[ [=[ }]=] ) +#!ly_detect_cycle_through_visitation: Detects if there is a cycle based on a list of visited +# items. If the passed item is in the list, then there is a cycle. +# \arg:item - item being checked for the cycle +# \arg:visited_items - list of visited items +# \arg:visited_items_var - list of visited items variable, "item" will be added to the list +# \arg:cycle(variable) - empty string if there is no cycle (an empty string in cmake evaluates +# to false). If there is a cycle a cycle dependency string detailing the sequence of items +# that produce a cycle, e.g. A --> B --> C --> A +# +function(ly_detect_cycle_through_visitation item visited_items visited_items_var cycle) + if(item IN_LIST visited_items) + unset(dependency_cycle_loop) + foreach(visited_item IN LISTS visited_items) + string(APPEND dependency_cycle_loop ${visited_item}) + if(visited_item STREQUAL item) + string(APPEND dependency_cycle_loop " (cycle starts)") + endif() + string(APPEND dependency_cycle_loop " --> ") + endforeach() + string(APPEND dependency_cycle_loop "${item} (cycle ends)") + set(${cycle} "${dependency_cycle_loop}" PARENT_SCOPE) + else() + set(cycle "" PARENT_SCOPE) # no cycles + endif() + list(APPEND visited_items ${item}) + set(${visited_items_var} "${visited_items}" PARENT_SCOPE) +endfunction() + #!ly_get_gem_load_dependencies: Retrieves the list of "load" dependencies for a target # Visits through only MANUALLY_ADDED_DEPENDENCIES of targets with a GEM_MODULE property # to determine which gems a target needs to load @@ -44,6 +72,13 @@ function(ly_get_gem_load_dependencies ly_GEM_LOAD_DEPENDENCIES ly_TARGET) if(NOT TARGET ${ly_TARGET}) return() # Nothing to do endif() + # Internally we use a third parameter to pass the list of targets that we have traversed. This is + # used to detect runtime cycles + if(ARGC EQUAL 3) + set(ly_CYCLE_DETECTION_TARGETS ${ARGV2}) + else() + set(ly_CYCLE_DETECTION_TARGETS "") + endif() # Optimize the search by caching gem load dependencies get_property(are_dependencies_cached GLOBAL PROPERTY LY_GEM_LOAD_DEPENDENCIES_${ly_TARGET} SET) @@ -54,6 +89,13 @@ function(ly_get_gem_load_dependencies ly_GEM_LOAD_DEPENDENCIES ly_TARGET) return() endif() + # detect cycles + unset(cycle_detected) + ly_detect_cycle_through_visitation(${ly_TARGET} "${ly_CYCLE_DETECTION_TARGETS}" ly_CYCLE_DETECTION_TARGETS cycle_detected) + if(cycle_detected) + message(FATAL_ERROR "Runtime dependency detected: ${cycle_detected}") + endif() + unset(all_gem_load_dependencies) # For load dependencies, we want to copy over the dependency and traverse them @@ -69,7 +111,7 @@ function(ly_get_gem_load_dependencies ly_GEM_LOAD_DEPENDENCIES ly_TARGET) # and recurse into its manually added dependencies if (is_gem_target) unset(dependencies) - ly_get_gem_load_dependencies(dependencies ${dealias_load_dependency}) + ly_get_gem_load_dependencies(dependencies ${dealias_load_dependency} "${ly_CYCLE_DETECTION_TARGETS}") list(APPEND all_gem_load_dependencies ${dependencies}) list(APPEND all_gem_load_dependencies ${dealias_load_dependency}) endif() diff --git a/engine.json b/engine.json index 05ccd0abfd..2d182c78aa 100644 --- a/engine.json +++ b/engine.json @@ -90,6 +90,7 @@ "AutomatedTesting" ], "templates": [ + "Templates/GemRepo", "Templates/AssetGem", "Templates/DefaultGem", "Templates/DefaultProject", diff --git a/scripts/o3de/o3de/disable_gem.py b/scripts/o3de/o3de/disable_gem.py index 01324d8500..158507fca1 100644 --- a/scripts/o3de/o3de/disable_gem.py +++ b/scripts/o3de/o3de/disable_gem.py @@ -69,7 +69,7 @@ def disable_gem_in_project(gem_name: str = None, return 1 gem_path = pathlib.Path(gem_path).resolve() # make sure this gem already exists if we're adding. We can always remove a gem. - if not gem_path.is_dir(): + if not gem_path.exists(): logger.error(f'Gem Path {gem_path} does not exist.') return 1 diff --git a/scripts/o3de/o3de/download.py b/scripts/o3de/o3de/download.py index 9b7c8cc782..e88355bf06 100644 --- a/scripts/o3de/o3de/download.py +++ b/scripts/o3de/o3de/download.py @@ -44,30 +44,34 @@ def validate_downloaded_zip_sha256(download_uri_json_data: dict, download_zip_pa try: sha256A = download_uri_json_data['sha256'] except KeyError as e: - logger.warn('SECURITY WARNING: The advertised o3de object you downloaded has no "sha256"!!! Be VERY careful!!!' + logger.warning('SECURITY WARNING: The advertised o3de object you downloaded has no "sha256"!!! Be VERY careful!!!' ' We cannot verify this is the actually the advertised object!!!') return 1 else: - sha256B = hashlib.sha256(download_zip_path.open('rb').read()).hexdigest() - if sha256A != sha256B: - logger.error(f'SECURITY VIOLATION: Downloaded zip sha256 {sha256B} does not match' - f' the advertised "sha256":{sha256A} in the f{manifest_json_name}.') - return 0 + if len(sha256A) == 0: + logger.warning('SECURITY WARNING: The advertised o3de object you downloaded has no "sha256"!!! Be VERY careful!!!' + ' We cannot verify this is the actually the advertised object!!!') + return 1 + + with download_zip_path.open('rb') as f: + sha256B = hashlib.sha256(f.read()).hexdigest() + if sha256A != sha256B: + logger.error(f'SECURITY VIOLATION: Downloaded zip sha256 {sha256B} does not match' + f' the advertised "sha256":{sha256A} in the f{manifest_json_name}.') + return 0 unzipped_manifest_json_data = unzip_manifest_json_data(download_zip_path, manifest_json_name) - # remove the sha256 if present in the advertised downloadable manifest json - # then compare it to the json in the zip, they should now be identical - try: - del download_uri_json_data['sha256'] - except KeyError as e: - pass + # do not include the data we know will not match/exist + for key in ['sha256','repo_name']: + if key in download_uri_json_data: + del download_uri_json_data[key] + if key in unzipped_manifest_json_data: + del unzipped_manifest_json_data[key] - sha256A = hashlib.sha256(json.dumps(download_uri_json_data, indent=4).encode('utf8')).hexdigest() - sha256B = hashlib.sha256(json.dumps(unzipped_manifest_json_data, indent=4).encode('utf8')).hexdigest() - if sha256A != sha256B: - logger.error('SECURITY VIOLATION: Downloaded manifest json does not match' - ' the advertised manifest json.') + if download_uri_json_data != unzipped_manifest_json_data: + logger.error(f'SECURITY VIOLATION: Downloaded {manifest_json_name} contents do not match' + ' the advertised manifest json contents.') return 0 return 1 @@ -102,7 +106,7 @@ def download_o3de_object(object_name: str, default_folder_name: str, dest_path: logger.error(f'Downloadable o3de object {object_name} not found.') return 1 - origin_uri = downloadable_object_data['originuri'] + origin_uri = downloadable_object_data['origin_uri'] parsed_uri = urllib.parse.urlparse(origin_uri) download_zip_result = utils.download_zip_file(parsed_uri, download_zip_path, force_overwrite, download_progress_callback) @@ -237,13 +241,13 @@ def is_o3de_object_update_available(object_name: str, downloadable_kwarg_key, lo try: repo_copy_updated_string = downloadable_object_data['last_updated'] except KeyError: - logger.warn(f'last_updated field not found for {object_name}.') + logger.warning(f'last_updated field not found for {object_name}.') return False try: local_last_updated_time = datetime.fromisoformat(local_last_updated) except ValueError: - logger.warn(f'last_updated field has incorrect format for local copy of {downloadable_kwarg_key} {object_name}.') + logger.warning(f'last_updated field has incorrect format for local copy of {downloadable_kwarg_key} {object_name}.') # Possible that an earlier version did not have this field so still want to check against cached downloadable version local_last_updated_time = datetime.min diff --git a/scripts/o3de/o3de/manifest.py b/scripts/o3de/o3de/manifest.py index 297d8e39d2..e46b819a7c 100644 --- a/scripts/o3de/o3de/manifest.py +++ b/scripts/o3de/o3de/manifest.py @@ -108,75 +108,79 @@ def get_o3de_third_party_folder() -> pathlib.Path: # o3de manifest file methods +def get_default_o3de_manifest_json_data() -> dict: + """ + Returns dict with default values suitable for storing + in the o3de_manifests.json + """ + username = os.path.split(get_home_folder())[-1] + + o3de_folder = get_o3de_folder() + default_engines_folder = get_o3de_engines_folder() + default_projects_folder = get_o3de_projects_folder() + default_gems_folder = get_o3de_gems_folder() + default_templates_folder = get_o3de_templates_folder() + default_restricted_folder = get_o3de_restricted_folder() + default_third_party_folder = get_o3de_third_party_folder() + + default_projects_restricted_folder = default_projects_folder / 'Restricted' + default_projects_restricted_folder.mkdir(parents=True, exist_ok=True) + default_gems_restricted_folder = default_gems_folder / 'Restricted' + default_gems_restricted_folder.mkdir(parents=True, exist_ok=True) + default_templates_restricted_folder = default_templates_folder / 'Restricted' + default_templates_restricted_folder.mkdir(parents=True, exist_ok=True) + + json_data = {} + json_data.update({'o3de_manifest_name': f'{username}'}) + json_data.update({'origin': o3de_folder.as_posix()}) + json_data.update({'default_engines_folder': default_engines_folder.as_posix()}) + json_data.update({'default_projects_folder': default_projects_folder.as_posix()}) + json_data.update({'default_gems_folder': default_gems_folder.as_posix()}) + json_data.update({'default_templates_folder': default_templates_folder.as_posix()}) + json_data.update({'default_restricted_folder': default_restricted_folder.as_posix()}) + json_data.update({'default_third_party_folder': default_third_party_folder.as_posix()}) + + json_data.update({'engines': []}) + json_data.update({'projects': []}) + json_data.update({'external_subdirectories': []}) + json_data.update({'templates': []}) + json_data.update({'restricted': []}) + json_data.update({'repos': []}) + + default_restricted_folder_json = default_restricted_folder / 'restricted.json' + if not default_restricted_folder_json.is_file(): + with default_restricted_folder_json.open('w') as s: + restricted_json_data = {} + restricted_json_data.update({'restricted_name': 'o3de'}) + s.write(json.dumps(restricted_json_data, indent=4) + '\n') + + default_projects_restricted_folder_json = default_projects_restricted_folder / 'restricted.json' + if not default_projects_restricted_folder_json.is_file(): + with default_projects_restricted_folder_json.open('w') as s: + restricted_json_data = {} + restricted_json_data.update({'restricted_name': 'projects'}) + s.write(json.dumps(restricted_json_data, indent=4) + '\n') + + default_gems_restricted_folder_json = default_gems_restricted_folder / 'restricted.json' + if not default_gems_restricted_folder_json.is_file(): + with default_gems_restricted_folder_json.open('w') as s: + restricted_json_data = {} + restricted_json_data.update({'restricted_name': 'gems'}) + s.write(json.dumps(restricted_json_data, indent=4) + '\n') + + default_templates_restricted_folder_json = default_templates_restricted_folder / 'restricted.json' + if not default_templates_restricted_folder_json.is_file(): + with default_templates_restricted_folder_json.open('w') as s: + restricted_json_data = {} + restricted_json_data.update({'restricted_name': 'templates'}) + s.write(json.dumps(restricted_json_data, indent=4) + '\n') + + return json_data + def get_o3de_manifest() -> pathlib.Path: manifest_path = get_o3de_folder() / 'o3de_manifest.json' if not manifest_path.is_file(): - username = os.path.split(get_home_folder())[-1] - - o3de_folder = get_o3de_folder() - default_registry_folder = get_o3de_registry_folder() - default_cache_folder = get_o3de_cache_folder() - default_downloads_folder = get_o3de_download_folder() - default_logs_folder = get_o3de_logs_folder() - default_engines_folder = get_o3de_engines_folder() - default_projects_folder = get_o3de_projects_folder() - default_gems_folder = get_o3de_gems_folder() - default_templates_folder = get_o3de_templates_folder() - default_restricted_folder = get_o3de_restricted_folder() - default_third_party_folder = get_o3de_third_party_folder() - - default_projects_restricted_folder = default_projects_folder / 'Restricted' - default_projects_restricted_folder.mkdir(parents=True, exist_ok=True) - default_gems_restricted_folder = default_gems_folder / 'Restricted' - default_gems_restricted_folder.mkdir(parents=True, exist_ok=True) - default_templates_restricted_folder = default_templates_folder / 'Restricted' - default_templates_restricted_folder.mkdir(parents=True, exist_ok=True) - - json_data = {} - json_data.update({'o3de_manifest_name': f'{username}'}) - json_data.update({'origin': o3de_folder.as_posix()}) - json_data.update({'default_engines_folder': default_engines_folder.as_posix()}) - json_data.update({'default_projects_folder': default_projects_folder.as_posix()}) - json_data.update({'default_gems_folder': default_gems_folder.as_posix()}) - json_data.update({'default_templates_folder': default_templates_folder.as_posix()}) - json_data.update({'default_restricted_folder': default_restricted_folder.as_posix()}) - json_data.update({'default_third_party_folder': default_third_party_folder.as_posix()}) - - json_data.update({'engines': []}) - json_data.update({'projects': []}) - json_data.update({'external_subdirectories': []}) - json_data.update({'templates': []}) - json_data.update({'restricted': []}) - json_data.update({'repos': []}) - - default_restricted_folder_json = default_restricted_folder / 'restricted.json' - if not default_restricted_folder_json.is_file(): - with default_restricted_folder_json.open('w') as s: - restricted_json_data = {} - restricted_json_data.update({'restricted_name': 'o3de'}) - s.write(json.dumps(restricted_json_data, indent=4) + '\n') - json_data.update({'default_restricted_folder': default_restricted_folder.as_posix()}) - - default_projects_restricted_folder_json = default_projects_restricted_folder / 'restricted.json' - if not default_projects_restricted_folder_json.is_file(): - with default_projects_restricted_folder_json.open('w') as s: - restricted_json_data = {} - restricted_json_data.update({'restricted_name': 'projects'}) - s.write(json.dumps(restricted_json_data, indent=4) + '\n') - - default_gems_restricted_folder_json = default_gems_restricted_folder / 'restricted.json' - if not default_gems_restricted_folder_json.is_file(): - with default_gems_restricted_folder_json.open('w') as s: - restricted_json_data = {} - restricted_json_data.update({'restricted_name': 'gems'}) - s.write(json.dumps(restricted_json_data, indent=4) + '\n') - - default_templates_restricted_folder_json = default_templates_restricted_folder / 'restricted.json' - if not default_templates_restricted_folder_json.is_file(): - with default_templates_restricted_folder_json.open('w') as s: - restricted_json_data = {} - restricted_json_data.update({'restricted_name': 'templates'}) - s.write(json.dumps(restricted_json_data, indent=4) + '\n') + json_data = get_default_o3de_manifest_json_data() with manifest_path.open('w') as s: s.write(json.dumps(json_data, indent=4) + '\n') @@ -188,6 +192,7 @@ def load_o3de_manifest(manifest_path: pathlib.Path = None) -> dict: """ Loads supplied manifest file or ~/.o3de/o3de_manifest.json if None + raises Json.JSONDecodeError if manifest data could not be decoded to JSON :param manifest_path: optional path to manifest file to load """ if not manifest_path: @@ -196,8 +201,10 @@ def load_o3de_manifest(manifest_path: pathlib.Path = None) -> dict: try: json_data = json.load(f) except json.JSONDecodeError as e: - logger.error(f'Manifest json failed to load: {str(e)}') - return {} + logger.error(f'Manifest json failed to load at path "{manifest_path}": {str(e)}') + # Re-raise the exception and let the caller + # determine if they can proceed + raise else: return json_data @@ -455,7 +462,7 @@ def get_json_data_file(object_json: pathlib.Path, try: object_json_data = json.load(f) except json.JSONDecodeError as e: - logger.warn(f'{object_json} failed to load: {e}') + logger.warning(f'{object_json} failed to load: {e}') else: return object_json_data @@ -589,14 +596,14 @@ def get_registered(engine_name: str = None, if isinstance(engine, dict): engine_path = pathlib.Path(engine['path']).resolve() else: - engine_path = pathlib.Path(engine_object).resolve() + engine_path = pathlib.Path(engine).resolve() engine_json = engine_path / 'engine.json' with engine_json.open('r') as f: try: engine_json_data = json.load(f) except json.JSONDecodeError as e: - logger.warn(f'{engine_json} failed to load: {str(e)}') + logger.warning(f'{engine_json} failed to load: {str(e)}') else: this_engines_name = engine_json_data['engine_name'] if this_engines_name == engine_name: @@ -611,7 +618,7 @@ def get_registered(engine_name: str = None, try: project_json_data = json.load(f) except json.JSONDecodeError as e: - logger.warn(f'{project_json} failed to load: {str(e)}') + logger.warning(f'{project_json} failed to load: {str(e)}') else: this_projects_name = project_json_data['project_name'] if this_projects_name == project_name: @@ -626,7 +633,7 @@ def get_registered(engine_name: str = None, try: gem_json_data = json.load(f) except json.JSONDecodeError as e: - logger.warn(f'{gem_json} failed to load: {str(e)}') + logger.warning(f'{gem_json} failed to load: {str(e)}') else: this_gems_name = gem_json_data['gem_name'] if this_gems_name == gem_name: @@ -641,7 +648,7 @@ def get_registered(engine_name: str = None, try: template_json_data = json.load(f) except json.JSONDecodeError as e: - logger.warn(f'{template_path} failed to load: {str(e)}') + logger.warning(f'{template_path} failed to load: {str(e)}') else: this_templates_name = template_json_data['template_name'] if this_templates_name == template_name: @@ -656,7 +663,7 @@ def get_registered(engine_name: str = None, try: restricted_json_data = json.load(f) except json.JSONDecodeError as e: - logger.warn(f'{restricted_json} failed to load: {str(e)}') + logger.warning(f'{restricted_json} failed to load: {str(e)}') else: this_restricted_name = restricted_json_data['restricted_name'] if this_restricted_name == restricted_name: @@ -689,7 +696,7 @@ def get_registered(engine_name: str = None, try: repo_json_data = json.load(f) except json.JSONDecodeError as e: - logger.warn(f'{cache_file} failed to load: {str(e)}') + logger.warning(f'{cache_file} failed to load: {str(e)}') else: this_repos_name = repo_json_data['repo_name'] if this_repos_name == repo_name: diff --git a/scripts/o3de/o3de/print_registration.py b/scripts/o3de/o3de/print_registration.py index b164243b7c..4b4c9d6515 100644 --- a/scripts/o3de/o3de/print_registration.py +++ b/scripts/o3de/o3de/print_registration.py @@ -326,7 +326,7 @@ def print_repos_data(repos_data: dict) -> int: try: repo_json_data = json.load(s) except json.JSONDecodeError as e: - logger.warn(f'{cache_file} failed to load: {str(e)}') + logger.warning(f'{cache_file} failed to load: {str(e)}') else: print(f'{repo_uri}/repo.json cached as:') print(cache_file) diff --git a/scripts/o3de/o3de/register.py b/scripts/o3de/o3de/register.py index 8a2bb788aa..2500df1568 100644 --- a/scripts/o3de/o3de/register.py +++ b/scripts/o3de/o3de/register.py @@ -485,12 +485,12 @@ def register_repo(json_data: dict, json_data['repos'].remove(repo_uri) if remove: - logger.warn(f'Removing repo uri {repo_uri}.') + logger.warning(f'Removing repo uri {repo_uri}.') return 0 repo_sha256 = hashlib.sha256(url.encode()) cache_file = manifest.get_o3de_cache_folder() / str(repo_sha256.hexdigest() + '.json') - result = utils.download_file(parsed_uri, cache_file) + result = utils.download_file(parsed_uri, cache_file, True) if result == 0: json_data.setdefault('repos', []).insert(0, repo_uri) @@ -560,6 +560,107 @@ def register_default_third_party_folder(json_data: dict, manifest.get_o3de_third_party_folder() if remove else default_third_party_folder, 'default_third_party_folder') + +def remove_invalid_o3de_projects(manifest_path: pathlib.Path = None) -> int: + if not manifest_path: + manifest_path = manifest.get_o3de_manifest() + + json_data = manifest.load_o3de_manifest(manifest_path) + + result = 0 + + for project in json_data.get('projects', []): + if not validation.valid_o3de_project_json(pathlib.Path(project).resolve() / 'project.json'): + logger.warning(f"Project path {project} is invalid.") + # Attempt to unregister all invalid projects even if previous projects failed to unregister + # but combine the result codes of each command. + result = register(project_path=pathlib.Path(project), remove=True) or result + + return result + + +def remove_invalid_o3de_objects() -> None: + for engine_path in manifest.get_engines(): + if not validation.valid_o3de_engine_json(pathlib.Path(engine_path).resolve() / 'engine.json'): + logger.warning(f"Engine path {engine_path} is invalid.") + register(engine_path=engine_path, remove=True) + + remove_invalid_o3de_projects() + + for external in manifest.get_external_subdirectories(): + external = pathlib.Path(external).resolve() + if not external.is_dir(): + logger.warning(f"External subdirectory {external} is invalid.") + register(engine_path=engine_path, external_subdir_path=external, remove=True) + + for template in manifest.get_templates(): + if not validation.valid_o3de_template_json(pathlib.Path(template).resolve() / 'template.json'): + logger.warning(f"Template path {template} is invalid.") + register(template_path=template, remove=True) + + for restricted in manifest.get_restricted(): + if not validation.valid_o3de_restricted_json(pathlib.Path(restricted).resolve() / 'restricted.json'): + logger.warning(f"Restricted path {restricted} is invalid.") + register(restricted_path=restricted, remove=True) + + json_data = manifest.load_o3de_manifest() + default_engines_folder = pathlib.Path( + json_data.get('default_engines_folder', manifest.get_o3de_engines_folder())).resolve() + if not default_engines_folder.is_dir(): + new_default_engines_folder = manifest.get_o3de_folder() / 'Engines' + new_default_engines_folder.mkdir(parents=True, exist_ok=True) + logger.warning( + f"Default engines folder {default_engines_folder} is invalid. Set default {new_default_engines_folder}") + register(default_engines_folder=new_default_engines_folder.as_posix()) + + default_projects_folder = pathlib.Path( + json_data.get('default_projects_folder', manifest.get_o3de_projects_folder())).resolve() + if not default_projects_folder.is_dir(): + new_default_projects_folder = manifest.get_o3de_folder() / 'Projects' + new_default_projects_folder.mkdir(parents=True, exist_ok=True) + logger.warning( + f"Default projects folder {default_projects_folder} is invalid. Set default {new_default_projects_folder}") + register(default_projects_folder=new_default_projects_folder.as_posix()) + + default_gems_folder = pathlib.Path(json_data.get('default_gems_folder', manifest.get_o3de_gems_folder())).resolve() + if not default_gems_folder.is_dir(): + new_default_gems_folder = manifest.get_o3de_folder() / 'Gems' + new_default_gems_folder.mkdir(parents=True, exist_ok=True) + logger.warning(f"Default gems folder {default_gems_folder} is invalid." + f" Set default {new_default_gems_folder}") + register(default_gems_folder=new_default_gems_folder.as_posix()) + + default_templates_folder = pathlib.Path( + json_data.get('default_templates_folder', manifest.get_o3de_templates_folder())).resolve() + if not default_templates_folder.is_dir(): + new_default_templates_folder = manifest.get_o3de_folder() / 'Templates' + new_default_templates_folder.mkdir(parents=True, exist_ok=True) + logger.warning( + f"Default templates folder {default_templates_folder} is invalid." + f" Set default {new_default_templates_folder}") + register(default_templates_folder=new_default_templates_folder.as_posix()) + + default_restricted_folder = pathlib.Path( + json_data.get('default_restricted_folder', manifest.get_o3de_restricted_folder())).resolve() + if not default_restricted_folder.is_dir(): + default_restricted_folder = manifest.get_o3de_folder() / 'Restricted' + default_restricted_folder.mkdir(parents=True, exist_ok=True) + logger.warning( + f"Default restricted folder {default_restricted_folder} is invalid." + f" Set default {default_restricted_folder}") + register(default_restricted_folder=default_restricted_folder.as_posix()) + + default_third_party_folder = pathlib.Path( + json_data.get('default_third_party_folder', manifest.get_o3de_third_party_folder())).resolve() + if not default_third_party_folder.is_dir(): + default_third_party_folder = manifest.get_o3de_folder() / '3rdParty' + default_third_party_folder.mkdir(parents=True, exist_ok=True) + logger.warning( + f"Default 3rd Party folder {default_third_party_folder} is invalid." + f" Set default {default_third_party_folder}") + register(default_third_party_folder=default_third_party_folder.as_posix()) + + def register(engine_path: pathlib.Path = None, project_path: pathlib.Path = None, gem_path: pathlib.Path = None, @@ -604,7 +705,18 @@ def register(engine_path: pathlib.Path = None, :return: 0 for success or non 0 failure code """ - json_data = manifest.load_o3de_manifest() + try: + json_data = manifest.load_o3de_manifest() + except json.JSONDecodeError: + if not force: + logger.error('O3DE object registration has halted due to JSON Decode Error in manifest at path:' + f' "{manifest.get_o3de_manifest()}".' + '\n Registration can be forced using the --force option,' + ' but that will result in the manifest using default data') + return 1 + else: + # Use a default manifest data an proceed + json_data = manifest.get_default_o3de_manifest_json_data() result = 0 @@ -679,99 +791,6 @@ def register(engine_path: pathlib.Path = None, return result -def remove_invalid_o3de_projects(manifest_path: pathlib.Path = None) -> int: - if not manifest_path: - manifest_path = manifest.get_o3de_manifest() - - json_data = manifest.load_o3de_manifest(manifest_path) - - result = 0 - - for project in json_data.get('projects', []): - if not validation.valid_o3de_project_json(pathlib.Path(project).resolve() / 'project.json'): - logger.warn(f"Project path {project} is invalid.") - # Attempt to unregister all invalid projects even if previous projects failed to unregister - # but combine the result codes of each command. - result = register(project_path=pathlib.Path(project), remove=True) or result - - return result - -def remove_invalid_o3de_objects() -> None: - for engine_path in manifest.get_engines(): - if not validation.valid_o3de_engine_json(pathlib.Path(engine_path).resolve() / 'engine.json'): - logger.warn(f"Engine path {engine_path} is invalid.") - register(engine_path=engine_path, remove=True) - - remove_invalid_o3de_projects() - - for external in manifest.get_external_subdirectories(): - external = pathlib.Path(external).resolve() - if not external.is_dir(): - logger.warn(f"External subdirectory {external} is invalid.") - register(engine_path=engine_path, external_subdir_path=external, remove=True) - - for template in manifest.get_templates(): - if not validation.valid_o3de_template_json(pathlib.Path(template).resolve() / 'template.json'): - logger.warn(f"Template path {template} is invalid.") - register(template_path=template, remove=True) - - for restricted in manifest.get_restricted(): - if not validation.valid_o3de_restricted_json(pathlib.Path(restricted).resolve() / 'restricted.json'): - logger.warn(f"Restricted path {restricted} is invalid.") - register(restricted_path=restricted, remove=True) - - json_data = manifest.load_o3de_manifest() - default_engines_folder = pathlib.Path(json_data.get('default_engines_folder', manifest.get_o3de_engines_folder())).resolve() - if not default_engines_folder.is_dir(): - new_default_engines_folder = manifest.get_o3de_folder() / 'Engines' - new_default_engines_folder.mkdir(parents=True, exist_ok=True) - logger.warn( - f"Default engines folder {default_engines_folder} is invalid. Set default {new_default_engines_folder}") - register(default_engines_folder=new_default_engines_folder.as_posix()) - - default_projects_folder = pathlib.Path(json_data.get('default_projects_folder', manifest.get_o3de_projects_folder())).resolve() - if not default_projects_folder.is_dir(): - new_default_projects_folder = manifest.get_o3de_folder() / 'Projects' - new_default_projects_folder.mkdir(parents=True, exist_ok=True) - logger.warn( - f"Default projects folder {default_projects_folder} is invalid. Set default {new_default_projects_folder}") - register(default_projects_folder=new_default_projects_folder.as_posix()) - - default_gems_folder = pathlib.Path(json_data.get('default_gems_folder', manifest.get_o3de_gems_folder())).resolve() - if not default_gems_folder.is_dir(): - new_default_gems_folder = manifest.get_o3de_folder() / 'Gems' - new_default_gems_folder.mkdir(parents=True, exist_ok=True) - logger.warn(f"Default gems folder {default_gems_folder} is invalid." - f" Set default {new_default_gems_folder}") - register(default_gems_folder=new_default_gems_folder.as_posix()) - - default_templates_folder = pathlib.Path(json_data.get('default_templates_folder', manifest.get_o3de_templates_folder())).resolve() - if not default_templates_folder.is_dir(): - new_default_templates_folder = manifest.get_o3de_folder() / 'Templates' - new_default_templates_folder.mkdir(parents=True, exist_ok=True) - logger.warn( - f"Default templates folder {default_templates_folder} is invalid." - f" Set default {new_default_templates_folder}") - register(default_templates_folder=new_default_templates_folder.as_posix()) - - default_restricted_folder = pathlib.Path(json_data.get('default_restricted_folder', manifest.get_o3de_restricted_folder())).resolve() - if not default_restricted_folder.is_dir(): - default_restricted_folder = manifest.get_o3de_folder() / 'Restricted' - default_restricted_folder.mkdir(parents=True, exist_ok=True) - logger.warn( - f"Default restricted folder {default_restricted_folder} is invalid." - f" Set default {default_restricted_folder}") - register(default_restricted_folder=default_restricted_folder.as_posix()) - - default_third_party_folder = pathlib.Path(json_data.get('default_third_party_folder', manifest.get_o3de_third_party_folder())).resolve() - if not default_third_party_folder.is_dir(): - default_third_party_folder = manifest.get_o3de_folder() / '3rdParty' - default_third_party_folder.mkdir(parents=True, exist_ok=True) - logger.warn( - f"Default 3rd Party folder {default_third_party_folder} is invalid." - f" Set default {default_third_party_folder}") - register(default_third_party_folder=default_third_party_folder.as_posix()) - def _run_register(args: argparse) -> int: if args.override_home_folder: diff --git a/scripts/o3de/o3de/repo.py b/scripts/o3de/o3de/repo.py index c8fac38605..22c7c54c8f 100644 --- a/scripts/o3de/o3de/repo.py +++ b/scripts/o3de/o3de/repo.py @@ -9,7 +9,6 @@ import json import logging import pathlib -import shutil import urllib.parse import urllib.request import hashlib @@ -24,6 +23,7 @@ def process_add_o3de_repo(file_name: str or pathlib.Path, repo_set: set) -> int: file_name = pathlib.Path(file_name).resolve() if not validation.valid_o3de_repo_json(file_name): + logger.error(f'Repository JSON {file_name} could not be loaded or is missing required values') return 1 cache_folder = manifest.get_o3de_cache_folder() @@ -114,7 +114,7 @@ def get_gem_json_paths_from_cached_repo(repo_uri: str) -> set: file_name = pathlib.Path(cache_filename).resolve() if not file_name.is_file(): - logger.error(f'Could not find cached repo json file for {repo_uri}') + logger.error(f'Could not find cached repository json file for {repo_uri}. Try refreshing the repository.') return gem_set with file_name.open('r') as f: @@ -139,7 +139,7 @@ def get_gem_json_paths_from_cached_repo(repo_uri: str) -> set: if cache_gem_json_filepath.is_file(): gem_set.add(cache_gem_json_filepath) else: - logger.warn(f'Could not find cached gem json file {cache_gem_json_filepath} for {o3de_object_uri} in repo {repo_uri}') + logger.warning(f'Could not find cached gem json file {cache_gem_json_filepath} for {o3de_object_uri} in repo {repo_uri}') return gem_set @@ -167,6 +167,7 @@ def refresh_repo(repo_uri: str, download_file_result = utils.download_file(parsed_uri, cache_file, True) if download_file_result != 0: + logger.error(f'Repo json {repo_uri} could not download.') return download_file_result if not validation.valid_o3de_repo_json(cache_file): @@ -217,10 +218,10 @@ def search_repo(manifest_json_data: dict, json_key = 'gem_name' search_func = lambda manifest_json_data: manifest_json_data if manifest_json_data.get(json_key, '') == gem_name else None elif isinstance(template_name, str) or isinstance(template_name, pathlib.PurePath): - o3de_object_uris = manifest_json_data['template'] + o3de_object_uris = manifest_json_data['templates'] manifest_json = 'template.json' json_key = 'template_name' - search_func = lambda manifest_json_data: manifest_json_data if manifest_json_data.get(json_key, '') == template_name_name else None + search_func = lambda manifest_json_data: manifest_json_data if manifest_json_data.get(json_key, '') == template_name else None elif isinstance(restricted_name, str) or isinstance(restricted_name, pathlib.PurePath): o3de_object_uris = manifest_json_data['restricted'] manifest_json = 'restricted.json' @@ -257,7 +258,7 @@ def search_o3de_object(manifest_json, o3de_object_uris, search_func): try: manifest_json_data = json.load(f) except json.JSONDecodeError as e: - logger.warn(f'{cache_file} failed to load: {str(e)}') + logger.warning(f'{cache_file} failed to load: {str(e)}') else: result_json_data = search_func(manifest_json_data) if result_json_data: diff --git a/scripts/o3de/o3de/utils.py b/scripts/o3de/o3de/utils.py index 88f84ae75e..6f1dd8b2c5 100644 --- a/scripts/o3de/o3de/utils.py +++ b/scripts/o3de/o3de/utils.py @@ -125,7 +125,8 @@ def download_file(parsed_uri, download_path: pathlib.Path, force_overwrite: bool """ if download_path.is_file(): if not force_overwrite: - logger.warn(f'File already downloaded to {download_path}.') + logger.error(f'File already downloaded to {download_path} and force_overwrite is not set.') + return 1 else: try: os.unlink(download_path) @@ -134,20 +135,25 @@ def download_file(parsed_uri, download_path: pathlib.Path, force_overwrite: bool return 1 if parsed_uri.scheme in ['http', 'https', 'ftp', 'ftps']: - with urllib.request.urlopen(parsed_uri.geturl()) as s: - download_file_size = 0 - try: - download_file_size = s.headers['content-length'] - except KeyError: - pass - def download_progress(downloaded_bytes): - if download_progress_callback: - return download_progress_callback(int(downloaded_bytes), int(download_file_size)) - return False - with download_path.open('wb') as f: - download_cancelled = copyfileobj(s, f, download_progress) - if download_cancelled: - return 1 + try: + with urllib.request.urlopen(parsed_uri.geturl()) as s: + download_file_size = 0 + try: + download_file_size = s.headers['content-length'] + except KeyError: + pass + def download_progress(downloaded_bytes): + if download_progress_callback: + return download_progress_callback(int(downloaded_bytes), int(download_file_size)) + return False + with download_path.open('wb') as f: + download_cancelled = copyfileobj(s, f, download_progress) + if download_cancelled: + logger.info(f'Download of file to {download_path} cancelled.') + return 1 + except urllib.error.HTTPError as e: + logger.error(f'HTTP Error {e.code} opening {parsed_uri.geturl()}') + return 1 else: origin_file = pathlib.Path(parsed_uri.geturl()).resolve() if not origin_file.is_file(): @@ -167,7 +173,7 @@ def download_zip_file(parsed_uri, download_zip_path: pathlib.Path, force_overwri return download_file_result if not zipfile.is_zipfile(download_zip_path): - logger.error(f"File zip {download_zip_path} is invalid.") + logger.error(f"File zip {download_zip_path} is invalid. Try re-downloading the file.") download_zip_path.unlink() return 1