diff --git a/AutomatedTesting/Assets/ImageGradients/image_grad_test_gsi.png b/AutomatedTesting/Assets/ImageGradients/image_grad_test_gsi.png new file mode 100644 index 0000000000..228aa877ce --- /dev/null +++ b/AutomatedTesting/Assets/ImageGradients/image_grad_test_gsi.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:171f38d536d7b805cc644513d22dae5552a4eef2bffb88e97e089898cf769530 +size 2126 diff --git a/AutomatedTesting/Assets/ImageGradients/lumberyard_gsi.png b/AutomatedTesting/Assets/ImageGradients/lumberyard_gsi.png deleted file mode 100644 index eab76f1f78..0000000000 --- a/AutomatedTesting/Assets/ImageGradients/lumberyard_gsi.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:6388466c97009fd3993e5d3b59a2b0961f623c6becbd0a12a0a5eb7bd8da5d4e -size 12302 diff --git a/AutomatedTesting/Gem/Editor/Scripts/__init__.py b/AutomatedTesting/Gem/Editor/Scripts/__init__.py new file mode 100644 index 0000000000..79f8fa4422 --- /dev/null +++ b/AutomatedTesting/Gem/Editor/Scripts/__init__.py @@ -0,0 +1,10 @@ +""" +All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or +its licensors. + +For complete copyright and license terms please see the LICENSE at the root of this +distribution (the "License"). All use of this software is governed by the License, +or, if provided, by the license below or the license accompanying this file. Do not +remove or modify any license notices. This file is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +""" diff --git a/AutomatedTesting/Gem/Editor/Scripts/bootstrap.py b/AutomatedTesting/Gem/Editor/Scripts/bootstrap.py new file mode 100644 index 0000000000..e41f9c1767 --- /dev/null +++ b/AutomatedTesting/Gem/Editor/Scripts/bootstrap.py @@ -0,0 +1,13 @@ +""" +All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or +its licensors. + +For complete copyright and license terms please see the LICENSE at the root of this +distribution (the "License"). All use of this software is governed by the License, +or, if provided, by the license below or the license accompanying this file. Do not +remove or modify any license notices. This file is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +""" +import sys, os +sys.path.append(os.path.dirname(os.path.abspath(__file__)) + '/../../PythonTests') +from PythonAssetBuilder import bootstrap_tests diff --git a/AutomatedTesting/Gem/PythonTests/CMakeLists.txt b/AutomatedTesting/Gem/PythonTests/CMakeLists.txt index b7a5f85087..c527aea98c 100644 --- a/AutomatedTesting/Gem/PythonTests/CMakeLists.txt +++ b/AutomatedTesting/Gem/PythonTests/CMakeLists.txt @@ -134,6 +134,25 @@ if(PAL_TRAIT_BUILD_TESTS_SUPPORTED AND PAL_TRAIT_BUILD_HOST_TOOLS) ) endif() +## Python Asset Builder ## +if(PAL_TRAIT_BUILD_TESTS_SUPPORTED AND PAL_TRAIT_BUILD_HOST_TOOLS) + ly_add_pytest( + NAME AutomatedTesting::PythonAssetBuilder + TEST_SUITE periodic + TEST_SERIAL + PATH ${CMAKE_CURRENT_LIST_DIR}/PythonAssetBuilder + TIMEOUT 3600 + RUNTIME_DEPENDENCIES + Legacy::Editor + Legacy::CryRenderNULL + AZ::AssetProcessor + AutomatedTesting.Assets + Gem::EditorPythonBindings.Editor + Gem::PythonAssetBuilder.Editor + COMPONENT TestTools + ) +endif() + ## Blast ## if(PAL_TRAIT_BUILD_TESTS_SUPPORTED AND PAL_TRAIT_BUILD_HOST_TOOLS) ly_add_pytest( diff --git a/AutomatedTesting/Gem/PythonTests/PythonAssetBuilder/AssetBuilder_test.py b/AutomatedTesting/Gem/PythonTests/PythonAssetBuilder/AssetBuilder_test.py new file mode 100644 index 0000000000..e914182542 --- /dev/null +++ b/AutomatedTesting/Gem/PythonTests/PythonAssetBuilder/AssetBuilder_test.py @@ -0,0 +1,57 @@ +""" +All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or +its licensors. + +For complete copyright and license terms please see the LICENSE at the root of this +distribution (the "License"). All use of this software is governed by the License, +or, if provided, by the license below or the license accompanying this file. Do not +remove or modify any license notices. This file is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +""" +# +# This launches the AssetProcessor and Editor then attempts to find the expected +# assets created by a Python Asset Builder and the output of a scene pipeline script +# +import sys +import os +import pytest +import logging +pytest.importorskip('ly_test_tools') + +import ly_test_tools.environment.file_system as file_system +import ly_test_tools.log.log_monitor +import ly_test_tools.environment.waiter as waiter + +@pytest.mark.SUITE_sandbox +@pytest.mark.parametrize('launcher_platform', ['windows_editor']) +@pytest.mark.parametrize('project', ['AutomatedTesting']) +@pytest.mark.parametrize('level', ['auto_test']) +class TestPythonAssetProcessing(object): + def test_DetectPythonCreatedAsset(self, request, editor, level, launcher_platform): + unexpected_lines = [] + expected_lines = [ + 'Mock asset exists', + 'Expected subId for asset (gem/pythontests/pythonassetbuilder/geom_group_fbx_cube_100cm_center.azmodel) found', + 'Expected subId for asset (gem/pythontests/pythonassetbuilder/geom_group_fbx_cube_100cm_X_negative.azmodel) found', + 'Expected subId for asset (gem/pythontests/pythonassetbuilder/geom_group_fbx_cube_100cm_X_positive.azmodel) found', + 'Expected subId for asset (gem/pythontests/pythonassetbuilder/geom_group_fbx_cube_100cm_center.azmodel) found', + 'Expected subId for asset (gem/pythontests/pythonassetbuilder/geom_group_fbx_cube_100cm_center.azmodel) found', + 'Expected subId for asset (gem/pythontests/pythonassetbuilder/geom_group_fbx_cube_100cm_center.azmodel) found', + 'Expected subId for asset (gem/pythontests/pythonassetbuilder/geom_group_fbx_cube_100cm_center.azmodel) found', + 'Expected subId for asset (gem/pythontests/pythonassetbuilder/geom_group_fbx_cube_100cm_center.azmodel) found' + ] + timeout = 180 + halt_on_unexpected = False + test_directory = os.path.join(os.path.dirname(__file__)) + testFile = os.path.join(test_directory, 'AssetBuilder_test_case.py') + editor.args.extend(['-NullRenderer', "--skipWelcomeScreenDialog", "--autotest_mode", "--runpythontest", testFile]) + + with editor.start(): + editorlog_file = os.path.join(editor.workspace.paths.project_log(), 'Editor.log') + log_monitor = ly_test_tools.log.log_monitor.LogMonitor(editor, editorlog_file) + waiter.wait_for( + lambda: editor.is_alive(), + timeout, + exc=("Log file '{}' was never opened by another process.".format(editorlog_file)), + interval=1) + log_monitor.monitor_log_for_lines(expected_lines, unexpected_lines, halt_on_unexpected, timeout) diff --git a/AutomatedTesting/Gem/PythonTests/PythonAssetBuilder/AssetBuilder_test_case.py b/AutomatedTesting/Gem/PythonTests/PythonAssetBuilder/AssetBuilder_test_case.py new file mode 100644 index 0000000000..54857c2067 --- /dev/null +++ b/AutomatedTesting/Gem/PythonTests/PythonAssetBuilder/AssetBuilder_test_case.py @@ -0,0 +1,52 @@ +""" +All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or +its licensors. + +For complete copyright and license terms please see the LICENSE at the root of this +distribution (the "License"). All use of this software is governed by the License, +or, if provided, by the license below or the license accompanying this file. Do not +remove or modify any license notices. This file is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +""" +import azlmbr.bus +import azlmbr.asset +import azlmbr.editor +import azlmbr.math +import azlmbr.legacy.general + +def raise_and_stop(msg): + print (msg) + 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') + +if (assetId.to_string().endswith(':54c06b89') is False): + raise_and_stop(f'Mock AssetId 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, expectedSubId): + 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 (assetIdString.endswith(':' + expectedSubId) is False): + raise_and_stop(f'Asset has unexpected asset ID ({assetIdString}) for ({generatedModelAssetPath})!') + else: + print(f'Expected subId for asset ({generatedModelAssetPath}) found') + +test_azmodel_product('gem/pythontests/pythonassetbuilder/geom_group_fbx_cube_100cm_center.azmodel', '10412075') +test_azmodel_product('gem/pythontests/pythonassetbuilder/geom_group_fbx_cube_100cm_X_positive.azmodel', '10d16e68') +test_azmodel_product('gem/pythontests/pythonassetbuilder/geom_group_fbx_cube_100cm_X_negative.azmodel', '10a71973') +test_azmodel_product('gem/pythontests/pythonassetbuilder/geom_group_fbx_cube_100cm_Y_positive.azmodel', '10130556') +test_azmodel_product('gem/pythontests/pythonassetbuilder/geom_group_fbx_cube_100cm_Y_negative.azmodel', '1065724d') +test_azmodel_product('gem/pythontests/pythonassetbuilder/geom_group_fbx_cube_100cm_Z_positive.azmodel', '1024be55') +test_azmodel_product('gem/pythontests/pythonassetbuilder/geom_group_fbx_cube_100cm_Z_negative.azmodel', '1052c94e') + +azlmbr.editor.EditorToolsApplicationRequestBus(azlmbr.bus.Broadcast, 'ExitNoPrompt') diff --git a/AutomatedTesting/Gem/PythonTests/PythonAssetBuilder/__init__.py b/AutomatedTesting/Gem/PythonTests/PythonAssetBuilder/__init__.py new file mode 100644 index 0000000000..6ed3dc4bda --- /dev/null +++ b/AutomatedTesting/Gem/PythonTests/PythonAssetBuilder/__init__.py @@ -0,0 +1,10 @@ +""" +All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or +its licensors. + +For complete copyright and license terms please see the LICENSE at the root of this +distribution (the "License"). All use of this software is governed by the License, +or, if provided, by the license below or the license accompanying this file. Do not +remove or modify any license notices. This file is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +""" \ No newline at end of file diff --git a/AutomatedTesting/Gem/PythonTests/PythonAssetBuilder/bootstrap_tests.py b/AutomatedTesting/Gem/PythonTests/PythonAssetBuilder/bootstrap_tests.py new file mode 100644 index 0000000000..9e7b738a4d --- /dev/null +++ b/AutomatedTesting/Gem/PythonTests/PythonAssetBuilder/bootstrap_tests.py @@ -0,0 +1,17 @@ +""" +All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or +its licensors. + +For complete copyright and license terms please see the LICENSE at the root of this +distribution (the "License"). All use of this software is governed by the License, +or, if provided, by the license below or the license accompanying this file. Do not +remove or modify any license notices. This file is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +""" +import os +import sys +try: + sys.path.append(os.path.dirname(os.path.abspath(__file__))) + import mock_asset_builder +except: + print ('skipping asset builder testing via mock_asset_builder') diff --git a/AutomatedTesting/Gem/PythonTests/PythonAssetBuilder/export_chunks_builder.py b/AutomatedTesting/Gem/PythonTests/PythonAssetBuilder/export_chunks_builder.py new file mode 100644 index 0000000000..ad68a486b1 --- /dev/null +++ b/AutomatedTesting/Gem/PythonTests/PythonAssetBuilder/export_chunks_builder.py @@ -0,0 +1,88 @@ +""" +All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or +its licensors. + +For complete copyright and license terms please see the LICENSE at the root of this +distribution (the "License"). All use of this software is governed by the License, +or, if provided, by the license below or the license accompanying this file. Do not +remove or modify any license notices. This file is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +""" +import uuid, os +import azlmbr.scene as sceneApi +import azlmbr.scene.graph +from scene_api import scene_data as sceneData + +def get_mesh_node_names(sceneGraph): + meshDataList = [] + node = sceneGraph.get_root() + children = [] + + while node.IsValid(): + # store children to process after siblings + if sceneGraph.has_node_child(node): + children.append(sceneGraph.get_node_child(node)) + + # store any node that has mesh data content + nodeContent = sceneGraph.get_node_content(node) + if nodeContent is not None and nodeContent.CastWithTypeName('MeshData'): + if sceneGraph.is_node_end_point(node) is False: + meshDataList.append(sceneData.SceneGraphName(sceneGraph.get_node_name(node))) + + # advance to next node + if sceneGraph.has_node_sibling(node): + node = sceneGraph.get_node_sibling(node) + elif children: + node = children.pop() + else: + node = azlmbr.scene.graph.NodeIndex() + + return meshDataList + +def update_manifest(scene): + graph = sceneData.SceneGraph(scene.graph) + meshNameList = get_mesh_node_names(graph) + sceneManifest = sceneData.SceneManifest() + sourceFilenameOnly = os.path.basename(scene.sourceFilename) + sourceFilenameOnly = sourceFilenameOnly.replace('.','_') + + for activeMeshIndex in range(len(meshNameList)): + chunkName = meshNameList[activeMeshIndex] + chunkPath = chunkName.get_path() + meshGroupName = '{}_{}'.format(sourceFilenameOnly, chunkName.get_name()) + meshGroup = sceneManifest.add_mesh_group(meshGroupName) + meshGroup['id'] = '{' + str(uuid.uuid5(uuid.NAMESPACE_DNS, sourceFilenameOnly + chunkPath)) + '}' + sceneManifest.mesh_group_add_comment(meshGroup, 'auto generated by scene manifest') + sceneManifest.mesh_group_add_advanced_coordinate_system(meshGroup, None, None, None, 1.0) + + # create selection node list + pathSet = set() + for meshIndex in range(len(meshNameList)): + targetPath = meshNameList[meshIndex].get_path() + if (activeMeshIndex == meshIndex): + sceneManifest.mesh_group_select_node(meshGroup, targetPath) + else: + if targetPath not in pathSet: + pathSet.update(targetPath) + sceneManifest.mesh_group_unselect_node(meshGroup, targetPath) + + return sceneManifest.export() + +mySceneJobHandler = None + +def on_update_manifest(args): + scene = args[0] + result = update_manifest(scene) + global mySceneJobHandler + mySceneJobHandler.disconnect() + mySceneJobHandler = None + return result + +def main(): + global mySceneJobHandler + mySceneJobHandler = sceneApi.ScriptBuildingNotificationBusHandler() + mySceneJobHandler.connect() + mySceneJobHandler.add_callback('OnUpdateManifest', on_update_manifest) + +if __name__ == "__main__": + main() diff --git a/AutomatedTesting/Gem/PythonTests/PythonAssetBuilder/geom_group.fbx b/AutomatedTesting/Gem/PythonTests/PythonAssetBuilder/geom_group.fbx new file mode 100644 index 0000000000..8945a5505a --- /dev/null +++ b/AutomatedTesting/Gem/PythonTests/PythonAssetBuilder/geom_group.fbx @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:66d38948309ef273adf74b63eaa38f8fc2e2bdfbab3933d2ee082ce6a8cb108e +size 30496 diff --git a/AutomatedTesting/Gem/PythonTests/PythonAssetBuilder/geom_group.fbx.assetinfo b/AutomatedTesting/Gem/PythonTests/PythonAssetBuilder/geom_group.fbx.assetinfo new file mode 100644 index 0000000000..707c6f3705 --- /dev/null +++ b/AutomatedTesting/Gem/PythonTests/PythonAssetBuilder/geom_group.fbx.assetinfo @@ -0,0 +1,9 @@ +{ + "values": + [ + { + "$type": "ScriptProcessorRule", + "scriptFilename": "Gem/PythonTests/PythonAssetBuilder/export_chunks_builder.py" + } + ] +} diff --git a/AutomatedTesting/Gem/PythonTests/PythonAssetBuilder/mock_asset_builder.py b/AutomatedTesting/Gem/PythonTests/PythonAssetBuilder/mock_asset_builder.py new file mode 100644 index 0000000000..3b695e3ccd --- /dev/null +++ b/AutomatedTesting/Gem/PythonTests/PythonAssetBuilder/mock_asset_builder.py @@ -0,0 +1,121 @@ +""" +All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or +its licensors. + +For complete copyright and license terms please see the LICENSE at the root of this +distribution (the "License"). All use of this software is governed by the License, +or, if provided, by the license below or the license accompanying this file. Do not +remove or modify any license notices. This file is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +""" +import azlmbr.asset +import azlmbr.asset.builder +import azlmbr.bus +import azlmbr.math +import os, traceback, binascii, sys + +jobKeyName = 'Mock Asset' + +def log_exception_traceback(): + exc_type, exc_value, exc_tb = sys.exc_info() + data = traceback.format_exception(exc_type, exc_value, exc_tb) + print(str(data)) + +# creates a single job to compile for each platform +def create_jobs(request): + # create job descriptor for each platform + jobDescriptorList = [] + for platformInfo in request.enabledPlatforms: + jobDesc = azlmbr.asset.builder.JobDescriptor() + jobDesc.jobKey = jobKeyName + jobDesc.set_platform_identifier(platformInfo.identifier) + jobDescriptorList.append(jobDesc) + + response = azlmbr.asset.builder.CreateJobsResponse() + response.result = azlmbr.asset.builder.CreateJobsResponse_ResultSuccess + response.createJobOutputs = jobDescriptorList + return response + +def on_create_jobs(args): + try: + request = args[0] + return create_jobs(request) + except: + log_exception_traceback() + # returing back a default CreateJobsResponse() records an asset error + return azlmbr.asset.builder.CreateJobsResponse() + +def process_file(request): + # prepare output folder + basePath, _ = os.path.split(request.sourceFile) + outputPath = os.path.join(request.tempDirPath, basePath) + os.makedirs(outputPath, exist_ok=True) + + # write out a mock file + basePath, sourceFile = os.path.split(request.sourceFile) + mockFilename = os.path.splitext(sourceFile)[0] + '.mock_asset' + mockFilename = os.path.join(basePath, mockFilename) + mockFilename = mockFilename.replace('\\', '/') + tempFilename = os.path.join(request.tempDirPath, mockFilename) + + # write out a tempFilename like a JSON + fileOutput = open(tempFilename, "w") + fileOutput.write('{}') + fileOutput.close() + + # generate a product asset file entry + subId = binascii.crc32(mockFilename.encode()) + mockAssetType = azlmbr.math.Uuid_CreateString('{9274AD17-3212-4651-9F3B-7DCCB080E467}', 0) + product = azlmbr.asset.builder.JobProduct(mockFilename, mockAssetType, subId) + product.dependenciesHandled = True + productOutputs = [] + productOutputs.append(product) + + # fill out response object + response = azlmbr.asset.builder.ProcessJobResponse() + response.outputProducts = productOutputs + response.resultCode = azlmbr.asset.builder.ProcessJobResponse_Success + response.dependenciesHandled = True + return response + +# using the incoming 'request' find the type of job via 'jobKey' to determine what to do +def on_process_job(args): + try: + request = args[0] + if (request.jobDescription.jobKey.startswith(jobKeyName)): + return process_file(request) + except: + log_exception_traceback() + # returning back an empty ProcessJobResponse() will record an error + return azlmbr.asset.builder.ProcessJobResponse() + +# register asset builder +def register_asset_builder(busId): + assetPattern = azlmbr.asset.builder.AssetBuilderPattern() + assetPattern.pattern = '*.mock' + assetPattern.type = azlmbr.asset.builder.AssetBuilderPattern_Wildcard + + builderDescriptor = azlmbr.asset.builder.AssetBuilderDesc() + builderDescriptor.name = "Mock Builder" + builderDescriptor.patterns = [assetPattern] + builderDescriptor.busId = busId + builderDescriptor.version = 1 + + outcome = azlmbr.asset.builder.PythonAssetBuilderRequestBus(azlmbr.bus.Broadcast, 'RegisterAssetBuilder', builderDescriptor) + if outcome.IsSuccess(): + # created the asset builder to hook into the notification bus + handler = azlmbr.asset.builder.PythonBuilderNotificationBusHandler() + handler.connect(busId) + handler.add_callback('OnCreateJobsRequest', on_create_jobs) + handler.add_callback('OnProcessJobRequest', on_process_job) + return handler + +# create the asset builder handler +busIdString = '{CF5C74C1-9ED4-5851-95B1-0B15090DBEC7}' +busId = azlmbr.math.Uuid_CreateString(busIdString, 0) +handler = None +try: + handler = register_asset_builder(busId) +except: + handler = None + log_exception_traceback() diff --git a/AutomatedTesting/Gem/PythonTests/PythonAssetBuilder/test_asset.mock b/AutomatedTesting/Gem/PythonTests/PythonAssetBuilder/test_asset.mock new file mode 100644 index 0000000000..6d6a52e643 --- /dev/null +++ b/AutomatedTesting/Gem/PythonTests/PythonAssetBuilder/test_asset.mock @@ -0,0 +1 @@ +mock data \ No newline at end of file diff --git a/AutomatedTesting/Gem/PythonTests/largeworlds/gradient_signal/EditorScripts/ImageGradient_ProcessedImageAssignedSuccessfully.py b/AutomatedTesting/Gem/PythonTests/largeworlds/gradient_signal/EditorScripts/ImageGradient_ProcessedImageAssignedSuccessfully.py index 6b4a8bf17c..ccc8c3f101 100755 --- a/AutomatedTesting/Gem/PythonTests/largeworlds/gradient_signal/EditorScripts/ImageGradient_ProcessedImageAssignedSuccessfully.py +++ b/AutomatedTesting/Gem/PythonTests/largeworlds/gradient_signal/EditorScripts/ImageGradient_ProcessedImageAssignedSuccessfully.py @@ -77,13 +77,13 @@ class TestImageGradient(EditorTestHelper): # 3) Assign the processed gradient signal image as the Image Gradient's image asset and verify success # First, check for the base image in the workspace - base_image = "lumberyard_gsi.png" + base_image = "image_grad_test_gsi.png" base_image_path = os.path.join("AutomatedTesting", "Assets", "ImageGradients", base_image) if os.path.isfile(base_image_path): print(f"{base_image} was found in the workspace") # Next, assign the processed image to the Image Gradient's Image Asset property - processed_image_path = os.path.join("Assets", "ImageGradients", "lumberyard_gsi.gradimage") + processed_image_path = os.path.join("Assets", "ImageGradients", "image_grad_test_gsi.gradimage") asset_id = asset.AssetCatalogRequestBus(bus.Broadcast, "GetAssetIdByPath", processed_image_path, math.Uuid(), False) hydra.get_set_test(image_gradient_entity, 0, "Configuration|Image Asset", asset_id) diff --git a/AutomatedTesting/Gem/PythonTests/largeworlds/gradient_signal/test_ImageGradient.py b/AutomatedTesting/Gem/PythonTests/largeworlds/gradient_signal/test_ImageGradient.py index 11712f8b65..8fc582c2c8 100755 --- a/AutomatedTesting/Gem/PythonTests/largeworlds/gradient_signal/test_ImageGradient.py +++ b/AutomatedTesting/Gem/PythonTests/largeworlds/gradient_signal/test_ImageGradient.py @@ -57,7 +57,7 @@ class TestImageGradientRequiresShape(object): "Entity has a Image Gradient component", "Entity has a Gradient Transform Modifier component", "Entity has a Box Shape component", - "lumberyard_gsi.png was found in the workspace", + "image_grad_test_gsi.png was found in the workspace", "Entity Configuration|Image Asset: SUCCESS", "ImageGradient_ProcessedImageAssignedSucessfully: result=SUCCESS", ] diff --git a/AutomatedTesting/LightingPresets/greenwich_park_02.lightingconfig.json b/AutomatedTesting/LightingPresets/greenwich_park_02.lightingconfig.json index 1646dd18a2..bfb92bbb6f 100644 --- a/AutomatedTesting/LightingPresets/greenwich_park_02.lightingconfig.json +++ b/AutomatedTesting/LightingPresets/greenwich_park_02.lightingconfig.json @@ -1,7 +1,6 @@ { "configurations": [ { - "autoSelect": false, "displayName": "Greenwich Park 02", "skyboxImageAsset": { "assetId": { @@ -64,7 +63,6 @@ "shadowCatcherOpacity": 0.20000000298023225 }, { - "autoSelect": false, "displayName": "Greenwich Park 02 (Alt)", "skyboxImageAsset": { "assetId": { diff --git a/CMakeLists.txt b/CMakeLists.txt index 2e0af34c08..a6f0dd086e 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -23,15 +23,11 @@ endif() include(cmake/Version.cmake) -set(INSTALLED_ENGINE TRUE) - if(NOT PROJECT_NAME) project(O3DE LANGUAGES C CXX VERSION ${LY_VERSION_STRING} ) - - set(INSTALLED_ENGINE FALSE) endif() include(cmake/Initialize.cmake) diff --git a/Code/CryEngine/CryCommon/IMovieSystem.h b/Code/CryEngine/CryCommon/IMovieSystem.h index 654ccfd240..7a1125ae2b 100644 --- a/Code/CryEngine/CryCommon/IMovieSystem.h +++ b/Code/CryEngine/CryCommon/IMovieSystem.h @@ -19,6 +19,7 @@ #include #include #include +#include #include #include @@ -914,9 +915,18 @@ struct IAnimStringTable */ struct IAnimSequence { - AZ_RTTI(IAnimSequence, "{A60F95F5-5A4A-47DB-B3BB-525BBC0BC8DB}") + AZ_RTTI(IAnimSequence, "{A60F95F5-5A4A-47DB-B3BB-525BBC0BC8DB}"); + AZ_CLASS_ALLOCATOR(IAnimSequence, AZ::SystemAllocator, 0); - static const int kSequenceVersion = 4; + static const int kSequenceVersion = 5; + + static void Reflect(AZ::ReflectContext* context) + { + if (auto serializeContext = azrtti_cast(context); serializeContext != nullptr) + { + serializeContext->Class(); + } + } //! Flags used for SetFlags(),GetFlags(),SetParentFlags(),GetParentFlags() methods. enum EAnimSequenceFlags diff --git a/Code/CryEngine/RenderDll/Common/PerInstanceConstantBufferPool.cpp b/Code/CryEngine/RenderDll/Common/PerInstanceConstantBufferPool.cpp index 7fa69f6026..f2475c0b48 100644 --- a/Code/CryEngine/RenderDll/Common/PerInstanceConstantBufferPool.cpp +++ b/Code/CryEngine/RenderDll/Common/PerInstanceConstantBufferPool.cpp @@ -274,6 +274,10 @@ void PerInstanceConstantBufferPool::SetConstantBuffer(SRendItem* renderItem) deviceManager.BindConstantBuffer(eHWSC_Vertex, m_PooledIndirectConstantBuffer[indirectId], eConstantBufferShaderSlot_SPIIndex); deviceManager.BindConstantBuffer(eHWSC_Pixel, m_PooledIndirectConstantBuffer[indirectId], eConstantBufferShaderSlot_SPIIndex); #else + AZ::u32 itemIndex = directId % SPI_NUM_INSTS_PER_CB; + AZ::u32 first[1] = {itemIndex * static_cast(sizeof(HLSL_PerInstanceConstantBuffer))}; + AZ::u32 count[1] = {static_cast(sizeof(HLSL_PerInstanceConstantBuffer))}; + deviceManager.BindConstantBuffer(eHWSC_Vertex, m_PooledConstantBuffer[bufferIndex], eConstantBufferShaderSlot_SPI, first[0], count[0]); deviceManager.BindConstantBuffer(eHWSC_Pixel, m_PooledConstantBuffer[bufferIndex], eConstantBufferShaderSlot_SPI, first[0], count[0]); #endif diff --git a/Code/CryEngine/RenderDll/Common/RenderMesh.cpp b/Code/CryEngine/RenderDll/Common/RenderMesh.cpp index 10bbfbf0e6..357731fc6d 100644 --- a/Code/CryEngine/RenderDll/Common/RenderMesh.cpp +++ b/Code/CryEngine/RenderDll/Common/RenderMesh.cpp @@ -755,6 +755,7 @@ lSysUpdate: buffer_handle_t nVB = ~0u; # if BUFFER_ENABLE_DIRECT_ACCESS && !defined(NULL_RENDERER) nVB = MS->m_nID; + int nFrame = gRenDev->m_RP.m_TI[gRenDev->m_RP.m_nFillThreadID].m_nFrameUpdateID; if ((nVB != ~0u && (MS->m_nFrameCreate != nFrame || MS->m_nElements != m_nVerts)) || !CRenderer::CV_r_buffer_enable_lockless_updates) # endif goto lSysCreate; diff --git a/Code/Framework/AzCore/AzCore/Component/ComponentApplication.cpp b/Code/Framework/AzCore/AzCore/Component/ComponentApplication.cpp index b8d3e12712..c55f565615 100644 --- a/Code/Framework/AzCore/AzCore/Component/ComponentApplication.cpp +++ b/Code/Framework/AzCore/AzCore/Component/ComponentApplication.cpp @@ -178,14 +178,16 @@ namespace AZ //! on an update to '/Amazon/AzCore/Bootstrap/project_path' key. struct UpdateProjectSettingsEventHandler { - UpdateProjectSettingsEventHandler(AZ::SettingsRegistryInterface& registry) + UpdateProjectSettingsEventHandler(AZ::SettingsRegistryInterface& registry, AZ::CommandLine& commandLine) : m_registry{ registry } + , m_commandLine{ commandLine } { } void operator()(AZStd::string_view path, AZ::SettingsRegistryInterface::Type) { using FixedValueString = AZ::SettingsRegistryInterface::FixedValueString; + // #1 Update the project settings when the project path is set const auto projectPathKey = FixedValueString(AZ::SettingsRegistryMergeUtils::BootstrapSettingsRootKey) + "/project_path"; AZ::IO::FixedMaxPath newProjectPath; if (SettingsRegistryMergeUtils::IsPathAncestorDescendantOrEqual(projectPathKey, path) @@ -194,6 +196,7 @@ namespace AZ UpdateProjectSettingsFromProjectPath(AZ::IO::PathView(newProjectPath)); } + // #2 Update the project specialization when the project name is set const auto projectNameKey = FixedValueString(AZ::SettingsRegistryMergeUtils::ProjectSettingsRootKey) + "/project_name"; FixedValueString newProjectName; if (SettingsRegistryMergeUtils::IsPathAncestorDescendantOrEqual(projectNameKey, path) @@ -201,6 +204,12 @@ namespace AZ { UpdateProjectSpecializationFromProjectName(newProjectName); } + + // #3 Update the ComponentApplication CommandLine instance when the command line settings are merged into the Settings Registry + if (path == AZ::SettingsRegistryMergeUtils::CommandLineValueChangedKey) + { + UpdateCommandLine(); + } } //! Add the project name as a specialization underneath the /Amazon/AzCore/Settings/Specializations path @@ -233,10 +242,16 @@ namespace AZ AZ::SettingsRegistryMergeUtils::MergeSettingsToRegistry_AddRuntimeFilePaths(m_registry); } + void UpdateCommandLine() + { + AZ::SettingsRegistryMergeUtils::GetCommandLineFromRegistry(m_registry, m_commandLine); + } + private: AZ::IO::FixedMaxPath m_oldProjectPath; AZ::SettingsRegistryInterface::FixedValueString m_oldProjectName; AZ::SettingsRegistryInterface& m_registry; + AZ::CommandLine& m_commandLine; }; void ComponentApplication::Descriptor::AllocatorRemapping::Reflect(ReflectContext* context, ComponentApplication* app) @@ -326,6 +341,16 @@ namespace AZ ; } } + + if (auto behaviorContext = azrtti_cast(context)) + { + behaviorContext->EBus("ComponentApplicationBus") + ->Attribute(AZ::Script::Attributes::Scope, AZ::Script::Attributes::ScopeFlags::Common) + ->Attribute(AZ::Script::Attributes::Category, "Components") + + ->Event("GetEntityName", &ComponentApplicationBus::Events::GetEntityName) + ->Event("SetEntityName", &ComponentApplicationBus::Events::SetEntityName); + } } //========================================================================= @@ -415,6 +440,12 @@ namespace AZ // Add the Command Line arguments into the SettingsRegistry SettingsRegistryMergeUtils::StoreCommandLineToRegistry(*m_settingsRegistry, m_commandLine); + // Add a notifier to update the project_settings when + // 1. The 'project_path' key changes + // 2. The project specialization when the 'project-name' key changes + // 3. The ComponentApplication command line when the command line is stored to the registry + m_projectChangedHandler = m_settingsRegistry->RegisterNotifier(UpdateProjectSettingsEventHandler{ *m_settingsRegistry, m_commandLine }); + // Merge Command Line arguments constexpr bool executeRegDumpCommands = false; SettingsRegistryMergeUtils::MergeSettingsToRegistry_CommandLine(*m_settingsRegistry, m_commandLine, executeRegDumpCommands); @@ -429,10 +460,6 @@ namespace AZ // for the application root. CalculateAppRoot(); - // Add a notifier to update the /Amazon/AzCore/Settings/Specializations - // when the 'project_path' property changes within the SettingsRegistry - m_projectChangedHandler = m_settingsRegistry->RegisterNotifier(UpdateProjectSettingsEventHandler{ *m_settingsRegistry }); - // Merge the bootstrap.cfg file into the Settings Registry as soon as the OSAllocator has been created. SettingsRegistryMergeUtils::MergeSettingsToRegistry_Bootstrap(*m_settingsRegistry); SettingsRegistryMergeUtils::MergeSettingsToRegistry_O3deUserRegistry(*m_settingsRegistry, AZ_TRAIT_OS_PLATFORM_CODENAME, {}); @@ -909,6 +936,8 @@ namespace AZ SettingsRegistryMergeUtils::MergeSettingsToRegistry_ProjectUserRegistry(registry, AZ_TRAIT_OS_PLATFORM_CODENAME, specializations, &scratchBuffer); SettingsRegistryMergeUtils::MergeSettingsToRegistry_CommandLine(registry, m_commandLine, true); #endif + // Update the Runtime file paths in case the "{BootstrapSettingsRootKey}/assets" key was overriden by a setting registry + AZ::SettingsRegistryMergeUtils::MergeSettingsToRegistry_AddRuntimeFilePaths(registry); } void ComponentApplication::SetSettingsRegistrySpecializations(SettingsRegistryInterface::Specializations& specializations) @@ -1031,6 +1060,20 @@ namespace AZ return AZStd::string(); } + //========================================================================= + // SetEntityName + //========================================================================= + bool ComponentApplication::SetEntityName(const EntityId& id, const AZStd::string_view name) + { + Entity* entity = FindEntity(id); + if (entity) + { + entity->SetName(name); + return true; + } + return false; + } + //========================================================================= // EnumerateEntities //========================================================================= diff --git a/Code/Framework/AzCore/AzCore/Component/ComponentApplication.h b/Code/Framework/AzCore/AzCore/Component/ComponentApplication.h index ef5c813573..3ebcf39d95 100644 --- a/Code/Framework/AzCore/AzCore/Component/ComponentApplication.h +++ b/Code/Framework/AzCore/AzCore/Component/ComponentApplication.h @@ -209,6 +209,7 @@ namespace AZ bool DeleteEntity(const EntityId& id) override; Entity* FindEntity(const EntityId& id) override; AZStd::string GetEntityName(const EntityId& id) override; + bool SetEntityName(const EntityId& id, const AZStd::string_view name) override; void EnumerateEntities(const ComponentApplicationRequests::EntityCallback& callback) override; ComponentApplication* GetApplication() override { return this; } /// Returns the serialize context that has been registered with the app, if there is one. diff --git a/Code/Framework/AzCore/AzCore/Component/ComponentApplicationBus.h b/Code/Framework/AzCore/AzCore/Component/ComponentApplicationBus.h index d0f161aa39..3582e6ebb8 100644 --- a/Code/Framework/AzCore/AzCore/Component/ComponentApplicationBus.h +++ b/Code/Framework/AzCore/AzCore/Component/ComponentApplicationBus.h @@ -130,7 +130,13 @@ namespace AZ //! @param entity A reference to the entity whose name you are seeking. //! @return The name of the entity with the specified entity ID. //! If no entity is found for the specified ID, it returns an empty string. - virtual AZStd::string GetEntityName(const EntityId& id) { (void)id; return AZStd::string(); }; + virtual AZStd::string GetEntityName(const EntityId& id) { (void)id; return AZStd::string(); } + + //! Sets the name of the entity that has the specified entity ID. + //! Entity names are not enforced to be unique. + //! @param entityId A reference to the entity whose name you want to change. + //! @return True if the name was changed successfully, false if it wasn't. + virtual bool SetEntityName([[maybe_unused]] const EntityId& id, [[maybe_unused]] const AZStd::string_view name) { return false; } //! The type that AZ::ComponentApplicationRequests::EnumerateEntities uses to //! pass entity callbacks to the application for enumeration. diff --git a/Code/Framework/AzCore/AzCore/Math/Quaternion.cpp b/Code/Framework/AzCore/AzCore/Math/Quaternion.cpp index ca09f8b453..143fe59ca7 100644 --- a/Code/Framework/AzCore/AzCore/Math/Quaternion.cpp +++ b/Code/Framework/AzCore/AzCore/Math/Quaternion.cpp @@ -258,7 +258,8 @@ namespace AZ Method("CreateFromMatrix3x3", &Quaternion::CreateFromMatrix3x3)-> Method("CreateFromMatrix4x4", &Quaternion::CreateFromMatrix4x4)-> Method("CreateFromAxisAngle", &Quaternion::CreateFromAxisAngle)-> - Method("CreateShortestArc", &Quaternion::CreateShortestArc) + Method("CreateShortestArc", &Quaternion::CreateShortestArc)-> + Method("CreateFromEulerAnglesDegrees", &Quaternion::CreateFromEulerAnglesDegrees) ; } } diff --git a/Code/Framework/AzCore/AzCore/Math/Transform.cpp b/Code/Framework/AzCore/AzCore/Math/Transform.cpp index 77d8658d0f..bb3f764492 100644 --- a/Code/Framework/AzCore/AzCore/Math/Transform.cpp +++ b/Code/Framework/AzCore/AzCore/Math/Transform.cpp @@ -250,6 +250,7 @@ namespace AZ Attribute(Script::Attributes::ExcludeFrom, Script::Attributes::ExcludeFlags::All)-> Attribute(Script::Attributes::Storage, Script::Attributes::StorageType::Value)-> Attribute(Script::Attributes::GenericConstructorOverride, &Internal::TransformDefaultConstructor)-> + Constructor()-> Method("GetBasis", &Transform::GetBasis)-> Method("GetBasisX", &Transform::GetBasisX)-> Method("GetBasisY", &Transform::GetBasisY)-> diff --git a/Code/Framework/AzCore/AzCore/Math/Vector2.cpp b/Code/Framework/AzCore/AzCore/Math/Vector2.cpp index bc5f6ecdad..c2a3a934b0 100644 --- a/Code/Framework/AzCore/AzCore/Math/Vector2.cpp +++ b/Code/Framework/AzCore/AzCore/Math/Vector2.cpp @@ -167,14 +167,14 @@ namespace AZ } } - AZ_MATH_INLINE Vector2::Vector2(const Vector3& source) + Vector2::Vector2(const Vector3& source) : m_x(source.GetX()) , m_y(source.GetY()) { } - AZ_MATH_INLINE Vector2::Vector2(const Vector4& source) + Vector2::Vector2(const Vector4& source) : m_x(source.GetX()) , m_y(source.GetY()) { diff --git a/Code/Framework/AzCore/AzCore/PlatformId/PlatformDefaults.cpp b/Code/Framework/AzCore/AzCore/PlatformId/PlatformDefaults.cpp new file mode 100644 index 0000000000..63aad1ecf4 --- /dev/null +++ b/Code/Framework/AzCore/AzCore/PlatformId/PlatformDefaults.cpp @@ -0,0 +1,340 @@ +/* +* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or +* its licensors. +* +* For complete copyright and license terms please see the LICENSE at the root of this +* distribution (the "License"). All use of this software is governed by the License, +* or, if provided, by the license below or the license accompanying this file. Do not +* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* +*/ + +#include +#include + +#include + +namespace AZ +{ + inline namespace PlatformDefaults + { + static const char* PlatformNames[PlatformId::NumPlatformIds] = { PlatformPC, PlatformES3, PlatformIOS, PlatformOSX, PlatformProvo, PlatformSalem, PlatformJasper, PlatformServer, PlatformAll, PlatformAllClient }; + + const char* PlatformIdToPalFolder(AZ::PlatformId platform) + { +#ifdef IOS +#define AZ_REDEFINE_IOS_AT_END IOS +#undef IOS +#endif + switch (platform) + { + case AZ::PC: + return "PC"; + case AZ::ES3: + return "Android"; + case AZ::IOS: + return "iOS"; + case AZ::OSX: + return "Mac"; + case AZ::PROVO: + return "Provo"; + case AZ::SALEM: + return "Salem"; + case AZ::JASPER: + return "Jasper"; + case AZ::SERVER: + return "Server"; + case AZ::ALL: + case AZ::ALL_CLIENT: + case AZ::NumPlatformIds: + case AZ::Invalid: + default: + return ""; + } + +#ifdef AZ_REDEFINE_IOS_AT_END +#define IOS AZ_REDEFINE_IOS_AT_END +#endif + } + + const char* OSPlatformToDefaultAssetPlatform(AZStd::string_view osPlatform) + { + if (osPlatform == PlatformCodeNameWindows || osPlatform == PlatformCodeNameLinux) + { + return PlatformPC; + } + else if (osPlatform == PlatformCodeNameMac) + { + return PlatformOSX; + } + else if (osPlatform == PlatformCodeNameAndroid) + { + return PlatformES3; + } + else if (osPlatform == PlatformCodeNameiOS) + { + return PlatformIOS; + } + else if (osPlatform == PlatformCodeNameProvo) + { + return PlatformProvo; + } + else if (osPlatform == PlatformCodeNameSalem) + { + return PlatformSalem; + } + else if (osPlatform == PlatformCodeNameJasper) + { + return PlatformJasper; + } + + AZ_Error("PlatformDefault", false, R"(Supplied OS platform "%.*s" does not have a corresponding default asset platform)", + aznumeric_cast(osPlatform.size()), osPlatform.data()); + return ""; + } + + PlatformFlags PlatformHelper::GetPlatformFlagFromPlatformIndex(PlatformId platformIndex) + { + if (platformIndex < 0 || platformIndex > PlatformId::NumPlatformIds) + { + return PlatformFlags::Platform_NONE; + } + if (platformIndex == PlatformId::ALL) + { + return PlatformFlags::Platform_ALL; + } + if (platformIndex == PlatformId::ALL_CLIENT) + { + return PlatformFlags::Platform_ALL_CLIENT; + } + return static_cast(1 << platformIndex); + } + + AZStd::fixed_vector PlatformHelper::GetPlatforms(PlatformFlags platformFlags) + { + AZStd::fixed_vector platforms; + for (int platformNum = 0; platformNum < PlatformId::NumPlatformIds; ++platformNum) + { + const bool isAllPlatforms = PlatformId::ALL == static_cast(platformNum) + && ((platformFlags & PlatformFlags::Platform_ALL) != PlatformFlags::Platform_NONE); + + const bool isAllClientPlatforms = PlatformId::ALL_CLIENT == static_cast(platformNum) + && ((platformFlags & PlatformFlags::Platform_ALL_CLIENT) != PlatformFlags::Platform_NONE); + + if (isAllPlatforms || isAllClientPlatforms + || (platformFlags & static_cast(1 << platformNum)) != PlatformFlags::Platform_NONE) + { + platforms.push_back(PlatformNames[platformNum]); + } + } + + return platforms; + } + + AZStd::fixed_vector PlatformHelper::GetPlatformsInterpreted(PlatformFlags platformFlags) + { + return GetPlatforms(GetPlatformFlagsInterpreted(platformFlags)); + } + + AZStd::fixed_vector PlatformHelper::GetPlatformIndices(PlatformFlags platformFlags) + { + AZStd::fixed_vector platformIndices; + for (int i = 0; i < PlatformId::NumPlatformIds; i++) + { + PlatformId index = static_cast(i); + if ((GetPlatformFlagFromPlatformIndex(index) & platformFlags) != PlatformFlags::Platform_NONE) + { + platformIndices.emplace_back(index); + } + } + return platformIndices; + } + + AZStd::fixed_vector PlatformHelper::GetPlatformIndicesInterpreted(PlatformFlags platformFlags) + { + return GetPlatformIndices(GetPlatformFlagsInterpreted(platformFlags)); + } + + PlatformFlags PlatformHelper::GetPlatformFlag(AZStd::string_view platform) + { + int platformIndex = GetPlatformIndexFromName(platform); + if (platformIndex == PlatformId::Invalid) + { + AZ_Error("PlatformDefault", false, "Invalid Platform ( %.*s ).\n", static_cast(platform.length()), platform.data()); + return PlatformFlags::Platform_NONE; + } + + if (platformIndex == PlatformId::ALL) + { + return PlatformFlags::Platform_ALL; + } + + if (platformIndex == PlatformId::ALL_CLIENT) + { + return PlatformFlags::Platform_ALL_CLIENT; + } + + return static_cast(1 << platformIndex); + } + + const char* PlatformHelper::GetPlatformName(PlatformId platform) + { + if (platform < 0 || platform > PlatformId::NumPlatformIds) + { + return "invalid"; + } + return PlatformNames[platform]; + } + + void PlatformHelper::AppendPlatformCodeNames(AZStd::fixed_vector& platformCodes, AZStd::string_view platformId) + { + PlatformId platform = GetPlatformIdFromName(platformId); + AZ_Assert(platform != PlatformId::Invalid, "Unsupported Platform ID: %.*s", static_cast(platformId.length()), platformId.data()); + AppendPlatformCodeNames(platformCodes, platform); + } + + void PlatformHelper::AppendPlatformCodeNames(AZStd::fixed_vector& platformCodes, PlatformId platformId) + { + // The IOS SDK has a macro that defines IOS as 1 which causes the enum below to be incorrectly converted to "PlatformId::1". +#pragma push_macro("IOS") +#undef IOS + // To reduce work the Asset Processor groups assets that can be shared between hardware platforms together. For this + // reason "PC" can for instance cover both the Windows and Linux platforms and "IOS" can cover AppleTV and iOS. + switch (platformId) + { + case PlatformId::PC: + platformCodes.emplace_back(PlatformCodeNameWindows); + platformCodes.emplace_back(PlatformCodeNameLinux); + break; + case PlatformId::ES3: + platformCodes.emplace_back(PlatformCodeNameAndroid); + break; + case PlatformId::IOS: + platformCodes.emplace_back(PlatformCodeNameiOS); + break; + case PlatformId::OSX: + platformCodes.emplace_back(PlatformCodeNameMac); + break; + case PlatformId::PROVO: + platformCodes.emplace_back(PlatformCodeNameProvo); + break; + case PlatformId::SALEM: + platformCodes.emplace_back(PlatformCodeNameSalem); + break; + case PlatformId::JASPER: + platformCodes.emplace_back(PlatformCodeNameJasper); + break; + case PlatformId::SERVER: + // Server is not a hardware platform + break; + default: + AZ_Assert(false, "Unsupported Platform ID: %i", platformId); + break; + } +#pragma pop_macro("IOS") + } + + int PlatformHelper::GetPlatformIndexFromName(AZStd::string_view platformName) + { + for (int idx = 0; idx < PlatformId::NumPlatformIds; idx++) + { + if (platformName == PlatformNames[idx]) + { + return idx; + } + } + + return PlatformId::Invalid; + } + + PlatformId PlatformHelper::GetPlatformIdFromName(AZStd::string_view platformName) + { + return aznumeric_caster(GetPlatformIndexFromName(platformName)); + } + + AssetPlatformCombinedString PlatformHelper::GetCommaSeparatedPlatformList(PlatformFlags platformFlags) + { + AZStd::fixed_vector platformNames = GetPlatforms(platformFlags); + AssetPlatformCombinedString platformsString; + AZ::StringFunc::Join(platformsString, platformNames.begin(), platformNames.end(), ", "); + return platformsString; + } + + PlatformFlags PlatformHelper::GetPlatformFlagsInterpreted(PlatformFlags platformFlags) + { + PlatformFlags returnFlags = PlatformFlags::Platform_NONE; + + if ((platformFlags & PlatformFlags::Platform_ALL) != PlatformFlags::Platform_NONE) + { + for (int i = 0; i < NumPlatforms; ++i) + { + auto platformId = static_cast(i); + + if (platformId != PlatformId::ALL && platformId != PlatformId::ALL_CLIENT) + { + returnFlags |= GetPlatformFlagFromPlatformIndex(platformId); + } + } + } + else if ((platformFlags & PlatformFlags::Platform_ALL_CLIENT) != PlatformFlags::Platform_NONE) + { + for (int i = 0; i < NumPlatforms; ++i) + { + auto platformId = static_cast(i); + + if (platformId != PlatformId::ALL && platformId != PlatformId::ALL_CLIENT && platformId != PlatformId::SERVER) + { + returnFlags |= GetPlatformFlagFromPlatformIndex(platformId); + } + } + } + else + { + returnFlags = platformFlags; + } + + return returnFlags; + } + + bool PlatformHelper::IsSpecialPlatform(PlatformFlags platformFlags) + { + return (platformFlags & PlatformFlags::Platform_ALL) != PlatformFlags::Platform_NONE + || (platformFlags & PlatformFlags::Platform_ALL_CLIENT) != PlatformFlags::Platform_NONE; + } + + bool HasFlagHelper(PlatformFlags flags, PlatformFlags checkPlatform) + { + return (flags & checkPlatform) == checkPlatform; + } + + + bool PlatformHelper::HasPlatformFlag(PlatformFlags flags, PlatformId checkPlatform) + { + // If checkPlatform contains any kind of invalid id, just exit out here + if (checkPlatform == PlatformId::Invalid || checkPlatform == NumPlatforms) + { + return false; + } + + // ALL_CLIENT + SERVER = ALL + if (HasFlagHelper(flags, PlatformFlags::Platform_ALL_CLIENT | PlatformFlags::Platform_SERVER)) + { + flags = PlatformFlags::Platform_ALL; + } + + if (HasFlagHelper(flags, PlatformFlags::Platform_ALL)) + { + // It doesn't matter what checkPlatform is set to in this case, just return true + return true; + } + + if (HasFlagHelper(flags, PlatformFlags::Platform_ALL_CLIENT)) + { + return checkPlatform != PlatformId::SERVER; + } + + return HasFlagHelper(flags, GetPlatformFlagFromPlatformIndex(checkPlatform)); + } + } +} diff --git a/Code/Framework/AzCore/AzCore/PlatformId/PlatformDefaults.h b/Code/Framework/AzCore/AzCore/PlatformId/PlatformDefaults.h new file mode 100644 index 0000000000..2d67c860cd --- /dev/null +++ b/Code/Framework/AzCore/AzCore/PlatformId/PlatformDefaults.h @@ -0,0 +1,157 @@ +/* +* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or +* its licensors. +* +* For complete copyright and license terms please see the LICENSE at the root of this +* distribution (the "License"). All use of this software is governed by the License, +* or, if provided, by the license below or the license accompanying this file. Do not +* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* +*/ + +#pragma once + +#include +#include +#include +#include +#include + +// On IOS builds IOS will be defined and interfere with the below enums +#pragma push_macro("IOS") +#undef IOS + +namespace AZ +{ + inline namespace PlatformDefaults + { + constexpr char PlatformPC[] = "pc"; + constexpr char PlatformES3[] = "es3"; + constexpr char PlatformIOS[] = "ios"; + constexpr char PlatformOSX[] = "osx_gl"; + constexpr char PlatformProvo[] = "provo"; + constexpr char PlatformSalem[] = "salem"; + constexpr char PlatformJasper[] = "jasper"; + constexpr char PlatformServer[] = "server"; + + constexpr char PlatformCodeNameWindows[] = "Windows"; + constexpr char PlatformCodeNameLinux[] = "Linux"; + constexpr char PlatformCodeNameAndroid[] = "Android"; + constexpr char PlatformCodeNameiOS[] = "iOS"; + constexpr char PlatformCodeNameMac[] = "Mac"; + constexpr char PlatformCodeNameProvo[] = "Provo"; + constexpr char PlatformCodeNameSalem[] = "Salem"; + constexpr char PlatformCodeNameJasper[] = "Jasper"; + constexpr char PlatformAll[] = "all"; + constexpr char PlatformAllClient[] = "all_client"; + + // Used for the capacity of a fixed vector to store the code names of platforms + // The value needs to be higher than the number of unique OS platforms that are supported(at this time 8) + constexpr size_t MaxPlatformCodeNames = 16; + + //! This platform enum have platform values in sequence and can also be used to get the platform count. + AZ_ENUM_WITH_UNDERLYING_TYPE(PlatformId, int, + (Invalid, -1), + PC, + ES3, + IOS, + OSX, + PROVO, + SALEM, + JASPER, + SERVER, // Corresponds to the customer's flavor of "server" which could be windows, ubuntu, etc + ALL, + ALL_CLIENT, + + // Add new platforms above this + NumPlatformIds + ); + constexpr int NumClientPlatforms = 7; + constexpr int NumPlatforms = NumClientPlatforms + 1; // 1 "Server" platform currently + enum class PlatformFlags : AZ::u32 + { + Platform_NONE = 0x00, + Platform_PC = 1 << PlatformId::PC, + Platform_ES3 = 1 << PlatformId::ES3, + Platform_IOS = 1 << PlatformId::IOS, + Platform_OSX = 1 << PlatformId::OSX, + Platform_PROVO = 1 << PlatformId::PROVO, + Platform_SALEM = 1 << PlatformId::SALEM, + Platform_JASPER = 1 << PlatformId::JASPER, + Platform_SERVER = 1 << PlatformId::SERVER, + + // A special platform that will always correspond to all platforms, even if new ones are added + Platform_ALL = 1ULL << 30, + + // A special platform that will always correspond to all non-server platforms, even if new ones are added + Platform_ALL_CLIENT = 1ULL << 31, + + AllNamedPlatforms = Platform_PC | Platform_ES3 | Platform_IOS | Platform_OSX | Platform_PROVO | Platform_SALEM | Platform_JASPER | Platform_SERVER, + }; + + AZ_DEFINE_ENUM_BITWISE_OPERATORS(PlatformFlags); + + // 32 characters should be more than enough to store a platform name + using AssetPlatformFixedString = AZStd::fixed_string<32>; + // Fixed string which can store a comma separated list of platforms names + // Additional byte is added to take into account the comma + using AssetPlatformCombinedString = AZStd::fixed_string < (AssetPlatformFixedString{}.max_size() + 1)* PlatformId::NumPlatformIds > ; + + const char* PlatformIdToPalFolder(PlatformId platform); + + const char* OSPlatformToDefaultAssetPlatform(AZStd::string_view osPlatform); + + //! Platform Helper is an utility class that can be used to retrieve platform related information + class PlatformHelper + { + public: + + //! Given a platformIndex returns the platform name + static const char* GetPlatformName(PlatformId platform); + + //! Converts the platform name to the platform code names as defined in AZ_TRAIT_OS_PLATFORM_CODENAME. + static void AppendPlatformCodeNames(AZStd::fixed_vector& platformCodes, AZStd::string_view platformName); + + //! Converts the platform name to the platform code names as defined in AZ_TRAIT_OS_PLATFORM_CODENAME. + static void AppendPlatformCodeNames(AZStd::fixed_vector& platformCodes, PlatformId platformId); + + //! Given a platform name returns a platform index. + //! If the platform is not found, the method returns -1. + static int GetPlatformIndexFromName(AZStd::string_view platformName); + + //! Given a platform name returns a platform id. + //! If the platform is not found, the method returns -1. + static PlatformId GetPlatformIdFromName(AZStd::string_view platformName); + + //! Given a platformIndex returns the platformFlags + static PlatformFlags GetPlatformFlagFromPlatformIndex(PlatformId platform); + + //! Given a platformFlags returns all the platform identifiers that are set. + static AZStd::fixed_vector GetPlatforms(PlatformFlags platformFlags); + //! Given a platformFlags returns all the platform identifiers that are set, with special flags interpreted. Do not use the result for saving + static AZStd::fixed_vector GetPlatformsInterpreted(PlatformFlags platformFlags); + + //! Given a platformFlags return a list of PlatformId indices + static AZStd::fixed_vector GetPlatformIndices(PlatformFlags platformFlags); + //! Given a platformFlags return a list of PlatformId indices, with special flags interpreted. Do not use the result for saving + static AZStd::fixed_vector GetPlatformIndicesInterpreted(PlatformFlags platformFlags); + + //! Given a platform identifier returns its corresponding platform flag. + static PlatformFlags GetPlatformFlag(AZStd::string_view platform); + + //! Given any platformFlags returns a string listing the input platforms + static AssetPlatformCombinedString GetCommaSeparatedPlatformList(PlatformFlags platformFlags); + + //! If platformFlags contains any special flags, they are removed and replaced with the normal flags they represent + static PlatformFlags GetPlatformFlagsInterpreted(PlatformFlags platformFlags); + + //! Returns true if platformFlags contains any special flags + static bool IsSpecialPlatform(PlatformFlags platformFlags); + + //! Returns true if platformFlags has checkPlatform flag set. + static bool HasPlatformFlag(PlatformFlags platformFlags, PlatformId checkPlatform); + }; + } +} +#pragma pop_macro("IOS") diff --git a/Code/Framework/AzCore/AzCore/Settings/SettingsRegistryMergeUtils.cpp b/Code/Framework/AzCore/AzCore/Settings/SettingsRegistryMergeUtils.cpp index 392e95bf6e..27f6f222dd 100644 --- a/Code/Framework/AzCore/AzCore/Settings/SettingsRegistryMergeUtils.cpp +++ b/Code/Framework/AzCore/AzCore/Settings/SettingsRegistryMergeUtils.cpp @@ -17,6 +17,7 @@ #include #include #include +#include #include #include #include @@ -132,23 +133,14 @@ namespace AZ::Internal AZ::IO::FixedMaxPath ScanUpRootLocator(AZStd::string_view rootFileToLocate) { - - AZStd::fixed_string executableDir; - if (AZ::Utils::GetExecutableDirectory(executableDir.data(), executableDir.capacity()) == Utils::ExecutablePathResult::Success) - { - // Update the size value of the executable directory fixed string to correctly be the length of the null-terminated string - // stored within it - executableDir.resize_no_construct(AZStd::char_traits::length(executableDir.data())); - } - - AZ::IO::FixedMaxPath engineRootCandidate{ executableDir }; + AZ::IO::FixedMaxPath rootCandidate{ AZ::Utils::GetExecutableDirectory() }; bool rootPathVisited = false; do { - if (AZ::IO::SystemFile::Exists((engineRootCandidate / rootFileToLocate).c_str())) + if (AZ::IO::SystemFile::Exists((rootCandidate / rootFileToLocate).c_str())) { - return engineRootCandidate; + return rootCandidate; } // Note for posix filesystems the parent directory of '/' is '/' and for windows @@ -156,38 +148,69 @@ namespace AZ::Internal // Validate that the parent directory isn't itself, that would imply // that it is the filesystem root path - AZ::IO::PathView parentPath = engineRootCandidate.ParentPath(); - rootPathVisited = (engineRootCandidate == parentPath); + AZ::IO::PathView parentPath = rootCandidate.ParentPath(); + rootPathVisited = (rootCandidate == parentPath); // Recurse upwards one directory - engineRootCandidate = AZStd::move(parentPath); + rootCandidate = AZStd::move(parentPath); } while (!rootPathVisited); return {}; } + void InjectSettingToCommandLineFront(AZ::SettingsRegistryInterface& settingsRegistry, + AZStd::string_view path, AZStd::string_view value) + { + AZ::CommandLine commandLine; + AZ::SettingsRegistryMergeUtils::GetCommandLineFromRegistry(settingsRegistry, commandLine); + AZ::CommandLine::ParamContainer paramContainer; + commandLine.Dump(paramContainer); + + auto projectPathOverride = AZStd::string::format(R"(--regset="%.*s=%.*s")", + aznumeric_cast(path.size()), path.data(), aznumeric_cast(value.size()), value.data()); + paramContainer.emplace(paramContainer.begin(), AZStd::move(projectPathOverride)); + commandLine.Parse(paramContainer); + AZ::SettingsRegistryMergeUtils::StoreCommandLineToRegistry(settingsRegistry, commandLine); + } } // namespace AZ::Internal namespace AZ::SettingsRegistryMergeUtils { + constexpr AZStd::string_view InternalScanUpEngineRootKey{ "/O3DE/Settings/Internal/engine_root_scan_up_path" }; + constexpr AZStd::string_view InternalScanUpProjectRootKey{ "/O3DE/Settings/Internal/project_root_scan_up_path" }; + AZ::IO::FixedMaxPath FindEngineRoot(SettingsRegistryInterface& settingsRegistry) { AZ::IO::FixedMaxPath engineRoot; - // This is the 'external' engine root key, as in passed from command-line or .setreg files. auto engineRootKey = SettingsRegistryInterface::FixedValueString::format("%s/engine_path", BootstrapSettingsRootKey); + + // Step 1 Run the scan upwards logic once to find the location of the engine.json if it exist + // Once this step is run the {InternalScanUpEngineRootKey} is set in the Settings Registry + // to have this scan logic only run once InternalScanUpEngineRootKey the supplied registry + if (settingsRegistry.GetType(InternalScanUpEngineRootKey) == SettingsRegistryInterface::Type::NoType) + { + // We can scan up from exe directory to find engine.json, use that for engine root if it exists. + engineRoot = Internal::ScanUpRootLocator("engine.json"); + // Set the {InternalScanUpEngineRootKey} to make sure this code path isn't called again for this settings registry + settingsRegistry.Set(InternalScanUpEngineRootKey, engineRoot.Native()); + if (!engineRoot.empty()) + { + settingsRegistry.Set(engineRootKey, engineRoot.Native()); + // Inject the engine root into the front of the command line settings + Internal::InjectSettingToCommandLineFront(settingsRegistry, engineRootKey, engineRoot.Native()); + return engineRoot; + } + } + + // Step 2 check if the engine_path key has been supplied if (settingsRegistry.Get(engineRoot.Native(), engineRootKey); !engineRoot.empty()) { return engineRoot; } - // We can scan up from exe directory to find engine.json, use that for engine root if it exists. - if (engineRoot = Internal::ScanUpRootLocator("engine.json"); !engineRoot.empty()) - { - settingsRegistry.Set(engineRootKey, engineRoot.c_str()); - return engineRoot; - } - + // Step 3 locate the project root and attempt to find the engine root using the registered engine + // for the project in the project.json file AZ::IO::FixedMaxPath projectRoot = FindProjectRoot(settingsRegistry); if (projectRoot.empty()) { @@ -207,16 +230,30 @@ namespace AZ::SettingsRegistryMergeUtils AZ::IO::FixedMaxPath FindProjectRoot(SettingsRegistryInterface& settingsRegistry) { AZ::IO::FixedMaxPath projectRoot; - // This is the 'external' project root key, as in passed from command-line or .setreg files. - auto projectRootKey = SettingsRegistryInterface::FixedValueString::format("%s/project_path", BootstrapSettingsRootKey); - if (settingsRegistry.Get(projectRoot.Native(), projectRootKey)) + const auto projectRootKey = SettingsRegistryInterface::FixedValueString::format("%s/project_path", BootstrapSettingsRootKey); + + // Step 1 Run the scan upwards logic once to find the location of the project.json if it exist + // Once this step is run the {InternalScanUpProjectRootKey} is set in the Settings Registry + // to have this scan logic only run once for the supplied registry + // SettingsRegistryInterface::GetType is used to check if a key is set + if (settingsRegistry.GetType(InternalScanUpProjectRootKey) == SettingsRegistryInterface::Type::NoType) { - return projectRoot; + projectRoot = Internal::ScanUpRootLocator("project.json"); + // Set the {InternalScanUpProjectRootKey} to make sure this code path isn't called again for this settings registry + settingsRegistry.Set(InternalScanUpProjectRootKey, projectRoot.Native()); + if (!projectRoot.empty()) + { + settingsRegistry.Set(projectRootKey, projectRoot.c_str()); + // Inject the project root into the front of the command line settings + Internal::InjectSettingToCommandLineFront(settingsRegistry, projectRootKey, projectRoot.Native()); + return projectRoot; + } } - if (projectRoot = Internal::ScanUpRootLocator("project.json"); !projectRoot.empty()) + // Step 2 Check the project-path key + // This is the project path root key, as in passed from command-line or .setreg files. + if (settingsRegistry.Get(projectRoot.Native(), projectRootKey)) { - settingsRegistry.Set(projectRootKey, projectRoot.c_str()); return projectRoot; } @@ -463,24 +500,13 @@ namespace AZ::SettingsRegistryMergeUtils void MergeSettingsToRegistry_Bootstrap(SettingsRegistryInterface& registry) { ConfigParserSettings parserSettings; - parserSettings.m_commentPrefixFunc = [](AZStd::string_view line) -> AZStd::string_view - { - constexpr AZStd::string_view commentPrefixes[]{ "--", ";","#" }; - for (AZStd::string_view commentPrefix : commentPrefixes) - { - if (size_t commentOffset = line.find(commentPrefix); commentOffset != AZStd::string_view::npos) - { - return line.substr(0, commentOffset); - } - } - return line; - }; parserSettings.m_registryRootPointerPath = BootstrapSettingsRootKey; MergeSettingsToRegistry_ConfigFile(registry, "bootstrap.cfg", parserSettings); } void MergeSettingsToRegistry_AddRuntimeFilePaths(SettingsRegistryInterface& registry) { + using FixedValueString = AZ::SettingsRegistryInterface::FixedValueString; // Binary folder AZ::IO::FixedMaxPath path = AZ::Utils::GetExecutableDirectory(); registry.Set(FilePathKey_BinaryFolder, path.LexicallyNormal().Native()); @@ -489,27 +515,25 @@ namespace AZ::SettingsRegistryMergeUtils AZ::IO::FixedMaxPath engineRoot = FindEngineRoot(registry); registry.Set(FilePathKey_EngineRootFolder, engineRoot.LexicallyNormal().Native()); - constexpr size_t bufferSize = 64; - auto buffer = AZStd::fixed_string::format("%s/project_path", BootstrapSettingsRootKey); - - AZ::SettingsRegistryInterface::FixedValueString projectPathKey(buffer); + auto projectPathKey = FixedValueString::format("%s/project_path", BootstrapSettingsRootKey); SettingsRegistryInterface::FixedValueString projectPathValue; if (registry.Get(projectPathValue, projectPathKey)) { // Cache folder // Get the name of the asset platform assigned by the bootstrap. First check for platform version such as "windows_assets" // and if that's missing just get "assets". - constexpr char platformName[] = AZ_TRAIT_OS_PLATFORM_CODENAME_LOWER; - - SettingsRegistryInterface::FixedValueString assetPlatform; - buffer = AZStd::fixed_string::format("%s/%s_assets", BootstrapSettingsRootKey, platformName); - AZStd::string_view assetPlatformKey(buffer); - if (!registry.Get(assetPlatform, assetPlatformKey)) + FixedValueString assetPlatform; + if (auto assetPlatformKey = FixedValueString::format("%s/%s_assets", BootstrapSettingsRootKey, AZ_TRAIT_OS_PLATFORM_CODENAME_LOWER); + !registry.Get(assetPlatform, assetPlatformKey)) { - buffer = AZStd::fixed_string::format("%s/assets", BootstrapSettingsRootKey); - assetPlatformKey = AZStd::string_view(buffer); + assetPlatformKey = FixedValueString::format("%s/assets", BootstrapSettingsRootKey); registry.Get(assetPlatform, assetPlatformKey); } + if (assetPlatform.empty()) + { + // Use the platform codename to retrieve the default asset platform value + assetPlatform = AZ::OSPlatformToDefaultAssetPlatform(AZ_TRAIT_OS_PLATFORM_CODENAME); + } // Project path - corresponds to the @devassets@ alias // NOTE: Here we append to engineRoot, but if projectPathValue is absolute then engineRoot is discarded. @@ -549,8 +573,7 @@ namespace AZ::SettingsRegistryMergeUtils { // Cache: project root - no corresponding fileIO alias, but this is where the asset database lives. // A registry override is accepted using the "project_cache_path" key. - buffer = AZStd::fixed_string::format("%s/project_cache_path", BootstrapSettingsRootKey); - AZStd::string_view projectCacheRootOverrideKey(buffer); + auto projectCacheRootOverrideKey = FixedValueString::format("%s/project_cache_path", BootstrapSettingsRootKey); // Clear path to make sure that the `project_cache_path` value isn't concatenated to the project path path.clear(); if (registry.Get(path.Native(), projectCacheRootOverrideKey)) @@ -807,6 +830,11 @@ namespace AZ::SettingsRegistryMergeUtils ++argumentIndex; commandLinePath.resize(commandLineRootSize); } + + // This key is used allow Notification Handlers to know when the command line has been updated within the + // registry. The value itself is meaningless. The JSON path of {CommandLineValueChangedKey} + // being passed to the Notification Event Handler indicates that the command line has be updated + registry.Set(CommandLineValueChangedKey, true); } bool GetCommandLineFromRegistry(SettingsRegistryInterface& registry, AZ::CommandLine& commandLine) @@ -823,10 +851,16 @@ namespace AZ::SettingsRegistryMergeUtils } else if (valueName == "Value" && !value.empty()) { - m_arguments.push_back(value); + // Make sure value types are in quotes in case they start with a command option prefix + m_arguments.push_back(QuoteArgument(value)); } } + AZStd::string QuoteArgument(AZStd::string_view arg) + { + return !arg.empty() ? AZStd::string::format(R"("%.*s")", aznumeric_cast(arg.size()), arg.data()) : AZStd::string{ arg }; + } + // The first parameter is skipped by the ComamndLine::Parse function so initialize // the container with one empty element AZ::CommandLine::ParamContainer m_arguments{ 1 }; diff --git a/Code/Framework/AzCore/AzCore/Settings/SettingsRegistryMergeUtils.h b/Code/Framework/AzCore/AzCore/Settings/SettingsRegistryMergeUtils.h index dad6c36d0f..10b3c2f18b 100644 --- a/Code/Framework/AzCore/AzCore/Settings/SettingsRegistryMergeUtils.h +++ b/Code/Framework/AzCore/AzCore/Settings/SettingsRegistryMergeUtils.h @@ -57,6 +57,9 @@ namespace AZ::SettingsRegistryMergeUtils //! Root key for where command line are stored at within the settings registry inline static constexpr char CommandLineRootKey[] = "/Amazon/AzCore/Runtime/CommandLine"; + //! Key set to trigger a notification that the CommandLine has been stored within the settings registry + //! The value of the key has no meaning. Notification Handlers only need to check if the key was supplied + inline static constexpr char CommandLineValueChangedKey[] = "/Amazon/AzCore/Runtime/CommandLineChanged"; //! Root key where raw project settings (project.json) file is merged to settings registry inline static constexpr char ProjectSettingsRootKey[] = "/Amazon/Project/Settings"; @@ -74,6 +77,20 @@ namespace AZ::SettingsRegistryMergeUtils //! If it's still not found, attempt to find the project (by similar means) then reconcile the //! engine root by inspecting project.json and the engine manifest file. AZ::IO::FixedMaxPath FindEngineRoot(SettingsRegistryInterface& settingsRegistry); + + //! The algorithm that is used to find the project root is as follows + //! 1. The first time this function is it performs a upward scan for a project.json file from + //! the executable directory and if found stores that path to an internal key. + //! In the same step it injects the path into the front of list of command line parameters + //! using the --regset="{BootstrapSettingsRootKey}/project_path=" value + //! 2. Next the "{BootstrapSettingsRootKey}/project_path" is checked to see if it has a project path set + //! + //! The order in which the project path settings are overridden proceeds in the following order + //! 1. project_path set in the /bootstrap.cfg file + //! 2. project_path set in a *.setreg/*.setregpatch file + //! 3. project_path found by scanning upwards from the executable directory to the project.json path + //! 4. project_path set on the Command line via either --regset="{BootstrapSettingsRootKey}/project_path=" + //! or --project_path= AZ::IO::FixedMaxPath FindProjectRoot(SettingsRegistryInterface& settingsRegistry); //! Query the specializations that will be used when loading the Settings Registry. diff --git a/Code/Framework/AzCore/AzCore/azcore_files.cmake b/Code/Framework/AzCore/AzCore/azcore_files.cmake index e100b240c2..5357ed66a6 100644 --- a/Code/Framework/AzCore/AzCore/azcore_files.cmake +++ b/Code/Framework/AzCore/AzCore/azcore_files.cmake @@ -607,6 +607,8 @@ set(FILES Utils/Utils.h Script/lua/lua.h Memory/HeapSchema.cpp + PlatformId/PlatformDefaults.h + PlatformId/PlatformDefaults.cpp PlatformId/PlatformId.h PlatformId/PlatformId.cpp Socket/AzSocket_fwd.h diff --git a/Code/Framework/AzCore/CMakeLists.txt b/Code/Framework/AzCore/CMakeLists.txt index c77205a760..db2c79f0c9 100644 --- a/Code/Framework/AzCore/CMakeLists.txt +++ b/Code/Framework/AzCore/CMakeLists.txt @@ -40,14 +40,13 @@ ly_add_target( ${common_dir} ${AZ_CORE_RADTELEMETRY_INCLUDE_DIRECTORIES} BUILD_DEPENDENCIES - PRIVATE - 3rdParty::zlib - 3rdParty::zstd - 3rdParty::cityhash PUBLIC 3rdParty::Lua 3rdParty::RapidJSON 3rdParty::RapidXML + 3rdParty::zlib + 3rdParty::zstd + 3rdParty::cityhash ${AZ_CORE_RADTELEMETRY_BUILD_DEPENDENCIES} ) ly_add_source_properties( diff --git a/Code/Framework/AzFramework/AzFramework/Entity/EntityDebugDisplayBus.h b/Code/Framework/AzFramework/AzFramework/Entity/EntityDebugDisplayBus.h index a5d3e657f5..f84f0276e1 100644 --- a/Code/Framework/AzFramework/AzFramework/Entity/EntityDebugDisplayBus.h +++ b/Code/Framework/AzFramework/AzFramework/Entity/EntityDebugDisplayBus.h @@ -105,8 +105,6 @@ namespace AzFramework virtual bool SetDrawInFrontMode(bool bOn) { (void)bOn; return false; } virtual AZ::u32 GetState() { return 0; } virtual AZ::u32 SetState(AZ::u32 state) { (void)state; return 0; } - virtual AZ::u32 SetStateFlag(AZ::u32 state) { (void)state; return 0; } - virtual AZ::u32 ClearStateFlag(AZ::u32 state) { (void)state; return 0; } virtual void PushMatrix(const AZ::Transform& tm) { (void)tm; } virtual void PopMatrix() {} diff --git a/Code/Framework/AzFramework/AzFramework/Font/FontInterface.h b/Code/Framework/AzFramework/AzFramework/Font/FontInterface.h new file mode 100644 index 0000000000..7c5bcce6d6 --- /dev/null +++ b/Code/Framework/AzFramework/AzFramework/Font/FontInterface.h @@ -0,0 +1,85 @@ +/* +* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or +* its licensors. +* +* For complete copyright and license terms please see the LICENSE at the root of this +* distribution (the "License"). All use of this software is governed by the License, +* or, if provided, by the license below or the license accompanying this file. Do not +* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* +*/ + +#pragma once + +#include +#include +#include +#include +#include + +namespace AzFramework +{ + using FontId = uint32_t; + static constexpr FontId InvalidFontId = 0xffffffffu; + + enum class TextHorizontalAlignment : uint16_t + { + Left, + Right, + Center + }; + + enum class TextVerticalAlignment : uint16_t + { + Top, + Bottom, + Center, + }; + + //! Standard parameters for drawing text on screen + struct TextDrawParameters + { + ViewportId m_drawViewportId = InvalidViewportId; //! Viewport to draw into + AZ::Vector3 m_position; //! world space position for 3d draws, screen space x,y,depth for 2d. + AZ::Color m_color = AZ::Colors::White; //! Color to draw the text + AZ::Vector2 m_scale = AZ::Vector2(1.0f); //! font scale + TextHorizontalAlignment m_hAlign = TextHorizontalAlignment::Left; //! Horizontal text alignment + TextVerticalAlignment m_vAlign = TextVerticalAlignment::Top; //! Vertical text alignment + bool m_monospace = false; //! disable character proportional spacing + bool m_depthTest = false; //! Test character against the depth buffer + bool m_virtual800x600ScreenSize = true; //! Text placement and size are scaled relative to a virtual 800x600 resolution + bool m_scaleWithWindow = false; //! Font gets bigger as the window gets bigger + bool m_multiline = true; //! text respects ascii newline characters + }; + + class FontDrawInterface + { + public: + AZ_RTTI(FontDrawInterface, "{545A7C14-CB3E-4A5B-B435-13EA606708EE}"); + + FontDrawInterface() = default; + virtual ~FontDrawInterface() = default; + + virtual void DrawScreenAlignedText2d( + const TextDrawParameters& params, + const AZStd::string_view& string) = 0; + virtual void DrawScreenAlignedText3d( + const TextDrawParameters& params, + const AZStd::string_view& string) = 0; + }; + + class FontQueryInterface + { + public: + AZ_RTTI(FontQueryInterface, "{4BDD8520-EBC1-4680-B25E-421BDF31750F}"); + + FontQueryInterface() = default; + virtual ~FontQueryInterface() = default; + + FontId GetFontId(const AZStd::string_view& fontName) const {return FontId(AZ::Crc32(fontName));} + virtual FontDrawInterface* GetFontDrawInterface(FontId) const = 0; + virtual FontDrawInterface* GetDefaultFontDrawInterface() const = 0; + + }; +} // namespace AzFramework diff --git a/Code/Framework/AzFramework/AzFramework/Platform/PlatformDefaults.cpp b/Code/Framework/AzFramework/AzFramework/Platform/PlatformDefaults.cpp deleted file mode 100644 index 81154bae35..0000000000 --- a/Code/Framework/AzFramework/AzFramework/Platform/PlatformDefaults.cpp +++ /dev/null @@ -1,338 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ - -#include -#include - -#include - -namespace AzFramework -{ - static const char* PlatformNames[PlatformId::NumPlatformIds] = { PlatformPC, PlatformES3, PlatformIOS, PlatformOSX, PlatformProvo, PlatformSalem, PlatformJasper, PlatformServer, PlatformAll, PlatformAllClient }; - - const char* PlatformIdToPalFolder(AzFramework::PlatformId platform) - { -#ifdef IOS -#define AZ_REDEFINE_IOS_AT_END IOS -#undef IOS -#endif - switch (platform) - { - case AzFramework::PC: - return "PC"; - case AzFramework::ES3: - return "Android"; - case AzFramework::IOS: - return "iOS"; - case AzFramework::OSX: - return "Mac"; - case AzFramework::PROVO: - return "Provo"; - case AzFramework::SALEM: - return "Salem"; - case AzFramework::JASPER: - return "Jasper"; - case AzFramework::SERVER: - return "Server"; - case AzFramework::ALL: - case AzFramework::ALL_CLIENT: - case AzFramework::NumPlatformIds: - case AzFramework::Invalid: - default: - return ""; - } - -#ifdef AZ_REDEFINE_IOS_AT_END -#define IOS AZ_REDEFINE_IOS_AT_END -#endif - } - - const char* OSPlatformToDefaultAssetPlatform(AZStd::string_view osPlatform) - { - if (osPlatform == PlatformCodeNameWindows || osPlatform == PlatformCodeNameLinux) - { - return PlatformPC; - } - else if (osPlatform == PlatformCodeNameMac) - { - return PlatformOSX; - } - else if (osPlatform == PlatformCodeNameAndroid) - { - return PlatformES3; - } - else if (osPlatform == PlatformCodeNameiOS) - { - return PlatformIOS; - } - else if (osPlatform == PlatformCodeNameProvo) - { - return PlatformProvo; - } - else if (osPlatform == PlatformCodeNameSalem) - { - return PlatformSalem; - } - else if (osPlatform == PlatformCodeNameJasper) - { - return PlatformJasper; - } - - AZ_Error("PlatformDefault", false, R"(Supplied OS platform "%.*s" does not have a corresponding default asset platform)", - aznumeric_cast(osPlatform.size()), osPlatform.data()); - return ""; - } - - PlatformFlags PlatformHelper::GetPlatformFlagFromPlatformIndex(PlatformId platformIndex) - { - if (platformIndex < 0 || platformIndex > PlatformId::NumPlatformIds) - { - return PlatformFlags::Platform_NONE; - } - if (platformIndex == PlatformId::ALL) - { - return PlatformFlags::Platform_ALL; - } - if (platformIndex == PlatformId::ALL_CLIENT) - { - return PlatformFlags::Platform_ALL_CLIENT; - } - return static_cast(1 << platformIndex); - } - - AZStd::fixed_vector PlatformHelper::GetPlatforms(PlatformFlags platformFlags) - { - AZStd::fixed_vector platforms; - for (int platformNum = 0; platformNum < PlatformId::NumPlatformIds; ++platformNum) - { - const bool isAllPlatforms = PlatformId::ALL == static_cast(platformNum) - && ((platformFlags & PlatformFlags::Platform_ALL) != PlatformFlags::Platform_NONE); - - const bool isAllClientPlatforms = PlatformId::ALL_CLIENT == static_cast(platformNum) - && ((platformFlags & PlatformFlags::Platform_ALL_CLIENT) != PlatformFlags::Platform_NONE); - - if (isAllPlatforms || isAllClientPlatforms - || (platformFlags & static_cast(1 << platformNum)) != PlatformFlags::Platform_NONE) - { - platforms.push_back(PlatformNames[platformNum]); - } - } - - return platforms; - } - - AZStd::fixed_vector PlatformHelper::GetPlatformsInterpreted(PlatformFlags platformFlags) - { - return GetPlatforms(GetPlatformFlagsInterpreted(platformFlags)); - } - - AZStd::fixed_vector PlatformHelper::GetPlatformIndices(PlatformFlags platformFlags) - { - AZStd::fixed_vector platformIndices; - for (int i = 0; i < PlatformId::NumPlatformIds; i++) - { - PlatformId index = static_cast(i); - if ((GetPlatformFlagFromPlatformIndex(index) & platformFlags) != PlatformFlags::Platform_NONE) - { - platformIndices.emplace_back(index); - } - } - return platformIndices; - } - - AZStd::fixed_vector PlatformHelper::GetPlatformIndicesInterpreted(PlatformFlags platformFlags) - { - return GetPlatformIndices(GetPlatformFlagsInterpreted(platformFlags)); - } - - PlatformFlags PlatformHelper::GetPlatformFlag(AZStd::string_view platform) - { - int platformIndex = GetPlatformIndexFromName(platform); - if (platformIndex == PlatformId::Invalid) - { - AZ_Error("PlatformDefault", false, "Invalid Platform ( %.*s ).\n", static_cast(platform.length()), platform.data()); - return PlatformFlags::Platform_NONE; - } - - if(platformIndex == PlatformId::ALL) - { - return PlatformFlags::Platform_ALL; - } - - if (platformIndex == PlatformId::ALL_CLIENT) - { - return PlatformFlags::Platform_ALL_CLIENT; - } - - return static_cast(1 << platformIndex); - } - - const char* PlatformHelper::GetPlatformName(PlatformId platform) - { - if (platform < 0 || platform > PlatformId::NumPlatformIds) - { - return "invalid"; - } - return PlatformNames[platform]; - } - - void PlatformHelper::AppendPlatformCodeNames(AZStd::fixed_vector& platformCodes, AZStd::string_view platformId) - { - PlatformId platform = GetPlatformIdFromName(platformId); - AZ_Assert(platform != PlatformId::Invalid, "Unsupported Platform ID: %.*s", static_cast(platformId.length()), platformId.data()); - AppendPlatformCodeNames(platformCodes, platform); - } - - void PlatformHelper::AppendPlatformCodeNames(AZStd::fixed_vector& platformCodes, PlatformId platformId) - { -// The IOS SDK has a macro that defines IOS as 1 which causes the enum below to be incorrectly converted to "PlatformId::1". -#pragma push_macro("IOS") -#undef IOS - // To reduce work the Asset Processor groups assets that can be shared between hardware platforms together. For this - // reason "PC" can for instance cover both the Windows and Linux platforms and "IOS" can cover AppleTV and iOS. - switch (platformId) - { - case PlatformId::PC: - platformCodes.emplace_back(PlatformCodeNameWindows); - platformCodes.emplace_back(PlatformCodeNameLinux); - break; - case PlatformId::ES3: - platformCodes.emplace_back(PlatformCodeNameAndroid); - break; - case PlatformId::IOS: - platformCodes.emplace_back(PlatformCodeNameiOS); - break; - case PlatformId::OSX: - platformCodes.emplace_back(PlatformCodeNameMac); - break; - case PlatformId::PROVO: - platformCodes.emplace_back(PlatformCodeNameProvo); - break; - case PlatformId::SALEM: - platformCodes.emplace_back(PlatformCodeNameSalem); - break; - case PlatformId::JASPER: - platformCodes.emplace_back(PlatformCodeNameJasper); - break; - case PlatformId::SERVER: - // Server is not a hardware platform - break; - default: - AZ_Assert(false, "Unsupported Platform ID: %i", platformId); - break; - } -#pragma pop_macro("IOS") - } - - int PlatformHelper::GetPlatformIndexFromName(AZStd::string_view platformName) - { - for (int idx = 0; idx < PlatformId::NumPlatformIds; idx++) - { - if (platformName == PlatformNames[idx]) - { - return idx; - } - } - - return PlatformId::Invalid; - } - - PlatformId PlatformHelper::GetPlatformIdFromName(AZStd::string_view platformName) - { - return aznumeric_caster(GetPlatformIndexFromName(platformName)); - } - - AssetPlatformCombinedString PlatformHelper::GetCommaSeparatedPlatformList(PlatformFlags platformFlags) - { - AZStd::fixed_vector platformNames = GetPlatforms(platformFlags); - AssetPlatformCombinedString platformsString; - AZ::StringFunc::Join(platformsString, platformNames.begin(), platformNames.end(), ", "); - return platformsString; - } - - PlatformFlags PlatformHelper::GetPlatformFlagsInterpreted(PlatformFlags platformFlags) - { - PlatformFlags returnFlags = PlatformFlags::Platform_NONE; - - if((platformFlags & PlatformFlags::Platform_ALL) != PlatformFlags::Platform_NONE) - { - for (int i = 0; i < NumPlatforms; ++i) - { - auto platformId = static_cast(i); - - if (platformId != PlatformId::ALL && platformId != PlatformId::ALL_CLIENT) - { - returnFlags |= GetPlatformFlagFromPlatformIndex(platformId); - } - } - } - else if((platformFlags & PlatformFlags::Platform_ALL_CLIENT) != PlatformFlags::Platform_NONE) - { - for (int i = 0; i < NumPlatforms; ++i) - { - auto platformId = static_cast(i); - - if (platformId != PlatformId::ALL && platformId != PlatformId::ALL_CLIENT && platformId != PlatformId::SERVER) - { - returnFlags |= GetPlatformFlagFromPlatformIndex(platformId); - } - } - } - else - { - returnFlags = platformFlags; - } - - return returnFlags; - } - - bool PlatformHelper::IsSpecialPlatform(PlatformFlags platformFlags) - { - return (platformFlags & PlatformFlags::Platform_ALL) != PlatformFlags::Platform_NONE - || (platformFlags & PlatformFlags::Platform_ALL_CLIENT) != PlatformFlags::Platform_NONE; - } - - bool HasFlagHelper(PlatformFlags flags, PlatformFlags checkPlatform) - { - return (flags & checkPlatform) == checkPlatform; - } - - - bool PlatformHelper::HasPlatformFlag(PlatformFlags flags, PlatformId checkPlatform) - { - // If checkPlatform contains any kind of invalid id, just exit out here - if(checkPlatform == PlatformId::Invalid || checkPlatform == NumPlatforms) - { - return false; - } - - // ALL_CLIENT + SERVER = ALL - if(HasFlagHelper(flags, PlatformFlags::Platform_ALL_CLIENT | PlatformFlags::Platform_SERVER)) - { - flags = PlatformFlags::Platform_ALL; - } - - if(HasFlagHelper(flags, PlatformFlags::Platform_ALL)) - { - // It doesn't matter what checkPlatform is set to in this case, just return true - return true; - } - - if(HasFlagHelper(flags, PlatformFlags::Platform_ALL_CLIENT)) - { - return checkPlatform != PlatformId::SERVER; - } - - return HasFlagHelper(flags, GetPlatformFlagFromPlatformIndex(checkPlatform)); - } - -} diff --git a/Code/Framework/AzFramework/AzFramework/Platform/PlatformDefaults.h b/Code/Framework/AzFramework/AzFramework/Platform/PlatformDefaults.h index d7f467ec0f..13f7fa20e5 100644 --- a/Code/Framework/AzFramework/AzFramework/Platform/PlatformDefaults.h +++ b/Code/Framework/AzFramework/AzFramework/Platform/PlatformDefaults.h @@ -12,144 +12,12 @@ #pragma once -#include -#include -#include -#include -#include - -// On IOS builds IOS will be defined and interfere with the below enums -#pragma push_macro("IOS") -#undef IOS +#include +// As the Platform defaults is needed within AzCore, +// those structures have been moved to AzCore and brought into +// The AzFramework namespace for backwards compatibility namespace AzFramework { - constexpr char PlatformPC[] = "pc"; - constexpr char PlatformES3[] = "es3"; - constexpr char PlatformIOS[] = "ios"; - constexpr char PlatformOSX[] = "osx_gl"; - constexpr char PlatformProvo[] = "provo"; - constexpr char PlatformSalem[] = "salem"; - constexpr char PlatformJasper[] = "jasper"; - constexpr char PlatformServer[] = "server"; - - constexpr char PlatformCodeNameWindows[] = "Windows"; - constexpr char PlatformCodeNameLinux[] = "Linux"; - constexpr char PlatformCodeNameAndroid[] = "Android"; - constexpr char PlatformCodeNameiOS[] = "iOS"; - constexpr char PlatformCodeNameMac[] = "Mac"; - constexpr char PlatformCodeNameProvo[] = "Provo"; - constexpr char PlatformCodeNameSalem[] = "Salem"; - constexpr char PlatformCodeNameJasper[] = "Jasper"; - constexpr char PlatformAll[] = "all"; - constexpr char PlatformAllClient[] = "all_client"; - - // Used for the capacity of a fixed vector to store the code names of platforms - // The value needs to be higher than the number of unique OS platforms that are supported(at this time 8) - constexpr size_t MaxPlatformCodeNames = 16; - - //! This platform enum have platform values in sequence and can also be used to get the platform count. - AZ_ENUM_WITH_UNDERLYING_TYPE(PlatformId, int, - (Invalid, -1), - PC, - ES3, - IOS, - OSX, - PROVO, - SALEM, - JASPER, - SERVER, // Corresponds to the customer's flavor of "server" which could be windows, ubuntu, etc - ALL, - ALL_CLIENT, - - // Add new platforms above this - NumPlatformIds - ); - constexpr int NumClientPlatforms = 7; - constexpr int NumPlatforms = NumClientPlatforms + 1; // 1 "Server" platform currently - enum class PlatformFlags : AZ::u32 - { - Platform_NONE = 0x00, - Platform_PC = 1 << PlatformId::PC, - Platform_ES3 = 1 << PlatformId::ES3, - Platform_IOS = 1 << PlatformId::IOS, - Platform_OSX = 1 << PlatformId::OSX, - Platform_PROVO = 1 << PlatformId::PROVO, - Platform_SALEM = 1 << PlatformId::SALEM, - Platform_JASPER = 1 << PlatformId::JASPER, - Platform_SERVER = 1 << PlatformId::SERVER, - - // A special platform that will always correspond to all platforms, even if new ones are added - Platform_ALL = 1ULL << 30, - - // A special platform that will always correspond to all non-server platforms, even if new ones are added - Platform_ALL_CLIENT = 1ULL << 31, - - AllNamedPlatforms = Platform_PC | Platform_ES3 | Platform_IOS | Platform_OSX | Platform_PROVO | Platform_SALEM | Platform_JASPER | Platform_SERVER, - }; - - AZ_DEFINE_ENUM_BITWISE_OPERATORS(PlatformFlags); - - // 32 characters should be more than enough to store a platform name - using AssetPlatformFixedString = AZStd::fixed_string<32>; - // Fixed string which can store a comma separated list of platforms names - // Additional byte is added to take into account the comma - using AssetPlatformCombinedString = AZStd::fixed_string<(AssetPlatformFixedString{}.max_size() + 1) * PlatformId::NumPlatformIds>; - - const char* PlatformIdToPalFolder(AzFramework::PlatformId platform); - - const char* OSPlatformToDefaultAssetPlatform(AZStd::string_view osPlatform); - - //! Platform Helper is an utility class that can be used to retrieve platform related information - class PlatformHelper - { - public: - - //! Given a platformIndex returns the platform name - static const char* GetPlatformName(PlatformId platform); - - //! Converts the platform name to the platform code names as defined in AZ_TRAIT_OS_PLATFORM_CODENAME. - static void AppendPlatformCodeNames(AZStd::fixed_vector& platformCodes, AZStd::string_view platformName); - - //! Converts the platform name to the platform code names as defined in AZ_TRAIT_OS_PLATFORM_CODENAME. - static void AppendPlatformCodeNames(AZStd::fixed_vector& platformCodes, PlatformId platformId); - - //! Given a platform name returns a platform index. - //! If the platform is not found, the method returns -1. - static int GetPlatformIndexFromName(AZStd::string_view platformName); - - //! Given a platform name returns a platform id. - //! If the platform is not found, the method returns -1. - static PlatformId GetPlatformIdFromName(AZStd::string_view platformName); - - //! Given a platformIndex returns the platformFlags - static PlatformFlags GetPlatformFlagFromPlatformIndex(PlatformId platform); - - //! Given a platformFlags returns all the platform identifiers that are set. - static AZStd::fixed_vector GetPlatforms(PlatformFlags platformFlags); - //! Given a platformFlags returns all the platform identifiers that are set, with special flags interpreted. Do not use the result for saving - static AZStd::fixed_vector GetPlatformsInterpreted(PlatformFlags platformFlags); - - //! Given a platformFlags return a list of PlatformId indices - static AZStd::fixed_vector GetPlatformIndices(PlatformFlags platformFlags); - //! Given a platformFlags return a list of PlatformId indices, with special flags interpreted. Do not use the result for saving - static AZStd::fixed_vector GetPlatformIndicesInterpreted(PlatformFlags platformFlags); - - //! Given a platform identifier returns its corresponding platform flag. - static PlatformFlags GetPlatformFlag(AZStd::string_view platform); - - //! Given any platformFlags returns a string listing the input platforms - static AssetPlatformCombinedString GetCommaSeparatedPlatformList(PlatformFlags platformFlags); - - //! If platformFlags contains any special flags, they are removed and replaced with the normal flags they represent - static PlatformFlags GetPlatformFlagsInterpreted(PlatformFlags platformFlags); - - //! Returns true if platformFlags contains any special flags - static bool IsSpecialPlatform(PlatformFlags platformFlags); - - //! Returns true if platformFlags has checkPlatform flag set. - static bool HasPlatformFlag(PlatformFlags platformFlags, PlatformId checkPlatform); - }; + using namespace AZ::PlatformDefaults; } - -#pragma pop_macro("IOS") diff --git a/Code/Framework/AzFramework/AzFramework/ProjectManager/ProjectManager.cpp b/Code/Framework/AzFramework/AzFramework/ProjectManager/ProjectManager.cpp index 5acf4e75d1..7e968ffcd8 100644 --- a/Code/Framework/AzFramework/AzFramework/ProjectManager/ProjectManager.cpp +++ b/Code/Framework/AzFramework/AzFramework/ProjectManager/ProjectManager.cpp @@ -42,8 +42,14 @@ namespace AzFramework::ProjectManager AZ::CommandLine commandLine; commandLine.Parse(argc, argv); AZ::SettingsRegistryImpl settingsRegistry; + // Store the Command line to the Setting Registry + + AZ::SettingsRegistryMergeUtils::StoreCommandLineToRegistry(settingsRegistry, commandLine); AZ::SettingsRegistryMergeUtils::MergeSettingsToRegistry_Bootstrap(settingsRegistry); AZ::SettingsRegistryMergeUtils::MergeSettingsToRegistry_O3deUserRegistry(settingsRegistry, AZ_TRAIT_OS_PLATFORM_CODENAME, {}); + // Retrieve Command Line from Settings Registry, it may have been updated by the call to FindEngineRoot() + // in MergeSettingstoRegistry_ConfigFile + AZ::SettingsRegistryMergeUtils::GetCommandLineFromRegistry(settingsRegistry, commandLine); AZ::SettingsRegistryMergeUtils::MergeSettingsToRegistry_CommandLine(settingsRegistry, commandLine, false); engineRootPath = AZ::SettingsRegistryMergeUtils::FindEngineRoot(settingsRegistry); projectRootPath = AZ::SettingsRegistryMergeUtils::FindProjectRoot(settingsRegistry); diff --git a/Code/Framework/AzFramework/AzFramework/Viewport/ScreenGeometry.h b/Code/Framework/AzFramework/AzFramework/Viewport/ScreenGeometry.h index 1b570ebb8e..d3ae4e16f3 100644 --- a/Code/Framework/AzFramework/AzFramework/Viewport/ScreenGeometry.h +++ b/Code/Framework/AzFramework/AzFramework/Viewport/ScreenGeometry.h @@ -14,6 +14,7 @@ #include #include +#include #include namespace AZ @@ -133,6 +134,18 @@ namespace AzFramework return !operator==(lhs, rhs); } + inline ScreenPoint ScreenPointFromNDC(const AZ::Vector3& screenNDC, const AZ::Vector2& viewportSize) + { + return ScreenPoint( + aznumeric_caster(std::round(screenNDC.GetX() * viewportSize.GetX())), + aznumeric_caster(std::round((1.0f - screenNDC.GetY()) * viewportSize.GetY()))); + } + + inline AZ::Vector2 NDCFromScreenPoint(const ScreenPoint& screenPoint, const AZ::Vector2& viewportSize) + { + return AZ::Vector2(aznumeric_cast(screenPoint.m_x), viewportSize.GetY() - aznumeric_cast(screenPoint.m_y)) / viewportSize; + } + //! Return an AZ::Vector2 from a ScreenPoint. inline AZ::Vector2 Vector2FromScreenPoint(const ScreenPoint& screenPoint) { diff --git a/Code/Framework/AzFramework/AzFramework/Viewport/ViewportScreen.cpp b/Code/Framework/AzFramework/AzFramework/Viewport/ViewportScreen.cpp index 3ca16897ba..5d2d02a398 100644 --- a/Code/Framework/AzFramework/AzFramework/Viewport/ViewportScreen.cpp +++ b/Code/Framework/AzFramework/AzFramework/Viewport/ViewportScreen.cpp @@ -101,20 +101,25 @@ namespace AzFramework cameraState.m_nearClip, cameraState.m_farClip); } - ScreenPoint WorldToScreen( - const AZ::Vector3& worldPosition, const AZ::Matrix4x4& cameraView, const AZ::Matrix4x4& cameraProjection, - const AZ::Vector2& viewportSize) + AZ::Vector3 WorldToScreenNDC( + const AZ::Vector3& worldPosition, const AZ::Matrix4x4& cameraView, const AZ::Matrix4x4& cameraProjection) { // transform the world space position to clip space const auto clipSpacePosition = cameraProjection * cameraView * AZ::Vector3ToVector4(worldPosition, 1.0f); // transform the clip space position to ndc space (perspective divide) const auto ndcPosition = clipSpacePosition / clipSpacePosition.GetW(); // transform ndc space from <-1,1> to <0, 1> range - const auto ndcNormalizedPosition = (AZ::Vector4ToVector2(ndcPosition) + AZ::Vector2::CreateOne()) * 0.5f; + return (AZ::Vector4ToVector3(ndcPosition) + AZ::Vector3::CreateOne()) * 0.5f; + } + + + ScreenPoint WorldToScreen( + const AZ::Vector3& worldPosition, const AZ::Matrix4x4& cameraView, 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 ScreenPoint( - aznumeric_caster(std::round(ndcNormalizedPosition.GetX() * viewportSize.GetX())), - aznumeric_caster(std::round(viewportSize.GetY() - (ndcNormalizedPosition.GetY() * viewportSize.GetY())))); + return ScreenPointFromNDC(ndcNormalizedPosition, viewportSize); } ScreenPoint WorldToScreen(const AZ::Vector3& worldPosition, const CameraState& cameraState) @@ -127,12 +132,8 @@ namespace AzFramework const ScreenPoint& screenPosition, const AZ::Matrix4x4& inverseCameraView, const AZ::Matrix4x4& inverseCameraProjection, const AZ::Vector2& viewportSize) { - const auto screenHeight = viewportSize.GetY(); - const auto flippedScreenPosition = - AZ::Vector2(aznumeric_caster(screenPosition.m_x), aznumeric_caster(screenHeight - screenPosition.m_y)); - - // convert screen space coordinates to <-1,1> range - const auto ndcPosition = (flippedScreenPosition / viewportSize) * 2.0f - AZ::Vector2::CreateOne(); + // convert screen space coordinates from <0, 1> to <-1,1> range + const auto ndcPosition = NDCFromScreenPoint(screenPosition, viewportSize) * 2.0f - AZ::Vector2::CreateOne(); // transform ndc space position to clip space const auto clipSpacePosition = inverseCameraProjection * Vector2ToVector4(ndcPosition, -1.0f, 1.0f); diff --git a/Code/Framework/AzFramework/AzFramework/Viewport/ViewportScreen.h b/Code/Framework/AzFramework/AzFramework/Viewport/ViewportScreen.h index 582e051bbb..a2c650465f 100644 --- a/Code/Framework/AzFramework/AzFramework/Viewport/ViewportScreen.h +++ b/Code/Framework/AzFramework/AzFramework/Viewport/ViewportScreen.h @@ -28,6 +28,11 @@ namespace AzFramework struct ScreenPoint; struct ViewportInfo; + //! Projects a position in world space to screen space normalized device coordinates for the given camera. + AZ::Vector3 WorldToScreenNDC( + const AZ::Vector3& worldPosition, const AZ::Matrix4x4& cameraView, const AZ::Matrix4x4& cameraProjection); + + //! Projects a position in world space to screen space for the given camera. ScreenPoint WorldToScreen(const AZ::Vector3& worldPosition, const CameraState& cameraState); diff --git a/Code/Framework/AzFramework/AzFramework/azframework_files.cmake b/Code/Framework/AzFramework/AzFramework/azframework_files.cmake index b37c1b259f..312a3766ac 100644 --- a/Code/Framework/AzFramework/AzFramework/azframework_files.cmake +++ b/Code/Framework/AzFramework/AzFramework/azframework_files.cmake @@ -145,6 +145,7 @@ set(FILES Components/NonUniformScaleComponent.cpp FileFunc/FileFunc.h FileFunc/FileFunc.cpp + Font/FontInterface.h Gem/GemInfo.cpp Gem/GemInfo.h StringFunc/StringFunc.h @@ -316,7 +317,6 @@ set(FILES Terrain/TerrainDataRequestBus.h Terrain/TerrainDataRequestBus.cpp Platform/PlatformDefaults.h - Platform/PlatformDefaults.cpp Windowing/WindowBus.h Windowing/NativeWindow.cpp Windowing/NativeWindow.h diff --git a/Code/Framework/AzFramework/CMakeLists.txt b/Code/Framework/AzFramework/CMakeLists.txt index f62f205efd..50e1fcb5a4 100644 --- a/Code/Framework/AzFramework/CMakeLists.txt +++ b/Code/Framework/AzFramework/CMakeLists.txt @@ -33,12 +33,12 @@ ly_add_target( BUILD_DEPENDENCIES PRIVATE AZ::AzCore + PUBLIC + AZ::GridMate 3rdParty::md5 3rdParty::zlib 3rdParty::zstd 3rdParty::lz4 - PUBLIC - AZ::GridMate ) if(LY_ENABLE_STATISTICAL_PROFILING) diff --git a/Code/Framework/AzGameFramework/AzGameFramework/Application/GameApplication.cpp b/Code/Framework/AzGameFramework/AzGameFramework/Application/GameApplication.cpp index f4fc9364f7..edd4af293d 100644 --- a/Code/Framework/AzGameFramework/AzGameFramework/Application/GameApplication.cpp +++ b/Code/Framework/AzGameFramework/AzGameFramework/Application/GameApplication.cpp @@ -80,6 +80,8 @@ namespace AzGameFramework AZ::SettingsRegistryMergeUtils::MergeSettingsToRegistry_ProjectUserRegistry(registry, AZ_TRAIT_OS_PLATFORM_CODENAME, specializations, &scratchBuffer); AZ::SettingsRegistryMergeUtils::MergeSettingsToRegistry_CommandLine(registry, m_commandLine, true); #endif + // Update the Runtime file paths in case the "{BootstrapSettingsRootKey}/assets" key was overriden by a setting registry + AZ::SettingsRegistryMergeUtils::MergeSettingsToRegistry_AddRuntimeFilePaths(registry); } AZ::ComponentTypeList GameApplication::GetRequiredSystemComponents() const diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/API/ToolsApplicationAPI.h b/Code/Framework/AzToolsFramework/AzToolsFramework/API/ToolsApplicationAPI.h index 0c631cf09e..f12ab71936 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/API/ToolsApplicationAPI.h +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/API/ToolsApplicationAPI.h @@ -578,16 +578,6 @@ namespace AzToolsFramework */ virtual bool IsEditorInIsolationMode() = 0; - /*! - * Get the engine root path that the current tool is running under. - */ - virtual const char* GetEngineRootPath() const = 0; - - /** - * Get the version of the engine the current tools application is running under - */ - virtual const char* GetEngineVersion() const = 0; - /** * Creates and adds a new entity to the tools application from components which match at least one of the requiredTags * The tag matching occurs on AZ::Edit::SystemComponentTags attribute from the reflected class data in the serialization context diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Application/ToolsApplication.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/Application/ToolsApplication.cpp index 352048f5f0..22c1390828 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Application/ToolsApplication.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Application/ToolsApplication.cpp @@ -224,112 +224,6 @@ namespace AzToolsFramework } // Internal -#define AZ_MAX_ENGINE_VERSION_LEN 64 - // Private Implementation class to manage the engine root and version - // Note: We are not using any AzCore classes because the ToolsApplication - // initialization happens early on, before the Allocators get instantiated, - // so we are using Qt privately instead - class ToolsApplication::EngineConfigImpl - { - private: - friend class ToolsApplication; - - typedef QMap EngineJsonMap; - - EngineConfigImpl(const char* logWindow, const char* fileName) - : m_logWindow(logWindow) - , m_fileName(fileName) - { - m_engineRoot[0] = '\0'; - m_engineVersion[0] = '\0'; - } - - char m_engineRoot[AZ_MAX_PATH_LEN]; - char m_engineVersion[AZ_MAX_ENGINE_VERSION_LEN]; - EngineJsonMap m_engineConfigMap; - const char* m_logWindow; - const char* m_fileName; - - - // Read an engine configuration into a map of key/value pairs - bool ReadEngineConfigIntoMap(QString engineJsonPath, EngineJsonMap& engineJsonMap) - { - QFile engineJsonFile(engineJsonPath); - if (!engineJsonFile.open(QIODevice::ReadOnly | QIODevice::Text)) - { - AZ_Warning(m_logWindow, false, "Unable to open file '%s' in the current root directory", engineJsonPath.toUtf8().data()); - return false; - } - - QByteArray engineJsonData = engineJsonFile.readAll(); - engineJsonFile.close(); - QJsonDocument engineJsonDoc(QJsonDocument::fromJson(engineJsonData)); - if (engineJsonDoc.isNull()) - { - AZ_Warning(m_logWindow, false, "Unable to read file '%s' in the current root directory", engineJsonPath.toUtf8().data()); - return false; - } - - QJsonObject engineJsonRoot = engineJsonDoc.object(); - for (const QString& configKey : engineJsonRoot.keys()) - { - QJsonValue configValue = engineJsonRoot[configKey]; - if (configValue.isString() || configValue.isDouble()) - { - // Only map strings and numbers, ignore every other type - engineJsonMap[configKey] = configValue.toString(); - } - else - { - AZ_Warning(m_logWindow, false, "Ignoring key '%s' from '%s', unsupported type.", configKey.toUtf8().data(), engineJsonPath.toUtf8().data()); - } - } - return true; - } - - // Initialize the engine config object based on the current - bool Initialize(const char* currentEngineRoot) - { - // Start with the app root as the engine root (legacy), but check to see if the engine root - // is external to the app root - azstrncpy(m_engineRoot, AZ_ARRAY_SIZE(m_engineRoot), currentEngineRoot, strlen(currentEngineRoot) + 1); - - // From the appRoot, check and see if we can read any external engine reference in engine.json - QString engineJsonFileName = QString(m_fileName); - QString engineJsonFilePath = QDir(currentEngineRoot).absoluteFilePath(engineJsonFileName); - - // From the appRoot, check and see if we can read any external engine reference in engine.json - if (!QFile::exists(engineJsonFilePath)) - { - AZ_Warning(m_logWindow, false, "Unable to find '%s' in the current app root directory.", m_fileName); - return false; - } - if (!ReadEngineConfigIntoMap(engineJsonFilePath, m_engineConfigMap)) - { - AZ_Warning(m_logWindow, false, "Defaulting root engine path to '%s'", currentEngineRoot); - return false; - } - - // Read in the local engine version value - auto localEngineVersionValue = m_engineConfigMap.find(QString(AzToolsFramework::Internal::s_engineConfigEngineVersionKey)); - QString localEngineVersion(localEngineVersionValue.value()); - azstrncpy(m_engineVersion, AZ_ARRAY_SIZE(m_engineVersion), localEngineVersion.toUtf8().data(), localEngineVersion.length() + 1); - - return true; - } - - const char* GetEngineRoot() const - { - return m_engineRoot; - } - - const char* GetEngineVersion() const - { - return m_engineVersion; - } - }; - - ToolsApplication::ToolsApplication(int* argc, char*** argv) : AzFramework::Application(argc, argv) , m_selectionBounds(AZ::Aabb()) @@ -339,7 +233,6 @@ namespace AzToolsFramework , m_isInIsolationMode(false) { ToolsApplicationRequests::Bus::Handler::BusConnect(); - m_engineConfigImpl.reset(new ToolsApplication::EngineConfigImpl(AzToolsFramework::Internal::s_startupLogWindow, AzToolsFramework::Internal::s_engineConfigFileName)); m_undoCache.RegisterToUndoCacheInterface(); } @@ -391,7 +284,6 @@ namespace AzToolsFramework void ToolsApplication::Start(const Descriptor& descriptor, const StartupParameters& startupParameters/* = StartupParameters()*/) { Application::Start(descriptor, startupParameters); - InitializeEngineConfig(); m_editorEntityManager.Start(); @@ -399,14 +291,6 @@ namespace AzToolsFramework AZ_Assert(m_editorEntityAPI, "ToolsApplication - Could not retrieve instance of EditorEntityAPI"); } - void ToolsApplication::InitializeEngineConfig() - { - if (!m_engineConfigImpl->Initialize(GetEngineRoot())) - { - AZ_Warning(AzToolsFramework::Internal::s_startupLogWindow, false, "Defaulting engine root path to '%s'", GetEngineRoot()); - } - } - void ToolsApplication::StartCommon(AZ::Entity* systemEntity) { Application::StartCommon(systemEntity); @@ -1832,16 +1716,6 @@ namespace AzToolsFramework return m_isInIsolationMode; } - const char* ToolsApplication::GetEngineRootPath() const - { - return m_engineConfigImpl->GetEngineRoot(); - } - - const char* ToolsApplication::GetEngineVersion() const - { - return m_engineConfigImpl->GetEngineVersion(); - } - void ToolsApplication::CreateAndAddEntityFromComponentTags(const AZStd::vector& requiredTags, const char* entityName) { if (!entityName || !entityName[0]) diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Application/ToolsApplication.h b/Code/Framework/AzToolsFramework/AzToolsFramework/Application/ToolsApplication.h index ef9f190309..0f038422ce 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Application/ToolsApplication.h +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Application/ToolsApplication.h @@ -150,8 +150,6 @@ namespace AzToolsFramework void EnterEditorIsolationMode() override; void ExitEditorIsolationMode() override; bool IsEditorInIsolationMode() override; - const char* GetEngineRootPath() const override; - const char* GetEngineVersion() const override; void CreateAndAddEntityFromComponentTags(const AZStd::vector& requiredTags, const char* entityName) override; @@ -174,7 +172,6 @@ namespace AzToolsFramework void CreateUndosForDirtyEntities(); void ConsistencyCheckUndoCache(); - void InitializeEngineConfig(); AZ::Aabb m_selectionBounds; EntityIdList m_selectedEntities; EntityIdList m_highlightedEntities; @@ -186,9 +183,6 @@ namespace AzToolsFramework bool m_isInIsolationMode; EntityIdSet m_isolatedEntityIdSet; - class EngineConfigImpl; - AZStd::unique_ptr m_engineConfigImpl; - EditorEntityAPI* m_editorEntityAPI = nullptr; EditorEntityManager m_editorEntityManager; diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/Search/SearchWidget.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/Search/SearchWidget.cpp index 7c2f26042f..d2edbcce32 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/Search/SearchWidget.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/Search/SearchWidget.cpp @@ -170,6 +170,15 @@ namespace AzToolsFramework return m_filter; } + QSharedPointer SearchWidget::GetStringFilter() const + { + return m_stringFilter; + } + + QSharedPointer SearchWidget::GetTypesFilter() const + { + return m_typesFilter; + } } // namespace AssetBrowser } // namespace AzToolsFramework diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/Search/SearchWidget.h b/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/Search/SearchWidget.h index 0453333c94..be649bc81d 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/Search/SearchWidget.h +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/Search/SearchWidget.h @@ -39,6 +39,10 @@ namespace AzToolsFramework QSharedPointer GetFilter() const; + QSharedPointer GetStringFilter() const; + + QSharedPointer GetTypesFilter() const; + QString GetFilterString() const { return textFilter(); } void ClearStringFilter() { ClearTextFilter(); } diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Entity/EditorEntityHelpers.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/Entity/EditorEntityHelpers.cpp index 6ab3625dd2..629dcd639d 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Entity/EditorEntityHelpers.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Entity/EditorEntityHelpers.cpp @@ -136,6 +136,48 @@ namespace AzToolsFramework return entity->GetName(); } + EntityList EntityIdListToEntityList(const EntityIdList& inputEntityIds) + { + EntityList entities; + entities.reserve(inputEntityIds.size()); + + for (AZ::EntityId entityId : inputEntityIds) + { + if (!entityId.IsValid()) + { + continue; + } + + if (auto entity = GetEntityById(entityId)) + { + entities.emplace_back(entity); + } + } + + return entities; + } + + EntityList EntityIdSetToEntityList(const EntityIdSet& inputEntityIds) + { + EntityList entities; + entities.reserve(inputEntityIds.size()); + + for (AZ::EntityId entityId : inputEntityIds) + { + if (!entityId.IsValid()) + { + continue; + } + + if (auto entity = GetEntityById(entityId)) + { + entities.emplace_back(entity); + } + } + + return entities; + } + void GetAllComponentsForEntity(const AZ::Entity* entity, AZ::Entity::ComponentArrayType& componentsOnEntity) { if (entity) @@ -1068,6 +1110,45 @@ namespace AzToolsFramework return !allEntityClonesContainer.m_entities.empty(); } + EntityIdSet GetCulledEntityHierarchy(const EntityIdList& entities) + { + EntityIdSet culledEntities; + + for (const AZ::EntityId& entityId : entities) + { + bool selectionIncludesTransformHeritage = false; + AZ::EntityId parentEntityId = entityId; + do + { + AZ::EntityId nextParentId; + AZ::TransformBus::EventResult( + /*result*/ nextParentId, + /*address*/ parentEntityId, + &AZ::TransformBus::Events::GetParentId); + parentEntityId = nextParentId; + if (!parentEntityId.IsValid()) + { + break; + } + for (const AZ::EntityId& parentCheck : entities) + { + if (parentCheck == parentEntityId) + { + selectionIncludesTransformHeritage = true; + break; + } + } + } while (parentEntityId.IsValid() && !selectionIncludesTransformHeritage); + + if (!selectionIncludesTransformHeritage) + { + culledEntities.insert(entityId); + } + } + + return culledEntities; + } + namespace Internal { void CloneSliceEntitiesAndChildren( diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Entity/EditorEntityHelpers.h b/Code/Framework/AzToolsFramework/AzToolsFramework/Entity/EditorEntityHelpers.h index 39f4c37c29..5454b19f7a 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Entity/EditorEntityHelpers.h +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Entity/EditorEntityHelpers.h @@ -47,6 +47,9 @@ namespace AzToolsFramework AZStd::string GetEntityName(const AZ::EntityId& entityId, const AZStd::string_view& nameOverride = {}); + EntityList EntityIdListToEntityList(const EntityIdList& inputEntityIds); + EntityList EntityIdSetToEntityList(const EntityIdSet& inputEntityIds); + template struct AddComponents { @@ -202,4 +205,8 @@ namespace AzToolsFramework /// Wrap EBus SetSelectedEntities call. void SelectEntities(const AzToolsFramework::EntityIdList& entities); + /// Return a set of entities, culling any that have an ancestor in the list. + /// e.g. This is useful for getting a concise set of entities that need to be duplicated. + EntityIdSet GetCulledEntityHierarchy(const EntityIdList& entities); + }; // namespace AzToolsFramework diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicHandler.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicHandler.cpp index 26191c97af..c64a9491c5 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicHandler.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicHandler.cpp @@ -61,8 +61,7 @@ namespace AzToolsFramework PrefabOperationResult PrefabPublicHandler::CreatePrefab(const AZStd::vector& entityIds, AZ::IO::PathView filePath) { // Retrieve entityList from entityIds - EntityList inputEntityList; - EntityIdListToEntityList(entityIds, inputEntityList); + EntityList inputEntityList = EntityIdListToEntityList(entityIds); // Find common root and top level entities bool entitiesHaveCommonRoot = false; @@ -419,8 +418,7 @@ namespace AzToolsFramework InstanceOptionalReference instance = GetOwnerInstanceByEntityId(entityIds[0]); // Retrieve entityList from entityIds - EntityList inputEntityList; - EntityIdListToEntityList(entityIds, inputEntityList); + EntityList inputEntityList = EntityIdListToEntityList(entityIds); AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); @@ -767,18 +765,5 @@ namespace AzToolsFramework return true; } - - void PrefabPublicHandler::EntityIdListToEntityList(const EntityIdList& inputEntityIds, EntityList& outEntities) - { - outEntities.reserve(inputEntityIds.size()); - - for (AZ::EntityId entityId : inputEntityIds) - { - if (entityId.IsValid()) - { - outEntities.emplace_back(GetEntityById(entityId)); - } - } - } } } diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicHandler.h b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicHandler.h index 80f28d7edb..d9dba2a32e 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicHandler.h +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicHandler.h @@ -70,7 +70,6 @@ namespace AzToolsFramework static Instance* GetParentInstance(Instance* instance); static Instance* GetAncestorOfInstanceThatIsChildOfRoot(const Instance* ancestor, Instance* descendant); static void GenerateContainerEntityTransform(const EntityList& topLevelEntities, AZ::Vector3& translation, AZ::Quaternion& rotation); - static void EntityIdListToEntityList(const EntityIdList& inputEntityIds, EntityList& outEntities); InstanceEntityMapperInterface* m_instanceEntityMapperInterface = nullptr; InstanceToTemplateInterface* m_instanceToTemplateInterface = nullptr; diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Thumbnails/ThumbnailWidget.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/Thumbnails/ThumbnailWidget.cpp index f2b81fdb98..1aefa6f189 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Thumbnails/ThumbnailWidget.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Thumbnails/ThumbnailWidget.cpp @@ -79,7 +79,9 @@ namespace AzToolsFramework int realHeight = qMin(aznumeric_cast(originalWidth /aspectRatio), originalHeight); int realWidth = aznumeric_cast(realHeight * aspectRatio); int x = (originalWidth - realWidth) / 2; - painter.drawPixmap(QRect(x, 0, realHeight, realWidth), pixmap); + // pixmap needs to be manually scaled to produce smoother result and avoid looking pixelated + // using painter.setRenderHint(QPainter::SmoothPixmapTransform); does not seem to work + painter.drawPixmap(QPoint(x, 0), pixmap.scaled(realWidth, realHeight, Qt::IgnoreAspectRatio, Qt::SmoothTransformation)); } QWidget::paintEvent(event); } diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/UI/Outliner/EntityOutlinerListModel.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/UI/Outliner/EntityOutlinerListModel.cpp index ea281aacf7..de10ae18b4 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/UI/Outliner/EntityOutlinerListModel.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/UI/Outliner/EntityOutlinerListModel.cpp @@ -1344,14 +1344,15 @@ namespace AzToolsFramework emit EnableSelectionUpdates(false); auto parentIndex = GetIndexFromEntity(parentId); auto childIndex = GetIndexFromEntity(childId); - beginRemoveRows(parentIndex, childIndex.row(), childIndex.row()); + beginResetModel(); } void EntityOutlinerListModel::OnEntityInfoUpdatedRemoveChildEnd(AZ::EntityId parentId, AZ::EntityId childId) { (void)childId; AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); - endRemoveRows(); + + endResetModel(); //must refresh partial lock/visibility of parents m_isFilterDirty = true; diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/UI/PropertyEditor/PropertyAssetCtrl.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/UI/PropertyEditor/PropertyAssetCtrl.cpp index bc27ffa5e1..261645e79a 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/UI/PropertyEditor/PropertyAssetCtrl.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/UI/PropertyEditor/PropertyAssetCtrl.cpp @@ -38,6 +38,7 @@ AZ_POP_DISABLE_WARNING #include #include #include +#include #include #include #include @@ -1212,9 +1213,8 @@ namespace AzToolsFramework if (!QFile::exists(path)) { - const char* engineRoot = nullptr; - AzToolsFramework::ToolsApplicationRequestBus::BroadcastResult(engineRoot, &AzToolsFramework::ToolsApplicationRequests::GetEngineRootPath); - QDir engineDir = engineRoot ? QDir(engineRoot) : QDir::current(); + AZ::IO::FixedMaxPathString engineRoot = AZ::Utils::GetEnginePath(); + QDir engineDir = !engineRoot.empty() ? QDir(QString(engineRoot.c_str())) : QDir::current(); path = engineDir.absoluteFilePath(iconPath.c_str()); } diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportSelection/EditorTransformComponentSelection.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportSelection/EditorTransformComponentSelection.cpp index 83632708d9..433602e6d8 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportSelection/EditorTransformComponentSelection.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportSelection/EditorTransformComponentSelection.cpp @@ -53,7 +53,7 @@ namespace AzToolsFramework float, cl_viewportGizmoAxisLabelOffset, 1.15f, nullptr, AZ::ConsoleFunctorFlags::Null, "The offset of the label for the viewport axis gizmo"); AZ_CVAR( - float, cl_viewportGizmoAxisLabelSize, 2.0f, nullptr, AZ::ConsoleFunctorFlags::Null, + float, cl_viewportGizmoAxisLabelSize, 1.0f, nullptr, AZ::ConsoleFunctorFlags::Null, "The size of each label for the viewport axis gizmo"); AZ_CVAR( AZ::Vector2, cl_viewportGizmoAxisScreenPosition, AZ::Vector2(0.045f, 0.9f), nullptr, @@ -3434,19 +3434,22 @@ namespace AzToolsFramework const auto cameraProjection = AzFramework::CameraProjection(gizmoCameraState); // screen space offset to move the 2d gizmo around - const AZ::Vector3 screenPosition = - (AZ::Vector2ToVector3(cl_viewportGizmoAxisScreenPosition) - AZ::Vector3(0.5f, 0.5f, 0.0f)) * - AZ::Vector2ToVector3(gizmoCameraState.m_viewportSize); + const AZ::Vector2 screenOffset = AZ::Vector2(cl_viewportGizmoAxisScreenPosition) - AZ::Vector2(0.5f, 0.5f); // map from a position in world space (relative to the the gizmo camera near the origin) to a position in // screen space const auto calculateGizmoAxis = - [&cameraView, &cameraProjection, &gizmoCameraState, &screenPosition] - (const AZ::Vector3& position) + [&cameraView, &cameraProjection, &screenOffset] + (const AZ::Vector3& axis) { - return AZ::Vector2ToVector3(AzFramework::Vector2FromScreenPoint( - AzFramework::WorldToScreen( - position, cameraView, cameraProjection, gizmoCameraState.m_viewportSize))) + screenPosition; + auto result = AZ::Vector2( + AzFramework::WorldToScreenNDC( + axis, + cameraView, + cameraProjection) + ); + result.SetY(1.0f - result.GetY()); + return result + screenOffset; }; // get all important axis positions in screen space @@ -3456,31 +3459,31 @@ namespace AzToolsFramework const auto gizmoEndAxisY = calculateGizmoAxis(-AZ::Vector3::CreateAxisY() * lineLength); const auto gizmoEndAxisZ = calculateGizmoAxis(-AZ::Vector3::CreateAxisZ() * lineLength); - const AZ::Vector3 gizmoAxisX = gizmoEndAxisX - gizmoStart; - const AZ::Vector3 gizmoAxisY = gizmoEndAxisY - gizmoStart; - const AZ::Vector3 gizmoAxisZ = gizmoEndAxisZ - gizmoStart; + const AZ::Vector2 gizmoAxisX = gizmoEndAxisX - gizmoStart; + const AZ::Vector2 gizmoAxisY = gizmoEndAxisY - gizmoStart; + const AZ::Vector2 gizmoAxisZ = gizmoEndAxisZ - gizmoStart; // draw the axes of the gizmo debugDisplay.SetLineWidth(cl_viewportGizmoAxisLineWidth); debugDisplay.SetColor(AZ::Colors::Red); - debugDisplay.DrawLine(gizmoStart, gizmoEndAxisX); + debugDisplay.DrawLine2d(gizmoStart, gizmoEndAxisX, 1.0f); debugDisplay.SetColor(AZ::Colors::Lime); - debugDisplay.DrawLine(gizmoStart, gizmoEndAxisY); + debugDisplay.DrawLine2d(gizmoStart, gizmoEndAxisY, 1.0f); debugDisplay.SetColor(AZ::Colors::Blue); - debugDisplay.DrawLine(gizmoStart, gizmoEndAxisZ); + debugDisplay.DrawLine2d(gizmoStart, gizmoEndAxisZ, 1.0f); debugDisplay.SetLineWidth(1.0f); const float labelOffset = cl_viewportGizmoAxisLabelOffset; - const auto labelOffsetX = gizmoStart + gizmoAxisX * labelOffset; - const auto labelOffsetY = gizmoStart + gizmoAxisY * labelOffset; - const auto labelOffsetZ = gizmoStart + gizmoAxisZ * labelOffset; + const auto labelXScreenPosition = (gizmoStart + (gizmoAxisX * labelOffset)) * editorCameraState.m_viewportSize; + const auto labelYScreenPosition = (gizmoStart + (gizmoAxisY * labelOffset)) * editorCameraState.m_viewportSize; + const auto labelZScreenPosition = (gizmoStart + (gizmoAxisZ * labelOffset)) * editorCameraState.m_viewportSize; // draw the label of of each axis for the gizmo const float labelSize = cl_viewportGizmoAxisLabelSize; debugDisplay.SetColor(AZ::Colors::White); - debugDisplay.Draw2dTextLabel(labelOffsetX.GetX(), labelOffsetX.GetY(), labelSize, "X", true); - debugDisplay.Draw2dTextLabel(labelOffsetY.GetX(), labelOffsetY.GetY(), labelSize, "Y", true); - debugDisplay.Draw2dTextLabel(labelOffsetZ.GetX(), labelOffsetZ.GetY(), labelSize, "Z", true); + debugDisplay.Draw2dTextLabel(labelXScreenPosition.GetX(), labelXScreenPosition.GetY(), labelSize, "X", true); + debugDisplay.Draw2dTextLabel(labelYScreenPosition.GetX(), labelYScreenPosition.GetY(), labelSize, "Y", true); + debugDisplay.Draw2dTextLabel(labelZScreenPosition.GetX(), labelZScreenPosition.GetY(), labelSize, "Z", true); } void EditorTransformComponentSelection::DisplayViewportSelection2d( diff --git a/Code/Framework/AzToolsFramework/Tests/AssetSeedManager.cpp b/Code/Framework/AzToolsFramework/Tests/AssetSeedManager.cpp index 2003f8eafd..5ccbd95f09 100644 --- a/Code/Framework/AzToolsFramework/Tests/AssetSeedManager.cpp +++ b/Code/Framework/AzToolsFramework/Tests/AssetSeedManager.cpp @@ -68,7 +68,7 @@ namespace UnitTest { assets[idx] = AssetId(AZ::Uuid::CreateRandom(), 0); AZ::Data::AssetInfo info; - info.m_relativePath = AZStd::string::format("Asset%d.txt", idx); + info.m_relativePath = AZStd::string::format("asset%d.txt", idx); m_assetsPath[idx] = info.m_relativePath; info.m_assetId = assets[idx]; m_assetRegistry->RegisterAsset(assets[idx], info); @@ -623,7 +623,7 @@ namespace UnitTest EXPECT_TRUE(Search(assetList1, assets[fileIndex])); if (m_fileStreams[0][fileIndex].Open(m_assetsPathFull[0][fileIndex].c_str(), AZ::IO::OpenMode::ModeWrite | AZ::IO::OpenMode::ModeBinary | AZ::IO::OpenMode::ModeCreatePath)) { - AZStd::string fileContent = AZStd::string::format("Asset%d.txt", fileIndex); + AZStd::string fileContent = AZStd::string::format("asset%d.txt", fileIndex); m_fileStreams[0][fileIndex].Write(fileContent.size(), fileContent.c_str()); m_fileStreams[0][fileIndex].Close(); } @@ -654,7 +654,7 @@ namespace UnitTest EXPECT_TRUE(Search(assetList1, assets[fileIndex])); if (m_fileStreams[0][fileIndex].Open(m_assetsPathFull[0][fileIndex].c_str(), AZ::IO::OpenMode::ModeWrite | AZ::IO::OpenMode::ModeBinary | AZ::IO::OpenMode::ModeCreatePath)) { - AZStd::string fileContent = AZStd::string::format("Asset%d.txt", fileIndex + 1);// changing file content + AZStd::string fileContent = AZStd::string::format("asset%d.txt", fileIndex + 1);// changing file content m_fileStreams[0][fileIndex].Write(fileContent.size(), fileContent.c_str()); m_fileStreams[0][fileIndex].Close(); } @@ -987,7 +987,7 @@ namespace UnitTest m_assetSeedManager->AddSeedAsset(assets[0], AzFramework::PlatformFlags::Platform_PC | AzFramework::PlatformFlags::Platform_OSX); - m_assetSeedManager->RemoveSeedAsset("Asset0.txt", AzFramework::PlatformFlags::Platform_PC | AzFramework::PlatformFlags::Platform_OSX); + m_assetSeedManager->RemoveSeedAsset("asset0.txt", AzFramework::PlatformFlags::Platform_PC | AzFramework::PlatformFlags::Platform_OSX); const AzFramework::AssetSeedList& secondSeedList = m_assetSeedManager->GetAssetSeedList(); EXPECT_EQ(secondSeedList.size(), 0); } @@ -1003,7 +1003,7 @@ namespace UnitTest m_assetSeedManager->AddSeedAsset(assets[0], AzFramework::PlatformFlags::Platform_PC | AzFramework::PlatformFlags::Platform_OSX); - m_assetSeedManager->RemoveSeedAsset("Asset0.txt", AzFramework::PlatformFlags::Platform_PC); + m_assetSeedManager->RemoveSeedAsset("asset0.txt", AzFramework::PlatformFlags::Platform_PC); const AzFramework::AssetSeedList& secondSeedList = m_assetSeedManager->GetAssetSeedList(); EXPECT_EQ(secondSeedList.size(), 1); } @@ -1017,7 +1017,7 @@ namespace UnitTest EXPECT_EQ(seedList.size(), 1); - m_assetSeedManager->RemoveSeedAsset("Asset1.txt", AzFramework::PlatformFlags::Platform_PC | AzFramework::PlatformFlags::Platform_OSX); + m_assetSeedManager->RemoveSeedAsset("asset1.txt", AzFramework::PlatformFlags::Platform_PC | AzFramework::PlatformFlags::Platform_OSX); const AzFramework::AssetSeedList& secondSeedList = m_assetSeedManager->GetAssetSeedList(); EXPECT_EQ(secondSeedList.size(), 1); } diff --git a/Code/Framework/AzToolsFramework/Tests/Entity/EditorEntityHelpersTests.cpp b/Code/Framework/AzToolsFramework/Tests/Entity/EditorEntityHelpersTests.cpp new file mode 100644 index 0000000000..51feacfa2b --- /dev/null +++ b/Code/Framework/AzToolsFramework/Tests/Entity/EditorEntityHelpersTests.cpp @@ -0,0 +1,57 @@ +/* +* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or +* its licensors. +* +* For complete copyright and license terms please see the LICENSE at the root of this +* distribution (the "License"). All use of this software is governed by the License, +* or, if provided, by the license below or the license accompanying this file. Do not +* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* +*/ + +#include + +#include +#include +#include + +namespace UnitTest +{ + class EditorEntityHelpersTest + : public ToolsApplicationFixture + { + void SetUpEditorFixtureImpl() override + { + m_parent1 = CreateDefaultEditorEntity("Parent1"); + m_child1 = CreateDefaultEditorEntity("Child1"); + m_child2 = CreateDefaultEditorEntity("Child2"); + m_grandChild1 = CreateDefaultEditorEntity("GrandChild1"); + m_parent2 = CreateDefaultEditorEntity("Parent2"); + + AZ::TransformBus::Event(m_child1, &AZ::TransformBus::Events::SetParent, m_parent1); + AZ::TransformBus::Event(m_child2, &AZ::TransformBus::Events::SetParent, m_parent1); + AZ::TransformBus::Event(m_grandChild1, &AZ::TransformBus::Events::SetParent, m_child1); + } + + public: + AZ::EntityId m_parent1; + AZ::EntityId m_child1; + AZ::EntityId m_child2; + AZ::EntityId m_grandChild1; + AZ::EntityId m_parent2; + }; + + TEST_F(EditorEntityHelpersTest, EditorEntityHelpersTests_GetCulledEntityHierarchy) + { + AzToolsFramework::EntityIdList testEntityIds{ m_parent1, m_child1, m_child2, m_grandChild1, m_parent2 }; + + AzToolsFramework::EntityIdSet culledSet = AzToolsFramework::GetCulledEntityHierarchy(testEntityIds); + + // There should only be two EntityIds returned (m_parent1, and m_parent2), + // since all the others should be culled out since they have a common ancestor + // in the list already + using ::testing::UnorderedElementsAre; + EXPECT_THAT(culledSet, UnorderedElementsAre(m_parent1, m_parent2)); + } +} diff --git a/Code/Framework/AzToolsFramework/Tests/aztoolsframeworktests_files.cmake b/Code/Framework/AzToolsFramework/Tests/aztoolsframeworktests_files.cmake index 7a2cd373a2..e54aa187e4 100644 --- a/Code/Framework/AzToolsFramework/Tests/aztoolsframeworktests_files.cmake +++ b/Code/Framework/AzToolsFramework/Tests/aztoolsframeworktests_files.cmake @@ -85,7 +85,9 @@ set(FILES Prefab/SpawnableSortEntitiesTestFixture.cpp Prefab/SpawnableSortEntitiesTestFixture.h Entity/EditorEntityContextComponentTests.cpp + Entity/EditorEntityHelpersTests.cpp Entity/EditorEntitySearchComponentTests.cpp + Entity/EditorEntitySelectionTests.cpp SliceStabilityTests/SliceStabilityTestFramework.h SliceStabilityTests/SliceStabilityTestFramework.cpp SliceStabilityTests/SliceStabilityCreateTests.cpp diff --git a/Code/Framework/GridMate/CMakeLists.txt b/Code/Framework/GridMate/CMakeLists.txt index f326bda179..20ce582307 100644 --- a/Code/Framework/GridMate/CMakeLists.txt +++ b/Code/Framework/GridMate/CMakeLists.txt @@ -28,8 +28,9 @@ ly_add_target( ${pal_dir} BUILD_DEPENDENCIES PRIVATE - 3rdParty::OpenSSL AZ::AzCore + PUBLIC + 3rdParty::OpenSSL ) ly_add_source_properties( diff --git a/Code/Sandbox/Editor/AlignTool.cpp b/Code/Sandbox/Editor/AlignTool.cpp deleted file mode 100644 index 4b3aedfbfa..0000000000 --- a/Code/Sandbox/Editor/AlignTool.cpp +++ /dev/null @@ -1,142 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#include "EditorDefs.h" - -#include "AlignTool.h" - -// Editor -#include "Objects/BaseObject.h" -#include "Objects/SelectionGroup.h" - -////////////////////////////////////////////////////////////////////////// -bool CAlignPickCallback::m_bActive = false; - -////////////////////////////////////////////////////////////////////////// -//! Called when object picked. -void CAlignPickCallback::OnPick(CBaseObject* picked) -{ - Matrix34 pickedTM(picked->GetWorldTM()); - - AABB pickedAABB; - picked->GetBoundBox(pickedAABB); - pickedAABB.Move(-pickedTM.GetTranslation()); - Vec3 pickedPivot = pickedAABB.GetCenter(); - - AABB pickedLocalAABB; - picked->GetLocalBounds(pickedLocalAABB); - - const Quat& pickedRot = picked->GetRotation(); - const Vec3& pickedScale = picked->GetScale(); - const Vec3& pickedPos = picked->GetPos(); - - bool bKeepScale = CheckVirtualKey(Qt::Key_Shift); - bool bKeepRotation = CheckVirtualKey(Qt::Key_Alt); - bool bAlignToBoundBox = CheckVirtualKey(Qt::Key_Control); - bool bApplyTransform = !bKeepScale && !bKeepRotation && !bAlignToBoundBox; - - { - bool bUndo = !CUndo::IsRecording(); - if (bUndo) - { - GetIEditor()->BeginUndo(); - } - - CSelectionGroup* selGroup = GetIEditor()->GetSelection(); - selGroup->FilterParents(); - - for (int i = 0; i < selGroup->GetFilteredCount(); i++) - { - CBaseObject* pMovedObj = selGroup->GetFilteredObject(i); - - if (bKeepScale || bKeepRotation || bApplyTransform) - { - if (bKeepScale && bKeepRotation) // Keep scale and rotation of a moved object - { - pMovedObj->SetWorldTM(Matrix34::Create(pMovedObj->GetScale(), pMovedObj->GetRotation(), pickedPos), eObjectUpdateFlags_UserInput); - } - else if (bKeepScale) // Keep only scale of a moved object - { - pMovedObj->SetWorldTM(Matrix34::Create(pMovedObj->GetScale(), pickedRot, pickedPos), eObjectUpdateFlags_UserInput); - } - else if (bKeepRotation) // Keep only rotation of a moved object - { - pMovedObj->SetWorldTM(Matrix34::Create(pickedScale, pMovedObj->GetRotation(), pickedPos), eObjectUpdateFlags_UserInput); - } - else // Scale, Rotation and Position of a picked object are applied to a moved object. - { - pMovedObj->SetWorldTM(pickedTM, eObjectUpdateFlags_UserInput); - } - } - else if (bAlignToBoundBox) // align to the bounding box. - { - if (pickedLocalAABB.GetVolume() == 0.0f) - { - continue; - } - - AABB movedLocalAABB; - pMovedObj->GetLocalBounds(movedLocalAABB); - if (fabs(movedLocalAABB.max.x - movedLocalAABB.min.x) < VEC_EPSILON && - fabs(movedLocalAABB.max.y - movedLocalAABB.min.y) < VEC_EPSILON && - fabs(movedLocalAABB.max.z - movedLocalAABB.min.z) < VEC_EPSILON) - { - continue; - } - - const Vec3& movedScale(pMovedObj->GetScale()); - Matrix34 movedScaleTM = Matrix34::CreateScale(movedScale); - AABB movedLocalScaledAABB; - movedLocalScaledAABB.min = movedScaleTM.TransformVector(movedLocalAABB.min); - movedLocalScaledAABB.max = movedScaleTM.TransformVector(movedLocalAABB.max); - - float fMovedWidth = movedLocalScaledAABB.max.x - movedLocalScaledAABB.min.x; - float fMovedHeight = movedLocalScaledAABB.max.z - movedLocalScaledAABB.min.z; - float fMovedLength = movedLocalScaledAABB.max.y - movedLocalScaledAABB.min.y; - - Matrix34 pickedScaleTM = Matrix34::CreateScale(picked->GetScale()); - AABB pickedLocalScaledAABB; - pickedLocalScaledAABB.min = pickedScaleTM.TransformVector(pickedLocalAABB.min); - pickedLocalScaledAABB.max = pickedScaleTM.TransformVector(pickedLocalAABB.max); - float fScaledPickedtWidth = pickedLocalScaledAABB.max.x - pickedLocalScaledAABB.min.x; - float fScaledPickedHeight = pickedLocalScaledAABB.max.z - pickedLocalScaledAABB.min.z; - float fScaledPickedLength = pickedLocalScaledAABB.max.y - pickedLocalScaledAABB.min.y; - - Vec3 scale((fScaledPickedtWidth / fMovedWidth) * movedScale.x, (fScaledPickedLength / fMovedLength) * movedScale.y, (fScaledPickedHeight / fMovedHeight) * movedScale.z); - Matrix34 scaleRotTM = Matrix34::Create(scale, pickedRot, Vec3(0, 0, 0)); - Vec3 movedPivot = scaleRotTM.TransformVector(movedLocalAABB.GetCenter()); - - pMovedObj->SetWorldTM(Matrix34::Create(scale, pickedRot, Vec3(pickedPos + (pickedPivot - movedPivot))), eObjectUpdateFlags_UserInput); - } - } - m_bActive = false; - if (bUndo) - { - GetIEditor()->AcceptUndo("Align To Object"); - } - } - delete this; -} - -//! Called when pick mode cancelled. -void CAlignPickCallback::OnCancelPick() -{ - m_bActive = false; - delete this; -} - -//! Return true if specified object is pickable. -bool CAlignPickCallback::OnPickFilter([[maybe_unused]] CBaseObject* filterObject) -{ - return true; -}; diff --git a/Code/Sandbox/Editor/AlignTool.h b/Code/Sandbox/Editor/AlignTool.h deleted file mode 100644 index 43cd01013d..0000000000 --- a/Code/Sandbox/Editor/AlignTool.h +++ /dev/null @@ -1,40 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_EDITOR_ALIGNTOOL_H -#define CRYINCLUDE_EDITOR_ALIGNTOOL_H - -#pragma once - -////////////////////////////////////////////////////////////////////////// -class CAlignPickCallback - : public IPickObjectCallback -{ -public: - CAlignPickCallback() { m_bActive = true; }; - //! Called when object picked. - virtual void OnPick(CBaseObject* picked); - //! Called when pick mode cancelled. - virtual void OnCancelPick(); - //! Return true if specified object is pickable. - virtual bool OnPickFilter(CBaseObject* filterObject); - - static bool IsActive() { return m_bActive; } - - virtual bool IsNeedSpecificBehaviorForSpaceAcce() { return true; } -private: - static bool m_bActive; -}; - - -#endif // CRYINCLUDE_EDITOR_ALIGNTOOL_H diff --git a/Code/Sandbox/Editor/AssetEditor/AssetEditorWindow.cpp b/Code/Sandbox/Editor/AssetEditor/AssetEditorWindow.cpp index 4645019261..53e2884943 100644 --- a/Code/Sandbox/Editor/AssetEditor/AssetEditorWindow.cpp +++ b/Code/Sandbox/Editor/AssetEditor/AssetEditorWindow.cpp @@ -20,6 +20,7 @@ // AzCore #include #include +#include // AzToolsFramework #include @@ -104,13 +105,9 @@ void AssetEditorWindow::SaveAssetAs(const AZStd::string_view assetPath) return; } - const char* engineRoot; - AzToolsFramework::ToolsApplicationRequestBus::BroadcastResult(engineRoot, &AzToolsFramework::ToolsApplicationRequests::GetEngineRootPath); + auto absoluteAssetPath = AZ::IO::FixedMaxPath(AZ::Utils::GetEnginePath()) / assetPath; - AZStd::string absoluteAssetPath; - AzFramework::StringFunc::Path::Join(engineRoot, assetPath.data(), absoluteAssetPath); - - if (!m_ui->m_assetEditorWidget->SaveAssetToPath(absoluteAssetPath)) + if (!m_ui->m_assetEditorWidget->SaveAssetToPath(absoluteAssetPath.Native())) { AZ_Warning("Asset Editor", false, "File was not saved correctly via SaveAssetAs."); } diff --git a/Code/Sandbox/Editor/Core/LevelEditorMenuHandler.cpp b/Code/Sandbox/Editor/Core/LevelEditorMenuHandler.cpp index 1c9e7d90d2..f00085d5ad 100644 --- a/Code/Sandbox/Editor/Core/LevelEditorMenuHandler.cpp +++ b/Code/Sandbox/Editor/Core/LevelEditorMenuHandler.cpp @@ -580,7 +580,6 @@ void LevelEditorMenuHandler::PopulateEditMenu(ActionManager::MenuWrapper& editMe auto alignMenu = modifyMenu.AddMenu(tr("Align")); alignMenu.AddAction(ID_OBJECTMODIFY_ALIGNTOGRID); - alignMenu.AddAction(ID_OBJECTMODIFY_ALIGN); alignMenu.AddAction(ID_MODIFY_ALIGNOBJTOSURF); auto constrainMenu = modifyMenu.AddMenu(tr("Constrain")); diff --git a/Code/Sandbox/Editor/CryEdit.cpp b/Code/Sandbox/Editor/CryEdit.cpp index dff5b2267c..7aefcffb5a 100644 --- a/Code/Sandbox/Editor/CryEdit.cpp +++ b/Code/Sandbox/Editor/CryEdit.cpp @@ -95,8 +95,6 @@ AZ_POP_DISABLE_WARNING #include "Core/QtEditorApplication.h" #include "StringDlg.h" -#include "LinkTool.h" -#include "AlignTool.h" #include "VoxelAligningTool.h" #include "NewLevelDialog.h" #include "GridSettingsDialog.h" @@ -126,7 +124,6 @@ AZ_POP_DISABLE_WARNING #include "EditorPreferencesDialog.h" #include "GraphicsSettingsDialog.h" #include "FeedbackDialog/FeedbackDialog.h" -#include "MatEditMainDlg.h" #include "AnimationContext.h" #include "GotoPositionDlg.h" @@ -401,8 +398,6 @@ void CCryEditApp::RegisterActionHandlers() ON_COMMAND(ID_EDITMODE_MOVE, OnEditmodeMove) ON_COMMAND(ID_EDITMODE_ROTATE, OnEditmodeRotate) ON_COMMAND(ID_EDITMODE_SCALE, OnEditmodeScale) - ON_COMMAND(ID_EDITTOOL_LINK, OnEditToolLink) - ON_COMMAND(ID_EDITTOOL_UNLINK, OnEditToolUnlink) ON_COMMAND(ID_EDITMODE_SELECT, OnEditmodeSelect) ON_COMMAND(ID_EDIT_ESCAPE, OnEditEscape) ON_COMMAND(ID_OBJECTMODIFY_SETAREA, OnObjectSetArea) @@ -422,7 +417,6 @@ void CCryEditApp::RegisterActionHandlers() ON_COMMAND(ID_SELECTION_SAVE, OnSelectionSave) ON_COMMAND(ID_IMPORT_ASSET, OnOpenAssetImporter) ON_COMMAND(ID_SELECTION_LOAD, OnSelectionLoad) - ON_COMMAND(ID_OBJECTMODIFY_ALIGN, OnAlignObject) ON_COMMAND(ID_MODIFY_ALIGNOBJTOSURF, OnAlignToVoxel) ON_COMMAND(ID_OBJECTMODIFY_ALIGNTOGRID, OnAlignToGrid) ON_COMMAND(ID_LOCK_SELECTION, OnLockSelection) @@ -1898,14 +1892,6 @@ BOOL CCryEditApp::InitInstance() CWipFeatureManager::Init(); #endif - if (GetIEditor()->IsInMatEditMode()) - { - m_pMatEditDlg = new CMatEditMainDlg(QStringLiteral("Material Editor")); - m_pEditor->InitFinished(); - m_pMatEditDlg->show(); - return true; - } - if (!m_bConsoleMode && !m_bPreviewMode) { GetIEditor()->UpdateViews(); @@ -2905,51 +2891,6 @@ void CCryEditApp::OnEditmodeScale() } } -////////////////////////////////////////////////////////////////////////// -void CCryEditApp::OnEditToolLink() -{ - // TODO: Add your command handler code here - if (qobject_cast(GetIEditor()->GetEditTool())) - { - GetIEditor()->SetEditTool(0); - } - else - { - GetIEditor()->SetEditTool(new CLinkTool()); - } -} - -////////////////////////////////////////////////////////////////////////// -void CCryEditApp::OnUpdateEditToolLink(QAction* action) -{ - if (!GetIEditor()->GetDocument()) - { - action->setEnabled(false); - return; - } - action->setEnabled(GetIEditor()->GetDocument()->IsDocumentReady()); - CEditTool* pEditTool = GetIEditor()->GetEditTool(); - action->setChecked(qobject_cast(pEditTool) != nullptr); -} - -////////////////////////////////////////////////////////////////////////// -void CCryEditApp::OnEditToolUnlink() -{ - CUndo undo("Unlink Object(s)"); - CSelectionGroup* pSelection = GetIEditor()->GetObjectManager()->GetSelection(); - for (int i = 0; i < pSelection->GetCount(); i++) - { - CBaseObject* pBaseObj = pSelection->GetObject(i); - pBaseObj->DetachThis(); - } -} - -////////////////////////////////////////////////////////////////////////// -void CCryEditApp::OnUpdateEditToolUnlink(QAction* action) -{ - action->setEnabled(false); -} - ////////////////////////////////////////////////////////////////////////// void CCryEditApp::OnEditmodeSelect() { @@ -3519,14 +3460,6 @@ void CCryEditApp::OnUpdateSelected(QAction* action) action->setEnabled(!GetIEditor()->GetSelection()->IsEmpty()); } -////////////////////////////////////////////////////////////////////////// -void CCryEditApp::OnAlignObject() -{ - // Align pick callback will release itself. - CAlignPickCallback* alignCallback = new CAlignPickCallback; - GetIEditor()->PickObject(alignCallback, 0, "Align to Object"); -} - ////////////////////////////////////////////////////////////////////////// void CCryEditApp::OnAlignToGrid() { @@ -3547,15 +3480,6 @@ void CCryEditApp::OnAlignToGrid() } } -////////////////////////////////////////////////////////////////////////// -void CCryEditApp::OnUpdateAlignObject(QAction* action) -{ - Q_ASSERT(action->isCheckable()); - action->setChecked(CAlignPickCallback::IsActive()); - - action->setEnabled(!GetIEditor()->GetSelection()->IsEmpty()); -} - ////////////////////////////////////////////////////////////////////////// void CCryEditApp::OnAlignToVoxel() { diff --git a/Code/Sandbox/Editor/CryEdit.h b/Code/Sandbox/Editor/CryEdit.h index 7480b34e5a..94c39991e9 100644 --- a/Code/Sandbox/Editor/CryEdit.h +++ b/Code/Sandbox/Editor/CryEdit.h @@ -28,7 +28,6 @@ class CCryDocManager; class CQuickAccessBar; -class CMatEditMainDlg; class CCryEditDoc; class CEditCommandLineInfo; class CMainFrame; @@ -225,10 +224,6 @@ public: void OnEditmodeMove(); void OnEditmodeRotate(); void OnEditmodeScale(); - void OnEditToolLink(); - void OnUpdateEditToolLink(QAction* action); - void OnEditToolUnlink(); - void OnUpdateEditToolUnlink(QAction* action); void OnEditmodeSelect(); void OnEditEscape(); void OnObjectSetArea(); @@ -257,10 +252,8 @@ public: void OnOpenAssetImporter(); void OnSelectionLoad(); void OnUpdateSelected(QAction* action); - void OnAlignObject(); void OnAlignToVoxel(); void OnAlignToGrid(); - void OnUpdateAlignObject(QAction* action); void OnUpdateAlignToVoxel(QAction* action); void OnLockSelection(); void OnEditLevelData(); @@ -367,7 +360,6 @@ private: //! Autotest mode: Special mode meant for automated testing, things like blocking dialogs or error report windows won't appear bool m_bAutotestMode = false; - CMatEditMainDlg* m_pMatEditDlg = nullptr; CConsoleDialog* m_pConsoleDialog = nullptr; AZ_PUSH_DISABLE_DLL_EXPORT_MEMBER_WARNING diff --git a/Code/Sandbox/Editor/EditorViewportWidget.cpp b/Code/Sandbox/Editor/EditorViewportWidget.cpp index a3b2542418..91c70b720f 100644 --- a/Code/Sandbox/Editor/EditorViewportWidget.cpp +++ b/Code/Sandbox/Editor/EditorViewportWidget.cpp @@ -276,9 +276,6 @@ void EditorViewportWidget::paintEvent([[maybe_unused]] QPaintEvent* event) if ((ge && ge->IsLevelLoaded()) || (GetType() != ET_ViewportCamera)) { setRenderOverlayVisible(true); - m_isOnPaint = true; - Update(); - m_isOnPaint = false; } else { @@ -809,6 +806,10 @@ void EditorViewportWidget::OnBeginPrepareRender() return; } + m_isOnPaint = true; + Update(); + m_isOnPaint = false; + float fNearZ = GetIEditor()->GetConsoleVar("cl_DefaultNearPlane"); float fFarZ = m_Camera.GetFarPlane(); @@ -880,6 +881,11 @@ void EditorViewportWidget::OnBeginPrepareRender() GetIEditor()->GetSystem()->SetViewCamera(m_Camera); + if (GetIEditor()->IsInGameMode()) + { + return; + } + PreWidgetRendering(); RenderAll(); @@ -905,11 +911,6 @@ void EditorViewportWidget::OnBeginPrepareRender() m_debugDisplay->DepthTestOn(); PostWidgetRendering(); - - if (!m_renderer->IsStereoEnabled()) - { - GetIEditor()->GetSystem()->RenderStatistics(); - } } ////////////////////////////////////////////////////////////////////////// @@ -1617,11 +1618,6 @@ void EditorViewportWidget::keyPressEvent(QKeyEvent* event) // because we want the movement to be butter smooth. if (!event->isAutoRepeat()) { - if (m_keyDown.isEmpty()) - { - grabKeyboard(); - } - m_keyDown.insert(event->key()); } diff --git a/Code/Sandbox/Editor/IEditor.h b/Code/Sandbox/Editor/IEditor.h index 7715e64fe5..722f2a7c25 100644 --- a/Code/Sandbox/Editor/IEditor.h +++ b/Code/Sandbox/Editor/IEditor.h @@ -391,21 +391,6 @@ enum EModifiedModule eModifiedAll = -1 }; -//! Callback class passed to PickObject. -struct IPickObjectCallback -{ - virtual ~IPickObjectCallback() = default; - - //! Called when object picked. - virtual void OnPick(CBaseObject* picked) = 0; - //! Called when pick mode cancelled. - virtual void OnCancelPick() = 0; - //! Return true if specified object is pickable. - virtual bool OnPickFilter([[maybe_unused]] CBaseObject* filterObject) { return true; }; - //! If need a specific behavior when holding space, return true or if not, return false. - virtual bool IsNeedSpecificBehaviorForSpaceAcce() { return false; } -}; - //! Class provided by editor for various registration functions. struct CRegistrationContext { @@ -570,20 +555,6 @@ struct IEditor //! Get access to object manager. virtual struct IObjectManager* GetObjectManager() = 0; virtual CSettingsManager* GetSettingsManager() = 0; - //! Set pick object mode. - //! When object picked callback will be called, with OnPick - //! If pick operation is canceled Cancel will be called - //! @param targetClass specifies objects of which class are supposed to be picked - //! @param bMultipick if true pick tool will pick multiple object - virtual void PickObject( - IPickObjectCallback* callback, - const QMetaObject* targetClass = 0, - const char* statusText = 0, - bool bMultipick = false) = 0; - //! Cancel current pick operation - virtual void CancelPick() = 0; - //! Return true if editor now in object picking mode - virtual bool IsPicking() = 0; //! Get DB manager that own items of specified type. virtual IDataBaseManager* GetDBItemManager(EDataBaseItemType itemType) = 0; //! Get Manager of Materials. diff --git a/Code/Sandbox/Editor/IEditorImpl.cpp b/Code/Sandbox/Editor/IEditorImpl.cpp index 4a0a73c9ac..399ac45794 100644 --- a/Code/Sandbox/Editor/IEditorImpl.cpp +++ b/Code/Sandbox/Editor/IEditorImpl.cpp @@ -65,7 +65,6 @@ AZ_POP_DISABLE_WARNING #include "UIEnumsDatabase.h" #include "Util/Ruler.h" #include "RenderHelpers/AxisHelper.h" -#include "PickObjectTool.h" #include "Settings.h" #include "Include/IObjectManager.h" #include "Include/ISourceControl.h" @@ -170,7 +169,6 @@ CEditorImpl::CEditorImpl() , m_pShaderEnum(nullptr) , m_pIconManager(nullptr) , m_bSelectionLocked(true) - , m_pPickTool(nullptr) , m_pAxisGizmo(nullptr) , m_pGameEngine(nullptr) , m_pAnimationContext(nullptr) @@ -794,11 +792,6 @@ void CEditorImpl::SetEditTool(CEditTool* tool, bool bStopCurrentTool) m_pEditTool->BeginEditParams(this, 0); } - // Make sure pick is aborted. - if (tool != m_pPickTool) - { - m_pPickTool = nullptr; - } Notify(eNotify_OnEditToolChange); } @@ -1069,34 +1062,6 @@ bool CEditorImpl::IsSelectionLocked() return m_bSelectionLocked; } -void CEditorImpl::PickObject(IPickObjectCallback* callback, const QMetaObject* targetClass, const char* statusText, bool bMultipick) -{ - m_pPickTool = new CPickObjectTool(callback, targetClass); - - static_cast(m_pPickTool.get())->SetMultiplePicks(bMultipick); - if (statusText) - { - m_pPickTool.get()->SetStatusText(statusText); - } - - SetEditTool(m_pPickTool); -} - -void CEditorImpl::CancelPick() -{ - SetEditTool(0); - m_pPickTool = 0; -} - -bool CEditorImpl::IsPicking() -{ - if (GetEditTool() == m_pPickTool && m_pPickTool != 0) - { - return true; - } - return false; -} - CViewManager* CEditorImpl::GetViewManager() { return m_pViewManager; diff --git a/Code/Sandbox/Editor/IEditorImpl.h b/Code/Sandbox/Editor/IEditorImpl.h index 9e3b3abc66..4a8d5fa191 100644 --- a/Code/Sandbox/Editor/IEditorImpl.h +++ b/Code/Sandbox/Editor/IEditorImpl.h @@ -181,10 +181,7 @@ public: void SelectObject(CBaseObject* obj); void LockSelection(bool bLock); bool IsSelectionLocked(); - void PickObject(IPickObjectCallback* callback, const QMetaObject* targetClass = 0, const char* statusText = 0, bool bMultipick = false); - void CancelPick(); - bool IsPicking(); IDataBaseManager* GetDBItemManager(EDataBaseItemType itemType); CMaterialManager* GetMaterialManager() { return m_pMaterialManager; } CMusicManager* GetMusicManager() { return m_pMusicManager; }; @@ -409,7 +406,6 @@ protected: QString m_primaryCDFolder; QString m_userFolder; bool m_bSelectionLocked; - _smart_ptr m_pPickTool; class CAxisGizmo* m_pAxisGizmo; CGameEngine* m_pGameEngine; CAnimationContext* m_pAnimationContext; diff --git a/Code/Sandbox/Editor/LayoutWnd.cpp b/Code/Sandbox/Editor/LayoutWnd.cpp index 56c0bcb849..34a96bca53 100644 --- a/Code/Sandbox/Editor/LayoutWnd.cpp +++ b/Code/Sandbox/Editor/LayoutWnd.cpp @@ -418,8 +418,11 @@ void CLayoutWnd::CreateLayout(EViewLayout layout, bool bBindViewports, EViewport QRect rcView = rect(); rcView.setBottom(rcView.bottom() - m_infoBar->height()); + // Ensure we delete our old view immediately so it can relinquish its backing ViewportContext if (m_maximizedView) - m_maximizedView->deleteLater(); + { + delete m_maximizedView; + } m_maximizedView = new CLayoutViewPane(this); m_maximizedView->SetId(0); diff --git a/Code/Sandbox/Editor/Lib/Tests/IEditorMock.h b/Code/Sandbox/Editor/Lib/Tests/IEditorMock.h index a290ef5de5..e48fb5fec1 100644 --- a/Code/Sandbox/Editor/Lib/Tests/IEditorMock.h +++ b/Code/Sandbox/Editor/Lib/Tests/IEditorMock.h @@ -90,9 +90,6 @@ public: MOCK_METHOD0(IsSelectionLocked, bool()); MOCK_METHOD0(GetObjectManager, struct IObjectManager* ()); MOCK_METHOD0(GetSettingsManager, CSettingsManager* ()); - MOCK_METHOD4(PickObject, void(IPickObjectCallback*,const QMetaObject*,const char* ,bool bMultipick)); - MOCK_METHOD0(CancelPick, void()); - MOCK_METHOD0(IsPicking, bool()); MOCK_METHOD1(GetDBItemManager, IDataBaseManager* (EDataBaseItemType)); MOCK_METHOD0(GetMaterialManager, CMaterialManager* ()); MOCK_METHOD0(GetMaterialManagerLibrary, IBaseLibraryManager* ()); diff --git a/Code/Sandbox/Editor/LinkTool.cpp b/Code/Sandbox/Editor/LinkTool.cpp deleted file mode 100644 index 4602875b77..0000000000 --- a/Code/Sandbox/Editor/LinkTool.cpp +++ /dev/null @@ -1,286 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#include "EditorDefs.h" - -#include "LinkTool.h" - -// Editor -#include "Viewport.h" -#include "Objects/EntityObject.h" -#include "Objects/SelectionGroup.h" -#include - -// AzCore -#include - -#ifdef LoadCursor -#undef LoadCursor -#endif - -namespace -{ - const float kGeomCacheNodePivotSizeScale = 0.0025f; -} - -////////////////////////////////////////////////////////////////////////// -CLinkTool::CLinkTool() - : m_nodeName(nullptr) - , m_pGeomCacheRenderNode(nullptr) -{ - m_pChild = NULL; - SetStatusText("Click on object and drag a link to a new parent"); - - m_hLinkCursor = CMFCUtils::LoadCursor(IDC_POINTER_LINK); - m_hLinkNowCursor = CMFCUtils::LoadCursor(IDC_POINTER_LINKNOW); - m_hCurrCursor = &m_hLinkCursor; - AZ::EntitySystemBus::Handler::BusConnect(); -} - -////////////////////////////////////////////////////////////////////////// -CLinkTool::~CLinkTool() -{ - AZ::EntitySystemBus::Handler::BusDisconnect(); -} - -////////////////////////////////////////////////////////////////////////// -void CLinkTool::LinkObject(CBaseObject* pChild, CBaseObject* pParent) -{ - if (pChild == NULL) - { - return; - } - - if (ChildIsValid(pParent, pChild)) - { - CUndo undo("Link Object"); - - if (qobject_cast(pChild)) - { - static_cast(pChild)->SetAttachTarget(""); - static_cast(pChild)->SetAttachType(CEntityObject::eAT_Pivot); - } - - pParent->AttachChild(pChild, true); - - QString str; - str = tr("%1 attached to %2").arg(pChild->GetName(), pParent->GetName()); - SetStatusText(str); - } - else - { - SetStatusText("Error: Cyclic linking or already linked."); - } -} - -////////////////////////////////////////////////////////////////////////// -void CLinkTool::LinkSelectedToParent(CBaseObject* pParent) -{ - if (pParent) - { - if (IsRelevant(pParent)) - { - CSelectionGroup* pSel = GetIEditor()->GetSelection(); - if (!pSel->GetCount()) - { - return; - } - CUndo undo("Link Object(s)"); - for (int i = 0; i < pSel->GetCount(); i++) - { - CBaseObject* pChild = pSel->GetObject(i); - if (pChild == pParent) - { - continue; - } - LinkObject(pChild, pParent); - } - } - } -} - -////////////////////////////////////////////////////////////////////////// -bool CLinkTool::MouseCallback(CViewport* view, EMouseEvent event, QPoint& point, [[maybe_unused]] int flags) -{ - view->SetCursorString(""); - - m_hCurrCursor = &m_hLinkCursor; - if (event == eMouseLDown) - { - HitContext hitInfo; - view->HitTest(point, hitInfo); - CBaseObject* obj = hitInfo.object; - if (obj) - { - if (IsRelevant(obj)) - { - m_StartDrag = obj->GetWorldPos(); - m_pChild = obj; - } - } - } - else if (event == eMouseLUp) - { - HitContext hitInfo; - view->HitTest(point, hitInfo); - CBaseObject* obj = hitInfo.object; - if (obj) - { - if (IsRelevant(obj)) - { - CSelectionGroup* pSelectionGroup = GetIEditor()->GetSelection(); - int nGroupCount = pSelectionGroup->GetCount(); - if (pSelectionGroup && nGroupCount > 1) - { - LinkSelectedToParent(obj); - } - if (!pSelectionGroup || nGroupCount <= 1 || !pSelectionGroup->IsContainObject(m_pChild)) - { - LinkObject(m_pChild, obj); - } - } - } - m_pChild = NULL; - } - else if (event == eMouseMove) - { - m_EndDrag = view->ViewToWorld(point); - m_nodeName = nullptr; - m_pGeomCacheRenderNode = nullptr; - - HitContext hitInfo; - if (view->HitTest(point, hitInfo)) - { - m_EndDrag = hitInfo.raySrc + hitInfo.rayDir * hitInfo.dist; - } - - CBaseObject* obj = hitInfo.object; - if (obj) - { - if (IsRelevant(obj)) - { - QString name = obj->GetName(); - if (hitInfo.name) - { - name += QString("\n ") + hitInfo.name; - } - - // Set Cursors. - view->SetCursorString(name); - if (m_pChild) - { - if (ChildIsValid(obj, m_pChild)) - { - m_hCurrCursor = &m_hLinkNowCursor; - } - } - } - } - } - return true; -} - -////////////////////////////////////////////////////////////////////////// -bool CLinkTool::OnKeyDown([[maybe_unused]] CViewport* view, uint32 nChar, [[maybe_unused]] uint32 nRepCnt, [[maybe_unused]] uint32 nFlags) -{ - if (nChar == VK_ESCAPE) - { - // Cancel selection. - GetIEditor()->SetEditTool(nullptr); - } - return false; -} - -////////////////////////////////////////////////////////////////////////// -void CLinkTool::Display(DisplayContext& dc) -{ - if (m_pChild && m_EndDrag != Vec3(ZERO)) - { - ColorF lineColor = (m_hCurrCursor == &m_hLinkNowCursor) ? ColorF(0, 1, 0) : ColorF(1, 0, 0); - dc.DrawLine(m_StartDrag, m_EndDrag, lineColor, lineColor); - } -} - -////////////////////////////////////////////////////////////////////////// -void CLinkTool::OnEntityDestruction(const AZ::EntityId& entityId) -{ - if (m_pChild && (m_pChild->GetType() == OBJTYPE_AZENTITY)) - { - CComponentEntityObject* childComponentEntity = static_cast(m_pChild); - AZ::EntityId childEntityId = childComponentEntity->GetAssociatedEntityId(); - if(entityId == childEntityId) - { - GetIEditor()->SetEditTool(nullptr); - } - } -} - -////////////////////////////////////////////////////////////////////////// -bool CLinkTool::ChildIsValid(CBaseObject* pParent, CBaseObject* pChild, int nDir) -{ - if (!pParent) - { - return false; - } - if (!pChild) - { - return false; - } - if (pParent == pChild) - { - return false; - } - - // Legacy entities and AZ entities shouldn't be linked. - if ((pParent->GetType() == OBJTYPE_AZENTITY) != (pChild->GetType() == OBJTYPE_AZENTITY)) - { - return false; - } - - CBaseObject* pObj; - if (nDir & 1) - { - pObj = pChild->GetParent(); - if (pObj) - { - if (!ChildIsValid(pParent, pObj, 1)) - { - return false; - } - } - } - if (nDir & 2) - { - for (int i = 0; i < pChild->GetChildCount(); i++) - { - pObj = pChild->GetChild(i); - if (pObj) - { - if (!ChildIsValid(pParent, pObj, 2)) - { - return false; - } - } - } - } - return true; -} - -////////////////////////////////////////////////////////////////////////// -bool CLinkTool::OnSetCursor(CViewport* vp) -{ - vp->SetCursor(*m_hCurrCursor); - return true; -} - -#include diff --git a/Code/Sandbox/Editor/LinkTool.h b/Code/Sandbox/Editor/LinkTool.h deleted file mode 100644 index a24370f7fe..0000000000 --- a/Code/Sandbox/Editor/LinkTool.h +++ /dev/null @@ -1,85 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -// Description : Definition of CLinkTool, tool used to link objects. - - -#ifndef CRYINCLUDE_EDITOR_LINKTOOL_H -#define CRYINCLUDE_EDITOR_LINKTOOL_H - -#pragma once - -#if !defined(Q_MOC_RUN) -#include -#include "EditTool.h" -#include "Include/IObjectManager.h" -#endif - -class CEntityObject; - -////////////////////////////////////////////////////////////////////////// -class CLinkTool - : public CEditTool - , public IObjectSelectCallback - , private AZ::EntitySystemBus::Handler -{ - Q_OBJECT -public: - Q_INVOKABLE CLinkTool(); // IPickObjectCallback *callback,CRuntimeClass *targetClass=NULL ); - - // Ovverides from CEditTool - bool MouseCallback(CViewport* view, EMouseEvent event, QPoint& point, int flags); - - virtual void BeginEditParams([[maybe_unused]] IEditor* ie, [[maybe_unused]] int flags) {}; - virtual void EndEditParams() {}; - - virtual void Display(DisplayContext& dc); - virtual bool OnKeyDown(CViewport* view, uint32 nChar, uint32 nRepCnt, uint32 nFlags); - virtual bool OnKeyUp([[maybe_unused]] CViewport* view, [[maybe_unused]] uint32 nChar, [[maybe_unused]] uint32 nRepCnt, [[maybe_unused]] uint32 nFlags) { return false; }; - - virtual bool OnSelectObject([[maybe_unused]] CBaseObject* obj) {return false; } - virtual bool CanSelectObject([[maybe_unused]] CBaseObject* obj) { return true; }; - - virtual bool OnSetCursor(CViewport* vp); - - void LinkSelectedToParent(CBaseObject* pParent); - -protected: - virtual ~CLinkTool(); - // Delete itself. - void DeleteThis() { delete this; }; - -private: - bool IsRelevant([[maybe_unused]] CBaseObject* obj) { return true; } - bool ChildIsValid(CBaseObject* pParent, CBaseObject* pChild, int nDir = 3); - void LinkObject(CBaseObject* pChild, CBaseObject* pParent); - void LinkToNode(CEntityObject* pChild, CEntityObject* pParent, const char* nodeName); - - // AZ::EntitySystemBus::Handler - void OnEntityDestruction(const AZ::EntityId& entityId) override; - - - CBaseObject* m_pChild; - Vec3 m_StartDrag; - Vec3 m_EndDrag; - - QCursor m_hLinkCursor; - QCursor m_hLinkNowCursor; - QCursor* m_hCurrCursor; - - const char* m_nodeName; - IGeomCacheRenderNode* m_pGeomCacheRenderNode; -}; - - -#endif // CRYINCLUDE_EDITOR_LINKTOOL_H diff --git a/Code/Sandbox/Editor/MainWindow.cpp b/Code/Sandbox/Editor/MainWindow.cpp index ab5e0cf559..6acd8cfc20 100644 --- a/Code/Sandbox/Editor/MainWindow.cpp +++ b/Code/Sandbox/Editor/MainWindow.cpp @@ -92,7 +92,6 @@ AZ_POP_DISABLE_WARNING #include "TrackView/TrackViewDialog.h" #include "ErrorReportDialog.h" -#include "Material/MaterialDialog.h" #include "LensFlareEditor/LensFlareEditor.h" #include "TimeOfDayDialog.h" @@ -1105,15 +1104,6 @@ void MainWindow::InitActions() .RegisterUpdateCallback(cryEdit, &CCryEditApp::OnUpdateSelected) .SetIcon(Style::icon("Align_to_grid")) .SetApplyHoverEffect(); - am->AddAction(ID_OBJECTMODIFY_ALIGN, tr("Align to object")).SetCheckable(true) -#if AZ_TRAIT_OS_PLATFORM_APPLE - .SetStatusTip(tr(u8"\u2318: Align an object to a bounding box, \u2325 : Keep Rotation of the moved object, Shift : Keep Scale of the moved object")) -#else - .SetStatusTip(tr("Ctrl: Align an object to a bounding box, Alt : Keep Rotation of the moved object, Shift : Keep Scale of the moved object")) -#endif - .RegisterUpdateCallback(cryEdit, &CCryEditApp::OnUpdateAlignObject) - .SetIcon(Style::icon("Align_to_Object")) - .SetApplyHoverEffect(); am->AddAction(ID_MODIFY_ALIGNOBJTOSURF, tr("Align object to surface (Hold CTRL)")).SetCheckable(true) .SetToolTip(tr("Align object to surface (Hold CTRL)")) .RegisterUpdateCallback(cryEdit, &CCryEditApp::OnUpdateAlignToVoxel) @@ -1450,15 +1440,6 @@ void MainWindow::InitActions() .SetApplyHoverEffect(); // Edit Mode Toolbar Actions - am->AddAction(ID_EDITTOOL_LINK, tr("Link an object to parent")) - .SetIcon(Style::icon("add_link")) - .SetApplyHoverEffect() - .SetCheckable(true) - .RegisterUpdateCallback(cryEdit, &CCryEditApp::OnUpdateEditToolLink); - am->AddAction(ID_EDITTOOL_UNLINK, tr("Unlink all selected objects")) - .SetIcon(Style::icon("remove_link")) - .SetApplyHoverEffect() - .RegisterUpdateCallback(cryEdit, &CCryEditApp::OnUpdateEditToolUnlink); am->AddAction(IDC_SELECTION_MASK, tr("Selected Object Types")); am->AddAction(ID_REF_COORDS_SYS, tr("Reference coordinate system")) .SetShortcut(tr("Ctrl+W")) @@ -1974,7 +1955,6 @@ void MainWindow::RegisterStdViewClasses() if (!AZ::Interface::Get()) { - CMaterialDialog::RegisterViewClass(); CLensFlareEditor::RegisterViewClass(); CTimeOfDayDialog::RegisterViewClass(); } diff --git a/Code/Sandbox/Editor/MatEditMainDlg.cpp b/Code/Sandbox/Editor/MatEditMainDlg.cpp deleted file mode 100644 index 9a96ad15d0..0000000000 --- a/Code/Sandbox/Editor/MatEditMainDlg.cpp +++ /dev/null @@ -1,110 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -// Description : implementation file - -#include "EditorDefs.h" - -#include "MatEditMainDlg.h" - -// Qt -#include -#include - -// Editor -#include "Material/MaterialDialog.h" -#include "Material/MaterialManager.h" -#include "MaterialSender.h" - - -CMatEditMainDlg::CMatEditMainDlg(const QString& title, QWidget* pParent /*=NULL*/) - : QWidget(pParent) -{ - resize(1000, 600); - - setWindowTitle(title); - - QTimer* t = new QTimer(this); - connect(t, &QTimer::timeout, this, &CMatEditMainDlg::OnKickIdle); - t->start(250); - - m_materialDialog = new CMaterialDialog(); // must be created after the timer - auto layout = new QVBoxLayout(this); - layout->addWidget(m_materialDialog); - -#ifdef Q_OS_WIN - if (auto aed = QAbstractEventDispatcher::instance()) - { - aed->installNativeEventFilter(this); - } -#endif -} - -CMatEditMainDlg::~CMatEditMainDlg() -{ -#ifdef Q_OS_WIN - if (auto aed = QAbstractEventDispatcher::instance()) - { - aed->removeNativeEventFilter(this); - } -#endif -} - -///////////////////////////////////////////////////////////////////////////// -// CMatEditMainDlg message handlers - -void CMatEditMainDlg::showEvent(QShowEvent*) -{ - if (QWindow *win = window()->windowHandle()) - { - // Make sure our top-level window decorator wrapper set this exact title - // 3ds Max Exporter will use ::FindWindow with this name - win->setTitle("Material Editor"); - } -} - -bool CMatEditMainDlg::nativeEventFilter(const QByteArray&, void* message, long*) -{ -#ifdef Q_OS_WIN - // WM_MATEDITSEND is Windows only. Used by 3ds Max exporter. - MSG* msg = static_cast(message); - if (msg->message == WM_MATEDITSEND) - { - OnMatEditSend(msg->wParam); - return true; - } -#endif - - return false; -} - -void CMatEditMainDlg::closeEvent(QCloseEvent* event) -{ - QWidget::closeEvent(event); - qApp->quit(); -} - -void CMatEditMainDlg::OnKickIdle() -{ - GetIEditor()->Notify(eNotify_OnIdleUpdate); -} - -void CMatEditMainDlg::OnMatEditSend(int param) -{ - if (param != eMSM_Init) - { - GetIEditor()->GetMaterialManager()->SyncMaterialEditor(); - } -} - -#include diff --git a/Code/Sandbox/Editor/MatEditMainDlg.h b/Code/Sandbox/Editor/MatEditMainDlg.h deleted file mode 100644 index b329933c1f..0000000000 --- a/Code/Sandbox/Editor/MatEditMainDlg.h +++ /dev/null @@ -1,48 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_EDITOR_MATEDITMAINDLG_H -#define CRYINCLUDE_EDITOR_MATEDITMAINDLG_H - -#pragma once - -#if !defined(Q_MOC_RUN) -#include -#include -#include -#endif - -class CMaterialDialog; - -class CMatEditMainDlg - : public QWidget - , public QAbstractNativeEventFilter -{ - Q_OBJECT -public: - explicit CMatEditMainDlg(const QString& title = QString(), QWidget* parent = nullptr); - ~CMatEditMainDlg(); - - bool nativeEventFilter(const QByteArray& eventType, void* message, long* result) override; - -protected: - void closeEvent(QCloseEvent* event) override; - void showEvent(QShowEvent* event) override; - -private: - void OnKickIdle(); - void OnMatEditSend(int param); - CMaterialDialog* m_materialDialog = nullptr; -}; - -#endif // CRYINCLUDE_EDITOR_MATEDITMAINDLG_H diff --git a/Code/Sandbox/Editor/Material/MaterialDialog.cpp b/Code/Sandbox/Editor/Material/MaterialDialog.cpp deleted file mode 100644 index 5d5f14ecd2..0000000000 --- a/Code/Sandbox/Editor/Material/MaterialDialog.cpp +++ /dev/null @@ -1,2290 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#include "EditorDefs.h" - -#include "MaterialDialog.h" - -// Qt -#include -#include -#include -#include -#include -#include -#include -#include - -// AzToolsFramework -#include // for AzToolsFramework::ViewPaneOptions - -// Editor -#include "IEditor.h" -#include "EditTool.h" -#include "MaterialImageListCtrl.h" -#include "MaterialManager.h" -#include "MaterialHelpers.h" -#include "ShaderEnum.h" -#include "MatEditPreviewDlg.h" -#include "Controls/ReflectedPropertyControl/ReflectedPropertyCtrl.h" -#include "Include/IObjectManager.h" -#include "Objects/BaseObject.h" -#include "Settings.h" -#include "Objects/SelectionGroup.h" -#include "LyViewPaneNames.h" - - -const QString EDITOR_OBJECTS_PATH("Objects\\Editor\\"); - -////////////////////////////////////////////////////////////////////////// -void CMaterialDialog::RegisterViewClass() -{ - AzToolsFramework::ViewPaneOptions opts; - opts.shortcut = QKeySequence(Qt::Key_M); - opts.canHaveMultipleInstances = true; - - AzToolsFramework::RegisterViewPane(MATERIAL_EDITOR_NAME, LyViewPane::CategoryTools, opts); - - GetIEditor()->GetSettingsManager()->AddToolVersion(MATERIAL_EDITOR_NAME, MATERIAL_EDITOR_VER); -} - -const GUID& CMaterialDialog::GetClassID() -{ - static const GUID guid = - { - 0xc7891863, 0x1665, 0x45ac, { 0xae, 0x51, 0x48, 0x66, 0x71, 0xbc, 0x8b, 0x12 } - }; - return guid; -} - -inline float RoundDegree(float val) -{ - return (float)((int)(val * 100 + 0.5f)) * 0.01f; -} - -////////////////////////////////////////////////////////////////////////// -// Material structures. -////////////////////////////////////////////////////////////////////////// - -#ifndef _countof -#define _countof(array) (sizeof(array) / sizeof(array[0])) -#endif - -struct STextureVars -{ - CSmartVariable is_tile[2]; - - CSmartVariableEnum etcgentype; - CSmartVariableEnum etcmrotatetype; - CSmartVariableEnum etcmumovetype; - CSmartVariableEnum etcmvmovetype; - CSmartVariableEnum etextype; - CSmartVariableEnum filter; - - CSmartVariable is_tcgprojected; - CSmartVariable tiling[3]; - CSmartVariable rotate[3]; - CSmartVariable offset[3]; - CSmartVariable tcmuoscrate; - CSmartVariable tcmvoscrate; - CSmartVariable tcmuoscamplitude; - CSmartVariable tcmvoscamplitude; - CSmartVariable tcmuoscphase; - CSmartVariable tcmvoscphase; - CSmartVariable tcmrotoscrate; - CSmartVariable tcmrotoscamplitude; - CSmartVariable tcmrotoscphase; - CSmartVariable tcmrotosccenter[2]; - - CSmartVariableArray tableTiling; - CSmartVariableArray tableOscillator; - CSmartVariableArray tableRotator; - - void Reset() - { - SEfTexModificator defaultTextureCoordinateModifier; - SEfResTexture defaultTextureResource; - for (int i = 0; i < 2; i++) - { - *is_tile[i] = defaultTextureResource.GetTiling(i); - *tcmrotosccenter[i] = defaultTextureCoordinateModifier.m_RotOscCenter[i]; - } - - for (int i = 0; i < 3; i++) - { - *rotate[i] = RoundDegree(Word2Degr(defaultTextureCoordinateModifier.m_Rot[i])); - *tiling[i] = defaultTextureCoordinateModifier.m_Tiling[i]; - *offset[i] = defaultTextureCoordinateModifier.m_Offs[i]; - } - - etcgentype = defaultTextureCoordinateModifier.m_eTGType; - etcmrotatetype = defaultTextureCoordinateModifier.m_eRotType; - etcmumovetype = defaultTextureCoordinateModifier.m_eMoveType[0]; - etcmvmovetype = defaultTextureCoordinateModifier.m_eMoveType[1]; - etextype = defaultTextureResource.m_Sampler.m_eTexType; - filter = defaultTextureResource.m_Filter; - is_tcgprojected = defaultTextureCoordinateModifier.m_bTexGenProjected; - - tcmuoscrate = defaultTextureCoordinateModifier.m_OscRate[0]; - tcmvoscrate = defaultTextureCoordinateModifier.m_OscRate[1]; - - tcmuoscamplitude = defaultTextureCoordinateModifier.m_OscAmplitude[0]; - tcmvoscamplitude = defaultTextureCoordinateModifier.m_OscAmplitude[1]; - - tcmuoscphase = defaultTextureCoordinateModifier.m_OscPhase[0]; - tcmvoscphase = defaultTextureCoordinateModifier.m_OscPhase[1]; - - tcmrotoscrate = RoundDegree(Word2Degr(defaultTextureCoordinateModifier.m_RotOscRate[2])); - tcmrotoscamplitude = RoundDegree(Word2Degr(defaultTextureCoordinateModifier.m_RotOscAmplitude[2])); - tcmrotoscphase = RoundDegree(Word2Degr(defaultTextureCoordinateModifier.m_RotOscPhase[2])); - } -}; - -struct SMaterialLayerVars -{ - CSmartVariable bNoDraw; // disable layer rendering (useful in some cases) - CSmartVariable bFadeOut; // fade out layer rendering and parent rendering - CSmartVariableEnum shader; // shader layer name -}; - -struct SVertexWaveFormUI -{ - CSmartVariableArray table; - CSmartVariableEnum waveFormType; - CSmartVariable level; - CSmartVariable amplitude; - CSmartVariable phase; - CSmartVariable frequency; -}; - -////////////////////////////////////////////////////////////////////////// -struct SVertexModUI -{ - CSmartVariableEnum type; - CSmartVariable fDividerX; - CSmartVariable fDividerY; - CSmartVariable fDividerZ; - CSmartVariable fDividerW; - CSmartVariable vNoiseScale; - SVertexWaveFormUI wave; -}; - -/** User Interface definition of material. -*/ -class CMaterialUI -{ -public: - CSmartVariableEnum shader; - CSmartVariable bNoShadow; - CSmartVariable bAdditive; - CSmartVariable bWire; - CSmartVariable b2Sided; - CSmartVariable opacity; - CSmartVariable alphaTest; - CSmartVariable emissiveIntensity; - CSmartVariable voxelCoverage; - CSmartVariable heatAmount; - CSmartVariable bScatter; - CSmartVariable bHideAfterBreaking; - CSmartVariable bFogVolumeShadingQualityHigh; - CSmartVariable bBlendTerrainColor; - //CSmartVariable bTranslucenseLayer; - CSmartVariableEnum surfaceType; - - CSmartVariable allowLayerActivation; - - ////////////////////////////////////////////////////////////////////////// - // Material Value Propagation for dynamic material switches, as for instance - // used by breakable glass - ////////////////////////////////////////////////////////////////////////// - CSmartVariableEnum matPropagate; - CSmartVariable bPropagateMaterialSettings; - CSmartVariable bPropagateOpactity; - CSmartVariable bPropagateLighting; - CSmartVariable bPropagateAdvanced; - CSmartVariable bPropagateTexture; - CSmartVariable bPropagateVertexDef; - CSmartVariable bPropagateShaderParams; - CSmartVariable bPropagateLayerPresets; - CSmartVariable bPropagateShaderGenParams; - - ////////////////////////////////////////////////////////////////////////// - // Lighting - ////////////////////////////////////////////////////////////////////////// - CSmartVariable diffuse; // Diffuse color 0..1 - CSmartVariable specular; // Specular color 0..1 - CSmartVariable smoothness; // Specular shininess. - CSmartVariable emissiveCol; // Emissive color 0..1 - - ////////////////////////////////////////////////////////////////////////// - // Textures. - ////////////////////////////////////////////////////////////////////////// - CSmartVariableArray textureVars[EFTT_MAX]; - CSmartVariableArray advancedTextureGroup[EFTT_MAX]; - STextureVars textures[EFTT_MAX]; - - ////////////////////////////////////////////////////////////////////////// - // Material layers settings - ////////////////////////////////////////////////////////////////////////// - - // 8 max for now. change this later - SMaterialLayerVars materialLayers[MTL_LAYER_MAX_SLOTS]; - - ////////////////////////////////////////////////////////////////////////// - - SVertexModUI vertexMod; - - CSmartVariableArray tableShader; - CSmartVariableArray tableOpacity; - CSmartVariableArray tableLighting; - CSmartVariableArray tableTexture; - CSmartVariableArray tableAdvanced; - CSmartVariableArray tableVertexMod; - CSmartVariableArray tableEffects; - - CSmartVariableArray tableShaderParams; - CSmartVariableArray tableShaderGenParams; - - CVarEnumList* enumTexType; - CVarEnumList* enumTexGenType; - CVarEnumList* enumTexModRotateType; - CVarEnumList* enumTexModUMoveType; - CVarEnumList* enumTexModVMoveType; - CVarEnumList* enumTexFilterType; - - CVarEnumList* enumVertexMod; - CVarEnumList* enumWaveType; - - ////////////////////////////////////////////////////////////////////////// - int texUsageMask; - - CVarBlockPtr m_vars; - - typedef std::map TVarChangeNotifications; - TVarChangeNotifications m_varChangeNotifications; - - ////////////////////////////////////////////////////////////////////////// - void SetFromMaterial(CMaterial* mtl); - void SetToMaterial(CMaterial* mtl, int propagationFlags = MTL_PROPAGATE_ALL); - void SetTextureNames(CMaterial* mtl); - - void SetShaderResources(const SInputShaderResources& srTextures, bool bSetTextures = true); - void GetShaderResources(SInputShaderResources& sr, int propagationFlags); - - void SetVertexDeform(const SInputShaderResources& sr); - void GetVertexDeform(SInputShaderResources& sr, int propagationFlags); - - void PropagateFromLinkedMaterial(CMaterial* mtl); - void PropagateToLinkedMaterial(CMaterial* mtl, CVarBlockPtr pShaderParamsBlock); - void NotifyObjectsAboutMaterialChange(IVariable* var); - - - ////////////////////////////////////////////////////////////////////////// - CMaterialUI() - { - } - - ~CMaterialUI() - { - } - - ////////////////////////////////////////////////////////////////////////// - CVarBlock* CreateVars() - { - m_vars = new CVarBlock; - - ////////////////////////////////////////////////////////////////////////// - // Init enums. - ////////////////////////////////////////////////////////////////////////// - enumTexType = new CVarEnumList(); - enumTexType->AddItem("2D", eTT_2D); - enumTexType->AddItem("Cube-Map", eTT_Cube); - enumTexType->AddItem("Nearest Cube-Map probe for alpha blended", eTT_NearestCube); - enumTexType->AddItem("Dynamic 2D-Map", eTT_Dyn2D); - enumTexType->AddItem("From User Params", eTT_User); - - enumTexGenType = new CVarEnumList(); - enumTexGenType->AddItem("Stream", ETG_Stream); - enumTexGenType->AddItem("World", ETG_World); - enumTexGenType->AddItem("Camera", ETG_Camera); - - enumTexModRotateType = new CVarEnumList(); - enumTexModRotateType->AddItem("No Change", ETMR_NoChange); - enumTexModRotateType->AddItem("Fixed Rotation", ETMR_Fixed); - enumTexModRotateType->AddItem("Constant Rotation", ETMR_Constant); - enumTexModRotateType->AddItem("Oscillated Rotation", ETMR_Oscillated); - - enumTexModUMoveType = new CVarEnumList(); - enumTexModUMoveType->AddItem("No Change", ETMM_NoChange); - enumTexModUMoveType->AddItem("Fixed Moving", ETMM_Fixed); - enumTexModUMoveType->AddItem("Constant Moving", ETMM_Constant); - enumTexModUMoveType->AddItem("Jitter Moving", ETMM_Jitter); - enumTexModUMoveType->AddItem("Pan Moving", ETMM_Pan); - enumTexModUMoveType->AddItem("Stretch Moving", ETMM_Stretch); - enumTexModUMoveType->AddItem("Stretch-Repeat Moving", ETMM_StretchRepeat); - - enumTexModVMoveType = new CVarEnumList(); - enumTexModVMoveType->AddItem("No Change", ETMM_NoChange); - enumTexModVMoveType->AddItem("Fixed Moving", ETMM_Fixed); - enumTexModVMoveType->AddItem("Constant Moving", ETMM_Constant); - enumTexModVMoveType->AddItem("Jitter Moving", ETMM_Jitter); - enumTexModVMoveType->AddItem("Pan Moving", ETMM_Pan); - enumTexModVMoveType->AddItem("Stretch Moving", ETMM_Stretch); - enumTexModVMoveType->AddItem("Stretch-Repeat Moving", ETMM_StretchRepeat); - - enumTexFilterType = new CVarEnumList(); - enumTexFilterType->AddItem("Default", FILTER_NONE); - enumTexFilterType->AddItem("Point", FILTER_POINT); - enumTexFilterType->AddItem("Linear", FILTER_LINEAR); - enumTexFilterType->AddItem("Bilinear", FILTER_BILINEAR); - enumTexFilterType->AddItem("Trilinear", FILTER_TRILINEAR); - enumTexFilterType->AddItem("Anisotropic 2x", FILTER_ANISO2X); - enumTexFilterType->AddItem("Anisotropic 4x", FILTER_ANISO4X); - enumTexFilterType->AddItem("Anisotropic 8x", FILTER_ANISO8X); - enumTexFilterType->AddItem("Anisotropic 16x", FILTER_ANISO16X); - - ////////////////////////////////////////////////////////////////////////// - // Vertex Mods. - ////////////////////////////////////////////////////////////////////////// - enumVertexMod = new CVarEnumList(); - enumVertexMod->AddItem("None", eDT_Unknown); - enumVertexMod->AddItem("Sin Wave", eDT_SinWave); - enumVertexMod->AddItem("Sin Wave using vertex color", eDT_SinWaveUsingVtxColor); - enumVertexMod->AddItem("Bulge", eDT_Bulge); - enumVertexMod->AddItem("Squeeze", eDT_Squeeze); - enumVertexMod->AddItem("FixedOffset", eDT_FixedOffset); - - ////////////////////////////////////////////////////////////////////////// - - enumWaveType = new CVarEnumList(); - enumWaveType->AddItem("Sin", eWF_Sin); - - ////////////////////////////////////////////////////////////////////////// - // Fill shaders enum. - ////////////////////////////////////////////////////////////////////////// - CVarEnumList* enumShaders = new CVarEnumList(); - { - CShaderEnum* pShaderEnum = GetIEditor()->GetShaderEnum(); - pShaderEnum->EnumShaders(); - for (int i = 0; i < pShaderEnum->GetShaderCount(); i++) - { - QString shaderName = pShaderEnum->GetShader(i); - if (shaderName.contains("_Overlay", Qt::CaseInsensitive)) - { - continue; - } - enumShaders->AddItem(shaderName, shaderName); - } - } - - ////////////////////////////////////////////////////////////////////////// - // Fill surface types. - ////////////////////////////////////////////////////////////////////////// - CVarEnumList* enumSurfaceTypes = new CVarEnumList(); - { - QStringList types; - types.push_back(""); // Push empty surface type. - ISurfaceTypeEnumerator* pSurfaceTypeEnum = gEnv->p3DEngine->GetMaterialManager()->GetSurfaceTypeManager()->GetEnumerator(); - if (pSurfaceTypeEnum) - { - for (ISurfaceType* pSurfaceType = pSurfaceTypeEnum->GetFirst(); pSurfaceType; pSurfaceType = pSurfaceTypeEnum->GetNext()) - { - types.push_back(pSurfaceType->GetName()); - } - std::sort(types.begin(), types.end()); - for (int i = 0; i < types.size(); i++) - { - QString name = types[i]; - if (name.left(4) == "mat_") - { - name.remove(0, 4); - } - enumSurfaceTypes->AddItem(name, types[i]); - } - } - } - - ////////////////////////////////////////////////////////////////////////// - // Init tables. - ////////////////////////////////////////////////////////////////////////// - AddVariable(m_vars, tableShader, "Material Settings", ""); - AddVariable(m_vars, tableOpacity, "Opacity Settings", ""); - AddVariable(m_vars, tableLighting, "Lighting Settings", ""); - AddVariable(m_vars, tableAdvanced, "Advanced", ""); - AddVariable(m_vars, tableTexture, "Texture Maps", ""); - AddVariable(m_vars, tableShaderParams, "Shader Params", ""); - AddVariable(m_vars, tableShaderGenParams, "Shader Generation Params", ""); - AddVariable(m_vars, tableVertexMod, "Vertex Deformation", ""); - - tableTexture->SetFlags(tableTexture->GetFlags() | IVariable::UI_ROLLUP2); - tableVertexMod->SetFlags(tableVertexMod->GetFlags() | IVariable::UI_ROLLUP2 | IVariable::UI_COLLAPSED); - tableAdvanced->SetFlags(tableAdvanced->GetFlags() | IVariable::UI_COLLAPSED); - tableShaderGenParams->SetFlags(tableShaderGenParams->GetFlags() | IVariable::UI_ROLLUP2 | IVariable::UI_COLLAPSED); - tableShaderParams->SetFlags(tableShaderParams->GetFlags() | IVariable::UI_ROLLUP2); - - - ////////////////////////////////////////////////////////////////////////// - // Shader. - ////////////////////////////////////////////////////////////////////////// - AddVariable(tableShader, shader, "Shader", "Selects shader type for specific surface response and options"); - AddVariable(tableShader, surfaceType, "Surface Type", "Defines how entities interact with surfaces using the material effects system"); - m_varChangeNotifications["Surface Type"] = MATERIALCHANGE_SURFACETYPE; - - shader->SetEnumList(enumShaders); - - surfaceType->SetEnumList(enumSurfaceTypes); - - // Properties that use this scriptingDescription are based on what's available in MaterialHelpers::SetGetMaterialParamVec3 and MaterialHelpers::SetGetMaterialParamFloat. - // This should match what's done in MaterialHelpers.cpp AddRealNameToDescription(). - auto scriptingDescription = [](const AZStd::string& scriptAccessibleName, const AZStd::string& description) { return description + "\n(Script Param Name = " + scriptAccessibleName + ")"; }; - - ////////////////////////////////////////////////////////////////////////// - // Opacity. - ////////////////////////////////////////////////////////////////////////// - AddVariable(tableOpacity, opacity, "Opacity", - scriptingDescription("opacity", "Sets the transparency amount. Uses 0-99 to set Alpha Blend and 100 for Opaque and Alpha Test.").c_str(), IVariable::DT_PERCENT); - AddVariable(tableOpacity, alphaTest, "AlphaTest", - scriptingDescription("alpha", "Uses the alpha mask and refines the transparent edge. Uses 0-50 to bias toward white or 50-100 to bias toward black.").c_str(), IVariable::DT_PERCENT); - AddVariable(tableOpacity, bAdditive, "Additive", "Adds material color to the background color resulting in a brighter transparent surface"); - opacity->SetLimits(0, 100, 1, true, true); - alphaTest->SetLimits(0, 100, 1, true, true); - - ////////////////////////////////////////////////////////////////////////// - // Lighting. - ////////////////////////////////////////////////////////////////////////// - AddVariable(tableLighting, diffuse, "Diffuse Color (Tint)", scriptingDescription("diffuse", "Tints the material diffuse color. Physically based materials should be left at white").c_str(), IVariable::DT_COLOR); - AddVariable(tableLighting, specular, "Specular Color", scriptingDescription("specular", "Reflective and shininess intensity and color of reflective highlights").c_str(), IVariable::DT_COLOR); - AddVariable(tableLighting, smoothness, "Smoothness", scriptingDescription("shininess", "Smoothness or glossiness simulating how light bounces off the surface").c_str()); - AddVariable(tableLighting, emissiveIntensity, "Emissive Intensity (kcd/m2)", scriptingDescription("emissive_intensity", "Brightness simulating light emitting from the surface making an object glow").c_str()); - AddVariable(tableLighting, emissiveCol, "Emissive Color", scriptingDescription("emissive_color", "Tints the emissive color").c_str(), IVariable::DT_COLOR); - emissiveIntensity->SetLimits(0, EMISSIVE_INTENSITY_SOFT_MAX, 1, true, false); - smoothness->SetLimits(0, 255, 1, true, true); - - ////////////////////////////////////////////////////////////////////////// - // Init texture variables. - ////////////////////////////////////////////////////////////////////////// - for (EEfResTextures texId = EEfResTextures(0); texId < EFTT_MAX; texId = EEfResTextures(texId + 1)) - { - if (!MaterialHelpers::IsAdjustableTexSlot(texId)) - { - continue; - } - - InitTextureVars(texId, MaterialHelpers::LookupTexName(texId), MaterialHelpers::LookupTexDesc(texId)); - } - - //AddVariable( tableAdvanced,bWire,"Wireframe" ); - AddVariable(tableAdvanced, allowLayerActivation, "Allow layer activation", ""); - AddVariable(tableAdvanced, b2Sided, "2 Sided", "Enables both sides of mesh faces to render"); - AddVariable(tableAdvanced, bNoShadow, "No Shadow", "Disables casting shadows from mesh faces"); - AddVariable(tableAdvanced, bScatter, "Use Scattering", "Deprecated"); - AddVariable(tableAdvanced, bHideAfterBreaking, "Hide After Breaking", "Causes the object to disappear after procedurally breaking"); - AddVariable(tableAdvanced, bFogVolumeShadingQualityHigh, "Fog Volume Shading Quality High", "high fog volume shading quality behaves more accurately with fog volumes."); - AddVariable(tableAdvanced, bBlendTerrainColor, "Blend Terrain Color", ""); - AddVariable(tableAdvanced, voxelCoverage, "Voxel Coverage", "Fine tunes occlusion amount for svogi feature. Higher values occlude more closely to object shape."); - voxelCoverage->SetLimits(0, 1.0f); - - ////////////////////////////////////////////////////////////////////////// - // Material Value Propagation for dynamic material switches, as for instance - // used by breakable glass - ////////////////////////////////////////////////////////////////////////// - AddVariable(tableAdvanced, matPropagate, "Link to Material", ""); - AddVariable(tableAdvanced, bPropagateMaterialSettings, "Propagate Material Settings", ""); - AddVariable(tableAdvanced, bPropagateOpactity, "Propagate Opacity Settings", ""); - AddVariable(tableAdvanced, bPropagateLighting, "Propagate Lighting Settings", ""); - AddVariable(tableAdvanced, bPropagateAdvanced, "Propagate Advanced Settings", ""); - AddVariable(tableAdvanced, bPropagateTexture, "Propagate Texture Maps", ""); - AddVariable(tableAdvanced, bPropagateShaderParams, "Propagate Shader Params", ""); - AddVariable(tableAdvanced, bPropagateShaderGenParams, "Propagate Shader Generation", ""); - AddVariable(tableAdvanced, bPropagateVertexDef, "Propagate Vertex Deformation", ""); - - ////////////////////////////////////////////////////////////////////////// - // Init Vertex Deformation. - ////////////////////////////////////////////////////////////////////////// - vertexMod.type->SetEnumList(enumVertexMod); - AddVariable(tableVertexMod, vertexMod.type, "Type", "Choose method to define how the vertices will deform"); - AddVariable(tableVertexMod, vertexMod.fDividerX, "Wave Length", "Length of wave deformation"); - - AddVariable(tableVertexMod, vertexMod.wave.table, "Parameters", "Fine tunes how the vertices deform"); - - vertexMod.wave.waveFormType->SetEnumList(enumWaveType); - AddVariable(vertexMod.wave.table, vertexMod.wave.waveFormType, "Type", "Sin type will include vertex color in calculation"); - AddVariable(vertexMod.wave.table, vertexMod.wave.level, "Level", "Scales the object equally in xyz"); - AddVariable(vertexMod.wave.table, vertexMod.wave.amplitude, "Amplitude", "Strength of vertex deformation (vertex color: b, normal: z)"); - AddVariable(vertexMod.wave.table, vertexMod.wave.phase, "Phase", "Offset of vertex deformation (vertex color: r, normal: x)"); - AddVariable(vertexMod.wave.table, vertexMod.wave.frequency, "Frequency", "Speed of vertex animation (vertex color: g, normal: y)"); - - return m_vars; - } - -private: - ////////////////////////////////////////////////////////////////////////// - void InitTextureVars(int id, const QString& name, const QString& desc) - { - textureVars[id]->SetFlags(IVariable::UI_BOLD); - textureVars[id]->SetFlags(textureVars[id]->GetFlags() | IVariable::UI_AUTO_EXPAND); - advancedTextureGroup[id]->SetFlags(advancedTextureGroup[id]->GetFlags() | IVariable::UI_COLLAPSED); - AddVariable(tableTexture, *textureVars[id], name.toUtf8().data(), desc.toUtf8().data(), IVariable::DT_TEXTURE); - AddVariable(*textureVars[id], *advancedTextureGroup[id], "Advanced", "Controls UV tiling, offset, and rotation as well as texture filtering"); - - AddVariable(*advancedTextureGroup[id], textures[id].etextype, "TexType", ""); - AddVariable(*advancedTextureGroup[id], textures[id].filter, "Filter", "Sets texture smoothing method to determine texture pixel quality"); - - AddVariable(*advancedTextureGroup[id], textures[id].is_tcgprojected, "IsProjectedTexGen", ""); - AddVariable(*advancedTextureGroup[id], textures[id].etcgentype, "TexGenType", "Controls UV projection behavior"); - - if (IsTextureModifierSupportedForTextureMap(static_cast(id))) - { - ////////////////////////////////////////////////////////////////////////// - // Tiling table. - AddVariable(*advancedTextureGroup[id], textures[id].tableTiling, "Tiling", "Controls UV tiling, offset, and rotation"); - { - CVariableArray& table = textures[id].tableTiling; - table.SetFlags(IVariable::UI_BOLD); - AddVariable(table, *textures[id].is_tile[0], "IsTileU", "Enables UV tiling on U"); - AddVariable(table, *textures[id].is_tile[1], "IsTileV", "Enables UV tiling on V"); - AddVariable(table, *textures[id].tiling[0], "TileU", "Multiplies tiled projection on U"); - AddVariable(table, *textures[id].tiling[1], "TileV", "Multiplies tiled projection on V"); - AddVariable(table, *textures[id].offset[0], "OffsetU", "Offsets texture projection on U"); - AddVariable(table, *textures[id].offset[1], "OffsetV", "Offsets texture projection on V"); - AddVariable(table, *textures[id].rotate[0], "RotateU", "Rotates texture projection on U"); - AddVariable(table, *textures[id].rotate[1], "RotateV", "Rotates texture projection on V"); - AddVariable(table, *textures[id].rotate[2], "RotateW", "Rotates texture projection on W"); - } - - ////////////////////////////////////////////////////////////////////////// - // Rotator tables. - AddVariable(*advancedTextureGroup[id], textures[id].tableRotator, "Rotator", "Controls the animated UV rotation"); - { - CVariableArray& table = textures[id].tableRotator; - table.SetFlags(IVariable::UI_BOLD); - AddVariable(table, textures[id].etcmrotatetype, "Type", "Controls the behavior of UV rotation"); - AddVariable(table, textures[id].tcmrotoscrate, "Rate", "Sets the speed (number of complete cycles per unit of time) of rotation"); - AddVariable(table, textures[id].tcmrotoscphase, "Phase", "Sets the initial offset of rotation"); - AddVariable(table, textures[id].tcmrotoscamplitude, "Amplitude", "Sets the strength (maximum value) of rotation"); - AddVariable(table, *textures[id].tcmrotosccenter[0], "CenterU", "Sets the center of rotation along U"); - AddVariable(table, *textures[id].tcmrotosccenter[1], "CenterV", "Sets the center of rotation along V"); - } - - ////////////////////////////////////////////////////////////////////////// - // Oscillator table - AddVariable(*advancedTextureGroup[id], textures[id].tableOscillator, "Oscillator", "Controls the animated UV oscillation"); - { - CVariableArray& table = textures[id].tableOscillator; - table.SetFlags(IVariable::UI_BOLD); - AddVariable(table, textures[id].etcmumovetype, "TypeU", "Sets the behavior of oscillation in the U direction"); - AddVariable(table, textures[id].etcmvmovetype, "TypeV", "Sets the behavior of oscillation in the V direction"); - AddVariable(table, textures[id].tcmuoscrate, "RateU", "Sets the speed (number of complete cycles per unit of time) of oscillation in U"); - AddVariable(table, textures[id].tcmvoscrate, "RateV", "Sets the speed (number of complete cycles per unit of time) of oscillation in V"); - AddVariable(table, textures[id].tcmuoscphase, "PhaseU", "Sets the initial offset of oscillation in U"); - AddVariable(table, textures[id].tcmvoscphase, "PhaseV", "Sets the initial offset of oscillation in V"); - AddVariable(table, textures[id].tcmuoscamplitude, "AmplitudeU", "Sets the strength (maximum value) of oscillation in U"); - AddVariable(table, textures[id].tcmvoscamplitude, "AmplitudeV", "Sets the strength (maximum value) of oscillation in V"); - } - } - - ////////////////////////////////////////////////////////////////////////// - // Assign enums tables to variable. - ////////////////////////////////////////////////////////////////////////// - textures[id].etextype->SetEnumList(enumTexType); - textures[id].etcgentype->SetEnumList(enumTexGenType); - textures[id].etcmrotatetype->SetEnumList(enumTexModRotateType); - textures[id].etcmumovetype->SetEnumList(enumTexModUMoveType); - textures[id].etcmvmovetype->SetEnumList(enumTexModVMoveType); - textures[id].filter->SetEnumList(enumTexFilterType); - } - ////////////////////////////////////////////////////////////////////////// - - void AddVariable(CVariableBase& varArray, CVariableBase& var, const char* varName, const char* varTooltip, unsigned char dataType = IVariable::DT_SIMPLE) - { - if (varName) - { - var.SetName(varName); - } - if (varTooltip) - { - var.SetDescription(varTooltip); - } - var.SetDataType(dataType); - varArray.AddVariable(&var); - } - ////////////////////////////////////////////////////////////////////////// - void AddVariable(CVarBlock* vars, CVariableBase& var, const char* varName, const char* varTooltip, unsigned char dataType = IVariable::DT_SIMPLE) - { - if (varName) - { - var.SetName(varName); - } - if (varTooltip) - { - var.SetDescription(varTooltip); - } - var.SetDataType(dataType); - vars->AddVariable(&var); - } - - void SetTextureResources(const SEfResTexture *pTextureRes, uint16 tex, bool bSetTextures); - void GetTextureResources(SInputShaderResources& sr, int texid, int propagationFlags); - void ResetTextureResources(uint16 tex); - Vec4 ToVec4(const ColorF& col) { return Vec4(col.r, col.g, col.b, col.a); } - Vec3 ToVec3(const ColorF& col) { return Vec3(col.r, col.g, col.b); } - ColorF ToCFColor(const Vec3& col) { return ColorF(col); } - ColorF ToCFColor(const Vec4& col) { return ColorF(col); } -}; - -////////////////////////////////////////////////////////////////////////// -void CMaterialUI::NotifyObjectsAboutMaterialChange(IVariable* var) -{ - if (!var) - { - return; - } - - TVarChangeNotifications::iterator it = m_varChangeNotifications.find(var->GetName()); - if (it == m_varChangeNotifications.end()) - { - return; - } - - CMaterial* pMaterial = GetIEditor()->GetMaterialManager()->GetCurrentMaterial(); - if (!pMaterial) - { - return; - } - - // Get a parent, if we are editing submaterial - if (pMaterial->GetParent() != 0) - { - pMaterial = pMaterial->GetParent(); - } - - CBaseObjectsArray objects; - GetIEditor()->GetObjectManager()->GetObjects(objects); - int numObjects = objects.size(); - for (int i = 0; i < numObjects; ++i) - { - CBaseObject* pObject = objects[i]; - if (pObject->GetRenderMaterial() == pMaterial) - { - pObject->OnMaterialChanged(it->second); - } - } -} - -////////////////////////////////////////////////////////////////////////// -void CMaterialUI::SetShaderResources(const SInputShaderResources& srTextures, bool bSetTextures) -{ - alphaTest = srTextures.m_AlphaRef; - voxelCoverage = (float) srTextures.m_VoxelCoverage / 255.0f; - - diffuse = ToVec3(srTextures.m_LMaterial.m_Diffuse); - specular = ToVec3(srTextures.m_LMaterial.m_Specular); - emissiveCol = ToVec3(srTextures.m_LMaterial.m_Emittance); - emissiveIntensity = srTextures.m_LMaterial.m_Emittance.a; - opacity = srTextures.m_LMaterial.m_Opacity; - smoothness = srTextures.m_LMaterial.m_Smoothness; - - SetVertexDeform(srTextures); - - - for (EEfResTextures texId = EEfResTextures(0); texId < EFTT_MAX; texId = EEfResTextures(texId + 1)) - { - if (!MaterialHelpers::IsAdjustableTexSlot(texId)) - { - continue; - } - - auto foundIter = srTextures.m_TexturesResourcesMap.find((ResourceSlotIndex)texId); - if (foundIter != srTextures.m_TexturesResourcesMap.end()) - { - const SEfResTexture* pTextureRes = const_cast(&foundIter->second); - SetTextureResources(pTextureRes, texId, bSetTextures); - } - else - { - ResetTextureResources(texId); - } - } -} - -////////////////////////////////////////////////////////////////////////// -void CMaterialUI::GetShaderResources(SInputShaderResources& sr, int propagationFlags) -{ - if (propagationFlags & MTL_PROPAGATE_OPACITY) - { - sr.m_LMaterial.m_Opacity = opacity; - sr.m_AlphaRef = alphaTest; - } - - if (propagationFlags & MTL_PROPAGATE_ADVANCED) - { - sr.m_VoxelCoverage = int_round(voxelCoverage * 255.0f); - } - - if (propagationFlags & MTL_PROPAGATE_LIGHTING) - { - sr.m_LMaterial.m_Diffuse = ToCFColor(diffuse); - sr.m_LMaterial.m_Specular = ToCFColor(specular); - sr.m_LMaterial.m_Emittance = ColorF(emissiveCol, emissiveIntensity); - sr.m_LMaterial.m_Smoothness = smoothness; - } - - GetVertexDeform(sr, propagationFlags); - - for (EEfResTextures texId = EEfResTextures(0); texId < EFTT_MAX; texId = EEfResTextures(texId + 1)) - { - if (!MaterialHelpers::IsAdjustableTexSlot(texId)) - { - continue; - } - - GetTextureResources(sr, texId, propagationFlags); - } -} - -////////////////////////////////////////////////////////////////////////// -void CMaterialUI::SetTextureResources( const SEfResTexture *pTextureRes, uint16 texSlot, bool bSetTextures) -{ - /* - // Enable/Disable texture map, depending on the mask. - int flags = textureVars[tex].GetFlags(); - if ((1 << tex) & texUsageMask) - flags &= ~IVariable::UI_DISABLED; - else - flags |= IVariable::UI_DISABLED; - textureVars[tex].SetFlags( flags ); - */ - - if (bSetTextures) - { - QString texFilename = pTextureRes->m_Name.c_str(); - texFilename = Path::ToUnixPath(texFilename); - textureVars[texSlot]->Set(texFilename); - } - - //textures[tex].amount = pTextureRes->m_Amount; - *textures[texSlot].is_tile[0] = pTextureRes->m_bUTile; - *textures[texSlot].is_tile[1] = pTextureRes->m_bVTile; - - *textures[texSlot].tiling[0] = pTextureRes->GetTiling(0); - *textures[texSlot].tiling[1] = pTextureRes->GetTiling(1); - *textures[texSlot].offset[0] = pTextureRes->GetOffset(0); - *textures[texSlot].offset[1] = pTextureRes->GetOffset(1); - textures[texSlot].filter = (int)pTextureRes->m_Filter; - textures[texSlot].etextype = pTextureRes->m_Sampler.m_eTexType; - - if (pTextureRes->m_Ext.m_pTexModifier) - { - textures[texSlot].etcgentype = pTextureRes->m_Ext.m_pTexModifier->m_eTGType; - textures[texSlot].etcmumovetype = pTextureRes->m_Ext.m_pTexModifier->m_eMoveType[0]; - textures[texSlot].etcmvmovetype = pTextureRes->m_Ext.m_pTexModifier->m_eMoveType[1]; - textures[texSlot].etcmrotatetype = pTextureRes->m_Ext.m_pTexModifier->m_eRotType; - textures[texSlot].is_tcgprojected = pTextureRes->m_Ext.m_pTexModifier->m_bTexGenProjected; - textures[texSlot].tcmuoscrate = pTextureRes->m_Ext.m_pTexModifier->m_OscRate[0]; - textures[texSlot].tcmuoscphase = pTextureRes->m_Ext.m_pTexModifier->m_OscPhase[0]; - textures[texSlot].tcmuoscamplitude = pTextureRes->m_Ext.m_pTexModifier->m_OscAmplitude[0]; - textures[texSlot].tcmvoscrate = pTextureRes->m_Ext.m_pTexModifier->m_OscRate[1]; - textures[texSlot].tcmvoscphase = pTextureRes->m_Ext.m_pTexModifier->m_OscPhase[1]; - textures[texSlot].tcmvoscamplitude = pTextureRes->m_Ext.m_pTexModifier->m_OscAmplitude[1]; - - for (int i = 0; i < 3; i++) - { - *textures[texSlot].rotate[i] = RoundDegree(Word2Degr(pTextureRes->m_Ext.m_pTexModifier->m_Rot[i])); - } - textures[texSlot].tcmrotoscrate = RoundDegree(Word2Degr(pTextureRes->m_Ext.m_pTexModifier->m_RotOscRate[2])); - textures[texSlot].tcmrotoscphase = RoundDegree(Word2Degr(pTextureRes->m_Ext.m_pTexModifier->m_RotOscPhase[2])); - textures[texSlot].tcmrotoscamplitude = RoundDegree(Word2Degr(pTextureRes->m_Ext.m_pTexModifier->m_RotOscAmplitude[2])); - *textures[texSlot].tcmrotosccenter[0] = pTextureRes->m_Ext.m_pTexModifier->m_RotOscCenter[0]; - *textures[texSlot].tcmrotosccenter[1] = pTextureRes->m_Ext.m_pTexModifier->m_RotOscCenter[1]; - } - else - { - textures[texSlot].etcgentype = 0; - textures[texSlot].etcmumovetype = 0; - textures[texSlot].etcmvmovetype = 0; - textures[texSlot].etcmrotatetype = 0; - textures[texSlot].is_tcgprojected = false; - textures[texSlot].tcmuoscrate = 0; - textures[texSlot].tcmuoscphase = 0; - textures[texSlot].tcmuoscamplitude = 0; - textures[texSlot].tcmvoscrate = 0; - textures[texSlot].tcmvoscphase = 0; - textures[texSlot].tcmvoscamplitude = 0; - - for (int i = 0; i < 3; i++) - { - *textures[texSlot].rotate[i] = 0; - } - - textures[texSlot].tcmrotoscrate = 0; - textures[texSlot].tcmrotoscphase = 0; - textures[texSlot].tcmrotoscamplitude = 0; - *textures[texSlot].tcmrotosccenter[0] = 0; - *textures[texSlot].tcmrotosccenter[1] = 0; - } -} - -////////////////////////////////////////////////////////////////////////// -void CMaterialUI::ResetTextureResources(uint16 texSlot) -{ - QString texFilename = ""; - textureVars[texSlot]->Set(texFilename); - textures[texSlot].Reset(); -} - -void CMaterialUI::GetTextureResources(SInputShaderResources& sr, int tex, int propagationFlags) -{ - if ((propagationFlags & MTL_PROPAGATE_TEXTURES) == 0) - { - return; - } - - QString texFilename; - textureVars[tex]->Get(texFilename); - if (texFilename.isEmpty()) - { - // Remove the texture if the path was cleared in the UI - sr.m_TexturesResourcesMap.erase(tex); - - // If the normal map/second normal map has been cleared in the UI, - // we must also clear the smoothness/second smoothness since smoothness lives in the alpha of the normal - if (tex == EFTT_NORMALS) - { - sr.m_TexturesResourcesMap.erase(EFTT_SMOOTHNESS); - } - // EFTT_CUSTOM_SECONDARY is the 2nd normal - if (tex == EFTT_CUSTOM_SECONDARY) - { - sr.m_TexturesResourcesMap.erase(EFTT_SECOND_SMOOTHNESS); - } - return; - } - texFilename = Path::ToUnixPath(texFilename); - - // Clear any texture resource that has no associated file - if (texFilename.size() > AZ_MAX_PATH_LEN) - { - AZ_Error("Material Editor", false, "Texture path exceeds the maximium allowable length of %d.", AZ_MAX_PATH_LEN); - return; - } - - // The following line will insert the slot if did not exist. - SEfResTexture* pTextureRes = &(sr.m_TexturesResourcesMap[tex]); - pTextureRes->m_Name = texFilename.toUtf8().data(); - - //pTextureRes->m_Amount = textures[tex].amount; - pTextureRes->m_bUTile = *textures[tex].is_tile[0]; - pTextureRes->m_bVTile = *textures[tex].is_tile[1]; - SEfTexModificator& texm = *pTextureRes->AddModificator(); - texm.m_bTexGenProjected = textures[tex].is_tcgprojected; - - texm.m_Tiling[0] = *textures[tex].tiling[0]; - texm.m_Tiling[1] = *textures[tex].tiling[1]; - texm.m_Offs[0] = *textures[tex].offset[0]; - texm.m_Offs[1] = *textures[tex].offset[1]; - pTextureRes->m_Filter = (int)textures[tex].filter; - pTextureRes->m_Sampler.m_eTexType = textures[tex].etextype; - texm.m_eRotType = textures[tex].etcmrotatetype; - texm.m_eTGType = textures[tex].etcgentype; - texm.m_eMoveType[0] = textures[tex].etcmumovetype; - texm.m_eMoveType[1] = textures[tex].etcmvmovetype; - texm.m_OscRate[0] = textures[tex].tcmuoscrate; - texm.m_OscPhase[0] = textures[tex].tcmuoscphase; - texm.m_OscAmplitude[0] = textures[tex].tcmuoscamplitude; - texm.m_OscRate[1] = textures[tex].tcmvoscrate; - texm.m_OscPhase[1] = textures[tex].tcmvoscphase; - texm.m_OscAmplitude[1] = textures[tex].tcmvoscamplitude; - - for (int i = 0; i < 3; i++) - { - texm.m_Rot[i] = Degr2Word(*textures[tex].rotate[i]); - } - texm.m_RotOscRate[2] = Degr2Word(textures[tex].tcmrotoscrate); - texm.m_RotOscPhase[2] = Degr2Word(textures[tex].tcmrotoscphase); - texm.m_RotOscAmplitude[2] = Degr2Word(textures[tex].tcmrotoscamplitude); - texm.m_RotOscCenter[0] = *textures[tex].tcmrotosccenter[0]; - texm.m_RotOscCenter[1] = *textures[tex].tcmrotosccenter[1]; - texm.m_RotOscCenter[2] = 0.0f; -} - -////////////////////////////////////////////////////////////////////////// -void CMaterialUI::SetVertexDeform(const SInputShaderResources& sr) -{ - vertexMod.type = (int)sr.m_DeformInfo.m_eType; - vertexMod.fDividerX = sr.m_DeformInfo.m_fDividerX; - vertexMod.vNoiseScale = sr.m_DeformInfo.m_vNoiseScale; - - vertexMod.wave.waveFormType = EWaveForm::eWF_Sin; - vertexMod.wave.amplitude = sr.m_DeformInfo.m_WaveX.m_Amp; - vertexMod.wave.level = sr.m_DeformInfo.m_WaveX.m_Level; - vertexMod.wave.phase = sr.m_DeformInfo.m_WaveX.m_Phase; - vertexMod.wave.frequency = sr.m_DeformInfo.m_WaveX.m_Freq; -} - -////////////////////////////////////////////////////////////////////////// -void CMaterialUI::GetVertexDeform(SInputShaderResources& sr, int propagationFlags) -{ - if ((propagationFlags & MTL_PROPAGATE_VERTEX_DEF) == 0) - { - return; - } - - sr.m_DeformInfo.m_eType = (EDeformType)((int)vertexMod.type); - sr.m_DeformInfo.m_fDividerX = vertexMod.fDividerX; - sr.m_DeformInfo.m_vNoiseScale = vertexMod.vNoiseScale; - - sr.m_DeformInfo.m_WaveX.m_eWFType = (EWaveForm)((int)vertexMod.wave.waveFormType); - sr.m_DeformInfo.m_WaveX.m_Amp = vertexMod.wave.amplitude; - sr.m_DeformInfo.m_WaveX.m_Level = vertexMod.wave.level; - sr.m_DeformInfo.m_WaveX.m_Phase = vertexMod.wave.phase; - sr.m_DeformInfo.m_WaveX.m_Freq = vertexMod.wave.frequency; -} - -void CMaterialUI::PropagateToLinkedMaterial(CMaterial* mtl, CVarBlockPtr pShaderParams) -{ - if (!mtl) - { - return; - } - CMaterial* subMtl = NULL, * parentMtl = mtl->GetParent(); - const QString& linkedMaterialName = matPropagate; - int propFlags = 0; - - if (parentMtl) - { - for (int i = 0; i < parentMtl->GetSubMaterialCount(); ++i) - { - CMaterial* pMtl = parentMtl->GetSubMaterial(i); - if (pMtl && pMtl != mtl && pMtl->GetFullName() == linkedMaterialName) - { - subMtl = pMtl; - break; - } - } - } - if (!linkedMaterialName.isEmpty() && subMtl) - { - // Ensure that the linked material is cleared if it can't be found anymore - mtl->LinkToMaterial(linkedMaterialName); - } - // Note: It's only allowed to propagate the shader params and shadergen params - // if we also propagate the actual shader to the linked material as well, else - // bogus values will be set - bPropagateShaderParams = (int)bPropagateShaderParams & - (int)bPropagateMaterialSettings; - bPropagateShaderGenParams = (int)bPropagateShaderGenParams & - (int)bPropagateMaterialSettings; - - propFlags |= MTL_PROPAGATE_MATERIAL_SETTINGS & - (int)bPropagateMaterialSettings; - propFlags |= MTL_PROPAGATE_OPACITY & - (int)bPropagateOpactity; - propFlags |= MTL_PROPAGATE_LIGHTING & - (int)bPropagateLighting; - propFlags |= MTL_PROPAGATE_ADVANCED & - (int)bPropagateAdvanced; - propFlags |= MTL_PROPAGATE_TEXTURES & - (int)bPropagateTexture; - propFlags |= MTL_PROPAGATE_SHADER_PARAMS & - (int)bPropagateShaderParams; - propFlags |= MTL_PROPAGATE_SHADER_GEN & - (int)bPropagateShaderGenParams; - propFlags |= MTL_PROPAGATE_VERTEX_DEF & - (int)bPropagateVertexDef; - propFlags |= MTL_PROPAGATE_LAYER_PRESETS & - (int)bPropagateLayerPresets; - mtl->SetPropagationFlags(propFlags); - - if (subMtl) - { - SetToMaterial(subMtl, propFlags | MTL_PROPAGATE_RESERVED); - if (propFlags & MTL_PROPAGATE_SHADER_PARAMS) - { - if (CVarBlock* pPublicVars = subMtl->GetPublicVars(mtl->GetShaderResources())) - { - subMtl->SetPublicVars(pPublicVars, subMtl); - } - } - if (propFlags & MTL_PROPAGATE_SHADER_GEN) - { - subMtl->SetShaderGenParamsVars(mtl->GetShaderGenParamsVars()); - } - subMtl->Update(); - subMtl->UpdateMaterialLayers(); - } -} - -void CMaterialUI::PropagateFromLinkedMaterial(CMaterial* mtl) -{ - if (!mtl) - { - return; - } - CMaterial* subMtl = NULL, * parentMtl = mtl->GetParent(); - const QString& linkedMaterialName = mtl->GetLinkedMaterialName(); - //CVarEnumList *enumMtls = new CVarEnumList; - if (parentMtl) - { - for (int i = 0; i < parentMtl->GetSubMaterialCount(); ++i) - { - CMaterial* pMtl = parentMtl->GetSubMaterial(i); - if (!pMtl || pMtl == mtl) - { - continue; - } - const QString& subMtlName = pMtl->GetFullName(); - //enumMtls->AddItem(subMtlName, subMtlName); - if (subMtlName == linkedMaterialName) - { - subMtl = pMtl; - break; - } - } - } - matPropagate = QString(); - //matPropagate.SetEnumList(enumMtls); - if (!linkedMaterialName.isEmpty() && !subMtl) - { - // Ensure that the linked material is cleared if it can't be found anymore - mtl->LinkToMaterial(QString()); - } - else - { - matPropagate = linkedMaterialName; - } - bPropagateMaterialSettings = mtl->GetPropagationFlags() & MTL_PROPAGATE_MATERIAL_SETTINGS; - bPropagateOpactity = mtl->GetPropagationFlags() & MTL_PROPAGATE_OPACITY; - bPropagateLighting = mtl->GetPropagationFlags() & MTL_PROPAGATE_LIGHTING; - bPropagateTexture = mtl->GetPropagationFlags() & MTL_PROPAGATE_TEXTURES; - bPropagateAdvanced = mtl->GetPropagationFlags() & MTL_PROPAGATE_ADVANCED; - bPropagateVertexDef = mtl->GetPropagationFlags() & MTL_PROPAGATE_VERTEX_DEF; - bPropagateShaderParams = mtl->GetPropagationFlags() & MTL_PROPAGATE_SHADER_PARAMS; - bPropagateLayerPresets = mtl->GetPropagationFlags() & MTL_PROPAGATE_LAYER_PRESETS; - bPropagateShaderGenParams = mtl->GetPropagationFlags() & MTL_PROPAGATE_SHADER_GEN; -} - -void CMaterialUI::SetFromMaterial(CMaterial* mtlIn) -{ - QString shaderName = mtlIn->GetShaderName(); - if (!shaderName.isEmpty()) - { - // Capitalize first letter. - shaderName = shaderName[0].toUpper() + shaderName.mid(1); - } - - shader = shaderName; - - int mtlFlags = mtlIn->GetFlags(); - bNoShadow = (mtlFlags & MTL_FLAG_NOSHADOW); - bAdditive = (mtlFlags & MTL_FLAG_ADDITIVE); - bWire = (mtlFlags & MTL_FLAG_WIRE); - b2Sided = (mtlFlags & MTL_FLAG_2SIDED); - bScatter = (mtlFlags & MTL_FLAG_SCATTER); - bHideAfterBreaking = (mtlFlags & MTL_FLAG_HIDEONBREAK); - bFogVolumeShadingQualityHigh = (mtlFlags & MTL_FLAG_FOG_VOLUME_SHADING_QUALITY_HIGH); - bBlendTerrainColor = (mtlFlags & MTL_FLAG_BLEND_TERRAIN); - texUsageMask = mtlIn->GetTexmapUsageMask(); - - allowLayerActivation = mtlIn->LayerActivationAllowed(); - - // Detail, decal and custom textures are always active. - const uint32 nDefaultFlagsEFTT = (1 << EFTT_DETAIL_OVERLAY) | (1 << EFTT_DECAL_OVERLAY) | (1 << EFTT_CUSTOM) | (1 << EFTT_CUSTOM_SECONDARY); - texUsageMask |= nDefaultFlagsEFTT; - if ((texUsageMask & (1 << EFTT_NORMALS))) - { - texUsageMask |= 1 << EFTT_NORMALS; - } - - surfaceType = mtlIn->GetSurfaceTypeName(); - SetShaderResources(mtlIn->GetShaderResources(), true); - - // Propagate settings and properties to a sub material if edited - PropagateFromLinkedMaterial(mtlIn); - - // set each material layer - SMaterialLayerResources* pMtlLayerResources = mtlIn->GetMtlLayerResources(); - for (int l(0); l < MTL_LAYER_MAX_SLOTS; ++l) - { - materialLayers[l].shader = pMtlLayerResources[l].m_shaderName; - materialLayers[l].bNoDraw = pMtlLayerResources[l].m_nFlags & MTL_LAYER_USAGE_NODRAW; - materialLayers[l].bFadeOut = pMtlLayerResources[l].m_nFlags & MTL_LAYER_USAGE_FADEOUT; - } -} - -void CMaterialUI::SetToMaterial(CMaterial* mtl, int propagationFlags) -{ - int mtlFlags = mtl->GetFlags(); - - if (propagationFlags & MTL_PROPAGATE_ADVANCED) - { - if (bNoShadow) - { - mtlFlags |= MTL_FLAG_NOSHADOW; - } - else - { - mtlFlags &= ~MTL_FLAG_NOSHADOW; - } - } - - if (propagationFlags & MTL_PROPAGATE_OPACITY) - { - if (bAdditive) - { - mtlFlags |= MTL_FLAG_ADDITIVE; - } - else - { - mtlFlags &= ~MTL_FLAG_ADDITIVE; - } - } - - if (bWire) - { - mtlFlags |= MTL_FLAG_WIRE; - } - else - { - mtlFlags &= ~MTL_FLAG_WIRE; - } - - if (propagationFlags & MTL_PROPAGATE_ADVANCED) - { - if (b2Sided) - { - mtlFlags |= MTL_FLAG_2SIDED; - } - else - { - mtlFlags &= ~MTL_FLAG_2SIDED; - } - - if (bScatter) - { - mtlFlags |= MTL_FLAG_SCATTER; - } - else - { - mtlFlags &= ~MTL_FLAG_SCATTER; - } - - if (bHideAfterBreaking) - { - mtlFlags |= MTL_FLAG_HIDEONBREAK; - } - else - { - mtlFlags &= ~MTL_FLAG_HIDEONBREAK; - } - - if (bFogVolumeShadingQualityHigh) - { - mtlFlags |= MTL_FLAG_FOG_VOLUME_SHADING_QUALITY_HIGH; - } - else - { - mtlFlags &= ~MTL_FLAG_FOG_VOLUME_SHADING_QUALITY_HIGH; - } - - if (bBlendTerrainColor) - { - mtlFlags |= MTL_FLAG_BLEND_TERRAIN; - } - else - { - mtlFlags &= ~MTL_FLAG_BLEND_TERRAIN; - } - } - - mtl->SetFlags(mtlFlags); - - mtl->SetLayerActivation(allowLayerActivation); - - // set each material layer - if (propagationFlags & MTL_PROPAGATE_LAYER_PRESETS) - { - SMaterialLayerResources* pMtlLayerResources = mtl->GetMtlLayerResources(); - for (int l(0); l < MTL_LAYER_MAX_SLOTS; ++l) - { - if (pMtlLayerResources[l].m_shaderName != materialLayers[l].shader) - { - pMtlLayerResources[l].m_shaderName = materialLayers[l].shader; - pMtlLayerResources[l].m_bRegetPublicParams = true; - } - - if (materialLayers[l].bNoDraw) - { - pMtlLayerResources[l].m_nFlags |= MTL_LAYER_USAGE_NODRAW; - } - else - { - pMtlLayerResources[l].m_nFlags &= ~MTL_LAYER_USAGE_NODRAW; - } - - if (materialLayers[l].bFadeOut) - { - pMtlLayerResources[l].m_nFlags |= MTL_LAYER_USAGE_FADEOUT; - } - else - { - pMtlLayerResources[l].m_nFlags &= ~MTL_LAYER_USAGE_FADEOUT; - } - } - } - - if (propagationFlags & MTL_PROPAGATE_MATERIAL_SETTINGS) - { - mtl->SetSurfaceTypeName(surfaceType); - // If shader name is different reload shader. - mtl->SetShaderName(shader); - } - - GetShaderResources(mtl->GetShaderResources(), propagationFlags); -} - -void CMaterialUI::SetTextureNames(CMaterial* mtl) -{ - SInputShaderResources& sr = mtl->GetShaderResources(); - - for ( auto& iter : sr.m_TexturesResourcesMap ) - { - uint16 texId = iter.first; - if (!MaterialHelpers::IsAdjustableTexSlot((EEfResTextures)texId)) - { - continue; - } - - SEfResTexture* pTextureRes = &(iter.second); - textureVars[texId]->Set(pTextureRes->m_Name.c_str()); - } -} - -////////////////////////////////////////////////////////////////////////// -////////////////////////////////////////////////////////////////////////// -class CMtlPickCallback - : public IPickObjectCallback -{ -public: - CMtlPickCallback() { m_bActive = true; }; - //! Called when object picked. - virtual void OnPick(CBaseObject* picked) - { - m_bActive = false; - CMaterial* pMtl = picked->GetMaterial(); - if (pMtl) - { - GetIEditor()->OpenMaterialLibrary(pMtl); - } - delete this; - } - //! Called when pick mode canceled. - virtual void OnCancelPick() - { - m_bActive = false; - delete this; - } - //! Return true if specified object is pickable. - virtual bool OnPickFilter(CBaseObject* filterObject) - { - // Check if object have material. - if (filterObject->GetMaterial()) - { - return true; - } - else - { - return false; - } - } - static bool IsActive() { return m_bActive; }; -private: - static bool m_bActive; -}; -bool CMtlPickCallback::m_bActive = false; -////////////////////////////////////////////////////////////////////////// - - -////////////////////////////////////////////////////////////////////////// -// CMaterialDialog implementation. -////////////////////////////////////////////////////////////////////////// -CMaterialDialog::CMaterialDialog(QWidget* parent /* = 0 */) - : QMainWindow(parent) - , m_wndMtlBrowser(0) -{ - m_propsCtrl = new TwoColumnPropertyControl; - m_propsCtrl->Setup(true, 150); - m_propsCtrl->SetSavedStateKey("MaterialDialog"); - m_propsCtrl->setMinimumWidth(460); - - m_placeHolderLabel = new QLabel(tr("Select a material in the Material Editor hierarchy to view properties")); - m_placeHolderLabel->setMinimumHeight(250); - m_placeHolderLabel->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Preferred); - - SEventLog toolEvent(MATERIAL_EDITOR_NAME, "", MATERIAL_EDITOR_VER); - GetIEditor()->GetSettingsManager()->RegisterEvent(toolEvent); - - m_pMatManager = GetIEditor()->GetMaterialManager(); - - m_shaderGenParamsVars = 0; - - m_textureSlots = 0; - - m_pMaterialUI = new CMaterialUI; - - m_bForceReloadPropsCtrl = true; - - m_pMaterialImageListModel.reset(new QMaterialImageListModel); - - m_pMaterialImageListCtrl.reset(new CMaterialImageListCtrl); - m_pMaterialImageListCtrl->setModel(m_pMaterialImageListModel.data()); - - // Immediately create dialog. - OnInitDialog(); - - GetIEditor()->RegisterNotifyListener(this); - m_pMatManager->AddListener(this); - m_propsCtrl->SetUndoCallback(AZStd::bind(&CMaterialDialog::OnUndo, this, AZStd::placeholders::_1)); - m_propsCtrl->SetStoreUndoByItems(false); - - // KDAB_TODO: hack until we have proper signal coming from the IEDitor - connect(QCoreApplication::eventDispatcher(), &QAbstractEventDispatcher::awake, this, &CMaterialDialog::UpdateActions); -} - -////////////////////////////////////////////////////////////////////////// -CMaterialDialog::~CMaterialDialog() -{ - m_pMatManager->RemoveListener(this); - GetIEditor()->UnregisterNotifyListener(this); - m_wndMtlBrowser->SetImageListCtrl(NULL); - - delete m_pMaterialUI; - m_vars = 0; - m_publicVars = 0; - m_shaderGenParamsVars = 0; - m_textureSlots = 0; - - m_propsCtrl->ClearUndoCallback(); - m_propsCtrl->RemoveAllItems(); - - SEventLog toolEvent(MATERIAL_EDITOR_NAME, "", MATERIAL_EDITOR_VER); - GetIEditor()->GetSettingsManager()->UnregisterEvent(toolEvent); -} - -BOOL CMaterialDialog::OnInitDialog() -{ - setWindowTitle(tr(LyViewPane::MaterialEditor)); - if (gEnv->p3DEngine) - { - ISurfaceTypeManager* pSurfaceTypeManager = gEnv->p3DEngine->GetMaterialManager()->GetSurfaceTypeManager(); - if (pSurfaceTypeManager) - { - pSurfaceTypeManager->LoadSurfaceTypes(); - } - } - - InitToolbar(IDR_DB_MATERIAL_BAR); - - setCorner(Qt::TopLeftCorner, Qt::LeftDockWidgetArea); - - // hide menu bar - menuBar()->hide(); - - // Create status bar. - { - m_statusBar = this->statusBar(); - m_statusBar->setSizeGripEnabled(false); - } - - QSplitter* centralWidget = new QSplitter(Qt::Horizontal, this); - setCentralWidget(centralWidget); - - QSplitter* rightWidget = new QSplitter(Qt::Vertical, centralWidget); - centralWidget->addWidget(rightWidget); - - rightWidget->addWidget(m_propsCtrl); - - m_vars = m_pMaterialUI->CreateVars(); - m_propsCtrl->AddVarBlock(m_vars); - - m_propsCtrl->setEnabled(false); - m_propsCtrl->hide(); - - ////////////////////////////////////////////////////////////////////////// - // Preview Pane - ////////////////////////////////////////////////////////////////////////// - { - rightWidget->insertWidget(0, m_pMaterialImageListCtrl.data()); - - int h = m_pMaterialImageListCtrl->sizeHint().height(); - m_pMaterialImageListCtrl->hide(); - rightWidget->setSizes({h, height() - h }); - } - - rightWidget->addWidget(m_placeHolderLabel); - m_placeHolderLabel->setAlignment(Qt::AlignCenter); - - ////////////////////////////////////////////////////////////////////////// - // Browser Pane - ////////////////////////////////////////////////////////////////////////// - if (!m_wndMtlBrowser) - { - m_wndMtlBrowser = new MaterialBrowserWidget(this); - m_wndMtlBrowser->SetListener(this); - m_wndMtlBrowser->SetImageListCtrl(m_pMaterialImageListCtrl.data()); - //m_wndMtlBrowser->resize(width() / 3, height()); - - centralWidget->insertWidget(0, m_wndMtlBrowser); - - int w = m_wndMtlBrowser->sizeHint().height(); - centralWidget->setSizes({ w, width() - w }); - centralWidget->setStretchFactor(0, 0); - centralWidget->setStretchFactor(1, 1); - - // Start the background processing of material files after the widget has been initialized - m_wndMtlBrowser->StartRecordUpdateJobs(); - } - - // Set the image list control to give stretch priority to the other widgets. This is both to avoid resizing the - // image list control when the window is resized and to avoid an issue with the QSplitter resizing the image list - // control when enabling/disabling the other two widgets. - const int materialImageControlIndex = 0; - const int materialImagePropertiesControlIndex = 1; - const int materialPlaceholderLabelIndex = 2; - rightWidget->setStretchFactor(materialImageControlIndex, 0); - rightWidget->setStretchFactor(materialImagePropertiesControlIndex, 1); - rightWidget->setStretchFactor(materialPlaceholderLabelIndex, 1); - - resize(1200, 800); - - return true; // return true unless you set the focus to a control - // EXCEPTION: OCX Property Pages should return FALSE -} - -void CMaterialDialog::closeEvent(QCloseEvent *ev) -{ - // We call save before running any dtors, as it might trigger a modal dialog / nested event loop - // asking to overwrite files, and that causes a crash - m_wndMtlBrowser->SaveCurrentMaterial(); - ev->accept(); // All good, dialog will close now -} - -////////////////////////////////////////////////////////////////////////// -// Create the toolbar -void CMaterialDialog::InitToolbar([[maybe_unused]] UINT nToolbarResID) -{ - // detect if the new viewport interaction model is enabled and give - // feedback to the user that certain operations are not yet compatible - const bool newViewportInteractionModelEnabled = GetIEditor()->IsNewViewportInteractionModelEnabled(); - const char* const newViewportInteractionModelWarning = - "This option is currently not available with the new Viewport Interaction Model enabled"; - - m_toolbar = addToolBar(tr("Material ToolBar")); - m_toolbar->setFloatable(false); - - QIcon assignselectionIcon; - assignselectionIcon.addPixmap(QPixmap{ ":/MaterialDialog/ToolBar/images/materialdialog_assignselection_normal.png" }, QIcon::Normal); - assignselectionIcon.addPixmap(QPixmap{ ":/MaterialDialog/ToolBar/images/materialdialog_assignselection_active.png" }, QIcon::Active); - assignselectionIcon.addPixmap(QPixmap{ ":/MaterialDialog/ToolBar/images/materialdialog_assignselection_disabled.png" }, QIcon::Disabled); - - m_assignToSelectionAction = - m_toolbar->addAction(assignselectionIcon, - newViewportInteractionModelEnabled - ? tr(newViewportInteractionModelWarning) - : tr("Assign Item to Selected Objects"), - this, SLOT(OnAssignMaterialToSelection())); - - QIcon resetIcon; - resetIcon.addPixmap(QPixmap{ ":/MaterialDialog/ToolBar/images/materialdialog_reset_normal.png" }, QIcon::Normal); - resetIcon.addPixmap(QPixmap{ ":/MaterialDialog/ToolBar/images/materialdialog_reset_active.png" }, QIcon::Active); - resetIcon.addPixmap(QPixmap{ ":/MaterialDialog/ToolBar/images/materialdialog_reset_disabled.png" }, QIcon::Disabled); - - m_resetAction = - m_toolbar->addAction(resetIcon, - newViewportInteractionModelEnabled - ? tr(newViewportInteractionModelWarning) - : tr("Reset Material on Selection to Default"), - this, SLOT(OnResetMaterialOnSelection())); - - QIcon getfromselectionIcon; - getfromselectionIcon.addPixmap(QPixmap{ ":/MaterialDialog/ToolBar/images/materialdialog_getfromselection_normal.png" }, QIcon::Normal); - getfromselectionIcon.addPixmap(QPixmap{ ":/MaterialDialog/ToolBar/images/materialdialog_getfromselection_active.png" }, QIcon::Active); - getfromselectionIcon.addPixmap(QPixmap{ ":/MaterialDialog/ToolBar/images/materialdialog_getfromselection_disabled.png" }, QIcon::Disabled); - - m_getFromSelectionAction = - m_toolbar->addAction( - getfromselectionIcon, - newViewportInteractionModelEnabled - ? tr(newViewportInteractionModelWarning) - : tr("Get Properties From Selection"), - this, SLOT(OnGetMaterialFromSelection())); - - QIcon pickIcon; - pickIcon.addPixmap(QPixmap{ ":/MaterialDialog/ToolBar/images/materialdialog_pick_normal.png" }, QIcon::Normal); - pickIcon.addPixmap(QPixmap{ ":/MaterialDialog/ToolBar/images/materialdialog_pick_active.png" }, QIcon::Active); - pickIcon.addPixmap(QPixmap{ ":/MaterialDialog/ToolBar/images/materialdialog_pick_disabled.png" }, QIcon::Disabled); - - m_pickAction = m_toolbar->addAction( - pickIcon, - newViewportInteractionModelEnabled - ? tr(newViewportInteractionModelWarning) - : tr("Pick Material from Object"), - this, SLOT(OnPickMtl())); - - m_pickAction->setCheckable(true); - - if (newViewportInteractionModelEnabled) - { - m_pickAction->setEnabled(false); - } - - QAction* sepAction = m_toolbar->addSeparator(); - m_filterTypeSelection = new QComboBox(this); - m_filterTypeSelection->addItem(tr("All Materials")); - m_filterTypeSelection->addItem(tr("Used In Level")); - m_filterTypeSelection->setMinimumWidth(150); - QAction* cbAction = m_toolbar->addWidget(m_filterTypeSelection); - m_filterTypeSelection->setCurrentIndex(0); - connect(m_filterTypeSelection, SIGNAL(currentIndexChanged(int)), this, SLOT(OnChangedBrowserListType(int))); - m_toolbar->addSeparator(); - QIcon addIcon; - addIcon.addPixmap(QPixmap{ ":/MaterialDialog/ToolBar/images/materialdialog_add_normal.png" }, QIcon::Normal); - addIcon.addPixmap(QPixmap{ ":/MaterialDialog/ToolBar/images/materialdialog_add_active.png" }, QIcon::Active); - addIcon.addPixmap(QPixmap{ ":/MaterialDialog/ToolBar/images/materialdialog_add_disabled.png" }, QIcon::Disabled); - m_addAction = m_toolbar->addAction(addIcon, tr("Add New Item"), this, SLOT(OnAddItem())); - QIcon saveIcon; - saveIcon.addPixmap(QPixmap{ ":/MaterialDialog/ToolBar/images/materialdialog_save_normal.png" }, QIcon::Normal); - saveIcon.addPixmap(QPixmap{ ":/MaterialDialog/ToolBar/images/materialdialog_save_active.png" }, QIcon::Active); - saveIcon.addPixmap(QPixmap{ ":/MaterialDialog/ToolBar/images/materialdialog_save_disabled.png" }, QIcon::Disabled); - m_saveAction = m_toolbar->addAction(saveIcon, tr("Save Item"), this, SLOT(OnSaveItem())); - QIcon removeIcon; - removeIcon.addPixmap(QPixmap{ ":/MaterialDialog/ToolBar/images/materialdialog_remove_normal.png" }, QIcon::Normal); - removeIcon.addPixmap(QPixmap{ ":/MaterialDialog/ToolBar/images/materialdialog_remove_active.png" }, QIcon::Active); - removeIcon.addPixmap(QPixmap{ ":/MaterialDialog/ToolBar/images/materialdialog_remove_disabled.png" }, QIcon::Disabled); - m_removeAction = m_toolbar->addAction(removeIcon, tr("Remove Item"), this, SLOT(OnDeleteItem())); - m_toolbar->addSeparator(); - QIcon copyIcon; - copyIcon.addPixmap(QPixmap{ ":/MaterialDialog/ToolBar/images/materialdialog_copy_normal.png" }, QIcon::Normal); - copyIcon.addPixmap(QPixmap{ ":/MaterialDialog/ToolBar/images/materialdialog_copy_active.png" }, QIcon::Active); - copyIcon.addPixmap(QPixmap{ ":/MaterialDialog/ToolBar/images/materialdialog_copy_disabled.png" }, QIcon::Disabled); - m_copyAction = m_toolbar->addAction(copyIcon, tr("Copy Material"), this, SLOT(OnCopy())); - QIcon pasteIcon; - pasteIcon.addPixmap(QPixmap{ ":/MaterialDialog/ToolBar/images/materialdialog_paste_normal.png" }, QIcon::Normal); - pasteIcon.addPixmap(QPixmap{ ":/MaterialDialog/ToolBar/images/materialdialog_paste_active.png" }, QIcon::Active); - pasteIcon.addPixmap(QPixmap{ ":/MaterialDialog/ToolBar/images/materialdialog_paste_disabled.png" }, QIcon::Disabled); - m_pasteAction = m_toolbar->addAction(pasteIcon, tr("Paste Material"), this, SLOT(OnPaste())); - m_toolbar->addSeparator(); - QIcon previewIcon; - previewIcon.addPixmap(QPixmap{ ":/MaterialDialog/ToolBar/images/materialdialog_preview_normal.png" }, QIcon::Normal); - previewIcon.addPixmap(QPixmap{ ":/MaterialDialog/ToolBar/images/materialdialog_preview_active.png" }, QIcon::Active); - previewIcon.addPixmap(QPixmap{ ":/MaterialDialog/ToolBar/images/materialdialog_preview_disabled.png" }, QIcon::Disabled); - m_previewAction = m_toolbar->addAction(previewIcon, tr("Open Large Material Preview Window"), this, SLOT(OnMaterialPreview())); - m_toolbar->addSeparator(); - QIcon resetViewportIcon; - resetViewportIcon.addPixmap(QPixmap{ ":/MaterialDialog/ToolBar/images/materialdialog_reset_viewport_normal.png" }, QIcon::Normal); - resetViewportIcon.addPixmap(QPixmap{ ":/MaterialDialog/ToolBar/images/materialdialog_reset_viewport_active.png" }, QIcon::Active); - resetViewportIcon.addPixmap(QPixmap{ ":/MaterialDialog/ToolBar/images/materialdialog_reset_viewport_disabled.png" }, QIcon::Disabled); - m_resetViewporAction = m_toolbar->addAction(resetViewportIcon, tr("Reset Material Viewport"), this, SLOT(OnResetMaterialViewport())); - - UpdateActions(); - setContextMenuPolicy(Qt::ContextMenuPolicy::NoContextMenu); - - connect(m_toolbar, &QToolBar::orientationChanged, m_toolbar, [=](Qt::Orientation orientation) - { - if (orientation == Qt::Vertical) - { - m_toolbar->removeAction(cbAction); - } - else - { - m_toolbar->insertAction(sepAction, cbAction); - } - }); -} - -////////////////////////////////////////////////////////////////////////// -void CMaterialDialog::ReloadItems() -{ - UpdateActions(); -} - -////////////////////////////////////////////////////////////////////////// -void CMaterialDialog::OnAddItem() -{ - m_wndMtlBrowser->OnAddNewMaterial(); - UpdateActions(); -} - -////////////////////////////////////////////////////////////////////////// -void CMaterialDialog::OnSaveItem() -{ - CMaterial* pMtl = GetSelectedMaterial(); - if (pMtl) - { - CMaterial* parent = pMtl->GetParent(); - - if (!pMtl->Save(false)) - { - if (!parent) - { - QMessageBox::warning(this, QString(), tr("The material file cannot be saved. The file is located in a PAK archive or access is denied")); - } - } - - if (parent) - { - //The reload function will clear all the sub-material references, and re-create them. - //Thus pMtl will point to old sub-material that should be deleted instead. - //So we need to set m_pMatManager's current material to the new one. - int index = -1; - - //Find the corresponding sub-material and record its index - for (int i = 0; i < parent->GetSubMaterialCount(); i++) - { - if (parent->GetSubMaterial(i) == pMtl) - { - index = i; - break; - } - } - pMtl->Reload(); - - if (index >= 0 && index < parent->GetSubMaterialCount()) - { - m_pMatManager->SetCurrentMaterial(parent->GetSubMaterial(index)); - } - else //If we can't find the sub-material, use parent instead - { - m_pMatManager->SetCurrentMaterial(parent); - } - } - else - { - pMtl->Reload(); - } - - } - UpdateActions(); -} - -////////////////////////////////////////////////////////////////////////// -void CMaterialDialog::OnDeleteItem() -{ - m_wndMtlBrowser->DeleteItem(); - UpdateActions(); -} - -////////////////////////////////////////////////////////////////////////// -void CMaterialDialog::SetMaterialVars([[maybe_unused]] CMaterial* mtl) -{ -} - - -////////////////////////////////////////////////////////////////////////// -void CMaterialDialog::UpdateShaderParamsUI(CMaterial* pMtl) -{ - ////////////////////////////////////////////////////////////////////////// - // Shader Gen Mask. - ////////////////////////////////////////////////////////////////////////// - IVariable* shaderGenParamsContainerVar = m_pMaterialUI->tableShaderGenParams.GetVar(); - if (m_propsCtrl->FindVariable(shaderGenParamsContainerVar)) - { - m_shaderGenParamsVars = pMtl->GetShaderGenParamsVars(); - m_propsCtrl->ReplaceVarBlock(shaderGenParamsContainerVar, m_shaderGenParamsVars); - } - - ////////////////////////////////////////////////////////////////////////// - // Shader Public Params. - ////////////////////////////////////////////////////////////////////////// - IVariable* publicVars = m_pMaterialUI->tableShaderParams.GetVar(); - if (m_propsCtrl->FindVariable(publicVars)) - { - bool bNeedUpdateMaterialFromUI = false; - CVarBlockPtr pPublicVars = pMtl->GetPublicVars(pMtl->GetShaderResources()); - if (m_publicVars && pPublicVars) - { - // list of shader parameters depends on list of shader generation parameters - // we need to keep values of vars which not presented in every combinations, - // but probably adjusted by user, to keep his work. - // m_excludedPublicVars is used for these values - if (m_excludedPublicVars.pMaterial) - { - if (m_excludedPublicVars.pMaterial != pMtl) - { - m_excludedPublicVars.vars.DeleteAllVariables(); - } - else - { - // find new presented vars in pPublicVars, which not existed in old m_publicVars - for (int j = pPublicVars->GetNumVariables() - 1; j >= 0; --j) - { - IVariable* pVar = pPublicVars->GetVariable(j); - bool isVarExist = false; - for (int i = m_publicVars->GetNumVariables() - 1; i >= 0; --i) - { - IVariable* pOldVar = m_publicVars->GetVariable(i); - if (!QString::compare(pOldVar->GetName(), pVar->GetName())) - { - isVarExist = true; - break; - } - } - if (!isVarExist) // var exist in new pPublicVars block, but not in previous (m_publicVars) - { - // try to find value for this var inside "excluded vars" collection - for (int i = m_excludedPublicVars.vars.GetNumVariables() - 1; i >= 0; --i) - { - IVariable* pStoredVar = m_excludedPublicVars.vars.GetVariable(i); - if (!QString::compare(pStoredVar->GetName(), pVar->GetName()) && pVar->GetDataType() == pStoredVar->GetDataType()) - { - pVar->CopyValue(pStoredVar); - m_excludedPublicVars.vars.DeleteVariable(pStoredVar); - bNeedUpdateMaterialFromUI = true; - break; - } - } - } - } - } - } - // We only want to collect vars if the old and new block are part of the same - // material, otherwise we are storing state from one material to an other. - if (m_excludedPublicVars.pMaterial == pMtl) - { - // collect excluded vars from old block (m_publicVars) - // which exist in m_publicVars but not in a new generated pPublicVars block - for (int i = m_publicVars->GetNumVariables() - 1; i >= 0; --i) - { - IVariable* pOldVar = m_publicVars->GetVariable(i); - bool isVarExist = false; - for (int j = pPublicVars->GetNumVariables() - 1; j >= 0; --j) - { - IVariable* pVar = pPublicVars->GetVariable(j); - if (!QString::compare(pOldVar->GetName(), pVar->GetName())) - { - isVarExist = true; - break; - } - } - if (!isVarExist) - { - m_excludedPublicVars.vars.AddVariable(pOldVar->Clone(false)); - } - } - } - m_excludedPublicVars.pMaterial = pMtl; - } - - m_publicVars = pPublicVars; - if (m_publicVars) - { - m_publicVars->Sort(); - } - - m_propsCtrl->ReplaceVarBlock(publicVars, m_publicVars); - - if (m_publicVars && bNeedUpdateMaterialFromUI) - { - pMtl->SetPublicVars(m_publicVars, pMtl); - } - } - IVariable* textureSlotsVar = m_pMaterialUI->tableTexture.GetVar(); - if (m_propsCtrl->FindVariable(textureSlotsVar)) - { - m_textureSlots = pMtl->UpdateTextureNames(m_pMaterialUI->textureVars); - m_propsCtrl->ReplaceVarBlock(textureSlotsVar, m_textureSlots); - } - - ////////////////////////////////////////////////////////////////////////// -} - -////////////////////////////////////////////////////////////////////////// -void CMaterialDialog::SelectItem(CBaseLibraryItem* item, bool bForceReload) -{ - static bool bNoRecursiveSelect = false; - if (bNoRecursiveSelect) - { - return; - } - - bool bChanged = item != m_pPrevSelectedItem || bForceReload; - - if (!bChanged) - { - return; - } - - m_pPrevSelectedItem = item; - - // Empty preview control. - //m_previewCtrl.SetEntity(0); - m_pMatManager->SetCurrentMaterial((CMaterial*)item); - - if (!item) - { - m_statusBar->clearMessage(); - m_propsCtrl->setEnabled(false); - m_propsCtrl->hide(); - m_pMaterialImageListCtrl->hide(); - m_placeHolderLabel->setText(tr("Select a material in the Material Editor hierarchy to view properties")); - m_placeHolderLabel->show(); - return; - } - - // Render preview geometry with current material - CMaterial* mtl = (CMaterial*)item; - - QString statusText; - if (mtl->IsPureChild() && mtl->GetParent()) - { - statusText = mtl->GetParent()->GetName() + " [" + mtl->GetName() + "]"; - } - else - { - statusText = mtl->GetName(); - } - - - if (mtl->IsDummy()) - { - statusText += " (Not Found)"; - } - else if (!mtl->CanModify()) - { - statusText += " (Read Only)"; - } - m_statusBar->showMessage(statusText); - - if (mtl->IsMultiSubMaterial()) - { - // Cannot edit it. - m_propsCtrl->setEnabled(false); - m_propsCtrl->EnableUpdateCallback(false); - m_propsCtrl->hide(); - - m_placeHolderLabel->setText(tr("Select a material to view properties")); - m_placeHolderLabel->show(); - - //return; - } - else - { - m_propsCtrl->setEnabled(true); - m_propsCtrl->EnableUpdateCallback(false); - m_propsCtrl->show(); - m_placeHolderLabel->hide(); - } - m_pMaterialImageListCtrl->show(); - - if (m_bForceReloadPropsCtrl) - { - // CPropertyCtrlEx skip OnPaint and another methods for redraw - // OnSize method is forced to invalidate control for redraw - m_propsCtrl->InvalidateCtrl(); - m_bForceReloadPropsCtrl = false; - } - - UpdatePreview(); - - // Update variables. - m_propsCtrl->EnableUpdateCallback(false); - m_pMaterialUI->SetFromMaterial(mtl); - m_propsCtrl->EnableUpdateCallback(true); - - mtl->SetShaderParamPublicScript(); - - ////////////////////////////////////////////////////////////////////////// - - ////////////////////////////////////////////////////////////////////////// - // Set Shader Gen Params. - ////////////////////////////////////////////////////////////////////////// - UpdateShaderParamsUI(mtl); - ////////////////////////////////////////////////////////////////////////// - - m_propsCtrl->SetUpdateCallback(AZStd::bind(&CMaterialDialog::OnUpdateProperties, this, AZStd::placeholders::_1)); - m_propsCtrl->EnableUpdateCallback(true); - - if (mtl->IsDummy()) - { - m_propsCtrl->setEnabled(false); - } - else - { - m_propsCtrl->setEnabled(true); - m_propsCtrl->SetGrayed(!mtl->CanModify()); - } - if (mtl) - { - m_pMaterialImageListCtrl->SelectMaterial(mtl); - } -} - -////////////////////////////////////////////////////////////////////////// -void CMaterialDialog::OnUpdateProperties(IVariable* var) -{ - CMaterial* mtl = GetSelectedMaterial(); - if (!mtl) - { - return; - } - - bool bShaderChanged = (m_pMaterialUI->shader == var); - bool bShaderGenMaskChanged = false; - if (m_shaderGenParamsVars) - { - bShaderGenMaskChanged = m_shaderGenParamsVars->IsContainsVariable(var); - } - - bool bMtlLayersChanged = false; - int nCurrLayer = -1; - - // Check for shader changes - for (int l(0); l < MTL_LAYER_MAX_SLOTS; ++l) - { - if ((m_pMaterialUI->materialLayers[l].shader == var)) - { - bMtlLayersChanged = true; - nCurrLayer = l; - break; - } - } - - ////////////////////////////////////////////////////////////////////////// - // Assign modified Shader Gen Params to shader. - ////////////////////////////////////////////////////////////////////////// - if (bShaderGenMaskChanged) - { - mtl->SetShaderGenParamsVars(m_shaderGenParamsVars); - } - ////////////////////////////////////////////////////////////////////////// - // Invalidate material and save changes. - //m_pMatManager->MarkMaterialAsModified(mtl); - // - - mtl->RecordUndo("Material parameter", true); - m_pMaterialUI->SetToMaterial(mtl); - mtl->Update(); - - // - ////////////////////////////////////////////////////////////////////////// - // Assign new public vars to material. - // Must be after material update. - ////////////////////////////////////////////////////////////////////////// - - GetIEditor()->SuspendUndo(); - - if (m_publicVars != NULL && !bShaderChanged) - { - mtl->SetPublicVars(m_publicVars, mtl); - } - - /* - bool bUpdateLayers = false; - for(int l(0); l < MTL_LAYER_MAX_SLOTS; ++l) - { - if ( m_varsMtlLayersShaderParams[l] != NULL && l != nCurrLayer) - { - SMaterialLayerResources *pCurrResource = pTemplateMtl ? &pTemplateMtl->GetMtlLayerResources()[l] : &pMtlLayerResources[l]; - SShaderItem &pCurrShaderItem = pCurrResource->m_pMatLayer->GetShaderItem(); - CVarBlock* pVarBlock = pTemplateMtl ? pTemplateMtl->GetPublicVars( pCurrResource->m_shaderResources ) : m_varsMtlLayersShaderParams[l]; - mtl->SetPublicVars( pVarBlock, pCurrResource->m_shaderResources, pCurrShaderItem.m_pShaderResources, pCurrShaderItem.m_pShader); - bUpdateLayers = true; - } - } - */ - //if( bUpdateLayers ) - { - mtl->UpdateMaterialLayers(); - } - - m_pMaterialUI->PropagateToLinkedMaterial(mtl, m_shaderGenParamsVars); - if (var) - { - GetIEditor()->GetMaterialManager()->HighlightedMaterialChanged(mtl); - m_pMaterialUI->NotifyObjectsAboutMaterialChange(var); - } - - GetIEditor()->ResumeUndo(); - - ////////////////////////////////////////////////////////////////////////// - - ////////////////////////////////////////////////////////////////////////// - if (bShaderChanged || bShaderGenMaskChanged || bMtlLayersChanged) - { - m_pMaterialUI->SetFromMaterial(mtl); - } - //m_pMaterialUI->SetTextureNames( mtl ); - - UpdatePreview(); - - // When shader changed. - if (bShaderChanged || bShaderGenMaskChanged || bMtlLayersChanged) - { - ////////////////////////////////////////////////////////////////////////// - // Set material layers params - ////////////////////////////////////////////////////////////////////////// - /* - if( bMtlLayersChanged) // only update changed shader in material layers - { - SMaterialLayerResources *pCurrResource = &pMtlLayerResources[nCurrLayer]; - - // delete old property item - if ( m_varsMtlLayersShaderParamsItems[nCurrLayer] ) - { - m_propsCtrl->DeleteItem( m_varsMtlLayersShaderParamsItems[nCurrLayer] ); - m_varsMtlLayersShaderParamsItems[nCurrLayer] = 0; - } - - m_varsMtlLayersShaderParams[nCurrLayer] = mtl->GetPublicVars( pCurrResource->m_shaderResources ); - - if ( m_varsMtlLayersShaderParams[nCurrLayer] ) - { - m_varsMtlLayersShaderParamsItems[nCurrLayer] = m_propsCtrl->AddVarBlockAt( m_varsMtlLayersShaderParams[nCurrLayer], "Shader Params", m_varsMtlLayersShaderItems[nCurrLayer] ); - } - } - */ - - UpdateShaderParamsUI(mtl); - } - - if (bShaderGenMaskChanged || bShaderChanged || bMtlLayersChanged) - { - m_propsCtrl->InvalidateCtrl(); - } - - m_pMaterialImageListModel->InvalidateMaterial(mtl); -} - -////////////////////////////////////////////////////////////////////////// -CMaterial* CMaterialDialog::GetSelectedMaterial() -{ - CBaseLibraryItem* pItem = m_pMatManager->GetCurrentMaterial(); - return (CMaterial*)pItem; -} - -////////////////////////////////////////////////////////////////////////// -void CMaterialDialog::OnAssignMaterialToSelection() -{ - CUndo undo("Assign Material To Selection"); - GetIEditor()->GetMaterialManager()->Command_AssignToSelection(); - UpdateActions(); -} - -////////////////////////////////////////////////////////////////////////// -void CMaterialDialog::OnSelectAssignedObjects() -{ - CUndo undo("Select Objects With Current Material"); - GetIEditor()->GetMaterialManager()->Command_SelectAssignedObjects(); - UpdateActions(); -} - -////////////////////////////////////////////////////////////////////////// -void CMaterialDialog::OnResetMaterialOnSelection() -{ - GetIEditor()->GetMaterialManager()->Command_ResetSelection(); - UpdateActions(); -} - -////////////////////////////////////////////////////////////////////////// -void CMaterialDialog::OnGetMaterialFromSelection() -{ - GetIEditor()->GetMaterialManager()->Command_SelectFromObject(); - UpdateActions(); -} - -////////////////////////////////////////////////////////////////////////// -void CMaterialDialog::DeleteItem([[maybe_unused]] CBaseLibraryItem* pItem) -{ - m_wndMtlBrowser->DeleteItem(); - UpdateActions(); -} - -////////////////////////////////////////////////////////////////////////// - -void CMaterialDialog::UpdateActions() -{ - if (isHidden()) - { - return; - } - - CMaterial* mtl = GetSelectedMaterial(); - if (mtl && mtl->CanModify(false)) - { - m_saveAction->setEnabled(true); - } - else - { - m_saveAction->setEnabled(false); - } - - if (GetIEditor()->GetEditTool() && GetIEditor()->GetEditTool()->GetClassDesc() && QString::compare(GetIEditor()->GetEditTool()->GetClassDesc()->ClassName(), "EditTool.PickMaterial") == 0) - { - m_pickAction->setChecked(true); - } - else - { - m_pickAction->setChecked(false); - } - - if (mtl && (!GetIEditor()->GetSelection()->IsEmpty() || GetIEditor()->IsInPreviewMode())) - { - m_assignToSelectionAction->setEnabled(true); - } - else - { - m_assignToSelectionAction->setEnabled(false); - } - - if (!GetIEditor()->GetSelection()->IsEmpty() || GetIEditor()->IsInPreviewMode()) - { - m_resetAction->setEnabled(true); - m_getFromSelectionAction->setEnabled(true); - } - else - { - m_resetAction->setEnabled(false); - m_getFromSelectionAction->setEnabled(false); - } -} - -////////////////////////////////////////////////////////////////////////// -void CMaterialDialog::OnPickMtl() -{ - if (GetIEditor()->GetEditTool() && QString::compare(GetIEditor()->GetEditTool()->GetClassDesc()->ClassName(), "EditTool.PickMaterial") == 0) - { - GetIEditor()->SetEditTool(NULL); - } - else - { - GetIEditor()->SetEditTool("EditTool.PickMaterial"); - } - UpdateActions(); -} - -////////////////////////////////////////////////////////////////////////// -void CMaterialDialog::OnCopy() -{ - m_wndMtlBrowser->OnCopy(); -} - -////////////////////////////////////////////////////////////////////////// -void CMaterialDialog::OnPaste() -{ - m_wndMtlBrowser->OnPaste(); -} - -////////////////////////////////////////////////////////////////////////// -void CMaterialDialog::OnMaterialPreview() -{ - if (!m_pPreviewDlg) - { - m_pPreviewDlg = new CMatEditPreviewDlg(this); - m_pPreviewDlg->show(); - } -} - -////////////////////////////////////////////////////////////////////////// -bool CMaterialDialog::SetItemName(CBaseLibraryItem* item, const QString& groupName, const QString& itemName) -{ - assert(item); - // Make prototype name. - QString fullName = groupName + "/" + itemName; - IDataBaseItem* pOtherItem = m_pMatManager->FindItemByName(fullName); - if (pOtherItem && pOtherItem != item) - { - // Ensure uniqness of name. - Warning("Duplicate Item Name %s", fullName.toUtf8().data()); - return false; - } - else - { - item->SetName(fullName); - } - return true; -} - - -////////////////////////////////////////////////////////////////////////// -void CMaterialDialog::OnBrowserSelectItem(IDataBaseItem* pItem, bool bForce) -{ - SelectItem((CBaseLibraryItem*)pItem, bForce); - UpdateActions(); -} - -////////////////////////////////////////////////////////////////////////// -void CMaterialDialog::UpdatePreview() -{ -}; - -////////////////////////////////////////////////////////////////////////// -void CMaterialDialog::OnChangedBrowserListType(int sel) -{ - m_wndMtlBrowser->ShowOnlyLevelMaterials(sel == 1); - m_pMatManager->SetCurrentMaterial(0); - UpdateActions(); -} - -////////////////////////////////////////////////////////////////////////// -void CMaterialDialog::OnUndo(IVariable* pVar) -{ - if (!m_pMatManager->GetCurrentMaterial()) - { - return; - } - - QString undoName; - if (pVar) - { - undoName = tr("%1 modified").arg(pVar->GetName()); - } - else - { - undoName = tr("Material parameter was modified"); - } - - if (!CUndo::IsRecording()) - { - if (!CUndo::IsSuspended()) - { - CUndo undo(undoName.toUtf8().data()); - m_pMatManager->GetCurrentMaterial()->RecordUndo(undoName.toUtf8().data(), true); - } - } - UpdateActions(); -} - -////////////////////////////////////////////////////////////////////////// -void CMaterialDialog::OnDataBaseItemEvent(IDataBaseItem* pItem, EDataBaseItemEvent event) -{ - switch (event) - { - case EDB_ITEM_EVENT_UPDATE_PROPERTIES: - if (pItem && pItem == m_pMatManager->GetCurrentMaterial()) - { - SelectItem(m_pMatManager->GetCurrentMaterial(), true); - } - break; - } -} - -// If an object is selected or de-selected, update the available actions in the Material Editor toolbar -void CMaterialDialog::OnEditorNotifyEvent(EEditorNotifyEvent event) -{ - switch (event) - { - case eNotify_OnSelectionChange: - UpdateActions(); - break; - case eNotify_OnCloseScene: - case eNotify_OnEndNewScene: - case eNotify_OnEndSceneOpen: - m_filterTypeSelection->setCurrentIndex(0); - break; - } -} - -void CMaterialDialog::OnResetMaterialViewport() -{ - m_pMaterialImageListCtrl->LoadModel(); -} - -#include diff --git a/Code/Sandbox/Editor/Material/MaterialDialog.h b/Code/Sandbox/Editor/Material/MaterialDialog.h deleted file mode 100644 index 48e68e2322..0000000000 --- a/Code/Sandbox/Editor/Material/MaterialDialog.h +++ /dev/null @@ -1,176 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#pragma once - -#if !defined(Q_MOC_RUN) -#include "MaterialBrowser.h" - -#include -#include -#include -#endif - -static const char* MATERIAL_EDITOR_NAME = "Material Editor"; -static const char* MATERIAL_EDITOR_VER = "1.00"; - - -class QComboBox; -class QLabel; - -class CMaterial; -class CMaterialManager; -class CMatEditPreviewDlg; -class CMaterialSender; -class CMaterialImageListCtrl; -class QMaterialImageListModel; -class TwoColumnPropertyControl; - -/** Dialog which hosts entity prototype library. -*/ - - -struct SMaterialExcludedVars -{ - CMaterial* pMaterial; - CVarBlock vars; - - SMaterialExcludedVars() - : pMaterial(nullptr) - { - } -}; - - -class CMaterialDialog - : public QMainWindow - , public IMaterialBrowserListener - , public IDataBaseManagerListener - , public IEditorNotifyListener -{ - Q_OBJECT -public: - CMaterialDialog(QWidget* parent = 0); - ~CMaterialDialog(); - - static void RegisterViewClass(); - static const GUID& GetClassID(); - -public slots: - void OnAssignMaterialToSelection(); - void OnResetMaterialOnSelection(); - void OnGetMaterialFromSelection(); - -protected: - BOOL OnInitDialog(); - void closeEvent(QCloseEvent *ev) override; - -protected slots: - void OnAddItem(); - void OnDeleteItem(); - void OnSaveItem(); - void OnPickMtl(); - void OnCopy(); - void OnPaste(); - void OnMaterialPreview(); - void OnSelectAssignedObjects(); - void OnChangedBrowserListType(int); - void OnResetMaterialViewport(); - - void UpdateActions(); - -protected: - ////////////////////////////////////////////////////////////////////////// - // Some functions can be overriden to modify standart functionality. - ////////////////////////////////////////////////////////////////////////// - virtual void InitToolbar(UINT nToolbarResID); - - virtual void SelectItem(CBaseLibraryItem* item, bool bForceReload = false); - virtual void DeleteItem(CBaseLibraryItem* pItem); - virtual bool SetItemName(CBaseLibraryItem* item, const QString& groupName, const QString& itemName); - virtual void ReloadItems(); - - ////////////////////////////////////////////////////////////////////////// - // IMaterialBrowserListener implementation. - ////////////////////////////////////////////////////////////////////////// - virtual void OnBrowserSelectItem(IDataBaseItem* pItem, bool bForce); - ////////////////////////////////////////////////////////////////////////// - - ////////////////////////////////////////////////////////////////////////// - // IDataBaseManagerListener implementation. - ////////////////////////////////////////////////////////////////////////// - virtual void OnDataBaseItemEvent(IDataBaseItem* pItem, EDataBaseItemEvent event); - ////////////////////////////////////////////////////////////////////////// - - // IEditorNotifyListener implementation. - virtual void OnEditorNotifyEvent(EEditorNotifyEvent event); - - ////////////////////////////////////////////////////////////////////////// - CMaterial* GetSelectedMaterial(); - void OnUpdateProperties(IVariable* var); - void OnUndo(IVariable* pVar); - - void UpdateShaderParamsUI(CMaterial* pMtl); - - void UpdatePreview(); - - //void SetTextureVars( CVariableArray *texVar,CMaterial *mtl,int id,const CString &name ); - void SetMaterialVars(CMaterial* mtl); - - MaterialBrowserWidget* m_wndMtlBrowser; - - QStatusBar* m_statusBar; - //CXTCaption m_wndCaption; - - TwoColumnPropertyControl* m_propsCtrl; - bool m_bForceReloadPropsCtrl; - - QLabel* m_placeHolderLabel; - - CBaseLibraryItem* m_pPrevSelectedItem; - - // Material manager. - CMaterialManager* m_pMatManager; - - CVarBlockPtr m_vars; - CVarBlockPtr m_publicVars; - - // collection of excluded vars from m_publicVars for remembering values - // when updating shader params - SMaterialExcludedVars m_excludedPublicVars; - - CVarBlockPtr m_shaderGenParamsVars; - CVarBlockPtr m_textureSlots; - - class CMaterialUI* m_pMaterialUI; - - QPointer m_pPreviewDlg; - - QScopedPointer m_pMaterialImageListCtrl; - QScopedPointer m_pMaterialImageListModel; - - QToolBar* m_toolbar; - QComboBox* m_filterTypeSelection; - QAction* m_addAction; - QAction* m_assignToSelectionAction; - QAction* m_copyAction; - QAction* m_getFromSelectionAction; - QAction* m_pasteAction; - QAction* m_pickAction; - QAction* m_previewAction; - QAction* m_removeAction; - QAction* m_resetAction; - QAction* m_saveAction; - QAction* m_resetViewporAction; -}; - diff --git a/Code/Sandbox/Editor/Material/MaterialDialog.qrc b/Code/Sandbox/Editor/Material/MaterialDialog.qrc index 43bfbd6ea0..c99e5b052a 100644 --- a/Code/Sandbox/Editor/Material/MaterialDialog.qrc +++ b/Code/Sandbox/Editor/Material/MaterialDialog.qrc @@ -1,39 +1,4 @@ - - images/materialdialog_add_disabled.png - images/materialdialog_copy_disabled.png - images/materialdialog_paste_disabled.png - images/materialdialog_preview_disabled.png - images/materialdialog_remove_disabled.png - images/materialdialog_save_disabled.png - images/materialdialog_assignselection_disabled.png - images/materialdialog_getfromselection_disabled.png - images/materialdialog_pick_disabled.png - images/materialdialog_reset_disabled.png - images/materialdialog_assignselection_active.png - images/materialdialog_assignselection_normal.png - images/materialdialog_add_active.png - images/materialdialog_add_normal.png - images/materialdialog_copy_active.png - images/materialdialog_copy_normal.png - images/materialdialog_getfromselection_active.png - images/materialdialog_getfromselection_normal.png - images/materialdialog_paste_active.png - images/materialdialog_paste_normal.png - images/materialdialog_pick_active.png - images/materialdialog_pick_normal.png - images/materialdialog_preview_active.png - images/materialdialog_preview_normal.png - images/materialdialog_remove_active.png - images/materialdialog_remove_normal.png - images/materialdialog_reset_active.png - images/materialdialog_reset_normal.png - images/materialdialog_save_active.png - images/materialdialog_save_normal.png - images/materialdialog_reset_viewport_active.png - images/materialdialog_reset_viewport_disabled.png - images/materialdialog_reset_viewport_normal.png - images/material_browser_00.png images/material_browser_01.png diff --git a/Code/Sandbox/Editor/Material/images/materialdialog_add.png b/Code/Sandbox/Editor/Material/images/materialdialog_add.png deleted file mode 100644 index aa8d657f23..0000000000 --- a/Code/Sandbox/Editor/Material/images/materialdialog_add.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:703f6875258486629bc1db68ce80fe1653f0d2876cd1252d03f72f6eae04dd84 -size 392 diff --git a/Code/Sandbox/Editor/Material/images/materialdialog_add_active.png b/Code/Sandbox/Editor/Material/images/materialdialog_add_active.png deleted file mode 100644 index 467365d1ad..0000000000 --- a/Code/Sandbox/Editor/Material/images/materialdialog_add_active.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:3f3c05f8425956e9c1e380fde9a65df8f0d341868900a3589d9f629f34a0ddf6 -size 251 diff --git a/Code/Sandbox/Editor/Material/images/materialdialog_add_disabled.png b/Code/Sandbox/Editor/Material/images/materialdialog_add_disabled.png deleted file mode 100644 index 399e45469e..0000000000 --- a/Code/Sandbox/Editor/Material/images/materialdialog_add_disabled.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:25554e93a4f0d9b904a2a3628c315ee55c0ad8831bb5891a9d7e27e5cb9a5416 -size 261 diff --git a/Code/Sandbox/Editor/Material/images/materialdialog_add_normal.png b/Code/Sandbox/Editor/Material/images/materialdialog_add_normal.png deleted file mode 100644 index 1eb8d63ef5..0000000000 --- a/Code/Sandbox/Editor/Material/images/materialdialog_add_normal.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:b2ee886c6e487a6490361609fdd44c64438e40c7e5a4c40fda866ec399ec4727 -size 256 diff --git a/Code/Sandbox/Editor/Material/images/materialdialog_assignselection.png b/Code/Sandbox/Editor/Material/images/materialdialog_assignselection.png deleted file mode 100644 index 72fdb0537a..0000000000 --- a/Code/Sandbox/Editor/Material/images/materialdialog_assignselection.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:943ff19774cbe8d47c1e8001a48e6d137fdac2c0af63c9092911c37be0d6d6a8 -size 471 diff --git a/Code/Sandbox/Editor/Material/images/materialdialog_assignselection_active.png b/Code/Sandbox/Editor/Material/images/materialdialog_assignselection_active.png deleted file mode 100644 index 605107f750..0000000000 --- a/Code/Sandbox/Editor/Material/images/materialdialog_assignselection_active.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:400d669d7a658968549f6ee776ee415b871b207c444d8797a404b76d536131b1 -size 325 diff --git a/Code/Sandbox/Editor/Material/images/materialdialog_assignselection_disabled.png b/Code/Sandbox/Editor/Material/images/materialdialog_assignselection_disabled.png deleted file mode 100644 index 3505f577a4..0000000000 --- a/Code/Sandbox/Editor/Material/images/materialdialog_assignselection_disabled.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:02bdc8aad92bb75b118c4a703a3e5b1369376620b3836a125faedc7f6b42b49b -size 330 diff --git a/Code/Sandbox/Editor/Material/images/materialdialog_assignselection_normal.png b/Code/Sandbox/Editor/Material/images/materialdialog_assignselection_normal.png deleted file mode 100644 index 0e9c984e1d..0000000000 --- a/Code/Sandbox/Editor/Material/images/materialdialog_assignselection_normal.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:38097d3041defeec0179390a73bb463e54e7f4c1f0b1a20e77ab3f69ea9cf13c -size 332 diff --git a/Code/Sandbox/Editor/Material/images/materialdialog_copy.png b/Code/Sandbox/Editor/Material/images/materialdialog_copy.png deleted file mode 100644 index 08fc0c6987..0000000000 --- a/Code/Sandbox/Editor/Material/images/materialdialog_copy.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:e1d9fe8e97655bf776b20e242d66900980721ba2f3ee93c02cd4062a8b872eed -size 433 diff --git a/Code/Sandbox/Editor/Material/images/materialdialog_copy_active.png b/Code/Sandbox/Editor/Material/images/materialdialog_copy_active.png deleted file mode 100644 index 67a010be86..0000000000 --- a/Code/Sandbox/Editor/Material/images/materialdialog_copy_active.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:468b68c44d8ef183b292c1bc6ca4dc583357f693db9ea2cd198fb2af22537be1 -size 249 diff --git a/Code/Sandbox/Editor/Material/images/materialdialog_copy_disabled.png b/Code/Sandbox/Editor/Material/images/materialdialog_copy_disabled.png deleted file mode 100644 index d585dbae6e..0000000000 --- a/Code/Sandbox/Editor/Material/images/materialdialog_copy_disabled.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:b27a1346f2edebe34ee06d7892a467bfc67952d0f8e4458e09a74a6dbf62fe98 -size 336 diff --git a/Code/Sandbox/Editor/Material/images/materialdialog_copy_normal.png b/Code/Sandbox/Editor/Material/images/materialdialog_copy_normal.png deleted file mode 100644 index 4b42f5c9a2..0000000000 --- a/Code/Sandbox/Editor/Material/images/materialdialog_copy_normal.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:c3f40524a96689b8c8549bc662415df654494baeeda6eed47e66b455ac902eeb -size 254 diff --git a/Code/Sandbox/Editor/Material/images/materialdialog_getfromselection.png b/Code/Sandbox/Editor/Material/images/materialdialog_getfromselection.png deleted file mode 100644 index 76c343a718..0000000000 --- a/Code/Sandbox/Editor/Material/images/materialdialog_getfromselection.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:cebe97de0d879d239fcd61595fd28b73760aa6452dcf4dabc54bfe034e2e33c1 -size 476 diff --git a/Code/Sandbox/Editor/Material/images/materialdialog_getfromselection_active.png b/Code/Sandbox/Editor/Material/images/materialdialog_getfromselection_active.png deleted file mode 100644 index cc58f4f767..0000000000 --- a/Code/Sandbox/Editor/Material/images/materialdialog_getfromselection_active.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:699ee40aeedfc50b7766e94ef66e645762eb183ddd6ce134b4bdab01c3957ab9 -size 327 diff --git a/Code/Sandbox/Editor/Material/images/materialdialog_getfromselection_disabled.png b/Code/Sandbox/Editor/Material/images/materialdialog_getfromselection_disabled.png deleted file mode 100644 index 6e4a425058..0000000000 --- a/Code/Sandbox/Editor/Material/images/materialdialog_getfromselection_disabled.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:5f1fd8a7cecb22901c6d73f2e6129f3bada0f94cf73d9a8fd2676a972faa5719 -size 348 diff --git a/Code/Sandbox/Editor/Material/images/materialdialog_getfromselection_normal.png b/Code/Sandbox/Editor/Material/images/materialdialog_getfromselection_normal.png deleted file mode 100644 index 1c319c319d..0000000000 --- a/Code/Sandbox/Editor/Material/images/materialdialog_getfromselection_normal.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:d432de9e921d23fbbf3c1b805f644b9554aa206011a87c063d167c30c7c4579e -size 335 diff --git a/Code/Sandbox/Editor/Material/images/materialdialog_paste.png b/Code/Sandbox/Editor/Material/images/materialdialog_paste.png deleted file mode 100644 index 95740d44d8..0000000000 --- a/Code/Sandbox/Editor/Material/images/materialdialog_paste.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:c006e70efd8bdb1dd5aac867db9d97de587e8d518ba0693d19c319e34a74c7d0 -size 501 diff --git a/Code/Sandbox/Editor/Material/images/materialdialog_paste_active.png b/Code/Sandbox/Editor/Material/images/materialdialog_paste_active.png deleted file mode 100644 index aabb4f2520..0000000000 --- a/Code/Sandbox/Editor/Material/images/materialdialog_paste_active.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:00c291361664d357502f5267fccd0a6fff0c3f2e906c0402d57ad9fa5ca7f023 -size 255 diff --git a/Code/Sandbox/Editor/Material/images/materialdialog_paste_disabled.png b/Code/Sandbox/Editor/Material/images/materialdialog_paste_disabled.png deleted file mode 100644 index 9abc336f71..0000000000 --- a/Code/Sandbox/Editor/Material/images/materialdialog_paste_disabled.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:d68fc8604a23eb3bcc0cac9bb6e83dd4dc4cdab70b0bdaec3c456559727c6b5b -size 354 diff --git a/Code/Sandbox/Editor/Material/images/materialdialog_paste_normal.png b/Code/Sandbox/Editor/Material/images/materialdialog_paste_normal.png deleted file mode 100644 index 158bf9d690..0000000000 --- a/Code/Sandbox/Editor/Material/images/materialdialog_paste_normal.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:4055c7f029d7711e5c32f3f74901bf1dcc1540fd2c0f3f30dc74743d7f2cc042 -size 355 diff --git a/Code/Sandbox/Editor/Material/images/materialdialog_pick.png b/Code/Sandbox/Editor/Material/images/materialdialog_pick.png deleted file mode 100644 index e08b45ac66..0000000000 --- a/Code/Sandbox/Editor/Material/images/materialdialog_pick.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:99e2c0378137bef94eb6f281e0168852540bf1ca823b9bcd4365ef2849db9956 -size 420 diff --git a/Code/Sandbox/Editor/Material/images/materialdialog_pick_active.png b/Code/Sandbox/Editor/Material/images/materialdialog_pick_active.png deleted file mode 100644 index 392b4ab63e..0000000000 --- a/Code/Sandbox/Editor/Material/images/materialdialog_pick_active.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:34075016c93f1914fe4d12ead7c5ee322a18466f08a476eff7c127e4e1429224 -size 290 diff --git a/Code/Sandbox/Editor/Material/images/materialdialog_pick_disabled.png b/Code/Sandbox/Editor/Material/images/materialdialog_pick_disabled.png deleted file mode 100644 index 865a91152d..0000000000 --- a/Code/Sandbox/Editor/Material/images/materialdialog_pick_disabled.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:dc289621f8a9d3e714cd985651d7d6f20495fb7be46e1f60c283d8920c730d0b -size 307 diff --git a/Code/Sandbox/Editor/Material/images/materialdialog_pick_normal.png b/Code/Sandbox/Editor/Material/images/materialdialog_pick_normal.png deleted file mode 100644 index 5c1086b22d..0000000000 --- a/Code/Sandbox/Editor/Material/images/materialdialog_pick_normal.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:7e9d5c878acf9fee4252cb854f192690d3f50d46dc4e5f5b1b5812b79fc2cdf7 -size 296 diff --git a/Code/Sandbox/Editor/Material/images/materialdialog_preview.png b/Code/Sandbox/Editor/Material/images/materialdialog_preview.png deleted file mode 100644 index c7d79780ee..0000000000 --- a/Code/Sandbox/Editor/Material/images/materialdialog_preview.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:e2e912c40f07ca3d2a9b2aa1c5caf3acc181436b6a1b560fc021450701331b4c -size 403 diff --git a/Code/Sandbox/Editor/Material/images/materialdialog_preview_active.png b/Code/Sandbox/Editor/Material/images/materialdialog_preview_active.png deleted file mode 100644 index d2e1d8230d..0000000000 --- a/Code/Sandbox/Editor/Material/images/materialdialog_preview_active.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:00663e473803ba6c2798c494676b0a65fd62d7484f6d7b51d9fc8955ad586477 -size 273 diff --git a/Code/Sandbox/Editor/Material/images/materialdialog_preview_disabled.png b/Code/Sandbox/Editor/Material/images/materialdialog_preview_disabled.png deleted file mode 100644 index 56716582bb..0000000000 --- a/Code/Sandbox/Editor/Material/images/materialdialog_preview_disabled.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:34b7d5520cfc8f00ff580558db4f0ec4297458d310321471204daa8678db5fc1 -size 298 diff --git a/Code/Sandbox/Editor/Material/images/materialdialog_preview_normal.png b/Code/Sandbox/Editor/Material/images/materialdialog_preview_normal.png deleted file mode 100644 index f54cd90c2a..0000000000 --- a/Code/Sandbox/Editor/Material/images/materialdialog_preview_normal.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:7bca1a8811739949aa2e87486f8697dfae5bc5238894dd1b95ae80aa6f80d517 -size 279 diff --git a/Code/Sandbox/Editor/Material/images/materialdialog_remove.png b/Code/Sandbox/Editor/Material/images/materialdialog_remove.png deleted file mode 100644 index d530169b78..0000000000 --- a/Code/Sandbox/Editor/Material/images/materialdialog_remove.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:db86d857b651a2fec80418f8b251447bb3fcf4c0cf64bdee12c3b656adbde29a -size 422 diff --git a/Code/Sandbox/Editor/Material/images/materialdialog_remove_active.png b/Code/Sandbox/Editor/Material/images/materialdialog_remove_active.png deleted file mode 100644 index 78ec0e0806..0000000000 --- a/Code/Sandbox/Editor/Material/images/materialdialog_remove_active.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:fef72444f077879d5c0186c9583f67aa45aafc23214d9e7de90a7c595609270f -size 258 diff --git a/Code/Sandbox/Editor/Material/images/materialdialog_remove_disabled.png b/Code/Sandbox/Editor/Material/images/materialdialog_remove_disabled.png deleted file mode 100644 index a69ef52e75..0000000000 --- a/Code/Sandbox/Editor/Material/images/materialdialog_remove_disabled.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:d2117fda3ed6a28032ae8f03ed7f9a7a0960f4691e49903c63b2150027dfe1ea -size 302 diff --git a/Code/Sandbox/Editor/Material/images/materialdialog_remove_normal.png b/Code/Sandbox/Editor/Material/images/materialdialog_remove_normal.png deleted file mode 100644 index b84a504285..0000000000 --- a/Code/Sandbox/Editor/Material/images/materialdialog_remove_normal.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:06b384ecc11ed2547a9bf466f585889d647c29a4883840070e444a382e80c41c -size 266 diff --git a/Code/Sandbox/Editor/Material/images/materialdialog_reset.png b/Code/Sandbox/Editor/Material/images/materialdialog_reset.png deleted file mode 100644 index e2eedad0bf..0000000000 --- a/Code/Sandbox/Editor/Material/images/materialdialog_reset.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:4b9ee01e7fe2f19b0e736efe09c2b81d3243e369375b4f26346e6abd499e54a6 -size 476 diff --git a/Code/Sandbox/Editor/Material/images/materialdialog_reset_active.png b/Code/Sandbox/Editor/Material/images/materialdialog_reset_active.png deleted file mode 100644 index e86ed4dcb8..0000000000 --- a/Code/Sandbox/Editor/Material/images/materialdialog_reset_active.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:935a041332be1fe11ed01c09a3cd367fb9ede7e7eb04909614943f80e741d35f -size 334 diff --git a/Code/Sandbox/Editor/Material/images/materialdialog_reset_disabled.png b/Code/Sandbox/Editor/Material/images/materialdialog_reset_disabled.png deleted file mode 100644 index 2e4e403a30..0000000000 --- a/Code/Sandbox/Editor/Material/images/materialdialog_reset_disabled.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:2b343233ab25a73fcdb4fff5509011497814fc4cb591065bdb3043a0f1092577 -size 342 diff --git a/Code/Sandbox/Editor/Material/images/materialdialog_reset_normal.png b/Code/Sandbox/Editor/Material/images/materialdialog_reset_normal.png deleted file mode 100644 index 8d8b8a1bd9..0000000000 --- a/Code/Sandbox/Editor/Material/images/materialdialog_reset_normal.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:1cc0183d7f57f15c4efeffb32795921f2f4e9c7965955fd0a392f826d5f6b6c8 -size 337 diff --git a/Code/Sandbox/Editor/Material/images/materialdialog_reset_viewport_active.png b/Code/Sandbox/Editor/Material/images/materialdialog_reset_viewport_active.png deleted file mode 100644 index 41590634f5..0000000000 --- a/Code/Sandbox/Editor/Material/images/materialdialog_reset_viewport_active.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:9a8467c1dcc343f637e0f7f5071a20b8881a43d567fb32fd96f5383f7b69bbb6 -size 430 diff --git a/Code/Sandbox/Editor/Material/images/materialdialog_reset_viewport_disabled.png b/Code/Sandbox/Editor/Material/images/materialdialog_reset_viewport_disabled.png deleted file mode 100644 index c6518416c0..0000000000 --- a/Code/Sandbox/Editor/Material/images/materialdialog_reset_viewport_disabled.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:0fd5ec79fc2c679f99ac5eb63d725f2cc815b09286bd0f3b5d2921eeb2e1e8cc -size 406 diff --git a/Code/Sandbox/Editor/Material/images/materialdialog_reset_viewport_normal.png b/Code/Sandbox/Editor/Material/images/materialdialog_reset_viewport_normal.png deleted file mode 100644 index eef1d5236f..0000000000 --- a/Code/Sandbox/Editor/Material/images/materialdialog_reset_viewport_normal.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:3e19713b6586581d2336e833d8ecbd78b4b8f15b1c49a29d80acbf05e8aae3df -size 418 diff --git a/Code/Sandbox/Editor/Material/images/materialdialog_save.png b/Code/Sandbox/Editor/Material/images/materialdialog_save.png deleted file mode 100644 index 4408a8ba1d..0000000000 --- a/Code/Sandbox/Editor/Material/images/materialdialog_save.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:4de0f4a102e5c4990d5d23e22b5cdd16532192f3a125758b608cd8c731278898 -size 355 diff --git a/Code/Sandbox/Editor/Material/images/materialdialog_save_active.png b/Code/Sandbox/Editor/Material/images/materialdialog_save_active.png deleted file mode 100644 index b0961d34a9..0000000000 --- a/Code/Sandbox/Editor/Material/images/materialdialog_save_active.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:d0b6f7c69112d124eac1123ffa840268c16148fef9ded3a67f84d3ad8d73eb96 -size 212 diff --git a/Code/Sandbox/Editor/Material/images/materialdialog_save_disabled.png b/Code/Sandbox/Editor/Material/images/materialdialog_save_disabled.png deleted file mode 100644 index cc694f079f..0000000000 --- a/Code/Sandbox/Editor/Material/images/materialdialog_save_disabled.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:0b795fb88a6f301d7ecc9ce75141bdcf9e6dca25043730661aa4d1f09b055d6f -size 222 diff --git a/Code/Sandbox/Editor/Material/images/materialdialog_save_normal.png b/Code/Sandbox/Editor/Material/images/materialdialog_save_normal.png deleted file mode 100644 index 6293be8be5..0000000000 --- a/Code/Sandbox/Editor/Material/images/materialdialog_save_normal.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:88fbce753cdd9381a814e3b2ec5d16df7cc26f2a37ad30b7010be71ae9183510 -size 214 diff --git a/Code/Sandbox/Editor/Objects/DisplayContextShared.inl b/Code/Sandbox/Editor/Objects/DisplayContextShared.inl index a4baf1fe89..dd5c248357 100644 --- a/Code/Sandbox/Editor/Objects/DisplayContextShared.inl +++ b/Code/Sandbox/Editor/Objects/DisplayContextShared.inl @@ -1245,28 +1245,6 @@ uint32 DisplayContext::SetState(uint32 state) return old; } -//! Set a new render state flags. -//! @param returns previous render state. -uint32 DisplayContext::SetStateFlag(uint32 state) -{ - uint32 old = m_renderState; - m_renderState |= state; - m_renderState = pRenderAuxGeom->GetRenderFlags().m_renderFlags; - pRenderAuxGeom->SetRenderFlags(m_renderState); - return old; -} - -//! Clear specified flags in render state. -//! @param returns previous render state. -uint32 DisplayContext::ClearStateFlag(uint32 state) -{ - uint32 old = m_renderState; - m_renderState &= ~state; - m_renderState = pRenderAuxGeom->GetRenderFlags().m_renderFlags; - pRenderAuxGeom->SetRenderFlags(m_renderState); - return old; -} - ////////////////////////////////////////////////////////////////////////// void DisplayContext::DepthTestOff() { diff --git a/Code/Sandbox/Editor/PickObjectTool.cpp b/Code/Sandbox/Editor/PickObjectTool.cpp deleted file mode 100644 index dc1fce110e..0000000000 --- a/Code/Sandbox/Editor/PickObjectTool.cpp +++ /dev/null @@ -1,173 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#include "EditorDefs.h" - -#include "PickObjectTool.h" - -// Editor -#include "Viewport.h" -#include "Include/HitContext.h" -#include "Objects/BaseObject.h" - - -////////////////////////////////////////////////////////////////////////// -CPickObjectTool::CPickObjectTool(IPickObjectCallback* callback, const QMetaObject* targetClass) -{ - assert(callback != 0); - m_callback = callback; - m_targetClass = targetClass; - m_bMultiPick = false; -} - -////////////////////////////////////////////////////////////////////////// -CPickObjectTool::~CPickObjectTool() -{ - GetIEditor()->GetObjectManager()->SetSelectCallback(0); - //m_prevSelectCallback = 0; - if (m_callback) - { - m_callback->OnCancelPick(); - } -} - -////////////////////////////////////////////////////////////////////////// -void CPickObjectTool::BeginEditParams([[maybe_unused]] IEditor* ie, [[maybe_unused]] int flags) -{ - QString str = "Pick object"; - if (m_targetClass) - { - str = tr("Pick %1 object").arg(m_targetClass->className()); - } - SetStatusText(str); - - //m_prevSelectCallback = - GetIEditor()->GetObjectManager()->SetSelectCallback(this); -} - -////////////////////////////////////////////////////////////////////////// -bool CPickObjectTool::MouseCallback(CViewport* view, EMouseEvent event, QPoint& point, [[maybe_unused]] int flags) -{ - if (event == eMouseLDown) - { - HitContext hitInfo; - view->HitTest(point, hitInfo); - CBaseObject* obj = hitInfo.object; - if (obj) - { - if (IsRelevant(obj)) - { - if (m_callback) - { - // Can pick this one. - m_callback->OnPick(obj); - } - if (!m_bMultiPick) - { - m_callback = 0; - GetIEditor()->SetEditTool(0); - } - } - } - } - else if (event == eMouseMove) - { - HitContext hitInfo; - view->HitTest(point, hitInfo); - CBaseObject* obj = hitInfo.object; - if (obj) - { - if (IsRelevant(obj)) - { - // Set Cursors. - view->SetCurrentCursor(STD_CURSOR_HIT, obj->GetName()); - } - } - } - return true; -} - -////////////////////////////////////////////////////////////////////////// -bool CPickObjectTool::OnSelectObject(CBaseObject* obj) -{ - if (IsRelevant(obj)) - { - // Can pick this one. - if (m_callback) - { - m_callback->OnPick(obj); - m_callback = 0; - } - if (!m_bMultiPick) - { - GetIEditor()->SetEditTool(0); - } - } - return false; -} - -////////////////////////////////////////////////////////////////////////// -bool CPickObjectTool::CanSelectObject(CBaseObject* obj) -{ - return IsRelevant(obj); -} - -////////////////////////////////////////////////////////////////////////// -bool CPickObjectTool::OnKeyDown([[maybe_unused]] CViewport* view, uint32 nChar, [[maybe_unused]] uint32 nRepCnt, [[maybe_unused]] uint32 nFlags) -{ - if (nChar == VK_ESCAPE) - { - // Cancel selection. - GetIEditor()->SetEditTool(0); - } - return false; -} - -////////////////////////////////////////////////////////////////////////// -bool CPickObjectTool::IsRelevant(CBaseObject* obj) -{ - assert(obj != 0); - if (obj == NULL) - { - return false; - } - if (!m_callback) - { - return false; - } - - if (!m_targetClass) - { - return m_callback->OnPickFilter(obj); - } - else - { - if (obj->metaObject() == m_targetClass || m_targetClass->cast(obj)) - { - return m_callback->OnPickFilter(obj); - } - } - return false; -} - -////////////////////////////////////////////////////////////////////////// -bool CPickObjectTool::IsNeedSpecificBehaviorForSpaceAcce() -{ - if (m_callback && m_callback->IsNeedSpecificBehaviorForSpaceAcce()) - { - return true; - } - return false; -} - -#include diff --git a/Code/Sandbox/Editor/PickObjectTool.h b/Code/Sandbox/Editor/PickObjectTool.h deleted file mode 100644 index 3b0241042a..0000000000 --- a/Code/Sandbox/Editor/PickObjectTool.h +++ /dev/null @@ -1,76 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -// Description : Definition of PickObjectTool, tool used to pick objects. - - -#ifndef CRYINCLUDE_EDITOR_PICKOBJECTTOOL_H -#define CRYINCLUDE_EDITOR_PICKOBJECTTOOL_H - -#if !defined(Q_MOC_RUN) -#include "EditTool.h" -#include "IObjectManager.h" -#endif - -#pragma once - -////////////////////////////////////////////////////////////////////////// -class CPickObjectTool - : public CEditTool - , public IObjectSelectCallback -{ - Q_OBJECT -public: - CPickObjectTool(IPickObjectCallback* callback, const QMetaObject* targetClass = NULL); - - //! If set to true, pick tool will not stop picking after first pick. - void SetMultiplePicks(bool bEnable) { m_bMultiPick = bEnable; }; - - // Ovverides from CEditTool - bool MouseCallback(CViewport* view, EMouseEvent event, QPoint& point, int flags); - - virtual void BeginEditParams(IEditor* ie, int flags); - virtual void EndEditParams() {}; - - virtual void Display([[maybe_unused]] DisplayContext& dc) {}; - virtual bool OnKeyDown(CViewport* view, uint32 nChar, uint32 nRepCnt, uint32 nFlags); - virtual bool OnKeyUp([[maybe_unused]] CViewport* view, [[maybe_unused]] uint32 nChar, [[maybe_unused]] uint32 nRepCnt, [[maybe_unused]] uint32 nFlags) { return false; }; - - ////////////////////////////////////////////////////////////////////////// - // IObjectSelectCallback - ////////////////////////////////////////////////////////////////////////// - virtual bool OnSelectObject(CBaseObject* obj); - virtual bool CanSelectObject(CBaseObject* obj); - ////////////////////////////////////////////////////////////////////////// - - virtual bool IsNeedSpecificBehaviorForSpaceAcce(); - -protected: - virtual ~CPickObjectTool(); - // Delete itself. - void DeleteThis() { delete this; }; - -private: - bool IsRelevant(CBaseObject* obj); - - //! Object that requested pick. - IPickObjectCallback* m_callback; - - //! If target class specified, will pick only objects that belongs to that runtime class. - const QMetaObject* m_targetClass; - - bool m_bMultiPick; -}; - - -#endif // CRYINCLUDE_EDITOR_PICKOBJECTTOOL_H diff --git a/Code/Sandbox/Editor/PythonEditorFuncs.cpp b/Code/Sandbox/Editor/PythonEditorFuncs.cpp index 5c74a950c2..f5de22387c 100644 --- a/Code/Sandbox/Editor/PythonEditorFuncs.cpp +++ b/Code/Sandbox/Editor/PythonEditorFuncs.cpp @@ -19,6 +19,8 @@ #include #include +#include + // AzToolsFramework #include #include @@ -293,9 +295,8 @@ namespace // If not found try editor folder if (!CFileUtil::FileExists(path)) { - const char* engineRoot = nullptr; - AzToolsFramework::ToolsApplicationRequestBus::BroadcastResult(engineRoot, &AzToolsFramework::ToolsApplicationRequests::GetEngineRootPath); - QDir engineDir = engineRoot ? QDir(engineRoot) : QDir::current(); + AZ::IO::FixedMaxPathString engineRoot = AZ::Utils::GetEnginePath(); + QDir engineDir = !engineRoot.empty() ? QDir(QString(engineRoot.c_str())) : QDir::current(); QString scriptFolder = engineDir.absoluteFilePath("Editor/Scripts/"); Path::ConvertBackSlashToSlash(scriptFolder); diff --git a/Code/Sandbox/Editor/Resource.h b/Code/Sandbox/Editor/Resource.h index a4bd2c1143..afcd0c7a6f 100644 --- a/Code/Sandbox/Editor/Resource.h +++ b/Code/Sandbox/Editor/Resource.h @@ -181,8 +181,6 @@ #define ID_TV_STOP 33568 #define ID_TV_PAUSE 33569 #define ID_ADDNODE 33570 -#define ID_EDITTOOL_LINK 33571 -#define ID_EDITTOOL_UNLINK 33572 #define ID_ADDSCENETRACK 33573 #define ID_FIND 33574 #define ID_SNAP_TO_GRID 33575 @@ -214,7 +212,6 @@ #define ID_TV_JUMPSTART 33601 #define ID_TV_PREVKEY 33602 #define ID_TV_NEXTKEY 33603 -#define ID_OBJECTMODIFY_ALIGN 33604 #define ID_PLAY_LOOP 33607 #define ID_TERRAIN 33611 #define ID_OBJECTMODIFY_ALIGNTOGRID 33619 diff --git a/Code/Sandbox/Editor/ToolBox.cpp b/Code/Sandbox/Editor/ToolBox.cpp index def7329e83..46c01ce864 100644 --- a/Code/Sandbox/Editor/ToolBox.cpp +++ b/Code/Sandbox/Editor/ToolBox.cpp @@ -18,6 +18,8 @@ #include "ToolBox.h" +#include + // AzToolsFramework #include #include @@ -419,9 +421,8 @@ void CToolBoxManager::Load(QString xmlpath, AmazonToolbar* pToolbar, bool bToolb } } - const char* engineRoot = nullptr; - AzToolsFramework::ToolsApplicationRequestBus::BroadcastResult(engineRoot, &AzToolsFramework::ToolsApplicationRequests::GetEngineRootPath); - QDir engineDir = engineRoot ? QDir(engineRoot) : QDir::current(); + AZ::IO::FixedMaxPathString engineRoot = AZ::Utils::GetEnginePath(); + QDir engineDir = !engineRoot.empty() ? QDir(QString(engineRoot.c_str())) : QDir::current(); string enginePath = PathUtil::AddSlash(engineDir.absolutePath().toUtf8().data()); diff --git a/Code/Sandbox/Editor/ToolbarManager.cpp b/Code/Sandbox/Editor/ToolbarManager.cpp index 4679f9cb6a..d39dabf034 100644 --- a/Code/Sandbox/Editor/ToolbarManager.cpp +++ b/Code/Sandbox/Editor/ToolbarManager.cpp @@ -585,13 +585,6 @@ AmazonToolbar ToolbarManager::GetEditModeToolbar() const t.AddAction(ID_TOOLBAR_WIDGET_UNDO, ORIGINAL_TOOLBAR_VERSION); t.AddAction(ID_TOOLBAR_WIDGET_REDO, ORIGINAL_TOOLBAR_VERSION); - if (!GetIEditor()->IsNewViewportInteractionModelEnabled()) - { - t.AddAction(ID_TOOLBAR_SEPARATOR, ORIGINAL_TOOLBAR_VERSION); - t.AddAction(ID_EDITTOOL_LINK, ORIGINAL_TOOLBAR_VERSION); - t.AddAction(ID_EDITTOOL_UNLINK, ORIGINAL_TOOLBAR_VERSION); - } - t.AddAction(ID_TOOLBAR_SEPARATOR, ORIGINAL_TOOLBAR_VERSION); if (!GetIEditor()->IsNewViewportInteractionModelEnabled()) @@ -630,7 +623,6 @@ AmazonToolbar ToolbarManager::GetObjectToolbar() const AmazonToolbar t = AmazonToolbar("Object", QObject::tr("Object Toolbar")); t.SetMainToolbar(true); t.AddAction(ID_GOTO_SELECTED, ORIGINAL_TOOLBAR_VERSION); - t.AddAction(ID_OBJECTMODIFY_ALIGN, ORIGINAL_TOOLBAR_VERSION); t.AddAction(ID_OBJECTMODIFY_ALIGNTOGRID, ORIGINAL_TOOLBAR_VERSION); t.AddAction(ID_OBJECTMODIFY_SETHEIGHT, ORIGINAL_TOOLBAR_VERSION); t.AddAction(ID_MODIFY_ALIGNOBJTOSURF, ORIGINAL_TOOLBAR_VERSION); diff --git a/Code/Sandbox/Editor/ViewportManipulatorController.cpp b/Code/Sandbox/Editor/ViewportManipulatorController.cpp index 910d037670..8ce2ea1cd9 100644 --- a/Code/Sandbox/Editor/ViewportManipulatorController.cpp +++ b/Code/Sandbox/Editor/ViewportManipulatorController.cpp @@ -95,6 +95,11 @@ bool ViewportManipulatorControllerInstance::HandleInputChannelEvent(const AzFram AZStd::optional overrideButton; AZStd::optional eventType; + // Because we receive events multiple times at separate priorities for manipulator events and + // viewport interaction events, we want to avoid updating our "last tick state" until we're on our last event, + // which currently is the low priority Interaction processor. + const bool finishedProcessingEvents = event.m_priority == InteractionPriority; + if (IsMouseMove(event.m_inputChannel)) { // Cache the ray trace results when doing manipulator interaction checks, no need to recalculate after @@ -120,10 +125,11 @@ bool ViewportManipulatorControllerInstance::HandleInputChannelEvent(const AzFram } else if (auto mouseButton = GetMouseButton(event.m_inputChannel); mouseButton != MouseButton::None) { + const AZ::u32 mouseButtonValue = static_cast(mouseButton); overrideButton = mouseButton; if (event.m_inputChannel.GetState() == InputChannel::State::Began) { - m_state.m_mouseButtons.m_mouseButtons |= static_cast(mouseButton); + m_state.m_mouseButtons.m_mouseButtons |= mouseButtonValue; if (IsDoubleClick(mouseButton)) { // Only remove the double click flag once we're done processing both Manipulator and Interaction events @@ -135,8 +141,8 @@ bool ViewportManipulatorControllerInstance::HandleInputChannelEvent(const AzFram } else { - // Only insert the double click timing once we're done processing both Manipulator and Interaction events, to avoid a false IsDoubleClick positive - if (event.m_priority == InteractionPriority) + // 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; } @@ -145,8 +151,18 @@ bool ViewportManipulatorControllerInstance::HandleInputChannelEvent(const AzFram } else if (event.m_inputChannel.GetState() == InputChannel::State::Ended) { - m_state.m_mouseButtons.m_mouseButtons &= ~static_cast(mouseButton); - eventType = MouseEvent::Up; + // If we've actually logged a mouse down event, forward a mouse up event. + // This prevents corner cases like the context menu thinking it should be opened even though no one clicked in this viewport, + // due to RenderViewportWidget ensuring all controllers get InputChannel::State::Ended events. + if (m_state.m_mouseButtons.m_mouseButtons & mouseButtonValue) + { + // Erase the button from our state if we're done processing events. + if (event.m_priority == InteractionPriority) + { + m_state.m_mouseButtons.m_mouseButtons &= ~mouseButtonValue; + } + eventType = MouseEvent::Up; + } } } else if (auto keyboardModifier = GetKeyboardModifier(event.m_inputChannel); keyboardModifier != KeyboardModifier::None) diff --git a/Code/Sandbox/Editor/editor_lib_files.cmake b/Code/Sandbox/Editor/editor_lib_files.cmake index 9084a566ae..5696931f26 100644 --- a/Code/Sandbox/Editor/editor_lib_files.cmake +++ b/Code/Sandbox/Editor/editor_lib_files.cmake @@ -316,8 +316,6 @@ set(FILES Material/MaterialHelpers.cpp Material/MaterialHelpers.h Material/MaterialDialog.qrc - Material/MaterialDialog.cpp - Material/MaterialDialog.h Material/MaterialPreviewModelView.cpp Material/MaterialPreviewModelView.h Material/PreviewModelView.cpp @@ -535,8 +533,6 @@ set(FILES Dialogs/PythonScriptsDialog.ui Dialogs/Generic/UserOptions.cpp Dialogs/Generic/UserOptions.h - AlignTool.cpp - AlignTool.h ObjectCloneTool.cpp ObjectCloneTool.h EditMode/SubObjectSelectionReferenceFrameCalculator.cpp @@ -547,10 +543,6 @@ set(FILES RotateTool.h EditTool.cpp EditTool.h - LinkTool.cpp - LinkTool.h - PickObjectTool.cpp - PickObjectTool.h VoxelAligningTool.cpp VoxelAligningTool.h Export/ExportManager.cpp @@ -632,8 +624,6 @@ set(FILES LensFlareEditor/LensFlareView.h LogFileImpl.cpp LogFileImpl.h - MatEditMainDlg.cpp - MatEditMainDlg.h MatEditPreviewDlg.cpp MatEditPreviewDlg.h Material/MaterialBrowser.cpp diff --git a/Code/Sandbox/Plugins/ComponentEntityEditorPlugin/SandboxIntegration.cpp b/Code/Sandbox/Plugins/ComponentEntityEditorPlugin/SandboxIntegration.cpp index e5311dbea9..9c917b25c0 100644 --- a/Code/Sandbox/Plugins/ComponentEntityEditorPlugin/SandboxIntegration.cpp +++ b/Code/Sandbox/Plugins/ComponentEntityEditorPlugin/SandboxIntegration.cpp @@ -670,9 +670,13 @@ void SandboxIntegrationManager::PopulateEditorGlobalContextMenu(QMenu* menu, con action = menu->addAction(QObject::tr("Create layer")); QObject::connect(action, &QAction::triggered, [this] { ContextMenu_NewLayer(); }); + AzToolsFramework::EntityIdList entities; + AzToolsFramework::ToolsApplicationRequests::Bus::BroadcastResult( + entities, + &AzToolsFramework::ToolsApplicationRequests::GetSelectedEntities); + SetupLayerContextMenu(menu); - AzToolsFramework::EntityIdSet flattenedSelection; - GetSelectedEntitiesSetWithFlattenedHierarchy(flattenedSelection); + AzToolsFramework::EntityIdSet flattenedSelection = AzToolsFramework::GetCulledEntityHierarchy(entities); AzToolsFramework::SetupAddToLayerMenu(menu, flattenedSelection, [this] { return ContextMenu_NewLayer(); }); SetupSliceContextMenu(menu); @@ -1220,10 +1224,14 @@ void SandboxIntegrationManager::CloneSelection(bool& handled) { AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); - AzToolsFramework::EntityIdSet duplicationSet; - GetSelectedEntitiesSetWithFlattenedHierarchy(duplicationSet); + AzToolsFramework::EntityIdList entities; + AzToolsFramework::ToolsApplicationRequests::Bus::BroadcastResult( + entities, + &AzToolsFramework::ToolsApplicationRequests::GetSelectedEntities); - if (duplicationSet.size() > 0) + AzToolsFramework::EntityIdSet duplicationSet = AzToolsFramework::GetCulledEntityHierarchy(entities); + + if (!duplicationSet.empty()) { AZStd::unordered_set clonedEntities; handled = AzToolsFramework::CloneInstantiatedEntities(duplicationSet, clonedEntities); @@ -2777,26 +2785,6 @@ AZ::u32 SandboxIntegrationManager::SetState(AZ::u32 state) return 0; } -AZ::u32 SandboxIntegrationManager::SetStateFlag(AZ::u32 state) -{ - if (m_dc) - { - return m_dc->SetStateFlag(state); - } - - return 0; -} - -AZ::u32 SandboxIntegrationManager::ClearStateFlag(AZ::u32 state) -{ - if (m_dc) - { - return m_dc->ClearStateFlag(state); - } - - return 0; -} - void SandboxIntegrationManager::PushMatrix(const AZ::Transform& tm) { if (m_dc) diff --git a/Code/Sandbox/Plugins/ComponentEntityEditorPlugin/SandboxIntegration.h b/Code/Sandbox/Plugins/ComponentEntityEditorPlugin/SandboxIntegration.h index e35fb5087a..36767605b2 100644 --- a/Code/Sandbox/Plugins/ComponentEntityEditorPlugin/SandboxIntegration.h +++ b/Code/Sandbox/Plugins/ComponentEntityEditorPlugin/SandboxIntegration.h @@ -268,8 +268,6 @@ private: bool SetDrawInFrontMode(bool bOn) override; AZ::u32 GetState() override; AZ::u32 SetState(AZ::u32 state) override; - AZ::u32 SetStateFlag(AZ::u32 state) override; - AZ::u32 ClearStateFlag(AZ::u32 state) override; void PushMatrix(const AZ::Transform& tm) override; void PopMatrix() override; diff --git a/Code/Tools/SceneAPI/FbxSceneBuilder/Importers/AssImpAnimationImporter.cpp b/Code/Tools/SceneAPI/FbxSceneBuilder/Importers/AssImpAnimationImporter.cpp index 2f71ebcb78..9522512619 100644 --- a/Code/Tools/SceneAPI/FbxSceneBuilder/Importers/AssImpAnimationImporter.cpp +++ b/Code/Tools/SceneAPI/FbxSceneBuilder/Importers/AssImpAnimationImporter.cpp @@ -42,7 +42,108 @@ namespace AZ // Downstream only supports 30 frames per second sample rate. Adjusting to 60 doubles the // length of the animations, they still play back at 30 frames per second. - const double AssImpAnimationImporter::s_defaultTimeStepSampleRate = 1.0 / 30.0; + const double AssImpAnimationImporter::s_defaultTimeStepBetweenFrames = 1.0 / 30.0; + + AZ::u32 GetNumKeyFrames(AZ::u32 keysSize, double duration, double ticksPerSecond) + { + if (AZ::IsClose(ticksPerSecond, 0)) + { + AZ_Warning("AnimationImporter", false, "Animation ticks per second should not be zero, defaulting to %d keyframes for animation.", keysSize); + return keysSize; + } + const double totalTicks = duration / ticksPerSecond; + AZ::u32 numKeys = keysSize; + // +1 because the animation is from [0, duration] - we have a keyframe at the end of the duration which needs to be included + double totalFramesAtDefaultTimeStep = totalTicks / AssImpAnimationImporter::s_defaultTimeStepBetweenFrames + 1; + if (!AZ::IsClose(totalFramesAtDefaultTimeStep, numKeys, 1)) + { + numKeys = AZStd::ceilf(totalFramesAtDefaultTimeStep); + } + return numKeys; + } + + double GetTimeForFrame(AZ::u32 frame, double ticksPerSecond) + { + return frame * AssImpAnimationImporter::s_defaultTimeStepBetweenFrames * ticksPerSecond; + } + + // Helper class to store key data, when translating from AssImp layout to the engine's scene format. + struct KeyData + { + KeyData(float value, float time) : + mValue(value), + mTime(time) + { + + } + + bool operator<(const KeyData& other) const + { + return mTime < other.mTime; + } + + float mValue = 0; + float mTime = 0; + }; + + template + void LerpTemplate(T& start, const T& end, float t) + { + start = start * (1.0f - t) + end * t; + } + + template<> + void LerpTemplate(aiQuaternion& start, const aiQuaternion& end, float t) + { + aiQuaternion::Interpolate(start, start, end, t); + } + + template<> + void LerpTemplate(float& start, const float& end, float t) + { + start = AZ::Lerp(start, end, t); + } + + template + bool SampleKeyFrame(FrameValueType& result, const KeyContainerType& keys, AZ::u32 numKeys, double time, AZ::u32& lastIndex) + { + if (numKeys == 0) + { + AZ_Error("AnimationImporter", numKeys > 0, "Animation key set must have at least 1 key"); + return false; + } + if (numKeys == 1) + { + result = keys[0].mValue; + return true; + } + + while (lastIndex < numKeys - 1 && time >= keys[lastIndex + 1].mTime) + { + ++lastIndex; + } + result = keys[lastIndex].mValue; + if (lastIndex < numKeys - 1) + { + auto nextValue = keys[lastIndex + 1].mValue; + float normalizedTimeBetweenFrames = 0; + if (keys[lastIndex + 1].mTime != keys[lastIndex].mTime) + { + normalizedTimeBetweenFrames = + (time - keys[lastIndex].mTime) / (keys[lastIndex + 1].mTime - keys[lastIndex].mTime); + } + else + { + AZ_Warning("AnimationImporter", false, + "Animation has keys with duplicate time %5.5f, at indices %d and %d. The second will be ignored.", + keys[lastIndex].mTime, + lastIndex, + lastIndex + 1); + } + LerpTemplate(result, nextValue, normalizedTimeBetweenFrames); + } + return true; + } AssImpAnimationImporter::AssImpAnimationImporter() { @@ -199,6 +300,14 @@ namespace AZ for (AZ::u32 animIndex = 0; animIndex < scene->mNumAnimations; ++animIndex) { const aiAnimation* animation = scene->mAnimations[animIndex]; + if (animation->mTicksPerSecond == 0) + { + AZ_Error( + "AnimationImporter", false, + "Animation name %s has a sample rate of 0 ticks per second and cannot be processed.", + animation->mName.C_Str()); + return Events::ProcessingResult::Failure; + } mapAnimationsFunc(animation->mNumChannels, animation->mChannels, animation, boneAnimations); @@ -410,70 +519,38 @@ namespace AZ anim->mNumPositionKeys, anim->mNumRotationKeys, anim->mNumScalingKeys); return Events::ProcessingResult::Failure; } - - auto sampleKeyFrame = [](const auto& keys, AZ::u32 numKeys, double time, AZ::u32& lastIndex) - { - AZ_Error("AnimationImporter", numKeys > 0, "Animation key set must have at least 1 key"); - - if (numKeys == 1) - { - return keys[0].mValue; - } - - auto returnValue = keys[0].mValue; - - for (AZ::u32 keyIndex = lastIndex; keyIndex < numKeys; ++keyIndex) - { - const auto& key = keys[keyIndex]; - lastIndex = keyIndex; - - // We want to return the key that exactly matches the time if possible, otherwise we'll keep track of the previous time - // If we don't find an exact match and end up going past the desired time (or run out of keyframes) then we return the previous key - if (key.mTime < time) - { - returnValue = key.mValue; - } - else if (AZ::IsClose(key.mTime, time)) - { - return key.mValue; - } - else - { - return returnValue; - } - } - - return returnValue; - }; // Resample the animations at a fixed time step. This matches the behaviour of // the previous SDK used. Longer term, this could be data driven, or based on the // smallest time step between key frames. // AssImp has an animation->mTicksPerSecond and animation->mDuration, but those // are less predictable than just using a fixed time step. - const double duration = animation->mDuration / animation->mTicksPerSecond; + // AssImp documentation claims animation->mDuration is the duration of the animation in ticks, but + // not all animations we've tested follow that pattern. Sometimes duration is in seconds. + const AZ::u32 numKeyFrames = GetNumKeyFrames( + AZStd::max(AZStd::max(anim->mNumScalingKeys, anim->mNumPositionKeys), anim->mNumRotationKeys), + animation->mDuration, + animation->mTicksPerSecond); - AZ::u32 numKeyFrames = AZStd::max(AZStd::max(anim->mNumScalingKeys, anim->mNumPositionKeys), anim->mNumRotationKeys); - if (!AZ::IsClose(duration / s_defaultTimeStepSampleRate, numKeyFrames, 1)) - { - double dT = duration / s_defaultTimeStepSampleRate; - numKeyFrames = AZStd::ceilf(dT) + 1; // +1 because the animation is from [0, duration] - we have a keyframe at the end of the duration which needs to be included - } - AZStd::shared_ptr createdAnimationData = AZStd::make_shared(); createdAnimationData->ReserveKeyFrames(numKeyFrames); - createdAnimationData->SetTimeStepBetweenFrames(s_defaultTimeStepSampleRate); + createdAnimationData->SetTimeStepBetweenFrames(s_defaultTimeStepBetweenFrames); AZ::u32 lastScaleIndex = 0; AZ::u32 lastPositionIndex = 0; AZ::u32 lastRotationIndex = 0; for (AZ::u32 frame = 0; frame < numKeyFrames; ++frame) { - double time = frame * s_defaultTimeStepSampleRate * animation->mTicksPerSecond; - aiVector3D scale = sampleKeyFrame(anim->mScalingKeys, anim->mNumScalingKeys, time, lastScaleIndex); - aiVector3D position = sampleKeyFrame(anim->mPositionKeys, anim->mNumPositionKeys, time, lastPositionIndex); - aiQuaternion rotation = sampleKeyFrame(anim->mRotationKeys, anim->mNumRotationKeys, time, lastRotationIndex); + const double time = GetTimeForFrame(frame, animation->mTicksPerSecond); + aiVector3D scale = aiVector3D(1.f, 1.f, 1.f), position = aiVector3D(0.f, 0.f, 0.f); + aiQuaternion rotation(1.f, 0.f, 0.f, 0.f); + if (!SampleKeyFrame(scale, anim->mScalingKeys, anim->mNumScalingKeys, time, lastScaleIndex) || + !SampleKeyFrame(position, anim->mPositionKeys, anim->mNumPositionKeys, time, lastPositionIndex) || + !SampleKeyFrame(rotation, anim->mRotationKeys, anim->mNumRotationKeys, time, lastRotationIndex)) + { + return Events::ProcessingResult::Failure; + } aiMatrix4x4 transform(scale, rotation, position); @@ -520,28 +597,6 @@ namespace AZ // SetTimeStepBetweenFrames set on the animation data // Keyframes. Weights (Values in FBX SDK) per key time. // Keyframes generated for every single frame of the animation. - - // Helper class to store key data, when translating from AssImp layout to the engine's scene format. - struct KeyData - { - KeyData(float weight, float time) : - m_weight(weight), - m_time(time) - { - - } - - bool operator<(const KeyData& other) const - { - return m_time < other.m_time; - } - - // Naming in the previous SDK (FBX SDK) and in the engine's scene format - // doesn't match AssImp's naming convention. - // weight here is the AssImp's name for the data, it was named value in FBX SDK. - float m_weight = 0; - float m_time = 0; - }; typedef AZStd::map> ValueToKeyDataMap; ValueToKeyDataMap valueToKeyDataMap; @@ -562,44 +617,27 @@ namespace AZ { AZStd::shared_ptr morphAnimNode = AZStd::make_shared(); - morphAnimNode->ReserveKeyFrames(animation->mDuration + 1); - morphAnimNode->SetTimeStepBetweenFrames(1.0 / animation->mTicksPerSecond); + + const AZ::u32 numKeyFrames = GetNumKeyFrames(keys.size(), animation->mDuration, animation->mTicksPerSecond); + morphAnimNode->ReserveKeyFrames(numKeyFrames); + morphAnimNode->SetTimeStepBetweenFrames(s_defaultTimeStepBetweenFrames); aiAnimMesh* aiAnimMesh = mesh->mAnimMeshes[meshIdx]; AZStd::string_view nodeName(aiAnimMesh->mName.C_Str()); const AZ::u32 maxKeys = keys.size(); AZ::u32 keyIdx = 0; - for (AZ::u32 time = 0; time <= animation->mDuration; ++time) + for (AZ::u32 frame = 0; frame <= numKeyFrames; ++frame) { - if (keyIdx < maxKeys - 1 && time >= keys[keyIdx+1].m_time) - { - ++keyIdx; - } - float weight_value = keys[keyIdx].m_weight; - if (keyIdx < maxKeys - 1) - { - float nextWeight = keys[keyIdx+1].m_weight; - float normalizedTimeBetweenFrames = 0; + const double time = GetTimeForFrame(frame, animation->mTicksPerSecond); - if (keys[keyIdx + 1].m_time != keys[keyIdx].m_time) - { - normalizedTimeBetweenFrames = - (time - keys[keyIdx].m_time) / (keys[keyIdx + 1].m_time - keys[keyIdx].m_time); - } - else - { - AZ_Warning("AnimationImporter", false, - "Morph target mesh %s has keys with duplicate time, at indices %d and %d. The second will be ignored.", - nodeName.data(), - keyIdx, - keyIdx+1); - } - - // AssImp and FBX both only support linear interpolation for blend shapes. - weight_value = AZ::Lerp(weight_value, nextWeight, normalizedTimeBetweenFrames); + float weight = 0; + if (!SampleKeyFrame(weight, keys, keys.size(), time, keyIdx)) + { + return Events::ProcessingResult::Failure; } - morphAnimNode->AddKeyFrame(weight_value); + + morphAnimNode->AddKeyFrame(weight); } diff --git a/Code/Tools/SceneAPI/FbxSceneBuilder/Importers/AssImpAnimationImporter.h b/Code/Tools/SceneAPI/FbxSceneBuilder/Importers/AssImpAnimationImporter.h index 72180dea1a..3c06153d04 100644 --- a/Code/Tools/SceneAPI/FbxSceneBuilder/Importers/AssImpAnimationImporter.h +++ b/Code/Tools/SceneAPI/FbxSceneBuilder/Importers/AssImpAnimationImporter.h @@ -45,7 +45,7 @@ namespace AZ const aiMeshMorphAnim* meshMorphAnim, const aiMesh* mesh); - static const double s_defaultTimeStepSampleRate; + static const double s_defaultTimeStepBetweenFrames; protected: static const char* s_animationNodeName; diff --git a/Code/Tools/SceneAPI/SceneCore/Containers/SceneGraph.cpp b/Code/Tools/SceneAPI/SceneCore/Containers/SceneGraph.cpp index 934b0154c9..87c265481f 100644 --- a/Code/Tools/SceneAPI/SceneCore/Containers/SceneGraph.cpp +++ b/Code/Tools/SceneAPI/SceneCore/Containers/SceneGraph.cpp @@ -43,7 +43,7 @@ namespace AZ AZ::BehaviorContext* behaviorContext = azrtti_cast(context); if (behaviorContext) { - behaviorContext->Class() + behaviorContext->Class("NodeIndex") ->Attribute(AZ::Script::Attributes::Scope, AZ::Script::Attributes::ScopeFlags::Common) ->Attribute(AZ::Script::Attributes::Module, "scene.graph") ->Constructor<>() @@ -57,7 +57,7 @@ namespace AZ ->Attribute(AZ::Script::Attributes::Operator, AZ::Script::Attributes::OperatorType::ToString) ; - behaviorContext->Class() + behaviorContext->Class("SceneGraphName") ->Attribute(AZ::Script::Attributes::Scope, AZ::Script::Attributes::ScopeFlags::Common) ->Attribute(AZ::Script::Attributes::Module, "scene.graph") ->Constructor() diff --git a/Gems/AWSClientAuth/Code/Include/Private/Authentication/AuthenticationNotificationBusBehaviorHandler.h b/Gems/AWSClientAuth/Code/Include/Private/Authentication/AuthenticationNotificationBusBehaviorHandler.h index c5e3c46cd4..c44327a5f2 100644 --- a/Gems/AWSClientAuth/Code/Include/Private/Authentication/AuthenticationNotificationBusBehaviorHandler.h +++ b/Gems/AWSClientAuth/Code/Include/Private/Authentication/AuthenticationNotificationBusBehaviorHandler.h @@ -12,6 +12,7 @@ #pragma once #include +#include namespace AWSClientAuth { @@ -28,74 +29,104 @@ namespace AWSClientAuth OnPasswordGrantMultiFactorConfirmSignInSuccess, OnPasswordGrantMultiFactorConfirmSignInFail, OnDeviceCodeGrantSignInSuccess, OnDeviceCodeGrantSignInFail, OnDeviceCodeGrantConfirmSignInSuccess, OnDeviceCodeGrantConfirmSignInFail, - OnRefreshTokensSuccess, OnRefreshTokensFail, - OnSignOut + OnRefreshTokensSuccess, OnRefreshTokensFail ); void OnPasswordGrantSingleFactorSignInSuccess(const AuthenticationTokens& authenticationToken) override { - Call(FN_OnPasswordGrantSingleFactorSignInSuccess, authenticationToken); + AZ::TickBus::QueueFunction([authenticationToken, this]() + { + Call(FN_OnPasswordGrantSingleFactorSignInSuccess, authenticationToken); + }); } void OnPasswordGrantSingleFactorSignInFail(const AZStd::string& error) override { - Call(FN_OnPasswordGrantSingleFactorSignInFail, error); + AZ::TickBus::QueueFunction([error, this]() + { + Call(FN_OnPasswordGrantSingleFactorSignInFail, error); + }); } void OnPasswordGrantMultiFactorSignInSuccess() override { - Call(FN_OnPasswordGrantMultiFactorSignInSuccess); + AZ::TickBus::QueueFunction([this]() + { + Call(FN_OnPasswordGrantMultiFactorSignInSuccess); + }); } void OnPasswordGrantMultiFactorSignInFail(const AZStd::string& error) override { - Call(FN_OnPasswordGrantMultiFactorSignInFail, error); + AZ::TickBus::QueueFunction([error, this]() + { + Call(FN_OnPasswordGrantMultiFactorSignInFail, error); + }); } void OnPasswordGrantMultiFactorConfirmSignInSuccess(const AuthenticationTokens& authenticationToken) override { - Call(FN_OnPasswordGrantMultiFactorConfirmSignInSuccess, authenticationToken); + AZ::TickBus::QueueFunction([authenticationToken, this]() + { + Call(FN_OnPasswordGrantMultiFactorConfirmSignInSuccess, authenticationToken); + }); } void OnPasswordGrantMultiFactorConfirmSignInFail(const AZStd::string& error) override { - Call(FN_OnPasswordGrantMultiFactorConfirmSignInFail, error); + AZ::TickBus::QueueFunction([error, this]() + { + Call(FN_OnPasswordGrantMultiFactorConfirmSignInFail, error); + }); } void OnDeviceCodeGrantSignInSuccess( const AZStd::string& userCode, const AZStd::string& verificationUrl, const int codeExpiresInSeconds) override { - Call(FN_OnDeviceCodeGrantSignInSuccess, userCode, verificationUrl, codeExpiresInSeconds); + AZ::TickBus::QueueFunction([userCode, verificationUrl, codeExpiresInSeconds, this]() + { + Call(FN_OnDeviceCodeGrantSignInSuccess, userCode, verificationUrl, codeExpiresInSeconds); + }); } void OnDeviceCodeGrantSignInFail(const AZStd::string& error) override { - Call(FN_OnDeviceCodeGrantSignInFail, error); + AZ::TickBus::QueueFunction([error, this]() + { + Call(FN_OnDeviceCodeGrantSignInFail, error); + }); } void OnDeviceCodeGrantConfirmSignInSuccess(const AuthenticationTokens& authenticationToken) override { - Call(FN_OnDeviceCodeGrantConfirmSignInSuccess, authenticationToken); + AZ::TickBus::QueueFunction([authenticationToken, this]() + { + Call(FN_OnDeviceCodeGrantConfirmSignInSuccess, authenticationToken); + }); } void OnDeviceCodeGrantConfirmSignInFail(const AZStd::string& error) override { - Call(FN_OnDeviceCodeGrantConfirmSignInFail, error); + AZ::TickBus::QueueFunction([error, this]() + { + Call(FN_OnDeviceCodeGrantConfirmSignInFail, error); + }); } void OnRefreshTokensSuccess(const AuthenticationTokens& authenticationToken) override { - Call(FN_OnRefreshTokensSuccess, authenticationToken); + AZ::TickBus::QueueFunction([authenticationToken, this]() + { + Call(FN_OnRefreshTokensSuccess, authenticationToken); + }); } void OnRefreshTokensFail(const AZStd::string& error) override { - Call(FN_OnRefreshTokensFail, error); - } - - void OnSignOut(const ProviderNameEnum& provideName) override - { - Call(FN_OnSignOut, provideName); + AZ::TickBus::QueueFunction([error, this]() + { + Call(FN_OnRefreshTokensFail, error); + }); } }; } // namespace AWSClientAuth diff --git a/Gems/AWSClientAuth/Code/Include/Private/Authentication/AuthenticationProviderManager.h b/Gems/AWSClientAuth/Code/Include/Private/Authentication/AuthenticationProviderManager.h index a9a2f2ad6e..a09a96ba5c 100644 --- a/Gems/AWSClientAuth/Code/Include/Private/Authentication/AuthenticationProviderManager.h +++ b/Gems/AWSClientAuth/Code/Include/Private/Authentication/AuthenticationProviderManager.h @@ -16,6 +16,7 @@ #include #include #include +#include #include #include @@ -23,7 +24,8 @@ namespace AWSClientAuth { //! Manages various authentication provider implementations and implements AuthenticationProvider Request bus. class AuthenticationProviderManager - : AuthenticationProviderRequestBus::Handler + : public AuthenticationProviderRequestBus::Handler + , public AuthenticationProviderScriptCanvasRequestBus::Handler { public: AZ_RTTI(AuthenticationProviderManager, "{45813BA5-9A46-4A2A-A923-C79CFBA0E63D}", IAuthenticationProviderRequests); @@ -43,6 +45,22 @@ namespace AWSClientAuth bool IsSignedIn(const ProviderNameEnum& providerName) override; bool SignOut(const ProviderNameEnum& providerName) override; AuthenticationTokens GetAuthenticationTokens(const ProviderNameEnum& providerName) override; + + // AuthenticationProviderScriptCanvasRequest interface + bool Initialize(const AZStd::vector& providerNames, const AZStd::string& settingsRegistryPath) override; + void PasswordGrantSingleFactorSignInAsync( + const AZStd::string& providerName, const AZStd::string& username, const AZStd::string& password) override; + void PasswordGrantMultiFactorSignInAsync( + const AZStd::string& providerName, const AZStd::string& username, const AZStd::string& password) override; + void PasswordGrantMultiFactorConfirmSignInAsync( + const AZStd::string& providerName, const AZStd::string& username, const AZStd::string& confirmationCode) override; + void DeviceCodeGrantSignInAsync(const AZStd::string& providerName) override; + void DeviceCodeGrantConfirmSignInAsync(const AZStd::string& providerName) override; + void RefreshTokensAsync(const AZStd::string& providerName) override; + void GetTokensWithRefreshAsync(const AZStd::string& providerName) override; + bool IsSignedIn(const AZStd::string& providerName) override; + bool SignOut(const AZStd::string& providerName) override; + AuthenticationTokens GetAuthenticationTokens(const AZStd::string& providerName) override; virtual AZStd::unique_ptr CreateAuthenticationProviderObject(const ProviderNameEnum& providerName); AZStd::map> m_authenticationProvidersMap; @@ -50,9 +68,9 @@ namespace AWSClientAuth private: bool IsProviderInitialized(const ProviderNameEnum& providerName); void ResetProviders(); + ProviderNameEnum GetProviderNameEnum(AZStd::string name); AZStd::shared_ptr m_settingsRegistry; - }; } // namespace AWSClientAuth diff --git a/Gems/AWSClientAuth/Code/Include/Private/Authentication/AuthenticationProviderScriptCanvasBus.h b/Gems/AWSClientAuth/Code/Include/Private/Authentication/AuthenticationProviderScriptCanvasBus.h new file mode 100644 index 0000000000..9ce508b497 --- /dev/null +++ b/Gems/AWSClientAuth/Code/Include/Private/Authentication/AuthenticationProviderScriptCanvasBus.h @@ -0,0 +1,103 @@ +/* +* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or +* its licensors. +* +* For complete copyright and license terms please see the LICENSE at the root of this +* distribution (the "License"). All use of this software is governed by the License, +* or, if provided, by the license below or the license accompanying this file. Do not +* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* +*/ +#pragma once + +#include +#include + +namespace AWSClientAuth +{ + //! Abstract class for authentication provider script canvas requests. + //! Private class to allow provide names to be string type instead of an enum as behavior context does not work well with enum's. + class IAuthenticationProviderScriptCanvasRequests + { + public: + AZ_TYPE_INFO(IAuthenticationProviderRequests, "{A8FD915F-9FF2-4BA3-8AA0-8CF7A94A323B}"); + + //! Parse the settings file for required settings for authentication providers. Instantiate and initialize authentication providers + //! @param providerNames List of provider names to instantiate and initialize for Authentication. + //! @param settingsRegistryPath Path for the settings registry file to use to configure providers. + //! @return bool True: if all providers initialized successfully. False: If any provider fails initialization. + virtual bool Initialize(const AZStd::vector& providerNames, const AZStd::string& settingsRegistryPath) = 0; + + //! Checks if user is signed in. + //! If access tokens are available and not expired. + //! @param providerName Provider to check signed in for + //! @return bool True if valid access token available, else False + virtual bool IsSignedIn(const AZStd::string& providerName) = 0; + + //! Get cached tokens from last last successful sign-in for the provider. + //! @param providerName Provider to get authentication tokens + //! @return AuthenticationTokens tokens from successful authentication. + virtual AuthenticationTokens GetAuthenticationTokens(const AZStd::string& providerName) = 0; + + // Below methods have corresponding notifications for success and failures. + + //! Call sign in endpoint for provider password grant flow. + //! @param providerName Provider to call sign in. + //! @param username Username to use to for sign in. + //! @param password Password to use to for sign in. + virtual void PasswordGrantSingleFactorSignInAsync(const AZStd::string& providerName, const AZStd::string& username, const AZStd::string& password) = 0; + + //! Call sign in endpoint for provider password grant multi factor authentication flow. + //! @param providerName Provider to call MFA sign in. + //! @param username Username to use for MFA sign in. + //! @param password Password to use for MFA sign in. + virtual void PasswordGrantMultiFactorSignInAsync(const AZStd::string& providerName, const AZStd::string& username, const AZStd::string& password) = 0; + + //! Call confirm endpoint for provider password grant multi factor authentication flow . + //! @param providerName Provider to call MFA confirm sign in. + //! @param username Username to use for MFA confirm. + //! @param confirmationCode Confirmation code (sent to email/text) to use for MFA confirm. + virtual void PasswordGrantMultiFactorConfirmSignInAsync(const AZStd::string& providerName, const AZStd::string& username, const AZStd::string& confirmationCode) = 0; + + //! Call code-pair endpoint for provider device grant flow. + //! @param providerName Provider to call device sign in. + virtual void DeviceCodeGrantSignInAsync(const AZStd::string& providerName) = 0; + + //! Call tokens endpoint for provider device grant flow. + //! @param providerName Provider to call device confirm sign in. + virtual void DeviceCodeGrantConfirmSignInAsync(const AZStd::string& providerName) = 0; + + //! Call refresh endpoint for provider refresh grant flow. + //! @param providerName Provider to call refresh tokens. + virtual void RefreshTokensAsync(const AZStd::string& providerName) = 0; + + //! Call refresh token if token not valid. If token valid, fires corresponding event. + //! @param providerName Provider to get access token for. + //! events: OnRefreshTokensSuccess, OnRefreshTokensFail + virtual void GetTokensWithRefreshAsync(const AZStd::string& providerName) = 0; + + //! Signs user out. + //! Clears all cached tokens. + //! @param providerName Provider to sign out. + //! @return bool True: Successfully sign out. + virtual bool SignOut(const AZStd::string& providerName) = 0; + + ////////////////////////////////////////////////////////////////////////// + }; + + //! Authentication Request bus for different supported providers. + class AuthenticationProviderScriptCanvasRequests + : public AZ::EBusTraits + { + public: + ////////////////////////////////////////////////////////////////////////// + // EBusTraits overrides + using MutexType = AZ::NullMutex; + static const AZ::EBusHandlerPolicy HandlerPolicy = AZ::EBusHandlerPolicy::Single; + static const AZ::EBusAddressPolicy AddressPolicy = AZ::EBusAddressPolicy::Single; + ////////////////////////////////////////////////////////////////////////// + }; + using AuthenticationProviderScriptCanvasRequestBus = AZ::EBus; + +} // namespace AWSClientAuth diff --git a/Gems/AWSClientAuth/Code/Include/Private/Authentication/AuthenticationProviderTypes.h b/Gems/AWSClientAuth/Code/Include/Private/Authentication/AuthenticationProviderTypes.h index 1e10e66307..8bd31d6aeb 100644 --- a/Gems/AWSClientAuth/Code/Include/Private/Authentication/AuthenticationProviderTypes.h +++ b/Gems/AWSClientAuth/Code/Include/Private/Authentication/AuthenticationProviderTypes.h @@ -15,6 +15,14 @@ namespace AWSClientAuth { + constexpr char ProvideNameEnumStringNone[] = "None"; + constexpr char ProvideNameEnumStringAWSCognitoIDP[] = "AWSCognitoIDP"; + constexpr char ProvideNameEnumStringLoginWithAmazon[] = "LoginWithAmazon"; + constexpr char ProvideNameEnumStringGoogle[] = "Google"; + constexpr char ProvideNameEnumStringApple[] = "Apple"; + constexpr char ProvideNameEnumStringFacebook[] = "Facebook"; + constexpr char ProvideNameEnumStringTwitch[] = "Twitch"; + //! Holds Login with Amazon provider serialized settings class LWAProviderSetting { diff --git a/Gems/AWSClientAuth/Code/Include/Private/Authorization/AWSCognitoAuthorizationNotificationBusBehaviorHandler.h b/Gems/AWSClientAuth/Code/Include/Private/Authorization/AWSCognitoAuthorizationNotificationBusBehaviorHandler.h index f690445c26..e26896fa06 100644 --- a/Gems/AWSClientAuth/Code/Include/Private/Authorization/AWSCognitoAuthorizationNotificationBusBehaviorHandler.h +++ b/Gems/AWSClientAuth/Code/Include/Private/Authorization/AWSCognitoAuthorizationNotificationBusBehaviorHandler.h @@ -12,6 +12,7 @@ #pragma once #include +#include #include namespace AWSClientAuth @@ -28,12 +29,18 @@ namespace AWSClientAuth void OnRequestAWSCredentialsSuccess(const ClientAuthAWSCredentials& awsCredentials) override { - Call(FN_OnRequestAWSCredentialsSuccess, awsCredentials); + AZ::TickBus::QueueFunction([awsCredentials, this]() + { + Call(FN_OnRequestAWSCredentialsSuccess, awsCredentials); + }); } void OnRequestAWSCredentialsFail(const AZStd::string& error) override { - Call(FN_OnRequestAWSCredentialsFail, error); + AZ::TickBus::QueueFunction([error, this]() + { + Call(FN_OnRequestAWSCredentialsFail, error); + }); } }; } // namespace AWSClientAuth diff --git a/Gems/AWSClientAuth/Code/Include/Private/UserManagement/UserManagementNotificationBusBehaviorHandler.h b/Gems/AWSClientAuth/Code/Include/Private/UserManagement/UserManagementNotificationBusBehaviorHandler.h index 06f2ae6e58..f5c2ca7ed1 100644 --- a/Gems/AWSClientAuth/Code/Include/Private/UserManagement/UserManagementNotificationBusBehaviorHandler.h +++ b/Gems/AWSClientAuth/Code/Include/Private/UserManagement/UserManagementNotificationBusBehaviorHandler.h @@ -12,6 +12,7 @@ #pragma once #include +#include namespace AWSClientAuth { @@ -32,62 +33,86 @@ namespace AWSClientAuth void OnEmailSignUpSuccess(const AZStd::string& uuid) override { - Call(FN_OnEmailSignUpSuccess, uuid); + AZ::TickBus::QueueFunction([uuid, this]() { + Call(FN_OnEmailSignUpSuccess, uuid); + }); } void OnEmailSignUpFail(const AZStd::string& error) override { - Call(FN_OnEmailSignUpFail, error); + AZ::TickBus::QueueFunction([error, this]() { + Call(FN_OnEmailSignUpFail, error); + }); } void OnPhoneSignUpSuccess(const AZStd::string& uuid) override { - Call(FN_OnPhoneSignUpSuccess, uuid); + AZ::TickBus::QueueFunction([uuid, this]() { + Call(FN_OnPhoneSignUpSuccess, uuid); + }); } void OnPhoneSignUpFail(const AZStd::string& error) override { - Call(FN_OnPhoneSignUpFail, error); + AZ::TickBus::QueueFunction([error, this]() { + Call(FN_OnPhoneSignUpFail, error); + }); } void OnConfirmSignUpSuccess() override { - Call(FN_OnConfirmSignUpSuccess); + AZ::TickBus::QueueFunction([this]() { + Call(FN_OnConfirmSignUpSuccess); + }); } void OnConfirmSignUpFail(const AZStd::string& error) override { - Call(FN_OnConfirmSignUpFail, error); + AZ::TickBus::QueueFunction([error, this]() { + Call(FN_OnConfirmSignUpFail, error); + }); } void OnForgotPasswordSuccess() override { - Call(FN_OnForgotPasswordSuccess); + AZ::TickBus::QueueFunction([this]() { + Call(FN_OnForgotPasswordSuccess); + }); } void OnForgotPasswordFail(const AZStd::string& error) override { - Call(FN_OnForgotPasswordFail, error); + AZ::TickBus::QueueFunction([error, this]() { + Call(FN_OnForgotPasswordFail, error); + }); } void OnConfirmForgotPasswordSuccess() override { - Call(FN_OnConfirmForgotPasswordSuccess); + AZ::TickBus::QueueFunction([this]() { + Call(FN_OnConfirmForgotPasswordSuccess); + }); } void OnConfirmForgotPasswordFail(const AZStd::string& error) override { - Call(FN_OnConfirmForgotPasswordFail, error); + AZ::TickBus::QueueFunction([error, this]() { + Call(FN_OnConfirmForgotPasswordFail, error); + }); } void OnEnableMFASuccess() override { - Call(FN_OnEnableMFASuccess); + AZ::TickBus::QueueFunction([this]() { + Call(FN_OnEnableMFASuccess); + }); } void OnEnableMFAFail(const AZStd::string& error) override { - Call(FN_OnEnableMFAFail, error); + AZ::TickBus::QueueFunction([error, this]() { + Call(FN_OnEnableMFAFail, error); + }); } }; } // namespace AWSClientAuth diff --git a/Gems/AWSClientAuth/Code/Include/Public/Authentication/AuthenticationProviderBus.h b/Gems/AWSClientAuth/Code/Include/Public/Authentication/AuthenticationProviderBus.h index 693adf1e65..9e822849bc 100644 --- a/Gems/AWSClientAuth/Code/Include/Public/Authentication/AuthenticationProviderBus.h +++ b/Gems/AWSClientAuth/Code/Include/Public/Authentication/AuthenticationProviderBus.h @@ -16,7 +16,7 @@ namespace AWSClientAuth { - //@ Abstract class for authentication provider requests. + //! Abstract class for authentication provider requests. class IAuthenticationProviderRequests { public: @@ -35,32 +35,40 @@ namespace AWSClientAuth virtual bool IsSignedIn(const ProviderNameEnum& providerName) = 0; //! Get cached tokens from last last successful sign-in for the provider. + //! @param providerName Provider to get authentication tokens. + //! @return AuthenticationTokens tokens from successful authentication. virtual AuthenticationTokens GetAuthenticationTokens(const ProviderNameEnum& providerName) = 0; // Below methods have corresponding notifications for success and failures. //! Call sign in endpoint for provider password grant flow. + //! @param providerName Provider to call sign in. //! @param username Username to use to for sign in. //! @param password Password to use to for sign in. virtual void PasswordGrantSingleFactorSignInAsync(const ProviderNameEnum& providerName, const AZStd::string& username, const AZStd::string& password) = 0; //! Call sign in endpoint for provider password grant multi factor authentication flow. + //! @param providerName Provider to call MFA sign in. //! @param username Username to use for MFA sign in. //! @param password Password to use for MFA sign in. virtual void PasswordGrantMultiFactorSignInAsync(const ProviderNameEnum& providerName, const AZStd::string& username, const AZStd::string& password) = 0; //! Call confirm endpoint for provider password grant multi factor authentication flow . + //! @param providerName Provider to call MFA confirm sign in. //! @param username Username to use for MFA confirm. //! @param confirmationCode Confirmation code (sent to email/text) to use for MFA confirm. virtual void PasswordGrantMultiFactorConfirmSignInAsync(const ProviderNameEnum& providerName, const AZStd::string& username, const AZStd::string& confirmationCode) = 0; //! Call code-pair endpoint for provider device grant flow. + //! @param providerName Provider to call device sign in. virtual void DeviceCodeGrantSignInAsync(const ProviderNameEnum& providerName) = 0; //! Call tokens endpoint for provider device grant flow. + //! @param providerName Provider to call device confirm sign in. virtual void DeviceCodeGrantConfirmSignInAsync(const ProviderNameEnum& providerName) = 0; //! Call refresh endpoint for provider refresh grant flow. + //! @param providerName Provider to call refresh tokens. virtual void RefreshTokensAsync(const ProviderNameEnum& providerName) = 0; //! Call refresh token if token not valid. If token valid, fires corresponding event. diff --git a/Gems/AWSClientAuth/Code/Include/Public/Authentication/AuthenticationTokens.h b/Gems/AWSClientAuth/Code/Include/Public/Authentication/AuthenticationTokens.h index 80138efd1b..3bb781f262 100644 --- a/Gems/AWSClientAuth/Code/Include/Public/Authentication/AuthenticationTokens.h +++ b/Gems/AWSClientAuth/Code/Include/Public/Authentication/AuthenticationTokens.h @@ -11,20 +11,15 @@ */ #pragma once +#include #include #include +#include +#include namespace AWSClientAuth { - enum class ProviderNameEnum - { - None, - AWSCognitoIDP, - LoginWithAmazon, - Google, - Apple, - Facebook - }; + AZ_ENUM_CLASS(ProviderNameEnum, None, AWSCognitoIDP, LoginWithAmazon, Twitch, Google, Apple, Facebook); //! Used to share authentication tokens to caller and to AWSCognitoAuthorizationController. class AuthenticationTokens @@ -55,6 +50,8 @@ namespace AWSClientAuth //! @return Expiration time in seconds. int GetTokensExpireTimeSeconds() const; + static void Reflect(AZ::ReflectContext* context); + private: int m_tokensExpireTimeSeconds = 0; AZStd::string m_accessToken; diff --git a/Gems/AWSClientAuth/Code/Include/Public/Authorization/ClientAuthAWSCredentials.h b/Gems/AWSClientAuth/Code/Include/Public/Authorization/ClientAuthAWSCredentials.h index 71a5703efd..2daac42a49 100644 --- a/Gems/AWSClientAuth/Code/Include/Public/Authorization/ClientAuthAWSCredentials.h +++ b/Gems/AWSClientAuth/Code/Include/Public/Authorization/ClientAuthAWSCredentials.h @@ -12,7 +12,7 @@ #pragma once -#include +#include #include #include @@ -24,6 +24,14 @@ namespace AWSClientAuth { public: AZ_TYPE_INFO(ClientAuthAWSCredentials, "{02FB32C4-B94E-4084-9049-3DF32F87BD76}"); + ClientAuthAWSCredentials() = default; + ClientAuthAWSCredentials(const ClientAuthAWSCredentials& other) + : m_accessKeyId(other.m_accessKeyId) + , m_secretKey(other.m_secretKey) + , m_sessionToken(other.m_sessionToken) + + { + } ClientAuthAWSCredentials(const AZStd::string& accessKeyId, const AZStd::string& secretKey, const AZStd::string& sessionToken) { @@ -50,6 +58,32 @@ namespace AWSClientAuth return m_sessionToken; } + static void Reflect(AZ::ReflectContext* context) + { + auto serializeContext = azrtti_cast(context); + if (serializeContext) + { + serializeContext->Class() + ->Field("AWSAccessKeyId", &ClientAuthAWSCredentials::m_accessKeyId) + ->Field("AWSSecretKey", &ClientAuthAWSCredentials::m_secretKey) + ->Field("AWSSessionToken", &ClientAuthAWSCredentials::m_sessionToken); + } + + AZ::BehaviorContext* behaviorContext = azrtti_cast(context); + if (behaviorContext) + { + behaviorContext->Class() + ->Attribute(AZ::Script::Attributes::Category, "AWSClientAuth") + ->Attribute(AZ::Script::Attributes::Storage, AZ::Script::Attributes::StorageType::Value) + ->Attribute(AZ::Script::Attributes::Scope, AZ::Script::Attributes::ScopeFlags::Common) + ->Constructor() + ->Constructor() + ->Property("AWSAccessKeyId", BehaviorValueGetter(&ClientAuthAWSCredentials::m_accessKeyId), BehaviorValueSetter(&ClientAuthAWSCredentials::m_accessKeyId)) + ->Property("AWSSecretKey", BehaviorValueGetter(&ClientAuthAWSCredentials::m_secretKey), BehaviorValueSetter(&ClientAuthAWSCredentials::m_secretKey)) + ->Property("AWSSessionToken", BehaviorValueGetter(&ClientAuthAWSCredentials::m_sessionToken), BehaviorValueSetter(&ClientAuthAWSCredentials::m_sessionToken)); + } + } + private: AZStd::string m_accessKeyId; AZStd::string m_secretKey; diff --git a/Gems/AWSClientAuth/Code/Include/Public/UserManagement/AWSCognitoUserManagementBus.h b/Gems/AWSClientAuth/Code/Include/Public/UserManagement/AWSCognitoUserManagementBus.h index 89ddf0a999..aff68db365 100644 --- a/Gems/AWSClientAuth/Code/Include/Public/UserManagement/AWSCognitoUserManagementBus.h +++ b/Gems/AWSClientAuth/Code/Include/Public/UserManagement/AWSCognitoUserManagementBus.h @@ -22,11 +22,12 @@ namespace AWSClientAuth public: AZ_TYPE_INFO(IAWSCognitoUserManagementRequests, "{A4C90F21-7056-4827-8C6B-401E6945697D}"); - //! Initialize Cognito User pool. + //! Initialize Cognito User pool using settings from resource mappings. //! @param settingsRegistryPath settingsRegistryPath Path for the settings registry file to use. virtual bool Initialize() = 0; // Requests interface + //! Cognito user pool email sign up start. //! @param username User name to use for sign up. //! @param password Password to use for sign up. @@ -59,7 +60,7 @@ namespace AWSClientAuth virtual void EnableMFAAsync(const AZStd::string& accessToken) = 0; }; - //! Manages various authentication provider implementations and implements AuthenticationProvider Request bus. + //! Implements AWS Cognito user pool user management requests. class AWSCognitoUserManagementRequests : public AZ::EBusTraits { diff --git a/Gems/AWSClientAuth/Code/Source/AWSClientAuthSystemComponent.cpp b/Gems/AWSClientAuth/Code/Source/AWSClientAuthSystemComponent.cpp index 20efa354cc..008d56da0b 100644 --- a/Gems/AWSClientAuth/Code/Source/AWSClientAuthSystemComponent.cpp +++ b/Gems/AWSClientAuth/Code/Source/AWSClientAuthSystemComponent.cpp @@ -22,6 +22,11 @@ #include #include +namespace AZ +{ + AZ_TYPE_INFO_SPECIALIZE(AWSClientAuth::ProviderNameEnum, "{FB34B23A-B249-47A2-B1F1-C05284B50CCC}"); +} + namespace AWSClientAuth { constexpr char SerializeComponentName[] = "AWSClientAuth"; @@ -44,20 +49,35 @@ namespace AWSClientAuth AWSClientAuth::GoogleProviderSetting::Reflect(*serialize); } + AWSClientAuth::AuthenticationTokens::Reflect(context); + AWSClientAuth::ClientAuthAWSCredentials::Reflect(context); + if (AZ::BehaviorContext* behaviorContext = azrtti_cast(context)) { - behaviorContext->EBus("AuthenticationProviderRequestBus") + behaviorContext->Enum<(int)ProviderNameEnum::None>("ProviderNameEnum_None") + ->Enum<(int)ProviderNameEnum::AWSCognitoIDP>("ProviderNameEnum_AWSCognitoIDP") + ->Enum<(int)ProviderNameEnum::LoginWithAmazon>("ProviderNameEnum_LoginWithAmazon") + ->Enum<(int)ProviderNameEnum::Google>("ProviderNameEnum_Google"); + + behaviorContext->EBus("AuthenticationProviderRequestBus") ->Attribute(AZ::Script::Attributes::Category, SerializeComponentName) - ->Event("Initialize", &AuthenticationProviderRequestBus::Events::Initialize) - ->Event("IsSignedIn", &AuthenticationProviderRequestBus::Events::IsSignedIn) - ->Event("GetAuthenticationTokens", &AuthenticationProviderRequestBus::Events::GetAuthenticationTokens) + ->Event("Initialize", &AuthenticationProviderScriptCanvasRequestBus::Events::Initialize) + ->Event("IsSignedIn", &AuthenticationProviderScriptCanvasRequestBus::Events::IsSignedIn) + ->Event("GetAuthenticationTokens", &AuthenticationProviderScriptCanvasRequestBus::Events::GetAuthenticationTokens) ->Event( - "PasswordGrantSingleFactorSignInAsync", &AuthenticationProviderRequestBus::Events::PasswordGrantSingleFactorSignInAsync) - ->Event("DeviceCodeGrantSignInAsync", &AuthenticationProviderRequestBus::Events::DeviceCodeGrantSignInAsync) - ->Event("DeviceCodeGrantConfirmSignInAsync", &AuthenticationProviderRequestBus::Events::DeviceCodeGrantConfirmSignInAsync) - ->Event("RefreshTokensAsync", &AuthenticationProviderRequestBus::Events::RefreshTokensAsync) - ->Event("GetTokensWithRefreshAsync", &AuthenticationProviderRequestBus::Events::GetTokensWithRefreshAsync) - ->Event("SignOut", &AuthenticationProviderRequestBus::Events::SignOut); + "PasswordGrantSingleFactorSignInAsync", + &AuthenticationProviderScriptCanvasRequestBus::Events::PasswordGrantSingleFactorSignInAsync) + ->Event( + "PasswordGrantMultiFactorSignInAsync", + &AuthenticationProviderScriptCanvasRequestBus::Events::PasswordGrantMultiFactorSignInAsync) + ->Event( + "PasswordGrantMultiFactorConfirmSignInAsync", + &AuthenticationProviderScriptCanvasRequestBus::Events::PasswordGrantMultiFactorConfirmSignInAsync) + ->Event("DeviceCodeGrantSignInAsync", &AuthenticationProviderScriptCanvasRequestBus::Events::DeviceCodeGrantSignInAsync) + ->Event("DeviceCodeGrantConfirmSignInAsync", &AuthenticationProviderScriptCanvasRequestBus::Events::DeviceCodeGrantConfirmSignInAsync) + ->Event("RefreshTokensAsync", &AuthenticationProviderScriptCanvasRequestBus::Events::RefreshTokensAsync) + ->Event("GetTokensWithRefreshAsync", &AuthenticationProviderScriptCanvasRequestBus::Events::GetTokensWithRefreshAsync) + ->Event("SignOut", &AuthenticationProviderScriptCanvasRequestBus::Events::SignOut); behaviorContext->EBus("AWSCognitoAuthorizationRequestBus") ->Attribute(AZ::Script::Attributes::Category, SerializeComponentName) @@ -77,11 +97,15 @@ namespace AWSClientAuth ->Event("ConfirmForgotPasswordAsync", &AWSCognitoUserManagementRequestBus::Events::ConfirmForgotPasswordAsync) ->Event("EnableMFAAsync", &AWSCognitoUserManagementRequestBus::Events::EnableMFAAsync); + behaviorContext->EBus("AuthenticationProviderNotificationBus") + ->Attribute(AZ::Script::Attributes::Category, SerializeComponentName) ->Handler(); behaviorContext->EBus("AWSCognitoUserManagementNotificationBus") + ->Attribute(AZ::Script::Attributes::Category, SerializeComponentName) ->Handler(); behaviorContext->EBus("AWSCognitoAuthorizationNotificationBus") + ->Attribute(AZ::Script::Attributes::Category, SerializeComponentName) ->Handler(); } } diff --git a/Gems/AWSClientAuth/Code/Source/Authentication/AWSCognitoAuthenticationProvider.cpp b/Gems/AWSClientAuth/Code/Source/Authentication/AWSCognitoAuthenticationProvider.cpp index eca5ba22c2..74865c0044 100644 --- a/Gems/AWSClientAuth/Code/Source/Authentication/AWSCognitoAuthenticationProvider.cpp +++ b/Gems/AWSClientAuth/Code/Source/Authentication/AWSCognitoAuthenticationProvider.cpp @@ -40,7 +40,7 @@ namespace AWSClientAuth AZ_UNUSED(settingsRegistry); AWSCore::AWSResourceMappingRequestBus::BroadcastResult( m_cognitoAppClientId, &AWSCore::AWSResourceMappingRequests::GetResourceNameId, CognitoAppClientIdResourceMappingKey); - AZ_Warning("AWSCognitoAuthenticationProvider", m_cognitoAppClientId.empty(), "Missing Cognito App Client Id from resource mappings. Calls to Cognito will fail."); + AZ_Warning("AWSCognitoAuthenticationProvider", !m_cognitoAppClientId.empty(), "Missing Cognito App Client Id from resource mappings. Calls to Cognito will fail."); return !m_cognitoAppClientId.empty(); } diff --git a/Gems/AWSClientAuth/Code/Source/Authentication/AuthenticationProviderManager.cpp b/Gems/AWSClientAuth/Code/Source/Authentication/AuthenticationProviderManager.cpp index 76d7c45c71..d4d2d0d67b 100644 --- a/Gems/AWSClientAuth/Code/Source/Authentication/AuthenticationProviderManager.cpp +++ b/Gems/AWSClientAuth/Code/Source/Authentication/AuthenticationProviderManager.cpp @@ -12,6 +12,7 @@ #include #include +#include #include #include @@ -25,12 +26,14 @@ namespace AWSClientAuth { AZ::Interface::Register(this); AuthenticationProviderRequestBus::Handler::BusConnect(); + AuthenticationProviderScriptCanvasRequestBus::Handler::BusConnect(); } AuthenticationProviderManager::~AuthenticationProviderManager() { ResetProviders(); m_settingsRegistry.reset(); + AuthenticationProviderScriptCanvasRequestBus::Handler::BusDisconnect(); AuthenticationProviderRequestBus::Handler::BusDisconnect(); AZ::Interface::Unregister(this); } @@ -38,12 +41,19 @@ namespace AWSClientAuth bool AuthenticationProviderManager::Initialize(const AZStd::vector& providerNames, const AZStd::string& settingsRegistryPath) { ResetProviders(); + AZ::IO::FileIOBase* fileIO = AZ::IO::FileIOBase::GetInstance(); + AZ_Assert(fileIO, "File IO is not initialized."); + m_settingsRegistry.reset(); m_settingsRegistry = AZStd::make_shared(); - if (!m_settingsRegistry->MergeSettingsFile(settingsRegistryPath, AZ::SettingsRegistryInterface::Format::JsonMergePatch)) + AZStd::array resolvedPath{}; + fileIO->ResolvePath(settingsRegistryPath.data(), resolvedPath.data(), resolvedPath.size()); + + + if (!m_settingsRegistry->MergeSettingsFile(resolvedPath.data(), AZ::SettingsRegistryInterface::Format::JsonMergePatch)) { - AZ_Error("AuthenticationProviderManager", true, "Error merging settings registry for path: %s", settingsRegistryPath.c_str()); + AZ_Error("AuthenticationProviderManager", true, "Error merging settings registry for path: %s", resolvedPath.data()); return false; } @@ -112,6 +122,7 @@ namespace AWSClientAuth { AuthenticationProviderNotificationBus::Broadcast(&AuthenticationProviderNotifications::OnRefreshTokensFail , "Provider is not initialized"); + return; } AuthenticationTokens tokens = m_authenticationProvidersMap[providerName]->GetAuthenticationTokens(); @@ -181,5 +192,77 @@ namespace AWSClientAuth } } + ProviderNameEnum AuthenticationProviderManager::GetProviderNameEnum(AZStd::string name) + { + auto enumValue = ProviderNameEnumNamespace::FromStringToProviderNameEnum(name); + if (enumValue.has_value()) + { + return enumValue.value(); + } + AZ_Warning("AuthenticationProviderManager", true, "Incorrect string value for enum: %s", name.c_str()); + return ProviderNameEnum::None; + } + + bool AuthenticationProviderManager::Initialize( + const AZStd::vector& providerNames, const AZStd::string& settingsRegistryPath) + { + AZStd::vector providerNamesEnum; + for (auto name : providerNames) + { + providerNamesEnum.push_back(GetProviderNameEnum(name)); + } + return Initialize(providerNamesEnum, settingsRegistryPath); + } + + void AuthenticationProviderManager::PasswordGrantSingleFactorSignInAsync(const AZStd::string& providerName, const AZStd::string& username, const AZStd::string& password) + { + PasswordGrantSingleFactorSignInAsync(GetProviderNameEnum(providerName), username, password); + } + + void AuthenticationProviderManager::PasswordGrantMultiFactorSignInAsync(const AZStd::string& providerName, const AZStd::string& username, const AZStd::string& password) + { + PasswordGrantMultiFactorSignInAsync(GetProviderNameEnum(providerName), username, password); + } + + void AuthenticationProviderManager::PasswordGrantMultiFactorConfirmSignInAsync(const AZStd::string& providerName, const AZStd::string& username, const AZStd::string& confirmationCode) + { + PasswordGrantMultiFactorConfirmSignInAsync(GetProviderNameEnum(providerName), username, confirmationCode); + } + + void AuthenticationProviderManager::DeviceCodeGrantSignInAsync(const AZStd::string& providerName) + { + DeviceCodeGrantSignInAsync(GetProviderNameEnum(providerName)); + } + + void AuthenticationProviderManager::DeviceCodeGrantConfirmSignInAsync(const AZStd::string& providerName) + { + DeviceCodeGrantConfirmSignInAsync(GetProviderNameEnum(providerName)); + } + + void AuthenticationProviderManager::RefreshTokensAsync(const AZStd::string& providerName) + { + RefreshTokensAsync(GetProviderNameEnum(providerName)); + } + + void AuthenticationProviderManager::GetTokensWithRefreshAsync(const AZStd::string& providerName) + { + GetTokensWithRefreshAsync(GetProviderNameEnum(providerName)); + } + + bool AuthenticationProviderManager::IsSignedIn(const AZStd::string& providerName) + { + return IsSignedIn(GetProviderNameEnum(providerName)); + } + + bool AuthenticationProviderManager::SignOut(const AZStd::string& providerName) + { + return SignOut(GetProviderNameEnum(providerName)); + } + + AuthenticationTokens AuthenticationProviderManager::GetAuthenticationTokens(const AZStd::string& providerName) + { + return GetAuthenticationTokens(GetProviderNameEnum(providerName)); + } + } // namespace AWSClientAuth diff --git a/Gems/AWSClientAuth/Code/Source/Authentication/AuthenticationTokens.cpp b/Gems/AWSClientAuth/Code/Source/Authentication/AuthenticationTokens.cpp index 9c078ad99c..737d6ae929 100644 --- a/Gems/AWSClientAuth/Code/Source/Authentication/AuthenticationTokens.cpp +++ b/Gems/AWSClientAuth/Code/Source/Authentication/AuthenticationTokens.cpp @@ -79,4 +79,30 @@ namespace AWSClientAuth { return m_tokensExpireTimeSeconds; } + + void AuthenticationTokens::Reflect(AZ::ReflectContext* context) + { + auto serializeContext = azrtti_cast(context); + if (serializeContext) + { + serializeContext->Class() + ->Field("AccessToken", &AuthenticationTokens::m_accessToken) + ->Field("OpenIdToken", &AuthenticationTokens::m_openIdToken) + ->Field("RefreshToken", &AuthenticationTokens::m_refreshToken); + } + + AZ::BehaviorContext* behaviorContext = azrtti_cast(context); + if (behaviorContext) + { + behaviorContext->Class() + ->Attribute(AZ::Script::Attributes::Category, "AWSClientAuth") + ->Attribute(AZ::Script::Attributes::Storage, AZ::Script::Attributes::StorageType::Value) + ->Attribute(AZ::Script::Attributes::Scope, AZ::Script::Attributes::ScopeFlags::Common) + ->Constructor() + ->Constructor() + ->Property("AccessToken", BehaviorValueGetter(&AuthenticationTokens::m_accessToken), BehaviorValueSetter(&AuthenticationTokens::m_accessToken)) + ->Property("OpenIdToken", BehaviorValueGetter(&AuthenticationTokens::m_openIdToken), BehaviorValueSetter(&AuthenticationTokens::m_accessToken)) + ->Property("RefreshToken", BehaviorValueGetter(&AuthenticationTokens::m_refreshToken), BehaviorValueSetter(&AuthenticationTokens::m_accessToken)); + } + } } // namespace AWSClientAuth diff --git a/Gems/AWSClientAuth/Code/Source/Authorization/AWSCognitoAuthorizationController.cpp b/Gems/AWSClientAuth/Code/Source/Authorization/AWSCognitoAuthorizationController.cpp index 4c10d968fc..5e2c07bdbb 100644 --- a/Gems/AWSClientAuth/Code/Source/Authorization/AWSCognitoAuthorizationController.cpp +++ b/Gems/AWSClientAuth/Code/Source/Authorization/AWSCognitoAuthorizationController.cpp @@ -71,15 +71,15 @@ namespace AWSClientAuth if (m_awsAccountId.empty() || m_cognitoIdentityPoolId.empty()) { - AZ_Warning("AWSCognitoUserManagementController", m_awsAccountId.empty(), "Missing AWS account id in resource mappings."); - AZ_Warning("AWSCognitoUserManagementController", m_cognitoIdentityPoolId.empty(), "Missing Cognito Identity pool id in resource mappings."); + 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; } AZStd::string userPoolId; AWSCore::AWSResourceMappingRequestBus::BroadcastResult( userPoolId, &AWSCore::AWSResourceMappingRequests::GetResourceNameId, CognitoUserPoolIdResourceMappingKey); - AZ_Warning("AWSCognitoUserManagementController", userPoolId.empty(), "Missing Cognito USer pool id in resource mappings. Cognito IDP authenticated identities will no work."); + AZ_Warning("AWSCognitoAuthorizationController", !userPoolId.empty(), "Missing Cognito User pool id in resource mappings. Cognito IDP authenticated identities will no work."); AZStd::string defaultRegion; AWSCore::AWSResourceMappingRequestBus::BroadcastResult( diff --git a/Gems/AWSClientAuth/Code/Source/UserManagement/AWSCognitoUserManagementController.cpp b/Gems/AWSClientAuth/Code/Source/UserManagement/AWSCognitoUserManagementController.cpp index 19d5d47d33..755b0e1f15 100644 --- a/Gems/AWSClientAuth/Code/Source/UserManagement/AWSCognitoUserManagementController.cpp +++ b/Gems/AWSClientAuth/Code/Source/UserManagement/AWSCognitoUserManagementController.cpp @@ -54,7 +54,7 @@ namespace AWSClientAuth AWSCore::AWSResourceMappingRequestBus::BroadcastResult( m_cognitoAppClientId, &AWSCore::AWSResourceMappingRequests::GetResourceNameId, CognitoAppClientIdResourceMappingKey); AZ_Warning( - "AWSCognitoUserManagementController", m_cognitoAppClientId.empty(), "Missing Cognito App Client Id from resource mappings. Calls to Cognito will fail."); + "AWSCognitoUserManagementController", !m_cognitoAppClientId.empty(), "Missing Cognito App Client Id from resource mappings. Calls to Cognito will fail."); return !m_cognitoAppClientId.empty(); } diff --git a/Gems/AWSClientAuth/Code/Tests/Authentication/AuthenticationProviderManagerMock.h b/Gems/AWSClientAuth/Code/Tests/Authentication/AuthenticationProviderManagerMock.h new file mode 100644 index 0000000000..e7b233c786 --- /dev/null +++ b/Gems/AWSClientAuth/Code/Tests/Authentication/AuthenticationProviderManagerMock.h @@ -0,0 +1,55 @@ +/* +* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or +* its licensors. +* +* For complete copyright and license terms please see the LICENSE at the root of this +* distribution (the "License"). All use of this software is governed by the License, +* or, if provided, by the license below or the license accompanying this file. Do not +* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* +*/ + +#pragma once + +#include +#include + +namespace AWSClientAuthUnitTest +{ + class AuthenticationProviderManagerLocalMock + : public AWSClientAuth::AuthenticationProviderManager + { + public: + using AWSClientAuth::AuthenticationProviderManager::DeviceCodeGrantConfirmSignInAsync; + using AWSClientAuth::AuthenticationProviderManager::DeviceCodeGrantSignInAsync; + using AWSClientAuth::AuthenticationProviderManager::GetAuthenticationTokens; + using AWSClientAuth::AuthenticationProviderManager::GetTokensWithRefreshAsync; + using AWSClientAuth::AuthenticationProviderManager::Initialize; + using AWSClientAuth::AuthenticationProviderManager::IsSignedIn; + using AWSClientAuth::AuthenticationProviderManager::m_authenticationProvidersMap; + using AWSClientAuth::AuthenticationProviderManager::PasswordGrantMultiFactorConfirmSignInAsync; + using AWSClientAuth::AuthenticationProviderManager::PasswordGrantMultiFactorSignInAsync; + using AWSClientAuth::AuthenticationProviderManager::PasswordGrantSingleFactorSignInAsync; + using AWSClientAuth::AuthenticationProviderManager::RefreshTokensAsync; + using AWSClientAuth::AuthenticationProviderManager::SignOut; + + AZStd::unique_ptr CreateAuthenticationProviderObjectMock( + const AWSClientAuth::ProviderNameEnum& providerName) + { + auto providerObject = AWSClientAuth::AuthenticationProviderManager::CreateAuthenticationProviderObject(providerName); + providerObject.reset(); + return AZStd::make_unique>(); + } + + AuthenticationProviderManagerLocalMock() + { + ON_CALL(*this, CreateAuthenticationProviderObject(testing::_)) + .WillByDefault(testing::Invoke(this, &AuthenticationProviderManagerLocalMock::CreateAuthenticationProviderObjectMock)); + } + + MOCK_METHOD1( + CreateAuthenticationProviderObject, + AZStd::unique_ptr(const AWSClientAuth::ProviderNameEnum&)); + }; +} // namespace AWSClientAuthUnitTest diff --git a/Gems/AWSClientAuth/Code/Tests/Authentication/AuthenticationProviderManagerScriptCanvasBusTest.cpp b/Gems/AWSClientAuth/Code/Tests/Authentication/AuthenticationProviderManagerScriptCanvasBusTest.cpp new file mode 100644 index 0000000000..7673840299 --- /dev/null +++ b/Gems/AWSClientAuth/Code/Tests/Authentication/AuthenticationProviderManagerScriptCanvasBusTest.cpp @@ -0,0 +1,261 @@ +/* +* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or +* its licensors. +* +* For complete copyright and license terms please see the LICENSE at the root of this +* distribution (the "License"). All use of this software is governed by the License, +* or, if provided, by the license below or the license accompanying this file. Do not +* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* +*/ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + +class AuthenticationProviderManagerScriptCanvasTest + : public AWSClientAuthUnitTest::AWSClientAuthGemAllocatorFixture +{ +protected: + void SetUp() override + { + AWSClientAuthUnitTest::AWSClientAuthGemAllocatorFixture::SetUp(); + + AWSClientAuth::LWAProviderSetting::Reflect(*m_serializeContext); + AWSClientAuth::GoogleProviderSetting::Reflect(*m_serializeContext); + + m_settingspath = AZStd::string::format("%s/%s/authenticationProvider.setreg", + m_testFolder->c_str(), AZ::SettingsRegistryInterface::RegistryFolder); + CreateTestFile("authenticationProvider.setreg" + , R"({ + "AWS": + { + "LoginWithAmazon": + { + "AppClientId": "TestLWAClientId", + "GrantType": "device_code", + "Scope": "profile", + "ResponseType": "device_code", + "OAuthCodeURL": "https://api.amazon.com/auth/o2/create/codepair", + "OAuthTokensURL": "https://oauth2.googleapis.com/token" + }, + "Google": + { + "AppClientId": "TestGoogleClientId", + "ClientSecret": "123", + "GrantType": "urn:ietf:params:oauth:grant-type:device_code", + "Scope": "profile", + "OAuthCodeURL": "https://oauth2.googleapis.com/device/code", + "OAuthTokensURL": "https://oauth2.googleapis.com/token" + } + } + })"); + + m_mockController = AZStd::make_unique>(); + } + + void TearDown() override + { + m_mockController.reset(); + AWSClientAuthUnitTest::AWSClientAuthGemAllocatorFixture::TearDown(); + } + +public: + AZStd::unique_ptr> m_mockController; + AZStd::string m_settingspath; + AZStd::vector m_enabledProviderNames { AWSClientAuth::ProvideNameEnumStringAWSCognitoIDP, + AWSClientAuth::ProvideNameEnumStringLoginWithAmazon, AWSClientAuth::ProvideNameEnumStringGoogle}; +}; + +TEST_F(AuthenticationProviderManagerScriptCanvasTest, Initialize_Success) +{ + ASSERT_TRUE(m_mockController->Initialize(m_enabledProviderNames, m_settingspath)); + ASSERT_TRUE(m_mockController->m_authenticationProvidersMap[AWSClientAuth::ProviderNameEnum::AWSCognitoIDP] != nullptr); +} + +TEST_F(AuthenticationProviderManagerScriptCanvasTest, PasswordGrantSingleFactorSignInAsync_Success) +{ + m_mockController->Initialize(m_enabledProviderNames, m_settingspath); + testing::NiceMock *cognitoProviderMock = (testing::NiceMock*)m_mockController->m_authenticationProvidersMap[AWSClientAuth::ProviderNameEnum::AWSCognitoIDP].get(); + + EXPECT_CALL(*cognitoProviderMock, PasswordGrantSingleFactorSignInAsync(testing::_, testing::_)).Times(1); + m_mockController->PasswordGrantSingleFactorSignInAsync(AWSClientAuth::ProvideNameEnumStringAWSCognitoIDP, AWSClientAuthUnitTest::TEST_USERNAME, AWSClientAuthUnitTest::TEST_PASSWORD); + cognitoProviderMock = nullptr; +} + +TEST_F(AuthenticationProviderManagerScriptCanvasTest, PasswordGrantSingleFactorSignInAsync_Fail_NonConfiguredProviderError) +{ + AZ_TEST_START_TRACE_SUPPRESSION; + m_mockController->PasswordGrantSingleFactorSignInAsync(AWSClientAuth::ProvideNameEnumStringApple, AWSClientAuthUnitTest::TEST_USERNAME, AWSClientAuthUnitTest::TEST_PASSWORD); + AZ_TEST_STOP_TRACE_SUPPRESSION(1); +} + +TEST_F(AuthenticationProviderManagerScriptCanvasTest, PasswordGrantMultiFactorSignInAsync_Success) +{ + m_mockController->Initialize(m_enabledProviderNames, m_settingspath); + testing::NiceMock* cognitoProviderMock = (testing::NiceMock*)m_mockController->m_authenticationProvidersMap[AWSClientAuth::ProviderNameEnum::AWSCognitoIDP].get(); + testing::NiceMock* lwaProviderMock = (testing::NiceMock*)m_mockController->m_authenticationProvidersMap[AWSClientAuth::ProviderNameEnum::LoginWithAmazon].get(); + + EXPECT_CALL(*cognitoProviderMock, PasswordGrantMultiFactorSignInAsync(testing::_, testing::_)).Times(1); + m_mockController->PasswordGrantMultiFactorSignInAsync(AWSClientAuth::ProvideNameEnumStringAWSCognitoIDP, AWSClientAuthUnitTest::TEST_USERNAME, AWSClientAuthUnitTest::TEST_PASSWORD); + + EXPECT_CALL(*lwaProviderMock, PasswordGrantMultiFactorSignInAsync(testing::_, testing::_)).Times(1); + m_mockController->PasswordGrantMultiFactorSignInAsync(AWSClientAuth::ProvideNameEnumStringLoginWithAmazon, AWSClientAuthUnitTest::TEST_USERNAME, AWSClientAuthUnitTest::TEST_PASSWORD); + + cognitoProviderMock = nullptr; +} + +TEST_F(AuthenticationProviderManagerScriptCanvasTest, PasswordGrantMultiFactorConfirmSignInAsync_Success) +{ + m_mockController->Initialize(m_enabledProviderNames, m_settingspath); + testing::NiceMock *cognitoProviderMock = (testing::NiceMock*)m_mockController->m_authenticationProvidersMap[AWSClientAuth::ProviderNameEnum::AWSCognitoIDP].get(); + testing::NiceMock *lwaProviderMock = (testing::NiceMock*)m_mockController->m_authenticationProvidersMap[AWSClientAuth::ProviderNameEnum::LoginWithAmazon].get(); + + EXPECT_CALL(*cognitoProviderMock, PasswordGrantMultiFactorConfirmSignInAsync(testing::_, testing::_)).Times(1); + m_mockController->PasswordGrantMultiFactorConfirmSignInAsync(AWSClientAuth::ProvideNameEnumStringAWSCognitoIDP, AWSClientAuthUnitTest::TEST_USERNAME, AWSClientAuthUnitTest::TEST_PASSWORD); + + EXPECT_CALL(*lwaProviderMock, PasswordGrantMultiFactorConfirmSignInAsync(testing::_, testing::_)).Times(1); + m_mockController->PasswordGrantMultiFactorConfirmSignInAsync(AWSClientAuth::ProvideNameEnumStringLoginWithAmazon, AWSClientAuthUnitTest::TEST_USERNAME, AWSClientAuthUnitTest::TEST_PASSWORD); + + cognitoProviderMock = nullptr; +} + +TEST_F(AuthenticationProviderManagerScriptCanvasTest, DeviceCodeGrantSignInAsync_Success) +{ + m_mockController->Initialize(m_enabledProviderNames, m_settingspath); + testing::NiceMock* cognitoProviderMock = (testing::NiceMock*)m_mockController->m_authenticationProvidersMap[AWSClientAuth::ProviderNameEnum::AWSCognitoIDP].get(); + testing::NiceMock* lwaProviderMock = (testing::NiceMock*)m_mockController->m_authenticationProvidersMap[AWSClientAuth::ProviderNameEnum::LoginWithAmazon].get(); + + EXPECT_CALL(*cognitoProviderMock, DeviceCodeGrantSignInAsync()).Times(1); + m_mockController->DeviceCodeGrantSignInAsync(AWSClientAuth::ProvideNameEnumStringAWSCognitoIDP); + + EXPECT_CALL(*lwaProviderMock, DeviceCodeGrantSignInAsync()).Times(1); + m_mockController->DeviceCodeGrantSignInAsync(AWSClientAuth::ProvideNameEnumStringLoginWithAmazon); + + cognitoProviderMock = nullptr; +} + + +TEST_F(AuthenticationProviderManagerScriptCanvasTest, DeviceCodeGrantConfirmSignInAsync_Success) +{ + m_mockController->Initialize(m_enabledProviderNames, m_settingspath); + testing::NiceMock* cognitoProviderMock = (testing::NiceMock*)m_mockController->m_authenticationProvidersMap[AWSClientAuth::ProviderNameEnum::AWSCognitoIDP].get(); + testing::NiceMock* lwaProviderMock = (testing::NiceMock*)m_mockController->m_authenticationProvidersMap[AWSClientAuth::ProviderNameEnum::LoginWithAmazon].get(); + + EXPECT_CALL(*cognitoProviderMock, DeviceCodeGrantConfirmSignInAsync()).Times(1); + m_mockController->DeviceCodeGrantConfirmSignInAsync(AWSClientAuth::ProvideNameEnumStringAWSCognitoIDP); + + EXPECT_CALL(*lwaProviderMock, DeviceCodeGrantConfirmSignInAsync()).Times(1); + m_mockController->DeviceCodeGrantConfirmSignInAsync(AWSClientAuth::ProvideNameEnumStringLoginWithAmazon); + + cognitoProviderMock = nullptr; +} + +TEST_F(AuthenticationProviderManagerScriptCanvasTest, RefreshTokenAsync_Success) +{ + m_mockController->Initialize(m_enabledProviderNames, m_settingspath); + testing::NiceMock *cognitoProviderMock = (testing::NiceMock*)m_mockController->m_authenticationProvidersMap[AWSClientAuth::ProviderNameEnum::AWSCognitoIDP].get(); + testing::NiceMock *lwaProviderMock = (testing::NiceMock*)m_mockController->m_authenticationProvidersMap[AWSClientAuth::ProviderNameEnum::LoginWithAmazon].get(); + + EXPECT_CALL(*cognitoProviderMock, RefreshTokensAsync()).Times(1); + m_mockController->RefreshTokensAsync(AWSClientAuth::ProvideNameEnumStringAWSCognitoIDP); + + EXPECT_CALL(*lwaProviderMock, RefreshTokensAsync()).Times(1); + m_mockController->RefreshTokensAsync(AWSClientAuth::ProvideNameEnumStringLoginWithAmazon); + + cognitoProviderMock = nullptr; +} + +TEST_F(AuthenticationProviderManagerScriptCanvasTest, GetTokensWithRefreshAsync_ValidToken_Success) +{ + m_mockController->Initialize(m_enabledProviderNames, m_settingspath); + testing::NiceMock* cognitoProviderMock = (testing::NiceMock*)m_mockController->m_authenticationProvidersMap[AWSClientAuth::ProviderNameEnum::AWSCognitoIDP].get(); + + AWSClientAuth::AuthenticationTokens tokens( + AWSClientAuthUnitTest::TEST_TOKEN, AWSClientAuthUnitTest::TEST_TOKEN, AWSClientAuthUnitTest::TEST_TOKEN, + AWSClientAuth::ProviderNameEnum::AWSCognitoIDP, 600); + EXPECT_CALL(*cognitoProviderMock, GetAuthenticationTokens()).Times(1).WillOnce(testing::Return(tokens)); + EXPECT_CALL(*cognitoProviderMock, RefreshTokensAsync()).Times(0); + EXPECT_CALL(m_authenticationProviderNotificationsBusMock, OnRefreshTokensSuccess(testing::_)).Times(1); + m_mockController->GetTokensWithRefreshAsync(AWSClientAuth::ProvideNameEnumStringAWSCognitoIDP); + + cognitoProviderMock = nullptr; +} + +TEST_F(AuthenticationProviderManagerScriptCanvasTest, GetTokensWithRefreshAsync_InvalidToken_Success) +{ + m_mockController->Initialize(m_enabledProviderNames, m_settingspath); + testing::NiceMock* cognitoProviderMock = (testing::NiceMock*)m_mockController->m_authenticationProvidersMap[AWSClientAuth::ProviderNameEnum::AWSCognitoIDP].get(); + AWSClientAuth::AuthenticationTokens tokens; + EXPECT_CALL(*cognitoProviderMock, GetAuthenticationTokens()).Times(1).WillOnce(testing::Return(tokens)); + EXPECT_CALL(*cognitoProviderMock, RefreshTokensAsync()).Times(1); + m_mockController->GetTokensWithRefreshAsync(AWSClientAuth::ProvideNameEnumStringAWSCognitoIDP); + + cognitoProviderMock = nullptr; +} + +TEST_F(AuthenticationProviderManagerScriptCanvasTest, GetTokensWithRefreshAsync_NotInitializedProvider_Fail) +{ + AZ_TEST_START_TRACE_SUPPRESSION; + EXPECT_CALL(m_authenticationProviderNotificationsBusMock, OnRefreshTokensSuccess(testing::_)).Times(0); + EXPECT_CALL(m_authenticationProviderNotificationsBusMock, OnRefreshTokensFail(testing::_)).Times(1); + m_mockController->GetTokensWithRefreshAsync(AWSClientAuth::ProvideNameEnumStringAWSCognitoIDP); + AZ_TEST_STOP_TRACE_SUPPRESSION(1); +} + +TEST_F(AuthenticationProviderManagerScriptCanvasTest, GetTokens_Success) +{ + m_mockController->Initialize(m_enabledProviderNames, m_settingspath); + testing::NiceMock* cognitoProviderMock = (testing::NiceMock*)m_mockController->m_authenticationProvidersMap[AWSClientAuth::ProviderNameEnum::AWSCognitoIDP].get(); + + AWSClientAuth::AuthenticationTokens tokens( + AWSClientAuthUnitTest::TEST_TOKEN, AWSClientAuthUnitTest::TEST_TOKEN, AWSClientAuthUnitTest::TEST_TOKEN, + AWSClientAuth::ProviderNameEnum::AWSCognitoIDP, 60); + + EXPECT_CALL(*cognitoProviderMock, GetAuthenticationTokens()).Times(1).WillOnce(testing::Return(tokens)); + m_mockController->GetAuthenticationTokens(AWSClientAuth::ProvideNameEnumStringAWSCognitoIDP); + + cognitoProviderMock = nullptr; +} + +TEST_F(AuthenticationProviderManagerScriptCanvasTest, IsSignedIn_Success) +{ + m_mockController->Initialize(m_enabledProviderNames, m_settingspath); + testing::NiceMock* cognitoProviderMock = (testing::NiceMock*)m_mockController->m_authenticationProvidersMap[AWSClientAuth::ProviderNameEnum::AWSCognitoIDP].get(); + + AWSClientAuth::AuthenticationTokens tokens( + AWSClientAuthUnitTest::TEST_TOKEN, AWSClientAuthUnitTest::TEST_TOKEN, AWSClientAuthUnitTest::TEST_TOKEN, + AWSClientAuth::ProviderNameEnum::AWSCognitoIDP, 60); + EXPECT_CALL(*cognitoProviderMock, GetAuthenticationTokens()).Times(1).WillOnce(testing::Return(tokens)); + m_mockController->IsSignedIn(AWSClientAuth::ProvideNameEnumStringAWSCognitoIDP); + + cognitoProviderMock = nullptr; +} + +TEST_F(AuthenticationProviderManagerScriptCanvasTest, SignOut_Success) +{ + m_mockController->Initialize(m_enabledProviderNames, m_settingspath); + testing::NiceMock* googleProviderMock = (testing::NiceMock*)m_mockController->m_authenticationProvidersMap[AWSClientAuth::ProviderNameEnum::Google].get(); + + EXPECT_CALL(*googleProviderMock, SignOut()).Times(1); + EXPECT_CALL(m_authenticationProviderNotificationsBusMock, OnSignOut(testing::_)).Times(1); + m_mockController->SignOut(AWSClientAuth::ProvideNameEnumStringGoogle); + + googleProviderMock = nullptr; +} + +TEST_F(AuthenticationProviderManagerScriptCanvasTest, Initialize_Fail_InvalidPath) +{ + AZ_TEST_START_TRACE_SUPPRESSION; + ASSERT_FALSE(m_mockController->Initialize(m_enabledProviderNames, "")); + AZ_TEST_STOP_TRACE_SUPPRESSION(1); +} diff --git a/Gems/AWSClientAuth/Code/Tests/Authentication/AuthenticationProviderManagerTest.cpp b/Gems/AWSClientAuth/Code/Tests/Authentication/AuthenticationProviderManagerTest.cpp index 9e7d189f5d..4b5bdfb841 100644 --- a/Gems/AWSClientAuth/Code/Tests/Authentication/AuthenticationProviderManagerTest.cpp +++ b/Gems/AWSClientAuth/Code/Tests/Authentication/AuthenticationProviderManagerTest.cpp @@ -10,8 +10,6 @@ * */ -#include -#include #include #include #include @@ -20,42 +18,7 @@ #include #include #include - -namespace AWSClientAuthUnitTest -{ - class AuthenticationProviderManagerLocalMock - : public AWSClientAuth::AuthenticationProviderManager - { - public: - using AWSClientAuth::AuthenticationProviderManager::m_authenticationProvidersMap; - using AWSClientAuth::AuthenticationProviderManager::Initialize; - using AWSClientAuth::AuthenticationProviderManager::PasswordGrantSingleFactorSignInAsync; - using AWSClientAuth::AuthenticationProviderManager::PasswordGrantMultiFactorSignInAsync; - using AWSClientAuth::AuthenticationProviderManager::PasswordGrantMultiFactorConfirmSignInAsync; - using AWSClientAuth::AuthenticationProviderManager::DeviceCodeGrantSignInAsync; - using AWSClientAuth::AuthenticationProviderManager::DeviceCodeGrantConfirmSignInAsync; - using AWSClientAuth::AuthenticationProviderManager::RefreshTokensAsync; - using AWSClientAuth::AuthenticationProviderManager::GetTokensWithRefreshAsync; - using AWSClientAuth::AuthenticationProviderManager::GetAuthenticationTokens; - using AWSClientAuth::AuthenticationProviderManager::SignOut; - using AWSClientAuth::AuthenticationProviderManager::IsSignedIn; - - AZStd::unique_ptr CreateAuthenticationProviderObjectMock(const AWSClientAuth::ProviderNameEnum& providerName) - { - auto providerObject = AWSClientAuth::AuthenticationProviderManager::CreateAuthenticationProviderObject(providerName); - providerObject.reset(); - return AZStd::make_unique>(); - } - - AuthenticationProviderManagerLocalMock() - { - ON_CALL(*this, CreateAuthenticationProviderObject(testing::_)).WillByDefault( - testing::Invoke(this, &AuthenticationProviderManagerLocalMock::CreateAuthenticationProviderObjectMock)); - } - - MOCK_METHOD1(CreateAuthenticationProviderObject, AZStd::unique_ptr(const AWSClientAuth::ProviderNameEnum&)); - }; -} +#include class AuthenticationProviderManagerTest @@ -239,6 +202,15 @@ TEST_F(AuthenticationProviderManagerTest, GetTokensWithRefreshAsync_InvalidToken cognitoProviderMock = nullptr; } +TEST_F(AuthenticationProviderManagerTest, GetTokensWithRefreshAsync_NotInitializedProvider_Fail) +{ + AZ_TEST_START_TRACE_SUPPRESSION; + EXPECT_CALL(m_authenticationProviderNotificationsBusMock, OnRefreshTokensSuccess(testing::_)).Times(0); + EXPECT_CALL(m_authenticationProviderNotificationsBusMock, OnRefreshTokensFail(testing::_)).Times(1); + m_mockController->GetTokensWithRefreshAsync(AWSClientAuth::ProviderNameEnum::AWSCognitoIDP); + AZ_TEST_STOP_TRACE_SUPPRESSION(1); +} + TEST_F(AuthenticationProviderManagerTest, GetTokens_Success) { m_mockController->Initialize(m_enabledProviderNames, m_settingspath); diff --git a/Gems/AWSClientAuth/Code/awsclientauth_files.cmake b/Gems/AWSClientAuth/Code/awsclientauth_files.cmake index 79da00076c..7e4734992f 100644 --- a/Gems/AWSClientAuth/Code/awsclientauth_files.cmake +++ b/Gems/AWSClientAuth/Code/awsclientauth_files.cmake @@ -20,6 +20,7 @@ set(FILES Include/Private/AWSClientAuthBus.h Include/Private/AWSClientAuthResourceMappingConstants.h Include/Private/Authentication/AuthenticationProviderTypes.h + Include/Private/Authentication/AuthenticationProviderScriptCanvasBus.h Include/Private/Authentication/AuthenticationProviderManager.h Include/Private/Authentication/AuthenticationNotificationBusBehaviorHandler.h diff --git a/Gems/AWSClientAuth/Code/awsclientauth_test_files.cmake b/Gems/AWSClientAuth/Code/awsclientauth_test_files.cmake index 6d3de7cc54..18aaa697dd 100644 --- a/Gems/AWSClientAuth/Code/awsclientauth_test_files.cmake +++ b/Gems/AWSClientAuth/Code/awsclientauth_test_files.cmake @@ -14,7 +14,9 @@ set(FILES Tests/AWSClientAuthGemTest.cpp Tests/AWSClientAuthSystemComponentTest.cpp + Tests/Authentication/AuthenticationProviderManagerMock.h Tests/Authentication/AuthenticationProviderManagerTest.cpp + Tests/Authentication/AuthenticationProviderManagerScriptCanvasBusTest.cpp Tests/Authentication/AWSCognitoAuthenticationProviderTest.cpp Tests/Authentication/LWAAuthenticationProviderTest.cpp Tests/Authentication/GoogleAuthenticationProviderTest.cpp diff --git a/Gems/AWSClientAuth/cdk/auth/cognito_identity_pool_role.py b/Gems/AWSClientAuth/cdk/auth/cognito_identity_pool_role.py index 0ebef83eba..3a2e413617 100755 --- a/Gems/AWSClientAuth/cdk/auth/cognito_identity_pool_role.py +++ b/Gems/AWSClientAuth/cdk/auth/cognito_identity_pool_role.py @@ -56,8 +56,7 @@ class CognitoIdentityPoolRole: # basic permissions stack_statement = iam.PolicyStatement( actions=[ - 's3:Get*', - 's3:List*' + 's3:ListBuckets' ], effect=iam.Effect.ALLOW, resources=[ diff --git a/Gems/Atom/Asset/Shader/Code/Source/Editor/ShaderVariantAssetBuilder.cpp b/Gems/Atom/Asset/Shader/Code/Source/Editor/ShaderVariantAssetBuilder.cpp index 034d0c7cf2..3572fb72ae 100644 --- a/Gems/Atom/Asset/Shader/Code/Source/Editor/ShaderVariantAssetBuilder.cpp +++ b/Gems/Atom/Asset/Shader/Code/Source/Editor/ShaderVariantAssetBuilder.cpp @@ -162,7 +162,7 @@ namespace AZ AZStd::string expectedHigherPrecedenceFileFullPath; AzFramework::StringFunc::Path::Join(gameProjectPath, RPI::ShaderVariantTreeAsset::CommonSubFolder, expectedHigherPrecedenceFileFullPath, false /* handle directory overlap? */, false /* be case insensitive? */); AzFramework::StringFunc::Path::Join(expectedHigherPrecedenceFileFullPath.c_str(), shaderProductFileRelativePath.c_str(), expectedHigherPrecedenceFileFullPath, false /* handle directory overlap? */, false /* be case insensitive? */); - AzFramework::StringFunc::Path::ReplaceExtension(expectedHigherPrecedenceFileFullPath, AZ::RPI::ShaderVariantAsset::Extension); + AzFramework::StringFunc::Path::ReplaceExtension(expectedHigherPrecedenceFileFullPath, AZ::RPI::ShaderVariantListSourceData::Extension); AzFramework::StringFunc::Path::Normalize(expectedHigherPrecedenceFileFullPath); AZStd::string normalizedShaderVariantListFileFullPath = shaderVariantListFileFullPath; @@ -407,17 +407,20 @@ namespace AZ const auto& jobParameters = request.m_jobDescription.m_jobParameters; if (jobParameters.find(ShaderVariantLoadErrorParam) != jobParameters.end()) { - if (jobParameters.find(ShouldExitEarlyFromProcessJobParam) != jobParameters.end()) - { - AZ_TracePrintf(ShaderVariantAssetBuilderName, "Doing nothing on behalf of [%s] because it's been overriden by game project.", jobParameters.at(ShaderVariantLoadErrorParam).c_str()); - response.m_resultCode = AssetBuilderSDK::ProcessJobResult_Success; - return; - } AZ_Error(ShaderVariantAssetBuilderName, false, "Error during CreateJobs: %s", jobParameters.at(ShaderVariantLoadErrorParam).c_str()); response.m_resultCode = AssetBuilderSDK::ProcessJobResult_Failed; return; } + if (jobParameters.find(ShouldExitEarlyFromProcessJobParam) != jobParameters.end()) + { + AZ_TracePrintf( + ShaderVariantAssetBuilderName, "Doing nothing on behalf of [%s] because it's been overriden by game project.", + jobParameters.at(ShaderVariantLoadErrorParam).c_str()); + response.m_resultCode = AssetBuilderSDK::ProcessJobResult_Success; + return; + } + AssetBuilderSDK::JobCancelListener jobCancelListener(request.m_jobId); if (jobCancelListener.IsCancelled()) { diff --git a/Gems/Atom/Tools/MaterialEditor/Assets/MaterialEditor/Materials/basic_grey.material b/Gems/Atom/Feature/Common/Assets/Materials/basic_grey.material similarity index 100% rename from Gems/Atom/Tools/MaterialEditor/Assets/MaterialEditor/Materials/basic_grey.material rename to Gems/Atom/Feature/Common/Assets/Materials/basic_grey.material diff --git a/Gems/Atom/Feature/Common/Assets/Passes/EnvironmentCubeMapForwardMSAA.pass b/Gems/Atom/Feature/Common/Assets/Passes/EnvironmentCubeMapForwardMSAA.pass index 60de5e10b9..aa422aa227 100644 --- a/Gems/Atom/Feature/Common/Assets/Passes/EnvironmentCubeMapForwardMSAA.pass +++ b/Gems/Atom/Feature/Common/Assets/Passes/EnvironmentCubeMapForwardMSAA.pass @@ -49,11 +49,6 @@ "IsArray": 1 } }, - { - "Name": "DepthStencilInputOutput", - "SlotType": "InputOutput", - "ScopeAttachmentUsage": "DepthStencil" - }, { "Name": "TileLightData", "SlotType": "Input", @@ -66,6 +61,13 @@ "ShaderInputName": "m_lightListRemapped", "ScopeAttachmentUsage": "Shader" }, + // Input/Outputs... + { + "Name": "DepthStencilInputOutput", + "SlotType": "InputOutput", + "ScopeAttachmentUsage": "DepthStencil" + }, + // Outputs... { "Name": "DiffuseOutput", "SlotType": "Output", @@ -222,11 +224,12 @@ "Attachment": "Output" } }, + "MultisampleSource": { + "Pass": "This", + "Attachment": "DepthStencilInputOutput" + }, "ImageDescriptor": { "Format": "R8G8B8A8_UNORM", - "MultisampleState": { - "samples": 4 - }, "SharedQueueMask": "Graphics" } }, diff --git a/Gems/Atom/Feature/Common/Assets/Passes/EnvironmentCubeMapPipeline.pass b/Gems/Atom/Feature/Common/Assets/Passes/EnvironmentCubeMapPipeline.pass index 79a42b11f7..0e2fb93359 100644 --- a/Gems/Atom/Feature/Common/Assets/Passes/EnvironmentCubeMapPipeline.pass +++ b/Gems/Atom/Feature/Common/Assets/Passes/EnvironmentCubeMapPipeline.pass @@ -9,7 +9,8 @@ "Slots": [ { "Name": "Output", - "SlotType": 2 + "SlotType": "InputOutput", + "ScopeAttachmentUsage": "RenderTarget" } ], "PassRequests": [ @@ -101,13 +102,8 @@ ] }, { - "Name": "DepthMSAAPass", - "TemplateName": "EnvironmentCubeMapDepthMSAAPassTemplate", - "PassData": { - "$type": "RasterPassData", - "DrawListTag": "depth", - "PipelineViewTag": "MainCamera" - }, + "Name": "DepthPrePass", + "TemplateName": "DepthMSAAParentTemplate", "Connections": [ { "LocalSlot": "SkinnedMeshes", @@ -115,70 +111,11 @@ "Pass": "SkinningPass", "Attachment": "SkinnedMeshOutputStream" } - } - ] - }, - // The light culling system can do highly accurate culling of transparent objects but it needs - // more depth information than the opaque geometry pass can provide - // Specifically the minimum and maximum depth of transparent objects - { - "Name": "DepthTransparentMinPass", - "TemplateName": "DepthPassTemplate", - "PassData": { - "$type": "RasterPassData", - "DrawListTag": "depthTransparentMin", - "PipelineViewTag": "MainCamera" - }, - "Connections": [ - { - "LocalSlot": "SkinnedMeshes", - "AttachmentRef": { - "Pass": "SkinningPass", - "Attachment": "SkinnedMeshOutputStream" - } - } - ] - }, - { - "Name": "DepthTransparentMaxPass", - "TemplateName": "DepthMaxPassTemplate", - "PassData": { - "$type": "RasterPassData", - "DrawListTag": "depthTransparentMax", - "PipelineViewTag": "MainCamera" - }, - "Connections": [ - { - "LocalSlot": "SkinnedMeshes", - "AttachmentRef": { - "Pass": "SkinningPass", - "Attachment": "SkinnedMeshOutputStream" - } - } - ] - }, - { - "Name": "LightCullingTilePreparePass", - "TemplateName": "LightCullingTilePrepareMSAATemplate", - "Connections": [ - { - "LocalSlot": "Depth", - "AttachmentRef": { - "Pass": "DepthMSAAPass", - "Attachment": "Output" - } }, { - "LocalSlot": "DepthTransparentMin", + "LocalSlot": "SwapChainOutput", "AttachmentRef": { - "Pass": "DepthTransparentMinPass", - "Attachment": "Output" - } - }, - { - "LocalSlot": "DepthTransparentMax", - "AttachmentRef": { - "Pass": "DepthTransparentMaxPass", + "Pass": "Parent", "Attachment": "Output" } } @@ -186,40 +123,27 @@ }, { "Name": "LightCullingPass", - "TemplateName": "LightCullingTemplate", + "TemplateName": "LightCullingParentTemplate", "Connections": [ { - "LocalSlot": "TileLightData", + "LocalSlot": "SkinnedMeshes", "AttachmentRef": { - "Pass": "LightCullingTilePreparePass", - "Attachment": "TileLightData" - } - } - ] - }, - { - "Name": "LightCullingRemapPass", - "TemplateName": "LightCullingRemapTemplate", - "Connections": [ - { - "LocalSlot": "TileLightData", - "AttachmentRef": { - "Pass": "LightCullingTilePreparePass", - "Attachment": "TileLightData" + "Pass": "SkinningPass", + "Attachment": "SkinnedMeshOutputStream" } }, { - "LocalSlot": "LightCount", + "LocalSlot": "DepthMSAA", "AttachmentRef": { - "Pass": "LightCullingPass", - "Attachment": "LightCount" + "Pass": "DepthPrePass", + "Attachment": "DepthMSAA" } }, { - "LocalSlot": "LightList", + "LocalSlot": "SwapChainOutput", "AttachmentRef": { - "Pass": "LightCullingPass", - "Attachment": "LightList" + "Pass": "Parent", + "Attachment": "Output" } } ] @@ -259,21 +183,21 @@ { "LocalSlot": "DepthStencilInputOutput", "AttachmentRef": { - "Pass": "DepthMSAAPass", - "Attachment": "Output" + "Pass": "DepthPrePass", + "Attachment": "DepthMSAA" } }, { "LocalSlot": "TileLightData", "AttachmentRef": { - "Pass": "LightCullingRemapPass", + "Pass": "LightCullingPass", "Attachment": "TileLightData" } }, { "LocalSlot": "LightListRemapped", "AttachmentRef": { - "Pass": "LightCullingRemapPass", + "Pass": "LightCullingPass", "Attachment": "LightListRemapped" } } diff --git a/Gems/Atom/Feature/Common/Assets/Passes/EnvironmentCubeMapSkyBox.pass b/Gems/Atom/Feature/Common/Assets/Passes/EnvironmentCubeMapSkyBox.pass index b16cd1cbcc..4c74f9e967 100644 --- a/Gems/Atom/Feature/Common/Assets/Passes/EnvironmentCubeMapSkyBox.pass +++ b/Gems/Atom/Feature/Common/Assets/Passes/EnvironmentCubeMapSkyBox.pass @@ -32,11 +32,12 @@ "Attachment": "SpecularInputOutput" } }, + "MultisampleSource": { + "Pass": "This", + "Attachment": "SpecularInputOutput" + }, "ImageDescriptor": { "Format": "R16G16B16A16_FLOAT", - "MultisampleState": { - "samples": 4 - }, "SharedQueueMask": "Graphics" } } diff --git a/Gems/Atom/Feature/Common/Code/Include/Atom/Feature/Mesh/MeshFeatureProcessor.h b/Gems/Atom/Feature/Common/Code/Include/Atom/Feature/Mesh/MeshFeatureProcessor.h index a595471813..7ad8bd8283 100644 --- a/Gems/Atom/Feature/Common/Code/Include/Atom/Feature/Mesh/MeshFeatureProcessor.h +++ b/Gems/Atom/Feature/Common/Code/Include/Atom/Feature/Mesh/MeshFeatureProcessor.h @@ -21,6 +21,7 @@ #include #include #include +#include namespace AZ { @@ -160,8 +161,14 @@ namespace AZ // called when reflection probes are modified in the editor so that meshes can re-evaluate their probes void UpdateMeshReflectionProbes(); - private: + void ForceRebuildDrawPackets(const AZ::ConsoleCommandContainer& arguments); + AZ_CONSOLEFUNC(MeshFeatureProcessor, + ForceRebuildDrawPackets, + AZ::ConsoleFunctorFlags::Null, + "(For Testing) Invalidates all mesh draw packets, causing them to rebuild on the next frame." + ); + MeshFeatureProcessor(const MeshFeatureProcessor&) = delete; // RPI::SceneNotificationBus::Handler overrides... diff --git a/Gems/Atom/Feature/Common/Code/Include/Atom/Feature/Utils/LightingPreset.h b/Gems/Atom/Feature/Common/Code/Include/Atom/Feature/Utils/LightingPreset.h index 1c220e0d8d..f1d8337a35 100644 --- a/Gems/Atom/Feature/Common/Code/Include/Atom/Feature/Utils/LightingPreset.h +++ b/Gems/Atom/Feature/Common/Code/Include/Atom/Feature/Utils/LightingPreset.h @@ -78,7 +78,6 @@ namespace AZ AZ_CLASS_ALLOCATOR(LightingPreset, AZ::SystemAllocator, 0); static void Reflect(AZ::ReflectContext* context); - bool m_autoSelect = false; AZStd::string m_displayName; AZ::Data::Asset m_iblDiffuseImageAsset; AZ::Data::Asset m_iblSpecularImageAsset; 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 896d6fb78f..9ca8c13859 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 @@ -32,7 +32,6 @@ namespace AZ AZ_CLASS_ALLOCATOR(ModelPreset, AZ::SystemAllocator, 0); static void Reflect(AZ::ReflectContext* context); - bool m_autoSelect = false; AZStd::string m_displayName; AZ::Data::Asset m_modelAsset; AZ::Data::Asset m_previewImageAsset; diff --git a/Gems/Atom/Feature/Common/Code/Source/AuxGeom/AuxGeomDrawQueue.cpp b/Gems/Atom/Feature/Common/Code/Source/AuxGeom/AuxGeomDrawQueue.cpp index fd4b5b28d1..dc53498c8b 100644 --- a/Gems/Atom/Feature/Common/Code/Source/AuxGeom/AuxGeomDrawQueue.cpp +++ b/Gems/Atom/Feature/Common/Code/Source/AuxGeom/AuxGeomDrawQueue.cpp @@ -289,7 +289,7 @@ namespace AZ void AuxGeomDrawQueue::DrawQuad( float width, float height, - const AZ::Transform& transform, + const AZ::Matrix3x4& transform, const AZ::Color& color, DrawStyle style, DepthTest depthTest, @@ -302,8 +302,8 @@ namespace AZ return; } - Transform noScaleTransform = transform; - noScaleTransform.ExtractScale(); + AZ::Matrix3x4 noScaleTransform = transform; + AZ::Vector3 scale = noScaleTransform.ExtractScale(); ShapeBufferEntry shape; shape.m_shapeType = ShapeType_Quad; @@ -311,9 +311,9 @@ namespace AZ shape.m_depthWrite = ConvertRPIDepthWriteFlag(depthWrite); shape.m_faceCullMode = ConvertRPIFaceCullFlag(faceCull); shape.m_color = color; - shape.m_rotationMatrix = Matrix3x3::CreateFromTransform(noScaleTransform); + shape.m_rotationMatrix = Matrix3x3::CreateFromMatrix3x4(noScaleTransform); shape.m_position = transform.GetTranslation(); - shape.m_scale = transform.GetScale() * Vector3(width, 1.0f, height); + shape.m_scale = scale * Vector3(width, 1.0f, height); shape.m_pointSize = m_pointSize; shape.m_viewProjOverrideIndex = viewProjOverrideIndex; diff --git a/Gems/Atom/Feature/Common/Code/Source/AuxGeom/AuxGeomDrawQueue.h b/Gems/Atom/Feature/Common/Code/Source/AuxGeom/AuxGeomDrawQueue.h index b959173ed1..53220c031d 100644 --- a/Gems/Atom/Feature/Common/Code/Source/AuxGeom/AuxGeomDrawQueue.h +++ b/Gems/Atom/Feature/Common/Code/Source/AuxGeom/AuxGeomDrawQueue.h @@ -62,7 +62,7 @@ namespace AZ void DrawTriangles(const AuxGeomDynamicIndexedDrawArguments& args, FaceCullMode faceCull = FaceCullMode::None) override; // Fixed shape draws - void DrawQuad(float width, float height, const AZ::Transform& transform, const AZ::Color& color, DrawStyle style, DepthTest depthTest, DepthWrite depthWrite, FaceCullMode faceCull, int32_t viewProjOverrideIndex) override; + 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 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; diff --git a/Gems/Atom/Feature/Common/Code/Source/Mesh/MeshFeatureProcessor.cpp b/Gems/Atom/Feature/Common/Code/Source/Mesh/MeshFeatureProcessor.cpp index 95bbe13586..5f39c6bc38 100644 --- a/Gems/Atom/Feature/Common/Code/Source/Mesh/MeshFeatureProcessor.cpp +++ b/Gems/Atom/Feature/Common/Code/Source/Mesh/MeshFeatureProcessor.cpp @@ -387,6 +387,11 @@ namespace AZ } } + void MeshFeatureProcessor::ForceRebuildDrawPackets([[maybe_unused]] const AZ::ConsoleCommandContainer& arguments) + { + m_forceRebuildDrawPackets = true; + } + void MeshFeatureProcessor::OnRenderPipelineAdded(RPI::RenderPipelinePtr pipeline) { m_forceRebuildDrawPackets = true;; diff --git a/Gems/Atom/Feature/Common/Code/Source/PostProcessing/BlendColorGradingLutsPass.cpp b/Gems/Atom/Feature/Common/Code/Source/PostProcessing/BlendColorGradingLutsPass.cpp index 206e58d5e6..e0ff253301 100644 --- a/Gems/Atom/Feature/Common/Code/Source/PostProcessing/BlendColorGradingLutsPass.cpp +++ b/Gems/Atom/Feature/Common/Code/Source/PostProcessing/BlendColorGradingLutsPass.cpp @@ -131,8 +131,13 @@ namespace AZ AZ_Assert(m_blendedLut.m_lutImage != nullptr, "BlendColorGradingLutsPass unable to acquire LUT image"); AZ::RHI::AttachmentId imageAttachmentId = AZ::RHI::AttachmentId("BlendColorGradingLutImageAttachmentId"); - [[maybe_unused]] RHI::ResultCode result = frameGraph.GetAttachmentDatabase().ImportImage(imageAttachmentId, m_blendedLut.m_lutImage); - AZ_Error("BlendColorGradingLutsPass", result == RHI::ResultCode::Success, "Failed to import compute buffer with error %d", result); + + // import this attachment if it wasn't imported + if (!frameGraph.GetAttachmentDatabase().IsAttachmentValid(imageAttachmentId)) + { + [[maybe_unused]] RHI::ResultCode result = frameGraph.GetAttachmentDatabase().ImportImage(imageAttachmentId, m_blendedLut.m_lutImage); + AZ_Error("BlendColorGradingLutsPass", result == RHI::ResultCode::Success, "Failed to import BlendColorGradingLutImageAttachmentId with error %d", result); + } RHI::ImageScopeAttachmentDescriptor desc; desc.m_attachmentId = imageAttachmentId; diff --git a/Gems/Atom/Feature/Common/Code/Source/ReflectionProbe/ReflectionProbe.cpp b/Gems/Atom/Feature/Common/Code/Source/ReflectionProbe/ReflectionProbe.cpp index 86c012731c..0826739119 100644 --- a/Gems/Atom/Feature/Common/Code/Source/ReflectionProbe/ReflectionProbe.cpp +++ b/Gems/Atom/Feature/Common/Code/Source/ReflectionProbe/ReflectionProbe.cpp @@ -248,6 +248,9 @@ namespace AZ AZ::RPI::RenderPipelineDescriptor environmentCubeMapPipelineDesc; environmentCubeMapPipelineDesc.m_mainViewTagName = "MainCamera"; + environmentCubeMapPipelineDesc.m_renderSettings.m_multisampleState.m_samples = 4; + environmentCubeMapPipelineDesc.m_renderSettings.m_size.m_width = RPI::EnvironmentCubeMapPass::CubeMapFaceSize; + environmentCubeMapPipelineDesc.m_renderSettings.m_size.m_height = RPI::EnvironmentCubeMapPass::CubeMapFaceSize; // create a unique name for the pipeline AZ::Uuid uuid = AZ::Uuid::CreateRandom(); diff --git a/Gems/Atom/Feature/Common/Code/Source/Utils/EditorLightingPreset.cpp b/Gems/Atom/Feature/Common/Code/Source/Utils/EditorLightingPreset.cpp index e7f9c8b09f..1da9463bd8 100644 --- a/Gems/Atom/Feature/Common/Code/Source/Utils/EditorLightingPreset.cpp +++ b/Gems/Atom/Feature/Common/Code/Source/Utils/EditorLightingPreset.cpp @@ -112,7 +112,6 @@ namespace AZ ->ClassElement(AZ::Edit::ClassElements::EditorData, "") ->Attribute(AZ::Edit::Attributes::AutoExpand, true) ->DataElement(AZ::Edit::UIHandlers::Default, &LightingPreset::m_displayName, "Display Name", "Identifier used for display and selection") - ->DataElement(AZ::Edit::UIHandlers::Default, &LightingPreset::m_autoSelect, "Auto Select", "When true, the configuration is automatically selected when loaded") ->DataElement(AZ::Edit::UIHandlers::Default, &LightingPreset::m_iblDiffuseImageAsset, "IBL Diffuse Image Asset", "IBL diffuse image asset reference") ->DataElement(AZ::Edit::UIHandlers::Default, &LightingPreset::m_iblSpecularImageAsset, "IBL Specular Image Asset", "IBL specular image asset reference") ->DataElement(AZ::Edit::UIHandlers::Default, &LightingPreset::m_skyboxImageAsset, "Skybox Image Asset", "Skybox image asset reference") diff --git a/Gems/Atom/Feature/Common/Code/Source/Utils/EditorModelPreset.cpp b/Gems/Atom/Feature/Common/Code/Source/Utils/EditorModelPreset.cpp index b8b0b610f3..bed320c45d 100644 --- a/Gems/Atom/Feature/Common/Code/Source/Utils/EditorModelPreset.cpp +++ b/Gems/Atom/Feature/Common/Code/Source/Utils/EditorModelPreset.cpp @@ -32,7 +32,6 @@ namespace AZ ->ClassElement(AZ::Edit::ClassElements::EditorData, "") ->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_autoSelect, "Auto Select", "When true, the configuration is automatically selected when loaded") ->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/LightingPreset.cpp b/Gems/Atom/Feature/Common/Code/Source/Utils/LightingPreset.cpp index 837a725a9f..77924b87a3 100644 --- a/Gems/Atom/Feature/Common/Code/Source/Utils/LightingPreset.cpp +++ b/Gems/Atom/Feature/Common/Code/Source/Utils/LightingPreset.cpp @@ -105,8 +105,7 @@ namespace AZ serializeContext->RegisterGenericType>(); serializeContext->Class() - ->Version(4) - ->Field("autoSelect", &LightingPreset::m_autoSelect) + ->Version(5) ->Field("displayName", &LightingPreset::m_displayName) ->Field("iblDiffuseImageAsset", &LightingPreset::m_iblDiffuseImageAsset) ->Field("iblSpecularImageAsset", &LightingPreset::m_iblSpecularImageAsset) @@ -128,7 +127,6 @@ namespace AZ ->Attribute(AZ::Script::Attributes::Module, "render") ->Constructor() ->Constructor() - ->Property("autoSelect", BehaviorValueProperty(&LightingPreset::m_autoSelect)) ->Property("displayName", BehaviorValueProperty(&LightingPreset::m_displayName)) ->Property("alternateSkyboxImageAsset", BehaviorValueProperty(&LightingPreset::m_alternateSkyboxImageAsset)) ->Property("skyboxImageAsset", BehaviorValueProperty(&LightingPreset::m_skyboxImageAsset)) diff --git a/Gems/Atom/Feature/Common/Code/Source/Utils/ModelPreset.cpp b/Gems/Atom/Feature/Common/Code/Source/Utils/ModelPreset.cpp index e93bfa527a..2795617c18 100644 --- a/Gems/Atom/Feature/Common/Code/Source/Utils/ModelPreset.cpp +++ b/Gems/Atom/Feature/Common/Code/Source/Utils/ModelPreset.cpp @@ -25,8 +25,7 @@ namespace AZ if (auto serializeContext = azrtti_cast(context)) { serializeContext->Class() - ->Version(2) - ->Field("autoSelect", &ModelPreset::m_autoSelect) + ->Version(3) ->Field("displayName", &ModelPreset::m_displayName) ->Field("modelAsset", &ModelPreset::m_modelAsset) ->Field("previewImageAsset", &ModelPreset::m_previewImageAsset) @@ -41,7 +40,6 @@ namespace AZ ->Attribute(AZ::Script::Attributes::Module, "render") ->Constructor() ->Constructor() - ->Property("autoSelect", BehaviorValueProperty(&ModelPreset::m_autoSelect)) ->Property("displayName", BehaviorValueProperty(&ModelPreset::m_displayName)) ->Property("modelAsset", BehaviorValueProperty(&ModelPreset::m_modelAsset)) ->Property("previewImageAsset", BehaviorValueProperty(&ModelPreset::m_previewImageAsset)) diff --git a/Gems/Atom/RHI/Code/Source/RHI.Reflect/Base.cpp b/Gems/Atom/RHI/Code/Source/RHI.Reflect/Base.cpp index 4d35411e09..21eb634159 100644 --- a/Gems/Atom/RHI/Code/Source/RHI.Reflect/Base.cpp +++ b/Gems/Atom/RHI/Code/Source/RHI.Reflect/Base.cpp @@ -16,6 +16,6 @@ namespace AZ { namespace RHI { - bool Validation::s_isEnabled = BuildOptions::IsDebugBuild; + bool Validation::s_isEnabled = BuildOptions::IsDebugBuild || BuildOptions::IsProfileBuild; } } diff --git a/Gems/Atom/RHI/DX12/Code/Source/RHI/FrameGraphCompiler.cpp b/Gems/Atom/RHI/DX12/Code/Source/RHI/FrameGraphCompiler.cpp index 1ae8a4ae96..7fc1db179a 100644 --- a/Gems/Atom/RHI/DX12/Code/Source/RHI/FrameGraphCompiler.cpp +++ b/Gems/Atom/RHI/DX12/Code/Source/RHI/FrameGraphCompiler.cpp @@ -404,6 +404,12 @@ namespace AZ Buffer& buffer = static_cast(*bufferFrameAttachment.GetBuffer()); RHI::BufferScopeAttachment* scopeAttachment = bufferFrameAttachment.GetFirstScopeAttachment(); + if (scopeAttachment == nullptr) + { + AZ_WarningOnce("RHI", false, "Imported BufferFrameAttachment isn't used in any Scope"); + return; + } + D3D12_RESOURCE_TRANSITION_BARRIER transition; transition.pResource = buffer.GetMemoryView().GetMemory(); transition.Subresource = D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES; @@ -471,6 +477,12 @@ namespace AZ Image& image = static_cast(*imageFrameAttachment.GetImage()); RHI::ImageScopeAttachment* scopeAttachment = imageFrameAttachment.GetFirstScopeAttachment(); + if (scopeAttachment == nullptr) + { + AZ_WarningOnce("RHI", false, "Imported ImageFrameAttachment isn't used in any Scope"); + return; + } + D3D12_RESOURCE_TRANSITION_BARRIER transition; transition.pResource = image.GetMemoryView().GetMemory(); 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 afba71a457..0e7f11e46e 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 @@ -138,7 +138,7 @@ namespace AZ //! @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 DrawQuad(float width, float height, const AZ::Transform& transform, 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; + virtual void DrawQuad(float width, float height, const AZ::Matrix3x4& transform, 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. diff --git a/Gems/Atom/RPI/Code/Include/Atom/RPI.Reflect/Material/MaterialPropertyValue.h b/Gems/Atom/RPI/Code/Include/Atom/RPI.Reflect/Material/MaterialPropertyValue.h index cafd31d8a5..758afb1c66 100644 --- a/Gems/Atom/RPI/Code/Include/Atom/RPI.Reflect/Material/MaterialPropertyValue.h +++ b/Gems/Atom/RPI/Code/Include/Atom/RPI.Reflect/Material/MaterialPropertyValue.h @@ -65,6 +65,7 @@ namespace AZ MaterialPropertyValue(const Vector4& value) : m_value(value) {} MaterialPropertyValue(const Color& value) : m_value(value) {} MaterialPropertyValue(const Data::Asset& value) : m_value(value) {} + MaterialPropertyValue(const Data::Instance& value) : m_value(value) {} MaterialPropertyValue(const AZStd::string& value) : m_value(value) {} //! Copy constructor diff --git a/Gems/Atom/RPI/Code/Source/RPI.Public/Buffer/Buffer.cpp b/Gems/Atom/RPI/Code/Source/RPI.Public/Buffer/Buffer.cpp index 81fd9e751b..afcf4670f3 100644 --- a/Gems/Atom/RPI/Code/Source/RPI.Public/Buffer/Buffer.cpp +++ b/Gems/Atom/RPI/Code/Source/RPI.Public/Buffer/Buffer.cpp @@ -74,7 +74,8 @@ namespace AZ const RHI::BufferView* Buffer::GetBufferView() const { - if(RHI::CheckBitsAny(m_rhiBuffer->GetDescriptor().m_bindFlags, RHI::BufferBindFlags::InputAssembly | RHI::BufferBindFlags::DynamicInputAssembly)) + if (m_rhiBuffer->GetDescriptor().m_bindFlags == RHI::BufferBindFlags::InputAssembly || + m_rhiBuffer->GetDescriptor().m_bindFlags == RHI::BufferBindFlags::DynamicInputAssembly) { AZ_Assert(false, "Input assembly buffer doesn't need a regular buffer view, it requires a stream or index buffer view."); diff --git a/Gems/Atom/RPI/Code/Source/RPI.Public/MeshDrawPacket.cpp b/Gems/Atom/RPI/Code/Source/RPI.Public/MeshDrawPacket.cpp index 1e5eaab20c..d0a277304e 100644 --- a/Gems/Atom/RPI/Code/Source/RPI.Public/MeshDrawPacket.cpp +++ b/Gems/Atom/RPI/Code/Source/RPI.Public/MeshDrawPacket.cpp @@ -17,11 +17,20 @@ #include #include #include +#include namespace AZ { namespace RPI { + AZ_CVAR(bool, + r_forceRootShaderVariantUsage, + false, + [](const bool&) { AZ::Interface::Get()->PerformCommand("MeshFeatureProcessor.ForceRebuildDrawPackets"); }, + ConsoleFunctorFlags::Null, + "(For Testing) Forces usage of root shader variant in the mesh draw packet level, ignoring any other shader variants that may exist." + ); + MeshDrawPacket::MeshDrawPacket( ModelLod& modelLod, size_t modelLodMeshIndex, @@ -187,7 +196,7 @@ namespace AZ } const ShaderVariantId finalVariantId = shaderOptions.GetShaderVariantId(); - const ShaderVariant& variant = shader->GetVariant(finalVariantId); + const ShaderVariant& variant = r_forceRootShaderVariantUsage ? shader->GetRootVariant() : shader->GetVariant(finalVariantId); Data::Instance drawSrg; if (drawSrgAsset) diff --git a/Gems/Atom/RPI/Code/Source/RPI.Public/Pass/Specific/EnvironmentCubeMapPass.cpp b/Gems/Atom/RPI/Code/Source/RPI.Public/Pass/Specific/EnvironmentCubeMapPass.cpp index 5ba43f9f7e..c72712bce5 100644 --- a/Gems/Atom/RPI/Code/Source/RPI.Public/Pass/Specific/EnvironmentCubeMapPass.cpp +++ b/Gems/Atom/RPI/Code/Source/RPI.Public/Pass/Specific/EnvironmentCubeMapPass.cpp @@ -57,7 +57,7 @@ namespace AZ PassConnection childInputConnection; childInputConnection.m_localSlot = "Output"; childInputConnection.m_attachmentRef.m_pass = "Parent"; - childInputConnection.m_attachmentRef.m_attachment = "CubeMapOutput"; + childInputConnection.m_attachmentRef.m_attachment = "Output"; childRequest.m_connections.emplace_back(childInputConnection); PassSystemInterface* passSystem = PassSystemInterface::Get(); @@ -120,15 +120,16 @@ namespace AZ // create output PassAttachment m_passAttachment = aznew PassAttachment(); - m_passAttachment->m_name = "CubeMapOutput"; - m_passAttachment->m_path = "CubeMapOutput"; + m_passAttachment->m_name = "Output"; + AZ::Name attachmentPath(AZStd::string::format("%s.%s", GetPathName().GetCStr(), m_passAttachment->m_name.GetCStr())); + m_passAttachment->m_path = attachmentPath; m_passAttachment->m_lifetime = RHI::AttachmentLifetimeType::Transient; m_passAttachment->m_descriptor = m_outputImageDesc; // create pass attachment binding PassAttachmentBinding outputAttachment; - outputAttachment.m_name = "CubeMapOutput"; - outputAttachment.m_slotType = PassSlotType::Output; + outputAttachment.m_name = "Output"; + outputAttachment.m_slotType = PassSlotType::InputOutput; outputAttachment.m_attachment = m_passAttachment; outputAttachment.m_scopeAttachmentUsage = RHI::ScopeAttachmentUsage::RenderTarget; diff --git a/Gems/Atom/RPI/Code/Source/RPI.Reflect/Base.cpp b/Gems/Atom/RPI/Code/Source/RPI.Reflect/Base.cpp index 7012a7cf88..8addb16a23 100644 --- a/Gems/Atom/RPI/Code/Source/RPI.Reflect/Base.cpp +++ b/Gems/Atom/RPI/Code/Source/RPI.Reflect/Base.cpp @@ -16,6 +16,6 @@ namespace AZ { namespace RPI { - bool Validation::s_isEnabled = RHI::BuildOptions::IsDebugBuild; + bool Validation::s_isEnabled = RHI::BuildOptions::IsDebugBuild || RHI::BuildOptions::IsProfileBuild; } } diff --git a/Gems/Atom/TestData/TestData/LightingPresets/urban_street_02.lightingpreset.azasset b/Gems/Atom/TestData/TestData/LightingPresets/urban_street_02.lightingpreset.azasset index d0a290649b..a676d5fba6 100644 --- a/Gems/Atom/TestData/TestData/LightingPresets/urban_street_02.lightingpreset.azasset +++ b/Gems/Atom/TestData/TestData/LightingPresets/urban_street_02.lightingpreset.azasset @@ -3,7 +3,6 @@ "Version": 1, "ClassName": "AZ::Render::LightingPreset", "ClassData": { - "autoSelect": false, "displayName": "Urban Street 02", "skyboxImageAsset": { "assetId": { diff --git a/Gems/Atom/Tools/AtomToolsFramework/Code/Source/Viewport/RenderViewportWidget.cpp b/Gems/Atom/Tools/AtomToolsFramework/Code/Source/Viewport/RenderViewportWidget.cpp index e08a5a045c..bf46ece27b 100644 --- a/Gems/Atom/Tools/AtomToolsFramework/Code/Source/Viewport/RenderViewportWidget.cpp +++ b/Gems/Atom/Tools/AtomToolsFramework/Code/Source/Viewport/RenderViewportWidget.cpp @@ -164,6 +164,8 @@ namespace AtomToolsFramework bool RenderViewportWidget::OnInputChannelEventFiltered(const AzFramework::InputChannel& inputChannel) { + bool shouldConsumeEvent = true; + // Grab keyboard focus if we've been clicked on. // Qt normally handles this for us, but we're filtering native events before they get // synthesized into QMouseEvents. @@ -175,9 +177,18 @@ namespace AtomToolsFramework // Don't consume new input events if we don't currently have focus. // We do forward Ended events, as they may be relevant to our current state // (e.g. a key gets released after we lose focus, it shouldn't remain "stuck"). - if (!hasFocus() && inputChannel.GetState() != AzFramework::InputChannel::State::Ended) + if (!hasFocus()) { - return false; + if (inputChannel.GetState() == AzFramework::InputChannel::State::Ended) + { + // Forward the input ended event to our controllers, but don't prevent other viewports from receiving it. + shouldConsumeEvent = false; + } + else + { + // Not an event we should listen to, abort. + return false; + } } // If we receive a mouse button event from outside of our viewport, ignore it even if we have focus. @@ -196,7 +207,9 @@ namespace AtomToolsFramework } AzFramework::NativeWindowHandle windowId = reinterpret_cast(winId()); - return m_controllerList->HandleInputChannelEvent({GetId(), windowId, inputChannel}); + const bool eventHandled = m_controllerList->HandleInputChannelEvent({GetId(), windowId, inputChannel}); + // If our controllers handled the event and it's one we can safely consume (i.e. it's not an Ended event that other viewports might need), consume it. + return eventHandled && shouldConsumeEvent; } void RenderViewportWidget::OnTick([[maybe_unused]]float deltaTime, AZ::ScriptTimePoint time) diff --git a/Gems/Atom/Tools/MaterialEditor/Assets/MaterialEditor/LightingPresets/_TEMPLATE_.lightingconfig.json.template b/Gems/Atom/Tools/MaterialEditor/Assets/MaterialEditor/LightingPresets/_TEMPLATE_.lightingconfig.json.template index 7cfa7edbc3..6d87c5eb7b 100644 --- a/Gems/Atom/Tools/MaterialEditor/Assets/MaterialEditor/LightingPresets/_TEMPLATE_.lightingconfig.json.template +++ b/Gems/Atom/Tools/MaterialEditor/Assets/MaterialEditor/LightingPresets/_TEMPLATE_.lightingconfig.json.template @@ -2,7 +2,6 @@ "configurations": [ { "displayName": "Substance: